diff --git a/CHANGELOG.md b/CHANGELOG.md index 9856c59f..564e3597 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,14 @@ +## v2.1.3 + +**features** +- new function `fetchCalendarUserAddresses` thanks to @pierreliefauche +- new type `calendarColor` on `DAVCalendar` + +##### improvements +- fetch updates, now use polyfill mode +- updated dependencies +- doc update by community + ## v2.1.2 **features** diff --git a/dist/package.json b/dist/package.json index 3b73c778..96993240 100644 --- a/dist/package.json +++ b/dist/package.json @@ -1,6 +1,6 @@ { "name": "tsdav", - "version": "2.1.2", + "version": "2.1.3", "description": "WebDAV, CALDAV, and CARDDAV client for Nodejs and the Browser", "keywords": [ "dav", diff --git a/dist/tsdav.cjs b/dist/tsdav.cjs index 5065d184..e229dea0 100644 --- a/dist/tsdav.cjs +++ b/dist/tsdav.cjs @@ -2,7 +2,7 @@ Object.defineProperty(exports, '__esModule', { value: true }); -var crossFetch = require('cross-fetch'); +require('cross-fetch/polyfill'); var getLogger = require('debug'); var convert = require('xml-js'); var base64 = require('base-64'); @@ -155,7 +155,7 @@ const davRequest = async (params) => { // )}` // ); // debug(xmlBody); - const davResponse = await crossFetch.fetch(url, { + const davResponse = await fetch(url, { headers: { 'Content-Type': 'text/xml;charset=UTF-8', ...cleanupFalsy(headers), @@ -276,7 +276,7 @@ const propfind = async (params) => { }; const createObject = async (params) => { const { url, data, headers, headersToExclude, fetchOptions = {} } = params; - return crossFetch.fetch(url, { + return fetch(url, { method: 'PUT', body: data, headers: excludeHeaders(headers, headersToExclude), @@ -285,7 +285,7 @@ const createObject = async (params) => { }; const updateObject = async (params) => { const { url, data, etag, headers, headersToExclude, fetchOptions = {} } = params; - return crossFetch.fetch(url, { + return fetch(url, { method: 'PUT', body: data, headers: excludeHeaders(cleanupFalsy({ 'If-Match': etag, ...headers }), headersToExclude), @@ -294,10 +294,10 @@ const updateObject = async (params) => { }; const deleteObject = async (params) => { const { url, headers, etag, headersToExclude, fetchOptions = {} } = params; - return crossFetch.fetch(url, { + return fetch(url, { method: 'DELETE', headers: excludeHeaders(cleanupFalsy({ 'If-Match': etag, ...headers }), headersToExclude), - ...fetchOptions + ...fetchOptions, }); }; @@ -571,11 +571,11 @@ var collection = /*#__PURE__*/Object.freeze({ /* eslint-disable no-underscore-dangle */ const debug$3 = getLogger('tsdav:addressBook'); const addressBookQuery = async (params) => { - const { url, props, filters, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, filters, depth, headers, headersToExclude, fetchOptions = {} } = params; return collectionQuery({ url, body: { - 'addressbook-query': { + 'addressbook-query': cleanupFalsy({ _attributes: getDAVAttribute([exports.DAVNamespace.CARDDAV, exports.DAVNamespace.DAV]), [`${exports.DAVNamespaceShort.DAV}:prop`]: props, filter: filters !== null && filters !== void 0 ? filters : { @@ -585,24 +585,24 @@ const addressBookQuery = async (params) => { }, }, }, - }, + }), }, defaultNamespace: exports.DAVNamespaceShort.CARDDAV, depth, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); }; const addressBookMultiGet = async (params) => { - const { url, props, objectUrls, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, objectUrls, depth, headers, headersToExclude, fetchOptions = {} } = params; return collectionQuery({ url, body: { - 'addressbook-multiget': { + 'addressbook-multiget': cleanupFalsy({ _attributes: getDAVAttribute([exports.DAVNamespace.DAV, exports.DAVNamespace.CARDDAV]), [`${exports.DAVNamespaceShort.DAV}:prop`]: props, [`${exports.DAVNamespaceShort.DAV}:href`]: objectUrls, - }, + }), }, defaultNamespace: exports.DAVNamespaceShort.CARDDAV, depth, @@ -611,7 +611,7 @@ const addressBookMultiGet = async (params) => { }); }; const fetchAddressBooks = async (params) => { - const { account, headers, props: customProps, headersToExclude, fetchOptions = {} } = params !== null && params !== void 0 ? params : {}; + const { account, headers, props: customProps, headersToExclude, fetchOptions = {}, } = params !== null && params !== void 0 ? params : {}; const requiredFields = ['homeUrl', 'rootUrl']; if (!account || !hasFields(account, requiredFields)) { if (!account) { @@ -648,11 +648,15 @@ const fetchAddressBooks = async (params) => { }) .map(async (addr) => ({ ...addr, - reports: await supportedReportSet({ collection: addr, headers: excludeHeaders(headers, headersToExclude), fetchOptions }), + reports: await supportedReportSet({ + collection: addr, + headers: excludeHeaders(headers, headersToExclude), + fetchOptions, + }), }))); }; const fetchVCards = async (params) => { - const { addressBook, headers, objectUrls, headersToExclude, urlFilter = (url) => url, useMultiGet = true, fetchOptions = {} } = params; + const { addressBook, headers, objectUrls, headersToExclude, urlFilter = (url) => url, useMultiGet = true, fetchOptions = {}, } = params; debug$3(`Fetching vcards from ${addressBook === null || addressBook === void 0 ? void 0 : addressBook.url}`); const requiredFields = ['url']; if (!addressBook || !hasFields(addressBook, requiredFields)) { @@ -669,7 +673,7 @@ const fetchVCards = async (params) => { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, - })).map((res) => { var _a; return (res.ok ? (_a = res.href) !== null && _a !== void 0 ? _a : '' : ''); })) + })).map((res) => { var _a; return (res.ok ? ((_a = res.href) !== null && _a !== void 0 ? _a : '') : ''); })) .map((url) => (url.startsWith('http') || !url ? url : new URL(url, addressBook.url).href)) .filter(urlFilter) .map((url) => new URL(url).pathname); @@ -685,7 +689,7 @@ const fetchVCards = async (params) => { objectUrls: vcardUrls, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } else { @@ -697,7 +701,7 @@ const fetchVCards = async (params) => { }, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } } @@ -711,7 +715,7 @@ const fetchVCards = async (params) => { }); }; const createVCard = async (params) => { - const { addressBook, vCardString, filename, headers, headersToExclude, fetchOptions = {} } = params; + const { addressBook, vCardString, filename, headers, headersToExclude, fetchOptions = {}, } = params; return createObject({ url: new URL(filename, addressBook.url).href, data: vCardString, @@ -720,7 +724,7 @@ const createVCard = async (params) => { 'If-None-Match': '*', ...headers, }, headersToExclude), - fetchOptions + fetchOptions, }); }; const updateVCard = async (params) => { @@ -742,7 +746,7 @@ const deleteVCard = async (params) => { url: vCard.url, etag: vCard.etag, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); }; @@ -783,7 +787,7 @@ const fetchCalendarUserAddresses = async (params) => { return addresses; }; const calendarQuery = async (params) => { - const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {} } = params; + const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, } = params; return collectionQuery({ url, body: { @@ -806,17 +810,17 @@ const calendarQuery = async (params) => { }); }; const calendarMultiGet = async (params) => { - const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {} } = params; + const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, } = params; return collectionQuery({ url, body: { - 'calendar-multiget': { + 'calendar-multiget': cleanupFalsy({ _attributes: getDAVAttribute([exports.DAVNamespace.DAV, exports.DAVNamespace.CALDAV]), [`${exports.DAVNamespaceShort.DAV}:prop`]: props, [`${exports.DAVNamespaceShort.DAV}:href`]: objectUrls, - ...conditionalParam('filter', filters), + filter: filters, timezone, - }, + }), }, defaultNamespace: exports.DAVNamespaceShort.CALDAV, depth, @@ -845,11 +849,11 @@ const makeCalendar = async (params) => { }, }, }, - fetchOptions + fetchOptions, }); }; const fetchCalendars = async (params) => { - const { headers, account, props: customProps, projectedProps, headersToExclude, fetchOptions = {} } = params !== null && params !== void 0 ? params : {}; + const { headers, account, props: customProps, projectedProps, headersToExclude, fetchOptions = {}, } = params !== null && params !== void 0 ? params : {}; const requiredFields = ['homeUrl', 'rootUrl']; if (!account || !hasFields(account, requiredFields)) { if (!account) { @@ -989,7 +993,7 @@ const fetchCalendarObjects = async (params) => { filters, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, })).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)) // patch up to full url if url is not full .filter(urlFilter) // custom filter function on calendar objects @@ -1023,7 +1027,7 @@ const fetchCalendarObjects = async (params) => { filters, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } else { @@ -1053,7 +1057,7 @@ const fetchCalendarObjects = async (params) => { objectUrls: calendarObjectUrls, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } } @@ -1076,7 +1080,7 @@ const createCalendarObject = async (params) => { 'If-None-Match': '*', ...headers, }, headersToExclude), - fetchOptions + fetchOptions, }); }; const updateCalendarObject = async (params) => { @@ -1089,7 +1093,7 @@ const updateCalendarObject = async (params) => { 'content-type': 'text/calendar; charset=utf-8', ...headers, }, headersToExclude), - fetchOptions + fetchOptions, }); }; const deleteCalendarObject = async (params) => { @@ -1098,7 +1102,7 @@ const deleteCalendarObject = async (params) => { url: calendarObject.url, etag: calendarObject.etag, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); }; /** @@ -1106,7 +1110,7 @@ const deleteCalendarObject = async (params) => { */ const syncCalendars = async (params) => { var _a; - const { oldCalendars, account, detailedResult, headers, headersToExclude, fetchOptions = {} } = params; + const { oldCalendars, account, detailedResult, headers, headersToExclude, fetchOptions = {}, } = params; if (!account) { throw new Error('Must have account before syncCalendars'); } @@ -1114,7 +1118,7 @@ const syncCalendars = async (params) => { const remoteCalendars = await fetchCalendars({ account, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); // no existing url const created = remoteCalendars.filter((rc) => localCalendars.every((lc) => !urlContains(lc.url, rc.url))); @@ -1185,7 +1189,7 @@ const freeBusyQuery = async (params) => { defaultNamespace: exports.DAVNamespaceShort.CALDAV, depth, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); return result[0]; }; @@ -1214,7 +1218,7 @@ const serviceDiscovery = async (params) => { const uri = new URL(`/.well-known/${account.accountType}`, endpoint); uri.protocol = (_a = endpoint.protocol) !== null && _a !== void 0 ? _a : 'http'; try { - const response = await crossFetch.fetch(uri.href, { + const response = await fetch(uri.href, { headers: excludeHeaders(headers, headersToExclude), method: 'PROPFIND', redirect: 'manual', @@ -1396,7 +1400,7 @@ const fetchOauthTokens = async (credentials, fetchOptions) => { }); debug(credentials.tokenUrl); debug(param.toString()); - const response = await crossFetch.fetch(credentials.tokenUrl, { + const response = await fetch(credentials.tokenUrl, { method: 'POST', body: param.toString(), headers: { @@ -1428,7 +1432,7 @@ const refreshAccessToken = async (credentials, fetchOptions) => { refresh_token: credentials.refreshToken, grant_type: 'refresh_token', }); - const response = await crossFetch.fetch(credentials.tokenUrl, { + const response = await fetch(credentials.tokenUrl, { method: 'POST', body: param.toString(), headers: { diff --git a/dist/tsdav.cjs.js b/dist/tsdav.cjs.js index 5065d184..e229dea0 100644 --- a/dist/tsdav.cjs.js +++ b/dist/tsdav.cjs.js @@ -2,7 +2,7 @@ Object.defineProperty(exports, '__esModule', { value: true }); -var crossFetch = require('cross-fetch'); +require('cross-fetch/polyfill'); var getLogger = require('debug'); var convert = require('xml-js'); var base64 = require('base-64'); @@ -155,7 +155,7 @@ const davRequest = async (params) => { // )}` // ); // debug(xmlBody); - const davResponse = await crossFetch.fetch(url, { + const davResponse = await fetch(url, { headers: { 'Content-Type': 'text/xml;charset=UTF-8', ...cleanupFalsy(headers), @@ -276,7 +276,7 @@ const propfind = async (params) => { }; const createObject = async (params) => { const { url, data, headers, headersToExclude, fetchOptions = {} } = params; - return crossFetch.fetch(url, { + return fetch(url, { method: 'PUT', body: data, headers: excludeHeaders(headers, headersToExclude), @@ -285,7 +285,7 @@ const createObject = async (params) => { }; const updateObject = async (params) => { const { url, data, etag, headers, headersToExclude, fetchOptions = {} } = params; - return crossFetch.fetch(url, { + return fetch(url, { method: 'PUT', body: data, headers: excludeHeaders(cleanupFalsy({ 'If-Match': etag, ...headers }), headersToExclude), @@ -294,10 +294,10 @@ const updateObject = async (params) => { }; const deleteObject = async (params) => { const { url, headers, etag, headersToExclude, fetchOptions = {} } = params; - return crossFetch.fetch(url, { + return fetch(url, { method: 'DELETE', headers: excludeHeaders(cleanupFalsy({ 'If-Match': etag, ...headers }), headersToExclude), - ...fetchOptions + ...fetchOptions, }); }; @@ -571,11 +571,11 @@ var collection = /*#__PURE__*/Object.freeze({ /* eslint-disable no-underscore-dangle */ const debug$3 = getLogger('tsdav:addressBook'); const addressBookQuery = async (params) => { - const { url, props, filters, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, filters, depth, headers, headersToExclude, fetchOptions = {} } = params; return collectionQuery({ url, body: { - 'addressbook-query': { + 'addressbook-query': cleanupFalsy({ _attributes: getDAVAttribute([exports.DAVNamespace.CARDDAV, exports.DAVNamespace.DAV]), [`${exports.DAVNamespaceShort.DAV}:prop`]: props, filter: filters !== null && filters !== void 0 ? filters : { @@ -585,24 +585,24 @@ const addressBookQuery = async (params) => { }, }, }, - }, + }), }, defaultNamespace: exports.DAVNamespaceShort.CARDDAV, depth, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); }; const addressBookMultiGet = async (params) => { - const { url, props, objectUrls, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, objectUrls, depth, headers, headersToExclude, fetchOptions = {} } = params; return collectionQuery({ url, body: { - 'addressbook-multiget': { + 'addressbook-multiget': cleanupFalsy({ _attributes: getDAVAttribute([exports.DAVNamespace.DAV, exports.DAVNamespace.CARDDAV]), [`${exports.DAVNamespaceShort.DAV}:prop`]: props, [`${exports.DAVNamespaceShort.DAV}:href`]: objectUrls, - }, + }), }, defaultNamespace: exports.DAVNamespaceShort.CARDDAV, depth, @@ -611,7 +611,7 @@ const addressBookMultiGet = async (params) => { }); }; const fetchAddressBooks = async (params) => { - const { account, headers, props: customProps, headersToExclude, fetchOptions = {} } = params !== null && params !== void 0 ? params : {}; + const { account, headers, props: customProps, headersToExclude, fetchOptions = {}, } = params !== null && params !== void 0 ? params : {}; const requiredFields = ['homeUrl', 'rootUrl']; if (!account || !hasFields(account, requiredFields)) { if (!account) { @@ -648,11 +648,15 @@ const fetchAddressBooks = async (params) => { }) .map(async (addr) => ({ ...addr, - reports: await supportedReportSet({ collection: addr, headers: excludeHeaders(headers, headersToExclude), fetchOptions }), + reports: await supportedReportSet({ + collection: addr, + headers: excludeHeaders(headers, headersToExclude), + fetchOptions, + }), }))); }; const fetchVCards = async (params) => { - const { addressBook, headers, objectUrls, headersToExclude, urlFilter = (url) => url, useMultiGet = true, fetchOptions = {} } = params; + const { addressBook, headers, objectUrls, headersToExclude, urlFilter = (url) => url, useMultiGet = true, fetchOptions = {}, } = params; debug$3(`Fetching vcards from ${addressBook === null || addressBook === void 0 ? void 0 : addressBook.url}`); const requiredFields = ['url']; if (!addressBook || !hasFields(addressBook, requiredFields)) { @@ -669,7 +673,7 @@ const fetchVCards = async (params) => { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, - })).map((res) => { var _a; return (res.ok ? (_a = res.href) !== null && _a !== void 0 ? _a : '' : ''); })) + })).map((res) => { var _a; return (res.ok ? ((_a = res.href) !== null && _a !== void 0 ? _a : '') : ''); })) .map((url) => (url.startsWith('http') || !url ? url : new URL(url, addressBook.url).href)) .filter(urlFilter) .map((url) => new URL(url).pathname); @@ -685,7 +689,7 @@ const fetchVCards = async (params) => { objectUrls: vcardUrls, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } else { @@ -697,7 +701,7 @@ const fetchVCards = async (params) => { }, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } } @@ -711,7 +715,7 @@ const fetchVCards = async (params) => { }); }; const createVCard = async (params) => { - const { addressBook, vCardString, filename, headers, headersToExclude, fetchOptions = {} } = params; + const { addressBook, vCardString, filename, headers, headersToExclude, fetchOptions = {}, } = params; return createObject({ url: new URL(filename, addressBook.url).href, data: vCardString, @@ -720,7 +724,7 @@ const createVCard = async (params) => { 'If-None-Match': '*', ...headers, }, headersToExclude), - fetchOptions + fetchOptions, }); }; const updateVCard = async (params) => { @@ -742,7 +746,7 @@ const deleteVCard = async (params) => { url: vCard.url, etag: vCard.etag, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); }; @@ -783,7 +787,7 @@ const fetchCalendarUserAddresses = async (params) => { return addresses; }; const calendarQuery = async (params) => { - const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {} } = params; + const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, } = params; return collectionQuery({ url, body: { @@ -806,17 +810,17 @@ const calendarQuery = async (params) => { }); }; const calendarMultiGet = async (params) => { - const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {} } = params; + const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, } = params; return collectionQuery({ url, body: { - 'calendar-multiget': { + 'calendar-multiget': cleanupFalsy({ _attributes: getDAVAttribute([exports.DAVNamespace.DAV, exports.DAVNamespace.CALDAV]), [`${exports.DAVNamespaceShort.DAV}:prop`]: props, [`${exports.DAVNamespaceShort.DAV}:href`]: objectUrls, - ...conditionalParam('filter', filters), + filter: filters, timezone, - }, + }), }, defaultNamespace: exports.DAVNamespaceShort.CALDAV, depth, @@ -845,11 +849,11 @@ const makeCalendar = async (params) => { }, }, }, - fetchOptions + fetchOptions, }); }; const fetchCalendars = async (params) => { - const { headers, account, props: customProps, projectedProps, headersToExclude, fetchOptions = {} } = params !== null && params !== void 0 ? params : {}; + const { headers, account, props: customProps, projectedProps, headersToExclude, fetchOptions = {}, } = params !== null && params !== void 0 ? params : {}; const requiredFields = ['homeUrl', 'rootUrl']; if (!account || !hasFields(account, requiredFields)) { if (!account) { @@ -989,7 +993,7 @@ const fetchCalendarObjects = async (params) => { filters, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, })).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)) // patch up to full url if url is not full .filter(urlFilter) // custom filter function on calendar objects @@ -1023,7 +1027,7 @@ const fetchCalendarObjects = async (params) => { filters, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } else { @@ -1053,7 +1057,7 @@ const fetchCalendarObjects = async (params) => { objectUrls: calendarObjectUrls, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } } @@ -1076,7 +1080,7 @@ const createCalendarObject = async (params) => { 'If-None-Match': '*', ...headers, }, headersToExclude), - fetchOptions + fetchOptions, }); }; const updateCalendarObject = async (params) => { @@ -1089,7 +1093,7 @@ const updateCalendarObject = async (params) => { 'content-type': 'text/calendar; charset=utf-8', ...headers, }, headersToExclude), - fetchOptions + fetchOptions, }); }; const deleteCalendarObject = async (params) => { @@ -1098,7 +1102,7 @@ const deleteCalendarObject = async (params) => { url: calendarObject.url, etag: calendarObject.etag, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); }; /** @@ -1106,7 +1110,7 @@ const deleteCalendarObject = async (params) => { */ const syncCalendars = async (params) => { var _a; - const { oldCalendars, account, detailedResult, headers, headersToExclude, fetchOptions = {} } = params; + const { oldCalendars, account, detailedResult, headers, headersToExclude, fetchOptions = {}, } = params; if (!account) { throw new Error('Must have account before syncCalendars'); } @@ -1114,7 +1118,7 @@ const syncCalendars = async (params) => { const remoteCalendars = await fetchCalendars({ account, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); // no existing url const created = remoteCalendars.filter((rc) => localCalendars.every((lc) => !urlContains(lc.url, rc.url))); @@ -1185,7 +1189,7 @@ const freeBusyQuery = async (params) => { defaultNamespace: exports.DAVNamespaceShort.CALDAV, depth, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); return result[0]; }; @@ -1214,7 +1218,7 @@ const serviceDiscovery = async (params) => { const uri = new URL(`/.well-known/${account.accountType}`, endpoint); uri.protocol = (_a = endpoint.protocol) !== null && _a !== void 0 ? _a : 'http'; try { - const response = await crossFetch.fetch(uri.href, { + const response = await fetch(uri.href, { headers: excludeHeaders(headers, headersToExclude), method: 'PROPFIND', redirect: 'manual', @@ -1396,7 +1400,7 @@ const fetchOauthTokens = async (credentials, fetchOptions) => { }); debug(credentials.tokenUrl); debug(param.toString()); - const response = await crossFetch.fetch(credentials.tokenUrl, { + const response = await fetch(credentials.tokenUrl, { method: 'POST', body: param.toString(), headers: { @@ -1428,7 +1432,7 @@ const refreshAccessToken = async (credentials, fetchOptions) => { refresh_token: credentials.refreshToken, grant_type: 'refresh_token', }); - const response = await crossFetch.fetch(credentials.tokenUrl, { + const response = await fetch(credentials.tokenUrl, { method: 'POST', body: param.toString(), headers: { diff --git a/dist/tsdav.d.ts b/dist/tsdav.d.ts index 0844e741..8ce428ac 100644 --- a/dist/tsdav.d.ts +++ b/dist/tsdav.d.ts @@ -105,6 +105,7 @@ type DAVCalendar = { components?: string[]; timezone?: string; projectedProps?: Record; + calendarColor?: string; } & DAVCollection; interface SmartCollectionSync { diff --git a/dist/tsdav.esm.js b/dist/tsdav.esm.js index b1af53ce..3f4ea415 100644 --- a/dist/tsdav.esm.js +++ b/dist/tsdav.esm.js @@ -1,4 +1,4 @@ -import { fetch } from 'cross-fetch'; +import 'cross-fetch/polyfill'; import getLogger from 'debug'; import convert from 'xml-js'; import { encode } from 'base-64'; @@ -293,7 +293,7 @@ const deleteObject = async (params) => { return fetch(url, { method: 'DELETE', headers: excludeHeaders(cleanupFalsy({ 'If-Match': etag, ...headers }), headersToExclude), - ...fetchOptions + ...fetchOptions, }); }; @@ -567,11 +567,11 @@ var collection = /*#__PURE__*/Object.freeze({ /* eslint-disable no-underscore-dangle */ const debug$3 = getLogger('tsdav:addressBook'); const addressBookQuery = async (params) => { - const { url, props, filters, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, filters, depth, headers, headersToExclude, fetchOptions = {} } = params; return collectionQuery({ url, body: { - 'addressbook-query': { + 'addressbook-query': cleanupFalsy({ _attributes: getDAVAttribute([DAVNamespace.CARDDAV, DAVNamespace.DAV]), [`${DAVNamespaceShort.DAV}:prop`]: props, filter: filters !== null && filters !== void 0 ? filters : { @@ -581,24 +581,24 @@ const addressBookQuery = async (params) => { }, }, }, - }, + }), }, defaultNamespace: DAVNamespaceShort.CARDDAV, depth, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); }; const addressBookMultiGet = async (params) => { - const { url, props, objectUrls, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, objectUrls, depth, headers, headersToExclude, fetchOptions = {} } = params; return collectionQuery({ url, body: { - 'addressbook-multiget': { + 'addressbook-multiget': cleanupFalsy({ _attributes: getDAVAttribute([DAVNamespace.DAV, DAVNamespace.CARDDAV]), [`${DAVNamespaceShort.DAV}:prop`]: props, [`${DAVNamespaceShort.DAV}:href`]: objectUrls, - }, + }), }, defaultNamespace: DAVNamespaceShort.CARDDAV, depth, @@ -607,7 +607,7 @@ const addressBookMultiGet = async (params) => { }); }; const fetchAddressBooks = async (params) => { - const { account, headers, props: customProps, headersToExclude, fetchOptions = {} } = params !== null && params !== void 0 ? params : {}; + const { account, headers, props: customProps, headersToExclude, fetchOptions = {}, } = params !== null && params !== void 0 ? params : {}; const requiredFields = ['homeUrl', 'rootUrl']; if (!account || !hasFields(account, requiredFields)) { if (!account) { @@ -644,11 +644,15 @@ const fetchAddressBooks = async (params) => { }) .map(async (addr) => ({ ...addr, - reports: await supportedReportSet({ collection: addr, headers: excludeHeaders(headers, headersToExclude), fetchOptions }), + reports: await supportedReportSet({ + collection: addr, + headers: excludeHeaders(headers, headersToExclude), + fetchOptions, + }), }))); }; const fetchVCards = async (params) => { - const { addressBook, headers, objectUrls, headersToExclude, urlFilter = (url) => url, useMultiGet = true, fetchOptions = {} } = params; + const { addressBook, headers, objectUrls, headersToExclude, urlFilter = (url) => url, useMultiGet = true, fetchOptions = {}, } = params; debug$3(`Fetching vcards from ${addressBook === null || addressBook === void 0 ? void 0 : addressBook.url}`); const requiredFields = ['url']; if (!addressBook || !hasFields(addressBook, requiredFields)) { @@ -665,7 +669,7 @@ const fetchVCards = async (params) => { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, - })).map((res) => { var _a; return (res.ok ? (_a = res.href) !== null && _a !== void 0 ? _a : '' : ''); })) + })).map((res) => { var _a; return (res.ok ? ((_a = res.href) !== null && _a !== void 0 ? _a : '') : ''); })) .map((url) => (url.startsWith('http') || !url ? url : new URL(url, addressBook.url).href)) .filter(urlFilter) .map((url) => new URL(url).pathname); @@ -681,7 +685,7 @@ const fetchVCards = async (params) => { objectUrls: vcardUrls, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } else { @@ -693,7 +697,7 @@ const fetchVCards = async (params) => { }, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } } @@ -707,7 +711,7 @@ const fetchVCards = async (params) => { }); }; const createVCard = async (params) => { - const { addressBook, vCardString, filename, headers, headersToExclude, fetchOptions = {} } = params; + const { addressBook, vCardString, filename, headers, headersToExclude, fetchOptions = {}, } = params; return createObject({ url: new URL(filename, addressBook.url).href, data: vCardString, @@ -716,7 +720,7 @@ const createVCard = async (params) => { 'If-None-Match': '*', ...headers, }, headersToExclude), - fetchOptions + fetchOptions, }); }; const updateVCard = async (params) => { @@ -738,7 +742,7 @@ const deleteVCard = async (params) => { url: vCard.url, etag: vCard.etag, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); }; @@ -779,7 +783,7 @@ const fetchCalendarUserAddresses = async (params) => { return addresses; }; const calendarQuery = async (params) => { - const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {} } = params; + const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, } = params; return collectionQuery({ url, body: { @@ -802,17 +806,17 @@ const calendarQuery = async (params) => { }); }; const calendarMultiGet = async (params) => { - const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {} } = params; + const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, } = params; return collectionQuery({ url, body: { - 'calendar-multiget': { + 'calendar-multiget': cleanupFalsy({ _attributes: getDAVAttribute([DAVNamespace.DAV, DAVNamespace.CALDAV]), [`${DAVNamespaceShort.DAV}:prop`]: props, [`${DAVNamespaceShort.DAV}:href`]: objectUrls, - ...conditionalParam('filter', filters), + filter: filters, timezone, - }, + }), }, defaultNamespace: DAVNamespaceShort.CALDAV, depth, @@ -841,11 +845,11 @@ const makeCalendar = async (params) => { }, }, }, - fetchOptions + fetchOptions, }); }; const fetchCalendars = async (params) => { - const { headers, account, props: customProps, projectedProps, headersToExclude, fetchOptions = {} } = params !== null && params !== void 0 ? params : {}; + const { headers, account, props: customProps, projectedProps, headersToExclude, fetchOptions = {}, } = params !== null && params !== void 0 ? params : {}; const requiredFields = ['homeUrl', 'rootUrl']; if (!account || !hasFields(account, requiredFields)) { if (!account) { @@ -985,7 +989,7 @@ const fetchCalendarObjects = async (params) => { filters, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, })).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)) // patch up to full url if url is not full .filter(urlFilter) // custom filter function on calendar objects @@ -1019,7 +1023,7 @@ const fetchCalendarObjects = async (params) => { filters, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } else { @@ -1049,7 +1053,7 @@ const fetchCalendarObjects = async (params) => { objectUrls: calendarObjectUrls, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } } @@ -1072,7 +1076,7 @@ const createCalendarObject = async (params) => { 'If-None-Match': '*', ...headers, }, headersToExclude), - fetchOptions + fetchOptions, }); }; const updateCalendarObject = async (params) => { @@ -1085,7 +1089,7 @@ const updateCalendarObject = async (params) => { 'content-type': 'text/calendar; charset=utf-8', ...headers, }, headersToExclude), - fetchOptions + fetchOptions, }); }; const deleteCalendarObject = async (params) => { @@ -1094,7 +1098,7 @@ const deleteCalendarObject = async (params) => { url: calendarObject.url, etag: calendarObject.etag, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); }; /** @@ -1102,7 +1106,7 @@ const deleteCalendarObject = async (params) => { */ const syncCalendars = async (params) => { var _a; - const { oldCalendars, account, detailedResult, headers, headersToExclude, fetchOptions = {} } = params; + const { oldCalendars, account, detailedResult, headers, headersToExclude, fetchOptions = {}, } = params; if (!account) { throw new Error('Must have account before syncCalendars'); } @@ -1110,7 +1114,7 @@ const syncCalendars = async (params) => { const remoteCalendars = await fetchCalendars({ account, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); // no existing url const created = remoteCalendars.filter((rc) => localCalendars.every((lc) => !urlContains(lc.url, rc.url))); @@ -1181,7 +1185,7 @@ const freeBusyQuery = async (params) => { defaultNamespace: DAVNamespaceShort.CALDAV, depth, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); return result[0]; }; diff --git a/dist/tsdav.js b/dist/tsdav.js index f1c4c380..5baca37f 100644 --- a/dist/tsdav.js +++ b/dist/tsdav.js @@ -29,659 +29,625 @@ function getAugmentedNamespace(n) { return a; } -var browserPonyfill = {exports: {}}; +(function(self) { + +((function (exports) { + + var global = + (typeof globalThis !== 'undefined' && globalThis) || + (typeof self !== 'undefined' && self) || + (typeof global !== 'undefined' && global); + + var support = { + searchParams: 'URLSearchParams' in global, + iterable: 'Symbol' in global && 'iterator' in Symbol, + blob: + 'FileReader' in global && + 'Blob' in global && + (function() { + try { + new Blob(); + return true + } catch (e) { + return false + } + })(), + formData: 'FormData' in global, + arrayBuffer: 'ArrayBuffer' in global + }; -(function (module, exports) { - // Save global object in a variable - var __global__ = - (typeof globalThis !== 'undefined' && globalThis) || - (typeof self !== 'undefined' && self) || - (typeof commonjsGlobal !== 'undefined' && commonjsGlobal); - // Create an object that extends from __global__ without the fetch function - var __globalThis__ = (function () { - function F() { - this.fetch = false; - this.DOMException = __global__.DOMException; - } - F.prototype = __global__; // Needed for feature detection on whatwg-fetch's code - return new F(); - })(); - // Wraps whatwg-fetch with a function scope to hijack the global object - // "globalThis" that's going to be patched - (function(globalThis) { - - ((function (exports) { - - var global = - (typeof globalThis !== 'undefined' && globalThis) || - (typeof self !== 'undefined' && self) || - (typeof global !== 'undefined' && global); - - var support = { - searchParams: 'URLSearchParams' in global, - iterable: 'Symbol' in global && 'iterator' in Symbol, - blob: - 'FileReader' in global && - 'Blob' in global && - (function() { - try { - new Blob(); - return true - } catch (e) { - return false - } - })(), - formData: 'FormData' in global, - arrayBuffer: 'ArrayBuffer' in global - }; + function isDataView(obj) { + return obj && DataView.prototype.isPrototypeOf(obj) + } + + if (support.arrayBuffer) { + var viewClasses = [ + '[object Int8Array]', + '[object Uint8Array]', + '[object Uint8ClampedArray]', + '[object Int16Array]', + '[object Uint16Array]', + '[object Int32Array]', + '[object Uint32Array]', + '[object Float32Array]', + '[object Float64Array]' + ]; - function isDataView(obj) { - return obj && DataView.prototype.isPrototypeOf(obj) - } + var isArrayBufferView = + ArrayBuffer.isView || + function(obj) { + return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1 + }; + } - if (support.arrayBuffer) { - var viewClasses = [ - '[object Int8Array]', - '[object Uint8Array]', - '[object Uint8ClampedArray]', - '[object Int16Array]', - '[object Uint16Array]', - '[object Int32Array]', - '[object Uint32Array]', - '[object Float32Array]', - '[object Float64Array]' - ]; - - var isArrayBufferView = - ArrayBuffer.isView || - function(obj) { - return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1 - }; - } + function normalizeName(name) { + if (typeof name !== 'string') { + name = String(name); + } + if (/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name) || name === '') { + throw new TypeError('Invalid character in header field name: "' + name + '"') + } + return name.toLowerCase() + } - function normalizeName(name) { - if (typeof name !== 'string') { - name = String(name); - } - if (/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name) || name === '') { - throw new TypeError('Invalid character in header field name: "' + name + '"') - } - return name.toLowerCase() - } + function normalizeValue(value) { + if (typeof value !== 'string') { + value = String(value); + } + return value + } - function normalizeValue(value) { - if (typeof value !== 'string') { - value = String(value); - } - return value - } + // Build a destructive iterator for the value list + function iteratorFor(items) { + var iterator = { + next: function() { + var value = items.shift(); + return {done: value === undefined, value: value} + } + }; - // Build a destructive iterator for the value list - function iteratorFor(items) { - var iterator = { - next: function() { - var value = items.shift(); - return {done: value === undefined, value: value} - } - }; + if (support.iterable) { + iterator[Symbol.iterator] = function() { + return iterator + }; + } - if (support.iterable) { - iterator[Symbol.iterator] = function() { - return iterator - }; - } + return iterator + } - return iterator - } + function Headers(headers) { + this.map = {}; - function Headers(headers) { - this.map = {}; - - if (headers instanceof Headers) { - headers.forEach(function(value, name) { - this.append(name, value); - }, this); - } else if (Array.isArray(headers)) { - headers.forEach(function(header) { - this.append(header[0], header[1]); - }, this); - } else if (headers) { - Object.getOwnPropertyNames(headers).forEach(function(name) { - this.append(name, headers[name]); - }, this); - } - } + if (headers instanceof Headers) { + headers.forEach(function(value, name) { + this.append(name, value); + }, this); + } else if (Array.isArray(headers)) { + headers.forEach(function(header) { + this.append(header[0], header[1]); + }, this); + } else if (headers) { + Object.getOwnPropertyNames(headers).forEach(function(name) { + this.append(name, headers[name]); + }, this); + } + } - Headers.prototype.append = function(name, value) { - name = normalizeName(name); - value = normalizeValue(value); - var oldValue = this.map[name]; - this.map[name] = oldValue ? oldValue + ', ' + value : value; - }; + Headers.prototype.append = function(name, value) { + name = normalizeName(name); + value = normalizeValue(value); + var oldValue = this.map[name]; + this.map[name] = oldValue ? oldValue + ', ' + value : value; + }; - Headers.prototype['delete'] = function(name) { - delete this.map[normalizeName(name)]; - }; + Headers.prototype['delete'] = function(name) { + delete this.map[normalizeName(name)]; + }; - Headers.prototype.get = function(name) { - name = normalizeName(name); - return this.has(name) ? this.map[name] : null - }; + Headers.prototype.get = function(name) { + name = normalizeName(name); + return this.has(name) ? this.map[name] : null + }; - Headers.prototype.has = function(name) { - return this.map.hasOwnProperty(normalizeName(name)) - }; + Headers.prototype.has = function(name) { + return this.map.hasOwnProperty(normalizeName(name)) + }; - Headers.prototype.set = function(name, value) { - this.map[normalizeName(name)] = normalizeValue(value); - }; + Headers.prototype.set = function(name, value) { + this.map[normalizeName(name)] = normalizeValue(value); + }; - Headers.prototype.forEach = function(callback, thisArg) { - for (var name in this.map) { - if (this.map.hasOwnProperty(name)) { - callback.call(thisArg, this.map[name], name, this); - } - } - }; + Headers.prototype.forEach = function(callback, thisArg) { + for (var name in this.map) { + if (this.map.hasOwnProperty(name)) { + callback.call(thisArg, this.map[name], name, this); + } + } + }; - Headers.prototype.keys = function() { - var items = []; - this.forEach(function(value, name) { - items.push(name); - }); - return iteratorFor(items) - }; + Headers.prototype.keys = function() { + var items = []; + this.forEach(function(value, name) { + items.push(name); + }); + return iteratorFor(items) + }; - Headers.prototype.values = function() { - var items = []; - this.forEach(function(value) { - items.push(value); - }); - return iteratorFor(items) - }; + Headers.prototype.values = function() { + var items = []; + this.forEach(function(value) { + items.push(value); + }); + return iteratorFor(items) + }; - Headers.prototype.entries = function() { - var items = []; - this.forEach(function(value, name) { - items.push([name, value]); - }); - return iteratorFor(items) - }; + Headers.prototype.entries = function() { + var items = []; + this.forEach(function(value, name) { + items.push([name, value]); + }); + return iteratorFor(items) + }; - if (support.iterable) { - Headers.prototype[Symbol.iterator] = Headers.prototype.entries; - } + if (support.iterable) { + Headers.prototype[Symbol.iterator] = Headers.prototype.entries; + } - function consumed(body) { - if (body.bodyUsed) { - return Promise.reject(new TypeError('Already read')) - } - body.bodyUsed = true; - } + function consumed(body) { + if (body.bodyUsed) { + return Promise.reject(new TypeError('Already read')) + } + body.bodyUsed = true; + } - function fileReaderReady(reader) { - return new Promise(function(resolve, reject) { - reader.onload = function() { - resolve(reader.result); - }; - reader.onerror = function() { - reject(reader.error); - }; - }) - } + function fileReaderReady(reader) { + return new Promise(function(resolve, reject) { + reader.onload = function() { + resolve(reader.result); + }; + reader.onerror = function() { + reject(reader.error); + }; + }) + } - function readBlobAsArrayBuffer(blob) { - var reader = new FileReader(); - var promise = fileReaderReady(reader); - reader.readAsArrayBuffer(blob); - return promise - } + function readBlobAsArrayBuffer(blob) { + var reader = new FileReader(); + var promise = fileReaderReady(reader); + reader.readAsArrayBuffer(blob); + return promise + } - function readBlobAsText(blob) { - var reader = new FileReader(); - var promise = fileReaderReady(reader); - reader.readAsText(blob); - return promise - } + function readBlobAsText(blob) { + var reader = new FileReader(); + var promise = fileReaderReady(reader); + reader.readAsText(blob); + return promise + } - function readArrayBufferAsText(buf) { - var view = new Uint8Array(buf); - var chars = new Array(view.length); + function readArrayBufferAsText(buf) { + var view = new Uint8Array(buf); + var chars = new Array(view.length); - for (var i = 0; i < view.length; i++) { - chars[i] = String.fromCharCode(view[i]); - } - return chars.join('') - } + for (var i = 0; i < view.length; i++) { + chars[i] = String.fromCharCode(view[i]); + } + return chars.join('') + } - function bufferClone(buf) { - if (buf.slice) { - return buf.slice(0) - } else { - var view = new Uint8Array(buf.byteLength); - view.set(new Uint8Array(buf)); - return view.buffer - } - } + function bufferClone(buf) { + if (buf.slice) { + return buf.slice(0) + } else { + var view = new Uint8Array(buf.byteLength); + view.set(new Uint8Array(buf)); + return view.buffer + } + } + + function Body() { + this.bodyUsed = false; + + this._initBody = function(body) { + /* + fetch-mock wraps the Response object in an ES6 Proxy to + provide useful test harness features such as flush. However, on + ES5 browsers without fetch or Proxy support pollyfills must be used; + the proxy-pollyfill is unable to proxy an attribute unless it exists + on the object before the Proxy is created. This change ensures + Response.bodyUsed exists on the instance, while maintaining the + semantic of setting Request.bodyUsed in the constructor before + _initBody is called. + */ + this.bodyUsed = this.bodyUsed; + this._bodyInit = body; + if (!body) { + this._bodyText = ''; + } else if (typeof body === 'string') { + this._bodyText = body; + } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { + this._bodyBlob = body; + } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { + this._bodyFormData = body; + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this._bodyText = body.toString(); + } else if (support.arrayBuffer && support.blob && isDataView(body)) { + this._bodyArrayBuffer = bufferClone(body.buffer); + // IE 10-11 can't handle a DataView body. + this._bodyInit = new Blob([this._bodyArrayBuffer]); + } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) { + this._bodyArrayBuffer = bufferClone(body); + } else { + this._bodyText = body = Object.prototype.toString.call(body); + } - function Body() { - this.bodyUsed = false; - - this._initBody = function(body) { - /* - fetch-mock wraps the Response object in an ES6 Proxy to - provide useful test harness features such as flush. However, on - ES5 browsers without fetch or Proxy support pollyfills must be used; - the proxy-pollyfill is unable to proxy an attribute unless it exists - on the object before the Proxy is created. This change ensures - Response.bodyUsed exists on the instance, while maintaining the - semantic of setting Request.bodyUsed in the constructor before - _initBody is called. - */ - this.bodyUsed = this.bodyUsed; - this._bodyInit = body; - if (!body) { - this._bodyText = ''; - } else if (typeof body === 'string') { - this._bodyText = body; - } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { - this._bodyBlob = body; - } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { - this._bodyFormData = body; - } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { - this._bodyText = body.toString(); - } else if (support.arrayBuffer && support.blob && isDataView(body)) { - this._bodyArrayBuffer = bufferClone(body.buffer); - // IE 10-11 can't handle a DataView body. - this._bodyInit = new Blob([this._bodyArrayBuffer]); - } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) { - this._bodyArrayBuffer = bufferClone(body); - } else { - this._bodyText = body = Object.prototype.toString.call(body); - } + if (!this.headers.get('content-type')) { + if (typeof body === 'string') { + this.headers.set('content-type', 'text/plain;charset=UTF-8'); + } else if (this._bodyBlob && this._bodyBlob.type) { + this.headers.set('content-type', this._bodyBlob.type); + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); + } + } + }; - if (!this.headers.get('content-type')) { - if (typeof body === 'string') { - this.headers.set('content-type', 'text/plain;charset=UTF-8'); - } else if (this._bodyBlob && this._bodyBlob.type) { - this.headers.set('content-type', this._bodyBlob.type); - } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { - this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); - } - } - }; + if (support.blob) { + this.blob = function() { + var rejected = consumed(this); + if (rejected) { + return rejected + } - if (support.blob) { - this.blob = function() { - var rejected = consumed(this); - if (rejected) { - return rejected - } + if (this._bodyBlob) { + return Promise.resolve(this._bodyBlob) + } else if (this._bodyArrayBuffer) { + return Promise.resolve(new Blob([this._bodyArrayBuffer])) + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as blob') + } else { + return Promise.resolve(new Blob([this._bodyText])) + } + }; - if (this._bodyBlob) { - return Promise.resolve(this._bodyBlob) - } else if (this._bodyArrayBuffer) { - return Promise.resolve(new Blob([this._bodyArrayBuffer])) - } else if (this._bodyFormData) { - throw new Error('could not read FormData body as blob') - } else { - return Promise.resolve(new Blob([this._bodyText])) - } - }; + this.arrayBuffer = function() { + if (this._bodyArrayBuffer) { + var isConsumed = consumed(this); + if (isConsumed) { + return isConsumed + } + if (ArrayBuffer.isView(this._bodyArrayBuffer)) { + return Promise.resolve( + this._bodyArrayBuffer.buffer.slice( + this._bodyArrayBuffer.byteOffset, + this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength + ) + ) + } else { + return Promise.resolve(this._bodyArrayBuffer) + } + } else { + return this.blob().then(readBlobAsArrayBuffer) + } + }; + } - this.arrayBuffer = function() { - if (this._bodyArrayBuffer) { - var isConsumed = consumed(this); - if (isConsumed) { - return isConsumed - } - if (ArrayBuffer.isView(this._bodyArrayBuffer)) { - return Promise.resolve( - this._bodyArrayBuffer.buffer.slice( - this._bodyArrayBuffer.byteOffset, - this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength - ) - ) - } else { - return Promise.resolve(this._bodyArrayBuffer) - } - } else { - return this.blob().then(readBlobAsArrayBuffer) - } - }; - } + this.text = function() { + var rejected = consumed(this); + if (rejected) { + return rejected + } - this.text = function() { - var rejected = consumed(this); - if (rejected) { - return rejected - } + if (this._bodyBlob) { + return readBlobAsText(this._bodyBlob) + } else if (this._bodyArrayBuffer) { + return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)) + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as text') + } else { + return Promise.resolve(this._bodyText) + } + }; - if (this._bodyBlob) { - return readBlobAsText(this._bodyBlob) - } else if (this._bodyArrayBuffer) { - return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)) - } else if (this._bodyFormData) { - throw new Error('could not read FormData body as text') - } else { - return Promise.resolve(this._bodyText) - } - }; + if (support.formData) { + this.formData = function() { + return this.text().then(decode) + }; + } - if (support.formData) { - this.formData = function() { - return this.text().then(decode) - }; - } + this.json = function() { + return this.text().then(JSON.parse) + }; - this.json = function() { - return this.text().then(JSON.parse) - }; + return this + } - return this - } + // HTTP methods whose capitalization should be normalized + var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']; - // HTTP methods whose capitalization should be normalized - var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']; + function normalizeMethod(method) { + var upcased = method.toUpperCase(); + return methods.indexOf(upcased) > -1 ? upcased : method + } - function normalizeMethod(method) { - var upcased = method.toUpperCase(); - return methods.indexOf(upcased) > -1 ? upcased : method - } + function Request(input, options) { + if (!(this instanceof Request)) { + throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.') + } - function Request(input, options) { - if (!(this instanceof Request)) { - throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.') - } + options = options || {}; + var body = options.body; - options = options || {}; - var body = options.body; + if (input instanceof Request) { + if (input.bodyUsed) { + throw new TypeError('Already read') + } + this.url = input.url; + this.credentials = input.credentials; + if (!options.headers) { + this.headers = new Headers(input.headers); + } + this.method = input.method; + this.mode = input.mode; + this.signal = input.signal; + if (!body && input._bodyInit != null) { + body = input._bodyInit; + input.bodyUsed = true; + } + } else { + this.url = String(input); + } - if (input instanceof Request) { - if (input.bodyUsed) { - throw new TypeError('Already read') - } - this.url = input.url; - this.credentials = input.credentials; - if (!options.headers) { - this.headers = new Headers(input.headers); - } - this.method = input.method; - this.mode = input.mode; - this.signal = input.signal; - if (!body && input._bodyInit != null) { - body = input._bodyInit; - input.bodyUsed = true; - } - } else { - this.url = String(input); - } + this.credentials = options.credentials || this.credentials || 'same-origin'; + if (options.headers || !this.headers) { + this.headers = new Headers(options.headers); + } + this.method = normalizeMethod(options.method || this.method || 'GET'); + this.mode = options.mode || this.mode || null; + this.signal = options.signal || this.signal; + this.referrer = null; - this.credentials = options.credentials || this.credentials || 'same-origin'; - if (options.headers || !this.headers) { - this.headers = new Headers(options.headers); - } - this.method = normalizeMethod(options.method || this.method || 'GET'); - this.mode = options.mode || this.mode || null; - this.signal = options.signal || this.signal; - this.referrer = null; + if ((this.method === 'GET' || this.method === 'HEAD') && body) { + throw new TypeError('Body not allowed for GET or HEAD requests') + } + this._initBody(body); - if ((this.method === 'GET' || this.method === 'HEAD') && body) { - throw new TypeError('Body not allowed for GET or HEAD requests') - } - this._initBody(body); - - if (this.method === 'GET' || this.method === 'HEAD') { - if (options.cache === 'no-store' || options.cache === 'no-cache') { - // Search for a '_' parameter in the query string - var reParamSearch = /([?&])_=[^&]*/; - if (reParamSearch.test(this.url)) { - // If it already exists then set the value with the current time - this.url = this.url.replace(reParamSearch, '$1_=' + new Date().getTime()); - } else { - // Otherwise add a new '_' parameter to the end with the current time - var reQueryString = /\?/; - this.url += (reQueryString.test(this.url) ? '&' : '?') + '_=' + new Date().getTime(); - } - } - } - } + if (this.method === 'GET' || this.method === 'HEAD') { + if (options.cache === 'no-store' || options.cache === 'no-cache') { + // Search for a '_' parameter in the query string + var reParamSearch = /([?&])_=[^&]*/; + if (reParamSearch.test(this.url)) { + // If it already exists then set the value with the current time + this.url = this.url.replace(reParamSearch, '$1_=' + new Date().getTime()); + } else { + // Otherwise add a new '_' parameter to the end with the current time + var reQueryString = /\?/; + this.url += (reQueryString.test(this.url) ? '&' : '?') + '_=' + new Date().getTime(); + } + } + } + } - Request.prototype.clone = function() { - return new Request(this, {body: this._bodyInit}) - }; + Request.prototype.clone = function() { + return new Request(this, {body: this._bodyInit}) + }; - function decode(body) { - var form = new FormData(); - body - .trim() - .split('&') - .forEach(function(bytes) { - if (bytes) { - var split = bytes.split('='); - var name = split.shift().replace(/\+/g, ' '); - var value = split.join('=').replace(/\+/g, ' '); - form.append(decodeURIComponent(name), decodeURIComponent(value)); - } - }); - return form - } + function decode(body) { + var form = new FormData(); + body + .trim() + .split('&') + .forEach(function(bytes) { + if (bytes) { + var split = bytes.split('='); + var name = split.shift().replace(/\+/g, ' '); + var value = split.join('=').replace(/\+/g, ' '); + form.append(decodeURIComponent(name), decodeURIComponent(value)); + } + }); + return form + } + + function parseHeaders(rawHeaders) { + var headers = new Headers(); + // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space + // https://tools.ietf.org/html/rfc7230#section-3.2 + var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' '); + // Avoiding split via regex to work around a common IE11 bug with the core-js 3.6.0 regex polyfill + // https://github.com/github/fetch/issues/748 + // https://github.com/zloirock/core-js/issues/751 + preProcessedHeaders + .split('\r') + .map(function(header) { + return header.indexOf('\n') === 0 ? header.substr(1, header.length) : header + }) + .forEach(function(line) { + var parts = line.split(':'); + var key = parts.shift().trim(); + if (key) { + var value = parts.join(':').trim(); + headers.append(key, value); + } + }); + return headers + } - function parseHeaders(rawHeaders) { - var headers = new Headers(); - // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space - // https://tools.ietf.org/html/rfc7230#section-3.2 - var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' '); - // Avoiding split via regex to work around a common IE11 bug with the core-js 3.6.0 regex polyfill - // https://github.com/github/fetch/issues/748 - // https://github.com/zloirock/core-js/issues/751 - preProcessedHeaders - .split('\r') - .map(function(header) { - return header.indexOf('\n') === 0 ? header.substr(1, header.length) : header - }) - .forEach(function(line) { - var parts = line.split(':'); - var key = parts.shift().trim(); - if (key) { - var value = parts.join(':').trim(); - headers.append(key, value); - } - }); - return headers - } + Body.call(Request.prototype); - Body.call(Request.prototype); + function Response(bodyInit, options) { + if (!(this instanceof Response)) { + throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.') + } + if (!options) { + options = {}; + } - function Response(bodyInit, options) { - if (!(this instanceof Response)) { - throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.') - } - if (!options) { - options = {}; - } + this.type = 'default'; + this.status = options.status === undefined ? 200 : options.status; + this.ok = this.status >= 200 && this.status < 300; + this.statusText = options.statusText === undefined ? '' : '' + options.statusText; + this.headers = new Headers(options.headers); + this.url = options.url || ''; + this._initBody(bodyInit); + } - this.type = 'default'; - this.status = options.status === undefined ? 200 : options.status; - this.ok = this.status >= 200 && this.status < 300; - this.statusText = options.statusText === undefined ? '' : '' + options.statusText; - this.headers = new Headers(options.headers); - this.url = options.url || ''; - this._initBody(bodyInit); - } + Body.call(Response.prototype); - Body.call(Response.prototype); + Response.prototype.clone = function() { + return new Response(this._bodyInit, { + status: this.status, + statusText: this.statusText, + headers: new Headers(this.headers), + url: this.url + }) + }; - Response.prototype.clone = function() { - return new Response(this._bodyInit, { - status: this.status, - statusText: this.statusText, - headers: new Headers(this.headers), - url: this.url - }) - }; + Response.error = function() { + var response = new Response(null, {status: 0, statusText: ''}); + response.type = 'error'; + return response + }; - Response.error = function() { - var response = new Response(null, {status: 0, statusText: ''}); - response.type = 'error'; - return response - }; + var redirectStatuses = [301, 302, 303, 307, 308]; - var redirectStatuses = [301, 302, 303, 307, 308]; + Response.redirect = function(url, status) { + if (redirectStatuses.indexOf(status) === -1) { + throw new RangeError('Invalid status code') + } - Response.redirect = function(url, status) { - if (redirectStatuses.indexOf(status) === -1) { - throw new RangeError('Invalid status code') - } + return new Response(null, {status: status, headers: {location: url}}) + }; - return new Response(null, {status: status, headers: {location: url}}) - }; + exports.DOMException = global.DOMException; + try { + new exports.DOMException(); + } catch (err) { + exports.DOMException = function(message, name) { + this.message = message; + this.name = name; + var error = Error(message); + this.stack = error.stack; + }; + exports.DOMException.prototype = Object.create(Error.prototype); + exports.DOMException.prototype.constructor = exports.DOMException; + } - exports.DOMException = global.DOMException; - try { - new exports.DOMException(); - } catch (err) { - exports.DOMException = function(message, name) { - this.message = message; - this.name = name; - var error = Error(message); - this.stack = error.stack; - }; - exports.DOMException.prototype = Object.create(Error.prototype); - exports.DOMException.prototype.constructor = exports.DOMException; - } + function fetch(input, init) { + return new Promise(function(resolve, reject) { + var request = new Request(input, init); - function fetch(input, init) { - return new Promise(function(resolve, reject) { - var request = new Request(input, init); + if (request.signal && request.signal.aborted) { + return reject(new exports.DOMException('Aborted', 'AbortError')) + } - if (request.signal && request.signal.aborted) { - return reject(new exports.DOMException('Aborted', 'AbortError')) - } + var xhr = new XMLHttpRequest(); - var xhr = new XMLHttpRequest(); + function abortXhr() { + xhr.abort(); + } - function abortXhr() { - xhr.abort(); - } + xhr.onload = function() { + var options = { + status: xhr.status, + statusText: xhr.statusText, + headers: parseHeaders(xhr.getAllResponseHeaders() || '') + }; + options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL'); + var body = 'response' in xhr ? xhr.response : xhr.responseText; + setTimeout(function() { + resolve(new Response(body, options)); + }, 0); + }; - xhr.onload = function() { - var options = { - status: xhr.status, - statusText: xhr.statusText, - headers: parseHeaders(xhr.getAllResponseHeaders() || '') - }; - options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL'); - var body = 'response' in xhr ? xhr.response : xhr.responseText; - setTimeout(function() { - resolve(new Response(body, options)); - }, 0); - }; + xhr.onerror = function() { + setTimeout(function() { + reject(new TypeError('Network request failed')); + }, 0); + }; - xhr.onerror = function() { - setTimeout(function() { - reject(new TypeError('Network request failed')); - }, 0); - }; + xhr.ontimeout = function() { + setTimeout(function() { + reject(new TypeError('Network request failed')); + }, 0); + }; - xhr.ontimeout = function() { - setTimeout(function() { - reject(new TypeError('Network request failed')); - }, 0); - }; + xhr.onabort = function() { + setTimeout(function() { + reject(new exports.DOMException('Aborted', 'AbortError')); + }, 0); + }; - xhr.onabort = function() { - setTimeout(function() { - reject(new exports.DOMException('Aborted', 'AbortError')); - }, 0); - }; + function fixUrl(url) { + try { + return url === '' && global.location.href ? global.location.href : url + } catch (e) { + return url + } + } - function fixUrl(url) { - try { - return url === '' && global.location.href ? global.location.href : url - } catch (e) { - return url - } - } + xhr.open(request.method, fixUrl(request.url), true); - xhr.open(request.method, fixUrl(request.url), true); + if (request.credentials === 'include') { + xhr.withCredentials = true; + } else if (request.credentials === 'omit') { + xhr.withCredentials = false; + } - if (request.credentials === 'include') { - xhr.withCredentials = true; - } else if (request.credentials === 'omit') { - xhr.withCredentials = false; - } + if ('responseType' in xhr) { + if (support.blob) { + xhr.responseType = 'blob'; + } else if ( + support.arrayBuffer && + request.headers.get('Content-Type') && + request.headers.get('Content-Type').indexOf('application/octet-stream') !== -1 + ) { + xhr.responseType = 'arraybuffer'; + } + } - if ('responseType' in xhr) { - if (support.blob) { - xhr.responseType = 'blob'; - } else if ( - support.arrayBuffer && - request.headers.get('Content-Type') && - request.headers.get('Content-Type').indexOf('application/octet-stream') !== -1 - ) { - xhr.responseType = 'arraybuffer'; - } - } + if (init && typeof init.headers === 'object' && !(init.headers instanceof Headers)) { + Object.getOwnPropertyNames(init.headers).forEach(function(name) { + xhr.setRequestHeader(name, normalizeValue(init.headers[name])); + }); + } else { + request.headers.forEach(function(value, name) { + xhr.setRequestHeader(name, value); + }); + } - if (init && typeof init.headers === 'object' && !(init.headers instanceof Headers)) { - Object.getOwnPropertyNames(init.headers).forEach(function(name) { - xhr.setRequestHeader(name, normalizeValue(init.headers[name])); - }); - } else { - request.headers.forEach(function(value, name) { - xhr.setRequestHeader(name, value); - }); - } + if (request.signal) { + request.signal.addEventListener('abort', abortXhr); - if (request.signal) { - request.signal.addEventListener('abort', abortXhr); + xhr.onreadystatechange = function() { + // DONE (success or failure) + if (xhr.readyState === 4) { + request.signal.removeEventListener('abort', abortXhr); + } + }; + } - xhr.onreadystatechange = function() { - // DONE (success or failure) - if (xhr.readyState === 4) { - request.signal.removeEventListener('abort', abortXhr); - } - }; - } + xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit); + }) + } - xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit); - }) - } + fetch.polyfill = true; - fetch.polyfill = true; + if (!global.fetch) { + global.fetch = fetch; + global.Headers = Headers; + global.Request = Request; + global.Response = Response; + } - if (!global.fetch) { - global.fetch = fetch; - global.Headers = Headers; - global.Request = Request; - global.Response = Response; - } + exports.Headers = Headers; + exports.Request = Request; + exports.Response = Response; + exports.fetch = fetch; - exports.Headers = Headers; - exports.Request = Request; - exports.Response = Response; - exports.fetch = fetch; - - return exports; - - }))({}); - })(__globalThis__); - // This is a ponyfill, so... - __globalThis__.fetch.ponyfill = true; - delete __globalThis__.fetch.polyfill; - // Choose between native implementation (__global__) or custom implementation (__globalThis__) - var ctx = __global__.fetch ? __global__ : __globalThis__; - exports = ctx.fetch; // To enable: import fetch from 'cross-fetch' - exports.default = ctx.fetch; // For TypeScript consumers without esModuleInterop. - exports.fetch = ctx.fetch; // To enable: import {fetch} from 'cross-fetch' - exports.Headers = ctx.Headers; - exports.Request = ctx.Request; - exports.Response = ctx.Response; - module.exports = exports; -} (browserPonyfill, browserPonyfill.exports)); - -var browserPonyfillExports = browserPonyfill.exports; + return exports; + +}))({}); +})(typeof self !== 'undefined' ? self : commonjsGlobal); var global$1 = (typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : @@ -9096,7 +9062,7 @@ const davRequest = async (params) => { // )}` // ); // debug(xmlBody); - const davResponse = await browserPonyfillExports.fetch(url, { + const davResponse = await fetch(url, { headers: { 'Content-Type': 'text/xml;charset=UTF-8', ...cleanupFalsy(headers), @@ -9217,7 +9183,7 @@ const propfind = async (params) => { }; const createObject = async (params) => { const { url, data, headers, headersToExclude, fetchOptions = {} } = params; - return browserPonyfillExports.fetch(url, { + return fetch(url, { method: 'PUT', body: data, headers: excludeHeaders(headers, headersToExclude), @@ -9226,7 +9192,7 @@ const createObject = async (params) => { }; const updateObject = async (params) => { const { url, data, etag, headers, headersToExclude, fetchOptions = {} } = params; - return browserPonyfillExports.fetch(url, { + return fetch(url, { method: 'PUT', body: data, headers: excludeHeaders(cleanupFalsy({ 'If-Match': etag, ...headers }), headersToExclude), @@ -9235,10 +9201,10 @@ const updateObject = async (params) => { }; const deleteObject = async (params) => { const { url, headers, etag, headersToExclude, fetchOptions = {} } = params; - return browserPonyfillExports.fetch(url, { + return fetch(url, { method: 'DELETE', headers: excludeHeaders(cleanupFalsy({ 'If-Match': etag, ...headers }), headersToExclude), - ...fetchOptions + ...fetchOptions, }); }; @@ -9512,11 +9478,11 @@ var collection = /*#__PURE__*/Object.freeze({ /* eslint-disable no-underscore-dangle */ const debug$3 = getLogger('tsdav:addressBook'); const addressBookQuery = async (params) => { - const { url, props, filters, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, filters, depth, headers, headersToExclude, fetchOptions = {} } = params; return collectionQuery({ url, body: { - 'addressbook-query': { + 'addressbook-query': cleanupFalsy({ _attributes: getDAVAttribute([DAVNamespace.CARDDAV, DAVNamespace.DAV]), [`${DAVNamespaceShort.DAV}:prop`]: props, filter: filters !== null && filters !== void 0 ? filters : { @@ -9526,24 +9492,24 @@ const addressBookQuery = async (params) => { }, }, }, - }, + }), }, defaultNamespace: DAVNamespaceShort.CARDDAV, depth, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); }; const addressBookMultiGet = async (params) => { - const { url, props, objectUrls, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, objectUrls, depth, headers, headersToExclude, fetchOptions = {} } = params; return collectionQuery({ url, body: { - 'addressbook-multiget': { + 'addressbook-multiget': cleanupFalsy({ _attributes: getDAVAttribute([DAVNamespace.DAV, DAVNamespace.CARDDAV]), [`${DAVNamespaceShort.DAV}:prop`]: props, [`${DAVNamespaceShort.DAV}:href`]: objectUrls, - }, + }), }, defaultNamespace: DAVNamespaceShort.CARDDAV, depth, @@ -9552,7 +9518,7 @@ const addressBookMultiGet = async (params) => { }); }; const fetchAddressBooks = async (params) => { - const { account, headers, props: customProps, headersToExclude, fetchOptions = {} } = params !== null && params !== void 0 ? params : {}; + const { account, headers, props: customProps, headersToExclude, fetchOptions = {}, } = params !== null && params !== void 0 ? params : {}; const requiredFields = ['homeUrl', 'rootUrl']; if (!account || !hasFields(account, requiredFields)) { if (!account) { @@ -9589,11 +9555,15 @@ const fetchAddressBooks = async (params) => { }) .map(async (addr) => ({ ...addr, - reports: await supportedReportSet({ collection: addr, headers: excludeHeaders(headers, headersToExclude), fetchOptions }), + reports: await supportedReportSet({ + collection: addr, + headers: excludeHeaders(headers, headersToExclude), + fetchOptions, + }), }))); }; const fetchVCards = async (params) => { - const { addressBook, headers, objectUrls, headersToExclude, urlFilter = (url) => url, useMultiGet = true, fetchOptions = {} } = params; + const { addressBook, headers, objectUrls, headersToExclude, urlFilter = (url) => url, useMultiGet = true, fetchOptions = {}, } = params; debug$3(`Fetching vcards from ${addressBook === null || addressBook === void 0 ? void 0 : addressBook.url}`); const requiredFields = ['url']; if (!addressBook || !hasFields(addressBook, requiredFields)) { @@ -9610,7 +9580,7 @@ const fetchVCards = async (params) => { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, - })).map((res) => { var _a; return (res.ok ? (_a = res.href) !== null && _a !== void 0 ? _a : '' : ''); })) + })).map((res) => { var _a; return (res.ok ? ((_a = res.href) !== null && _a !== void 0 ? _a : '') : ''); })) .map((url) => (url.startsWith('http') || !url ? url : new URL(url, addressBook.url).href)) .filter(urlFilter) .map((url) => new URL(url).pathname); @@ -9626,7 +9596,7 @@ const fetchVCards = async (params) => { objectUrls: vcardUrls, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } else { @@ -9638,7 +9608,7 @@ const fetchVCards = async (params) => { }, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } } @@ -9652,7 +9622,7 @@ const fetchVCards = async (params) => { }); }; const createVCard = async (params) => { - const { addressBook, vCardString, filename, headers, headersToExclude, fetchOptions = {} } = params; + const { addressBook, vCardString, filename, headers, headersToExclude, fetchOptions = {}, } = params; return createObject({ url: new URL(filename, addressBook.url).href, data: vCardString, @@ -9661,7 +9631,7 @@ const createVCard = async (params) => { 'If-None-Match': '*', ...headers, }, headersToExclude), - fetchOptions + fetchOptions, }); }; const updateVCard = async (params) => { @@ -9683,7 +9653,7 @@ const deleteVCard = async (params) => { url: vCard.url, etag: vCard.etag, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); }; @@ -9724,7 +9694,7 @@ const fetchCalendarUserAddresses = async (params) => { return addresses; }; const calendarQuery = async (params) => { - const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {} } = params; + const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, } = params; return collectionQuery({ url, body: { @@ -9747,17 +9717,17 @@ const calendarQuery = async (params) => { }); }; const calendarMultiGet = async (params) => { - const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {} } = params; + const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, } = params; return collectionQuery({ url, body: { - 'calendar-multiget': { + 'calendar-multiget': cleanupFalsy({ _attributes: getDAVAttribute([DAVNamespace.DAV, DAVNamespace.CALDAV]), [`${DAVNamespaceShort.DAV}:prop`]: props, [`${DAVNamespaceShort.DAV}:href`]: objectUrls, - ...conditionalParam('filter', filters), + filter: filters, timezone, - }, + }), }, defaultNamespace: DAVNamespaceShort.CALDAV, depth, @@ -9786,11 +9756,11 @@ const makeCalendar = async (params) => { }, }, }, - fetchOptions + fetchOptions, }); }; const fetchCalendars = async (params) => { - const { headers, account, props: customProps, projectedProps, headersToExclude, fetchOptions = {} } = params !== null && params !== void 0 ? params : {}; + const { headers, account, props: customProps, projectedProps, headersToExclude, fetchOptions = {}, } = params !== null && params !== void 0 ? params : {}; const requiredFields = ['homeUrl', 'rootUrl']; if (!account || !hasFields(account, requiredFields)) { if (!account) { @@ -9930,7 +9900,7 @@ const fetchCalendarObjects = async (params) => { filters, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, })).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)) // patch up to full url if url is not full .filter(urlFilter) // custom filter function on calendar objects @@ -9964,7 +9934,7 @@ const fetchCalendarObjects = async (params) => { filters, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } else { @@ -9994,7 +9964,7 @@ const fetchCalendarObjects = async (params) => { objectUrls: calendarObjectUrls, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } } @@ -10017,7 +9987,7 @@ const createCalendarObject = async (params) => { 'If-None-Match': '*', ...headers, }, headersToExclude), - fetchOptions + fetchOptions, }); }; const updateCalendarObject = async (params) => { @@ -10030,7 +10000,7 @@ const updateCalendarObject = async (params) => { 'content-type': 'text/calendar; charset=utf-8', ...headers, }, headersToExclude), - fetchOptions + fetchOptions, }); }; const deleteCalendarObject = async (params) => { @@ -10039,7 +10009,7 @@ const deleteCalendarObject = async (params) => { url: calendarObject.url, etag: calendarObject.etag, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); }; /** @@ -10047,7 +10017,7 @@ const deleteCalendarObject = async (params) => { */ const syncCalendars = async (params) => { var _a; - const { oldCalendars, account, detailedResult, headers, headersToExclude, fetchOptions = {} } = params; + const { oldCalendars, account, detailedResult, headers, headersToExclude, fetchOptions = {}, } = params; if (!account) { throw new Error('Must have account before syncCalendars'); } @@ -10055,7 +10025,7 @@ const syncCalendars = async (params) => { const remoteCalendars = await fetchCalendars({ account, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); // no existing url const created = remoteCalendars.filter((rc) => localCalendars.every((lc) => !urlContains(lc.url, rc.url))); @@ -10126,7 +10096,7 @@ const freeBusyQuery = async (params) => { defaultNamespace: DAVNamespaceShort.CALDAV, depth, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); return result[0]; }; @@ -10155,7 +10125,7 @@ const serviceDiscovery = async (params) => { const uri = new URL(`/.well-known/${account.accountType}`, endpoint); uri.protocol = (_a = endpoint.protocol) !== null && _a !== void 0 ? _a : 'http'; try { - const response = await browserPonyfillExports.fetch(uri.href, { + const response = await fetch(uri.href, { headers: excludeHeaders(headers, headersToExclude), method: 'PROPFIND', redirect: 'manual', @@ -10502,7 +10472,7 @@ const fetchOauthTokens = async (credentials, fetchOptions) => { }); debug(credentials.tokenUrl); debug(param.toString()); - const response = await browserPonyfillExports.fetch(credentials.tokenUrl, { + const response = await fetch(credentials.tokenUrl, { method: 'POST', body: param.toString(), headers: { @@ -10534,7 +10504,7 @@ const refreshAccessToken = async (credentials, fetchOptions) => { refresh_token: credentials.refreshToken, grant_type: 'refresh_token', }); - const response = await browserPonyfillExports.fetch(credentials.tokenUrl, { + const response = await fetch(credentials.tokenUrl, { method: 'POST', body: param.toString(), headers: { diff --git a/dist/tsdav.min.cjs b/dist/tsdav.min.cjs index 3c1fdaf5..01821f3a 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("cross-fetch"),r=require("debug"),a=require("xml-js"),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 n,c;exports.DAVNamespaceShort=void 0,(n=exports.DAVNamespaceShort||(exports.DAVNamespaceShort={})).CALDAV="c",n.CARDDAV="card",n.CALENDAR_SERVER="cs",n.CALDAV_APPLE="ca",n.DAV="d",function(e){e.VEVENT="VEVENT",e.VTODO="VTODO",e.VJOURNAL="VJOURNAL",e.VFREEBUSY="VFREEBUSY",e.VTIMEZONE="VTIMEZONE",e.VALARM="VALARM"}(c||(c={}));const d=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})),{}),h=e=>Object.entries(e).reduce(((e,[t,r])=>r?{...e,[t]:r}:e),{}),u=(e,t)=>t?{[e]:t}:{},f=(e,t)=>e?t&&0!==t.length?Object.fromEntries(Object.entries(e).filter((([e])=>!t.includes(e)))):e:{};var m=Object.freeze({__proto__:null,cleanupFalsy:h,conditionalParam:u,excludeHeaders:f,getDAVAttribute:p,urlContains:l,urlEquals:i});const A=r("tsdav:request"),v=async e=>{var r;const{url:s,init:o,convertIncoming:n=!0,parseOutgoing:c=!0,fetchOptions:i={}}=e,{headers:l={},body:p,namespace:u,method:f,attributes:m}=o,v=n?a.js2xml({_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}},...p,_attributes:m},{compact:!0,spaces:2,elementNameFn:e=>u&&!/^.+:.+/.test(e)?`${u}:${e}`:e}):p,D=await t.fetch(s,{headers:{"Content-Type":"text/xml;charset=UTF-8",...h(l)},body:v,method:f,...i}),y=await D.text();if(!D.ok||!(null===(r=D.headers.get("content-type"))||void 0===r?void 0:r.includes("xml"))||!c)return[{href:D.url,ok:D.ok,status:D.status,statusText:D.statusText,raw:y}];const O=a.xml2js(y,{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]=d(e)}else r[s]=d(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(O.multistatus.response)?O.multistatus.response:[O.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:O,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:s,headersToExclude:o,fetchOptions:n={}}=e;return v({url:t,init:{method:"PROPFIND",headers:f(h({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:n})},y=async e=>{const{url:r,data:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e;return t.fetch(r,{method:"PUT",body:a,headers:f(s,o),...n})},O=async e=>{const{url:r,data:a,etag:s,headers:o,headersToExclude:n,fetchOptions:c={}}=e;return t.fetch(r,{method:"PUT",body:a,headers:f(h({"If-Match":s,...o}),n),...c})},V=async e=>{const{url:r,headers:a,etag:s,headersToExclude:o,fetchOptions:n={}}=e;return t.fetch(r,{method:"DELETE",headers:f(h({"If-Match":s,...a}),o),...n})};var x=Object.freeze({__proto__:null,createObject:y,davRequest:v,deleteObject:V,propfind:D,updateObject:O});function C(e,t){const r=e=>t.every((t=>e[t]));return Array.isArray(e)?e.every((e=>r(e))):r(e)}const g=(e,t)=>t.reduce(((t,r)=>e[r]?t:`${t.length?`${t},`:""}${r.toString()}`),""),b=r("tsdav:collection"),w=async e=>{const{url:t,body:r,depth:a,defaultNamespace:s=exports.DAVNamespaceShort.DAV,headers:o,headersToExclude:n,fetchOptions:c={}}=e,d=await v({url:t,init:{method:"REPORT",headers:f(h({depth:a,...o}),n),namespace:s,body:r},fetchOptions:c});return 1!==d.length||d[0].raw?d:[]},S=async e=>{const{url:t,props:r,depth:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e;return v({url:t,init:{method:"MKCOL",headers:f(h({depth:a,...s}),o),namespace:exports.DAVNamespaceShort.DAV,body:r?{mkcol:{set:{prop:r}}}:void 0},fetchOptions:n})},N=async e=>{var t,r,a,s,o;const{collection:n,headers:c,headersToExclude:d,fetchOptions:i={}}=e;return null!==(o=null===(s=null===(a=null===(r=null===(t=(await D({url:n.url,props:{[`${exports.DAVNamespaceShort.DAV}:supported-report-set`]:{}},depth:"0",headers:f(c,d),fetchOptions: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:[]},$=async e=>{var t,r,a;const{collection:s,headers:o,headersToExclude:n,fetchOptions:c={}}=e,d=(await D({url:s.url,props:{[`${exports.DAVNamespaceShort.CALENDAR_SERVER}:getctag`]:{}},depth:"0",headers:f(o,n),fetchOptions:c})).filter((e=>l(s.url,e.href)))[0];if(!d)throw new Error("Collection does not exist on server");return{isDirty:`${s.ctag}`!=`${null===(t=d.props)||void 0===t?void 0:t.getctag}`,newCtag:null===(a=null===(r=d.props)||void 0===r?void 0:r.getctag)||void 0===a?void 0:a.toString()}},E=e=>{const{url:t,props:r,headers:a,syncLevel:s,syncToken:o,headersToExclude:n,fetchOptions:c}=e;return v({url:t,init:{method:"REPORT",namespace:exports.DAVNamespaceShort.DAV,headers:f({...a},n),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:c})},T=async e=>{var t,r,a,s,o,n,c,d,i,p,h;const{collection:u,method:m,headers:A,headersToExclude:v,account:D,detailedResult:y,fetchOptions:O={}}=e,V=["accountType","homeUrl"];if(!D||!C(D,V)){if(!D)throw new Error("no account for smartCollectionSync");throw new Error(`account must have ${g(D,V)} before smartCollectionSync`)}const x=null!=m?m:(null===(t=u.reports)||void 0===t?void 0:t.includes("syncCollection"))?"webdav":"basic";if(b(`smart collection sync with type ${D.accountType} and method ${x}`),"webdav"===x){const e=await E({url:u.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:u.syncToken,headers:f(A,v),fetchOptions:O}),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)),p=t.filter((e=>404===e.status)).map((e=>e.href)),h=(i.length&&null!==(a=await(null===(r=null==u?void 0:u.objectMultiGet)||void 0===r?void 0:r.call(u,{url:u.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:f(A,v),fetchOptions:O})))&&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==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===(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}})),m=null!==(s=u.objects)&&void 0!==s?s:[],V=h.filter((e=>m.every((t=>!l(t.url,e.url))))),x=m.reduce(((e,t)=>{const r=h.find((e=>l(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),C=p.map((e=>({url:e,etag:""}))),g=m.filter((e=>h.some((t=>l(e.url,t.url)&&t.etag===e.etag))));return{...u,objects:y?{created:V,updated:x,deleted:C}:[...g,...V,...x],syncToken:null!==(d=null===(c=null===(n=null===(o=e[0])||void 0===o?void 0:o.raw)||void 0===n?void 0:n.multistatus)||void 0===c?void 0:c.syncToken)&&void 0!==d?d:u.syncToken}}if("basic"===x){const{isDirty:e,newCtag:t}=await $({collection:u,headers:f(A,v),fetchOptions:O}),r=null!==(i=u.objects)&&void 0!==i?i:[],a=null!==(h=await(null===(p=u.fetchObjects)||void 0===p?void 0:p.call(u,{collection:u,headers:f(A,v),fetchOptions:O})))&&void 0!==h?h:[],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{...u,objects:y?{created:s,updated:o,deleted:n}:[...c,...s,...o],ctag:t}}return y?{...u,objects:{created:[],updated:[],deleted:[]}}:u};var k=Object.freeze({__proto__:null,collectionQuery:w,isCollectionDirty:$,makeCollection:S,smartCollectionSync:T,supportedReportSet:N,syncCollection:E});const U=r("tsdav:addressBook"),_=async e=>{const{url:t,props:r,filters:a,depth:s,headers:o,headersToExclude:n,fetchOptions:c={}}=e;return w({url:t,body:{"addressbook-query":{_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:f(o,n),fetchOptions:c})},R=async e=>{const{url:t,props:r,objectUrls:a,depth:s,headers:o,headersToExclude:n,fetchOptions:c={}}=e;return w({url:t,body:{"addressbook-multiget":{_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:f(o,n),fetchOptions:c})},j=async e=>{const{account:t,headers:r,props:a,headersToExclude:s,fetchOptions:o={}}=null!=e?e:{},n=["homeUrl","rootUrl"];if(!t||!C(t,n)){if(!t)throw new Error("no account for fetchAddressBooks");throw new Error(`account must have ${g(t,n)} before fetchAddressBooks`)}const c=await D({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:f(r,s),fetchOptions: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,a,s,o,n,c,d,i,l;const p=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 U(`Found address book named ${"string"==typeof p?p:""},\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 p?p:"",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 N({collection:e,headers:f(r,s),fetchOptions:o})}))))},L=async e=>{const{addressBook:t,headers:r,objectUrls:a,headersToExclude:s,urlFilter:o=e=>e,useMultiGet:n=!0,fetchOptions:c={}}=e;U(`Fetching vcards from ${null==t?void 0:t.url}`);const d=["url"];if(!t||!C(t,d)){if(!t)throw new Error("cannot fetchVCards for undefined addressBook");throw new Error(`addressBook must have ${g(t,d)} before fetchVCards`)}const i=(null!=a?a:(await _({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{}},depth:"1",headers:f(r,s),fetchOptions:c})).map((e=>{var t;return e.ok&&null!==(t=e.href)&&void 0!==t?t:""}))).map((e=>e.startsWith("http")||!e?e:new URL(e,t.url).href)).filter(o).map((e=>new URL(e).pathname));let l=[];return i.length>0&&(l=n?await R({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CARDDAV}:address-data`]:{}},objectUrls:i,depth:"1",headers:f(r,s),fetchOptions:c}):await _({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CARDDAV}:address-data`]:{}},depth:"1",headers:f(r,s),fetchOptions:c})),l.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}}))},H=async e=>{const{addressBook:t,vCardString:r,filename:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e;return y({url:new URL(a,t.url).href,data:r,headers:f({"content-type":"text/vcard; charset=utf-8","If-None-Match":"*",...s},o),fetchOptions:n})},P=async e=>{const{vCard:t,headers:r,headersToExclude:a,fetchOptions:s={}}=e;return O({url:t.url,data:t.data,etag:t.etag,headers:f({"content-type":"text/vcard; charset=utf-8",...r},a),fetchOptions:s})},B=async e=>{const{vCard:t,headers:r,headersToExclude:a,fetchOptions:s={}}=e;return V({url:t.url,etag:t.etag,headers:f(r,a),fetchOptions:s})};var F=Object.freeze({__proto__:null,addressBookMultiGet:R,addressBookQuery:_,createVCard:H,deleteVCard:B,fetchAddressBooks:j,fetchVCards:L,updateVCard:P});const M=r("tsdav:calendar"),I=async e=>{var t,r,a;const{account:s,headers:o,headersToExclude:n,fetchOptions:c={}}=e,d=["principalUrl","rootUrl"];if(!C(s,d))throw new Error(`account must have ${g(s,d)} before fetchUserAddresses`);M(`Fetch user addresses from ${s.principalUrl}`);const i=(await D({url:s.principalUrl,props:{[`${exports.DAVNamespaceShort.CALDAV}:calendar-user-address-set`]:{}},depth:"0",headers:f(o,n),fetchOptions:c})).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 M(`Fetched calendar user addresses ${p}`),p},z=async e=>{const{url:t,props:r,filters:a,timezone:s,depth:o,headers:n,headersToExclude:c,fetchOptions:d={}}=e;return w({url:t,body:{"calendar-query":h({_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:f(n,c),fetchOptions:d})},Z=async e=>{const{url:t,props:r,objectUrls:a,filters:s,timezone:o,depth:n,headers:c,headersToExclude:d,fetchOptions:i={}}=e;return w({url:t,body:{"calendar-multiget":{_attributes:p([exports.DAVNamespace.DAV,exports.DAVNamespace.CALDAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,[`${exports.DAVNamespaceShort.DAV}:href`]:a,...u("filter",s),timezone:o}},defaultNamespace:exports.DAVNamespaceShort.CALDAV,depth:n,headers:f(c,d),fetchOptions:i})},q=async e=>{const{url:t,props:r,depth:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e;return v({url:t,init:{method:"MKCALENDAR",headers:f(h({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:n})},Q=async e=>{const{headers:t,account:r,props:a,projectedProps:s,headersToExclude:o,fetchOptions:n={}}=null!=e?e:{},d=["homeUrl","rootUrl"];if(!r||!C(r,d)){if(!r)throw new Error("no account for fetchCalendars");throw new Error(`account must have ${g(r,d)} before fetchCalendars`)}const i=await D({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:f(t,o),fetchOptions:n});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;return(Array.isArray(null===(t=e.props)||void 0===t?void 0:t.supportedCalendarComponentSet.comp)?null===(r=e.props)||void 0===r?void 0:r.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(s=null===(a=e.props)||void 0===a?void 0:a.supportedCalendarComponentSet.comp)||void 0===s?void 0:s._attributes.name]).some((e=>Object.values(c).includes(e)))})).map((e=>{var t,a,o,n,c,d,i,l,p,h,f,m,A,v,D,y;const O=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 O?O:"",timezone:"string"==typeof V?V:"",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===(p=e.props)||void 0===p?void 0:p.displayname,components:Array.isArray(null===(h=e.props)||void 0===h?void 0:h.supportedCalendarComponentSet.comp)?null===(f=e.props)||void 0===f?void 0:f.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(A=null===(m=e.props)||void 0===m?void 0:m.supportedCalendarComponentSet.comp)||void 0===A?void 0:A._attributes.name],resourcetype:Object.keys(null===(v=e.props)||void 0===v?void 0:v.resourcetype),syncToken:null===(D=e.props)||void 0===D?void 0:D.syncToken,...u("projectedProps",Object.fromEntries(Object.entries(null!==(y=e.props)&&void 0!==y?y:{}).filter((([e])=>null==s?void 0:s[e]))))}})).map((async e=>({...e,reports:await N({collection:e,headers:f(t,o),fetchOptions:n})}))))},G=async e=>{const{calendar:t,objectUrls:r,filters:a,timeRange:s,headers:o,expand:n,urlFilter:c=e=>Boolean(null==e?void 0:e.includes(".ics")),useMultiGet:d=!0,headersToExclude:i,fetchOptions:l={}}=e;if(s){const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(s.start)&&e.test(s.end)||t.test(s.start)&&t.test(s.end)))throw new Error("invalid timeRange format, not in ISO8601")}M(`Fetching calendar objects from ${null==t?void 0:t.url}`);const p=["url"];if(!t||!C(t,p)){if(!t)throw new Error("cannot fetchCalendarObjects for undefined calendar");throw new Error(`calendar must have ${g(t,p)} before fetchCalendarObjects`)}const h=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`}}}:{}}}}],u=(null!=r?r:(await z({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{...n&&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:h,depth:"1",headers:f(o,i),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(c).map((e=>new URL(e).pathname));let m=[];return u.length>0&&(m=!d||n?await z({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CALDAV}:calendar-data`]:{...n&&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:h,depth:"1",headers:f(o,i),fetchOptions:l}):await Z({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CALDAV}:calendar-data`]:{...n&&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:u,depth:"1",headers:f(o,i),fetchOptions:l})),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}}))},J=async e=>{const{calendar:t,iCalString:r,filename:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e;return y({url:new URL(a,t.url).href,data:r,headers:f({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*",...s},o),fetchOptions:n})},K=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={}}=e;return O({url:t.url,data:t.data,etag:t.etag,headers:f({"content-type":"text/calendar; charset=utf-8",...r},a),fetchOptions:s})},W=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={}}=e;return V({url:t.url,etag:t.etag,headers:f(r,a),fetchOptions:s})},Y=async e=>{var t;const{oldCalendars:r,account:a,detailedResult:s,headers:o,headersToExclude:n,fetchOptions:c={}}=e;if(!a)throw new Error("Must have account before syncCalendars");const d=null!==(t=null!=r?r:a.calendars)&&void 0!==t?t:[],i=await Q({account:a,headers:f(o,n),fetchOptions:c}),p=i.filter((e=>d.every((t=>!l(t.url,e.url)))));M(`new calendars: ${p.map((e=>e.displayName))}`);const h=d.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}),[]);M(`updated calendars: ${h.map((e=>e.displayName))}`);const u=await Promise.all(h.map((async e=>await T({collection:{...e,objectMultiGet:Z},method:"webdav",headers:f(o,n),account:a,fetchOptions:c})))),m=d.filter((e=>i.every((t=>!l(t.url,e.url)))));M(`deleted calendars: ${m.map((e=>e.displayName))}`);const A=d.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:h,deleted:m}:[...A,...p,...u]},X=async e=>{const{url:t,timeRange:r,depth:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e;if(!r)throw new Error("timeRange is required");{const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(r.start)&&e.test(r.end)||t.test(r.start)&&t.test(r.end)))throw new Error("invalid timeRange format, not in ISO8601")}return(await w({url:t,body:{"free-busy-query":h({_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:f(s,o),fetchOptions:n}))[0]};var ee=Object.freeze({__proto__:null,calendarMultiGet:Z,calendarQuery:z,createCalendarObject:J,deleteCalendarObject:W,fetchCalendarObjects:G,fetchCalendarUserAddresses:I,fetchCalendars:Q,freeBusyQuery:X,makeCalendar:q,syncCalendars:Y,updateCalendarObject:K});const te=r("tsdav:account"),re=async e=>{var r,a;te("Service discovery...");const{account:s,headers:o,headersToExclude:n,fetchOptions:c={}}=e,d=new URL(s.serverUrl),i=new URL(`/.well-known/${s.accountType}`,d);i.protocol=null!==(r=d.protocol)&&void 0!==r?r:"http";try{const e=await t.fetch(i.href,{headers:f(o,n),method:"PROPFIND",redirect:"manual",...c});if(e.status>=300&&e.status<400){const t=e.headers.get("Location");if("string"==typeof t&&t.length){te(`Service discovery redirected to ${t}`);const e=new URL(t,d);return e.hostname===i.hostname&&i.port&&!e.port&&(e.port=i.port),e.protocol=null!==(a=d.protocol)&&void 0!==a?a:"http",e.href}}}catch(e){te(`Service discovery failed: ${e.stack}`)}return d.href},ae=async e=>{var t,r,a,s,o;const{account:n,headers:c,headersToExclude:d,fetchOptions:i={}}=e,l=["rootUrl"];if(!C(n,l))throw new Error(`account must have ${g(n,l)} before fetchPrincipalUrl`);te(`Fetching principal url from path ${n.rootUrl}`);const[p]=await D({url:n.rootUrl,props:{[`${exports.DAVNamespaceShort.DAV}:current-user-principal`]:{}},depth:"0",headers:f(c,d),fetchOptions:i});if(!p.ok&&(te(`Fetch principal url failed: ${p.statusText}`),401===p.status))throw new Error("Invalid credentials");return te(`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:"",n.rootUrl).href},se=async e=>{var t,r;const{account:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e,c=["principalUrl","rootUrl"];if(!C(a,c))throw new Error(`account must have ${g(a,c)} before fetchHomeUrl`);te(`Fetch home url from ${a.principalUrl}`);const d=(await D({url:a.principalUrl,props:"caldav"===a.accountType?{[`${exports.DAVNamespaceShort.CALDAV}:calendar-home-set`]:{}}:{[`${exports.DAVNamespaceShort.CARDDAV}:addressbook-home-set`]:{}},depth:"0",headers:f(s,o),fetchOptions:n})).find((e=>l(a.principalUrl,e.href)));if(!d||!d.ok)throw new Error("cannot find homeUrl");const i=new URL("caldav"===a.accountType?null===(t=null==d?void 0:d.props)||void 0===t?void 0:t.calendarHomeSet.href:null===(r=null==d?void 0:d.props)||void 0===r?void 0:r.addressbookHomeSet.href,a.rootUrl).href;return te(`Fetched home url ${i}`),i},oe=async e=>{const{account:t,headers:r,loadCollections:a=!1,loadObjects:s=!1,headersToExclude:o,fetchOptions:n={}}=e,c={...t};return c.rootUrl=await re({account:t,headers:f(r,o),fetchOptions:n}),c.principalUrl=await ae({account:c,headers:f(r,o),fetchOptions:n}),c.homeUrl=await se({account:c,headers:f(r,o),fetchOptions:n}),(a||s)&&("caldav"===t.accountType?c.calendars=await Q({headers:f(r,o),account:c,fetchOptions:n}):"carddav"===t.accountType&&(c.addressBooks=await j({headers:f(r,o),account:c,fetchOptions:n}))),s&&("caldav"===t.accountType&&c.calendars?c.calendars=await Promise.all(c.calendars.map((async e=>({...e,objects:await G({calendar:e,headers:f(r,o),fetchOptions:n})})))):"carddav"===t.accountType&&c.addressBooks&&(c.addressBooks=await Promise.all(c.addressBooks.map((async e=>({...e,objects:await L({addressBook:e,headers:f(r,o),fetchOptions:n})})))))),c};var ne=Object.freeze({__proto__:null,createAccount:oe,fetchHomeUrl:se,fetchPrincipalUrl:ae,serviceDiscovery:re});const ce=r("tsdav:authHelper"),de=(e,t)=>(...r)=>e({...t,...r[0]}),ie=e=>(ce(`Basic auth token generated: ${s.encode(`${e.username}:${e.password}`)}`),{authorization:`Basic ${s.encode(`${e.username}:${e.password}`)}`}),le=async(e,r)=>{const a=["authorizationCode","redirectUrl","clientId","clientSecret","tokenUrl"];if(!C(e,a))throw new Error(`Oauth credentials missing: ${g(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});ce(e.tokenUrl),ce(s.toString());const o=await t.fetch(e.tokenUrl,{method:"POST",body:s.toString(),headers:{"content-length":`${s.toString().length}`,"content-type":"application/x-www-form-urlencoded"},...null!=r?r:{}});if(o.ok){return await o.json()}return ce(`Fetch Oauth tokens failed: ${await o.text()}`),{}},pe=async(e,r)=>{const a=["refreshToken","clientId","clientSecret","tokenUrl"];if(!C(e,a))throw new Error(`Oauth credentials missing: ${g(e,a)}`);const s=new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,refresh_token:e.refreshToken,grant_type:"refresh_token"}),o=await t.fetch(e.tokenUrl,{method:"POST",body:s.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},...null!=r?r:{}});if(o.ok){return await o.json()}return ce(`Refresh access token failed: ${await o.text()}`),{}},he=async(e,t)=>{var r;ce("Fetching oauth headers");let a={};return e.refreshToken?(e.refreshToken&&!e.accessToken||Date.now()>(null!==(r=e.expiration)&&void 0!==r?r:0))&&(a=await pe(e,t)):a=await le(e,t),ce(`Oauth tokens fetched: ${a.access_token}`),{tokens:a,headers:{authorization:`Bearer ${a.access_token}`}}};var ue=Object.freeze({__proto__:null,defaultParam:de,fetchOauthTokens:le,getBasicAuthHeaders:ie,getOauthHeaders:he,refreshAccessToken:pe});const fe=async e=>{var t;const{serverUrl:r,credentials:a,authMethod:s,defaultAccountType:o,authFunction:n}=e;let c={};switch(s){case"Basic":c=ie(a);break;case"Oauth":c=(await he(a)).headers;break;case"Digest":c={Authorization:`Digest ${a.digestString}`};break;case"Custom":c=null!==(t=await(null==n?void 0:n(a)))&&void 0!==t?t:{};break;default:throw new Error("Invalid auth method")}const d=o?await oe({account:{serverUrl:r,credentials:a,accountType:o},headers:c}):void 0,i=de(y,{url:r,headers:c}),l=de(O,{headers:c,url:r}),p=de(V,{headers:c,url:r}),h=de(D,{headers:c}),u=de(w,{headers:c}),f=de(S,{headers:c}),m=de(E,{headers:c}),A=de(N,{headers:c}),x=de($,{headers:c}),C=de(T,{headers:c,account:d}),g=de(z,{headers:c}),b=de(Z,{headers:c}),k=de(q,{headers:c}),U=de(Q,{headers:c,account:d}),F=de(I,{headers:c,account:d}),M=de(G,{headers:c}),X=de(J,{headers:c}),ee=de(K,{headers:c}),te=de(W,{headers:c}),re=de(Y,{account:d,headers:c}),ae=de(_,{headers:c}),se=de(R,{headers:c});return{davRequest:async e=>{const{init:t,...r}=e,{headers:a,...s}=t;return v({...r,init:{...s,headers:{...c,...a}}})},propfind:h,createAccount:async e=>{const{account:t,headers:s,loadCollections:o,loadObjects:n}=e;return oe({account:{serverUrl:r,credentials:a,...t},headers:{...c,...s},loadCollections:o,loadObjects:n})},createObject:i,updateObject:l,deleteObject:p,calendarQuery:g,addressBookQuery:ae,collectionQuery:u,makeCollection:f,calendarMultiGet:b,makeCalendar:k,syncCollection:m,supportedReportSet:A,isCollectionDirty:x,smartCollectionSync:C,fetchCalendars:U,fetchCalendarUserAddresses:F,fetchCalendarObjects:M,createCalendarObject:X,updateCalendarObject:ee,deleteCalendarObject:te,syncCalendars:re,fetchAddressBooks:de(j,{account:d,headers:c}),addressBookMultiGet:se,fetchVCards:de(L,{headers:c}),createVCard:de(H,{headers:c}),updateVCard:de(P,{headers:c}),deleteVCard:de(B,{headers:c})}};class me{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:{}}async login(){var e;switch(this.authMethod){case"Basic":this.authHeaders=ie(this.credentials);break;case"Oauth":this.authHeaders=(await he(this.credentials,this.fetchOptions)).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 oe({account:{serverUrl:this.serverUrl,credentials:this.credentials,accountType:this.accountType},headers:this.authHeaders,fetchOptions:this.fetchOptions}):void 0}async davRequest(e){const{init:t,...r}=e,{headers:a,...s}=t;return v({...r,init:{...s,headers:{...this.authHeaders,...a}},fetchOptions:this.fetchOptions})}async createObject(...e){return de(y,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateObject(...e){return de(O,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteObject(...e){return de(V,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async propfind(...e){return de(D,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createAccount(e){const{account:t,headers:r,loadCollections:a,loadObjects:s,fetchOptions:o}=e;return oe({account:{serverUrl:this.serverUrl,credentials:this.credentials,...t},headers:{...this.authHeaders,...r},loadCollections:a,loadObjects:s,fetchOptions:null!=o?o:this.fetchOptions})}async collectionQuery(...e){return de(w,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async makeCollection(...e){return de(S,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async syncCollection(...e){return de(E,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async supportedReportSet(...e){return de(N,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async isCollectionDirty(...e){return de($,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async smartCollectionSync(...e){return de(T,{headers:this.authHeaders,fetchOptions:this.fetchOptions,account:this.account})(e[0])}async calendarQuery(...e){return de(z,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async makeCalendar(...e){return de(q,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async calendarMultiGet(...e){return de(Z,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async fetchCalendars(...e){return de(Q,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(null==e?void 0:e[0])}async fetchCalendarUserAddresses(...e){return de(I,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(null==e?void 0:e[0])}async fetchCalendarObjects(...e){return de(G,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createCalendarObject(...e){return de(J,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateCalendarObject(...e){return de(K,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteCalendarObject(...e){return de(W,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async syncCalendars(...e){return de(Y,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(e[0])}async addressBookQuery(...e){return de(_,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async addressBookMultiGet(...e){return de(R,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async fetchAddressBooks(...e){return de(j,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(null==e?void 0:e[0])}async fetchVCards(...e){return de(L,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createVCard(...e){return de(H,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateVCard(...e){return de(P,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteVCard(...e){return de(B,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}}var Ae=Object.freeze({__proto__:null,DAVClient:me,createDAVClient:fe}),ve={DAVNamespace:exports.DAVNamespace,DAVNamespaceShort:exports.DAVNamespaceShort,DAVAttributeMap:o,...Ae,...x,...k,...ne,...F,...ee,...ue,...m};exports.DAVAttributeMap=o,exports.DAVClient=me,exports.addressBookQuery=_,exports.calendarMultiGet=Z,exports.calendarQuery=z,exports.cleanupFalsy=h,exports.collectionQuery=w,exports.createAccount=oe,exports.createCalendarObject=J,exports.createDAVClient=fe,exports.createObject=y,exports.createVCard=H,exports.davRequest=v,exports.default=ve,exports.deleteCalendarObject=W,exports.deleteObject=V,exports.deleteVCard=B,exports.fetchAddressBooks=j,exports.fetchCalendarObjects=G,exports.fetchCalendarUserAddresses=I,exports.fetchCalendars=Q,exports.fetchOauthTokens=le,exports.fetchVCards=L,exports.freeBusyQuery=X,exports.getBasicAuthHeaders=ie,exports.getDAVAttribute=p,exports.getOauthHeaders=he,exports.isCollectionDirty=$,exports.makeCalendar=q,exports.propfind=D,exports.refreshAccessToken=pe,exports.smartCollectionSync=T,exports.supportedReportSet=N,exports.syncCalendars=Y,exports.syncCollection=E,exports.updateCalendarObject=K,exports.updateObject=O,exports.updateVCard=P,exports.urlContains=l,exports.urlEquals=i; +"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),require("cross-fetch/polyfill");var e,t=require("debug"),r=require("xml-js"),a=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 s={[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 o,n;exports.DAVNamespaceShort=void 0,(o=exports.DAVNamespaceShort||(exports.DAVNamespaceShort={})).CALDAV="c",o.CARDDAV="card",o.CALENDAR_SERVER="cs",o.CALDAV_APPLE="ca",o.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 c=e=>{const t=Number(e);if(!Number.isNaN(t))return t;const r=e.toLowerCase();return"true"===r||"false"!==r&&e},d=(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)},i=(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)},l=e=>e.reduce(((e,t)=>({...e,[s[t]]:t})),{}),p=e=>Object.entries(e).reduce(((e,[t,r])=>r?{...e,[t]:r}:e),{}),h=(e,t)=>t?{[e]:t}:{},u=(e,t)=>e?t&&0!==t.length?Object.fromEntries(Object.entries(e).filter((([e])=>!t.includes(e)))):e:{};var f=Object.freeze({__proto__:null,cleanupFalsy:p,conditionalParam:h,excludeHeaders:u,getDAVAttribute:l,urlContains:i,urlEquals:d});const m=t("tsdav:request"),A=async e=>{var t;const{url:a,init:s,convertIncoming:o=!0,parseOutgoing:n=!0,fetchOptions:d={}}=e,{headers:i={},body:l,namespace:h,method:u,attributes:f}=s,A=o?r.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,v=await fetch(a,{headers:{"Content-Type":"text/xml;charset=UTF-8",...p(i)},body:A,method:u,...d}),D=await v.text();if(!v.ok||!(null===(t=v.headers.get("content-type"))||void 0===t?void 0:t.includes("xml"))||!n)return[{href:v.url,ok:v.ok,status:v.status,statusText:v.statusText,raw:D}];const y=r.xml2js(D,{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]=c(e)}else r[s]=c(e)}catch(e){m(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(y.multistatus.response)?y.multistatus.response:[y.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:y,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:n={}}=e;return A({url:t,init:{method:"PROPFIND",headers:u(p({depth:a,...s}),o),namespace:exports.DAVNamespaceShort.DAV,body:{propfind:{_attributes:l([exports.DAVNamespace.CALDAV,exports.DAVNamespace.CALDAV_APPLE,exports.DAVNamespace.CALENDAR_SERVER,exports.DAVNamespace.CARDDAV,exports.DAVNamespace.DAV]),prop:r}}},fetchOptions:n})},D=async e=>{const{url:t,data:r,headers:a,headersToExclude:s,fetchOptions:o={}}=e;return fetch(t,{method:"PUT",body:r,headers:u(a,s),...o})},y=async e=>{const{url:t,data:r,etag:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e;return fetch(t,{method:"PUT",body:r,headers:u(p({"If-Match":a,...s}),o),...n})},O=async e=>{const{url:t,headers:r,etag:a,headersToExclude:s,fetchOptions:o={}}=e;return fetch(t,{method:"DELETE",headers:u(p({"If-Match":a,...r}),s),...o})};var V=Object.freeze({__proto__:null,createObject:D,davRequest:A,deleteObject:O,propfind:v,updateObject:y});function x(e,t){const r=e=>t.every((t=>e[t]));return Array.isArray(e)?e.every((e=>r(e))):r(e)}const C=(e,t)=>t.reduce(((t,r)=>e[r]?t:`${t.length?`${t},`:""}${r.toString()}`),""),g=t("tsdav:collection"),b=async e=>{const{url:t,body:r,depth:a,defaultNamespace:s=exports.DAVNamespaceShort.DAV,headers:o,headersToExclude:n,fetchOptions:c={}}=e,d=await A({url:t,init:{method:"REPORT",headers:u(p({depth:a,...o}),n),namespace:s,body:r},fetchOptions:c});return 1!==d.length||d[0].raw?d:[]},w=async e=>{const{url:t,props:r,depth:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e;return A({url:t,init:{method:"MKCOL",headers:u(p({depth:a,...s}),o),namespace:exports.DAVNamespaceShort.DAV,body:r?{mkcol:{set:{prop:r}}}:void 0},fetchOptions:n})},S=async e=>{var t,r,a,s,o;const{collection:n,headers:c,headersToExclude:d,fetchOptions:i={}}=e;return null!==(o=null===(s=null===(a=null===(r=null===(t=(await v({url:n.url,props:{[`${exports.DAVNamespaceShort.DAV}:supported-report-set`]:{}},depth:"0",headers:u(c,d),fetchOptions: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:[]},N=async e=>{var t,r,a;const{collection:s,headers:o,headersToExclude:n,fetchOptions:c={}}=e,d=(await v({url:s.url,props:{[`${exports.DAVNamespaceShort.CALENDAR_SERVER}:getctag`]:{}},depth:"0",headers:u(o,n),fetchOptions:c})).filter((e=>i(s.url,e.href)))[0];if(!d)throw new Error("Collection does not exist on server");return{isDirty:`${s.ctag}`!=`${null===(t=d.props)||void 0===t?void 0:t.getctag}`,newCtag:null===(a=null===(r=d.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:n,fetchOptions:c}=e;return A({url:t,init:{method:"REPORT",namespace:exports.DAVNamespaceShort.DAV,headers:u({...a},n),body:{"sync-collection":{_attributes:l([exports.DAVNamespace.CALDAV,exports.DAVNamespace.CARDDAV,exports.DAVNamespace.DAV]),"sync-level":s,"sync-token":o,[`${exports.DAVNamespaceShort.DAV}:prop`]:r}}},fetchOptions:c})},E=async e=>{var t,r,a,s,o,n,c,d,l,p,h;const{collection:f,method:m,headers:A,headersToExclude:v,account:D,detailedResult:y,fetchOptions:O={}}=e,V=["accountType","homeUrl"];if(!D||!x(D,V)){if(!D)throw new Error("no account for smartCollectionSync");throw new Error(`account must have ${C(D,V)} before smartCollectionSync`)}const b=null!=m?m:(null===(t=f.reports)||void 0===t?void 0:t.includes("syncCollection"))?"webdav":"basic";if(g(`smart collection sync with type ${D.accountType} and method ${b}`),"webdav"===b){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:u(A,v),fetchOptions:O}),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})),l=t.filter((e=>404!==e.status)).map((e=>e.href)),p=t.filter((e=>404===e.status)).map((e=>e.href)),h=(l.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:l,depth:"1",headers:u(A,v),fetchOptions:O})))&&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==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===(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}})),m=null!==(s=f.objects)&&void 0!==s?s:[],V=h.filter((e=>m.every((t=>!i(t.url,e.url))))),x=m.reduce(((e,t)=>{const r=h.find((e=>i(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),C=p.map((e=>({url:e,etag:""}))),g=m.filter((e=>h.some((t=>i(e.url,t.url)&&t.etag===e.etag))));return{...f,objects:y?{created:V,updated:x,deleted:C}:[...g,...V,...x],syncToken:null!==(d=null===(c=null===(n=null===(o=e[0])||void 0===o?void 0:o.raw)||void 0===n?void 0:n.multistatus)||void 0===c?void 0:c.syncToken)&&void 0!==d?d:f.syncToken}}if("basic"===b){const{isDirty:e,newCtag:t}=await N({collection:f,headers:u(A,v),fetchOptions:O}),r=null!==(l=f.objects)&&void 0!==l?l:[],a=null!==(h=await(null===(p=f.fetchObjects)||void 0===p?void 0:p.call(f,{collection:f,headers:u(A,v),fetchOptions:O})))&&void 0!==h?h:[],s=a.filter((e=>r.every((t=>!i(t.url,e.url))))),o=r.reduce(((e,t)=>{const r=a.find((e=>i(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),n=r.filter((e=>a.every((t=>!i(t.url,e.url))))),c=r.filter((e=>a.some((t=>i(e.url,t.url)&&t.etag===e.etag))));if(e)return{...f,objects:y?{created:s,updated:o,deleted:n}:[...c,...s,...o],ctag:t}}return y?{...f,objects:{created:[],updated:[],deleted:[]}}:f};var T=Object.freeze({__proto__:null,collectionQuery:b,isCollectionDirty:N,makeCollection:w,smartCollectionSync:E,supportedReportSet:S,syncCollection:$});const k=t("tsdav:addressBook"),U=async e=>{const{url:t,props:r,filters:a,depth:s,headers:o,headersToExclude:n,fetchOptions:c={}}=e;return b({url:t,body:{"addressbook-query":p({_attributes:l([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:u(o,n),fetchOptions:c})},_=async e=>{const{url:t,props:r,objectUrls:a,depth:s,headers:o,headersToExclude:n,fetchOptions:c={}}=e;return b({url:t,body:{"addressbook-multiget":p({_attributes:l([exports.DAVNamespace.DAV,exports.DAVNamespace.CARDDAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,[`${exports.DAVNamespaceShort.DAV}:href`]:a})},defaultNamespace:exports.DAVNamespaceShort.CARDDAV,depth:s,headers:u(o,n),fetchOptions:c})},R=async e=>{const{account:t,headers:r,props:a,headersToExclude:s,fetchOptions:o={}}=null!=e?e:{},n=["homeUrl","rootUrl"];if(!t||!x(t,n)){if(!t)throw new Error("no account for fetchAddressBooks");throw new Error(`account must have ${C(t,n)} before fetchAddressBooks`)}const c=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:u(r,s),fetchOptions: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,a,s,o,n,c,d,i,l;const p=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 k(`Found address book named ${"string"==typeof p?p:""},\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 p?p:"",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 S({collection:e,headers:u(r,s),fetchOptions:o})}))))},j=async e=>{const{addressBook:t,headers:r,objectUrls:a,headersToExclude:s,urlFilter:o=e=>e,useMultiGet:n=!0,fetchOptions:c={}}=e;k(`Fetching vcards from ${null==t?void 0:t.url}`);const d=["url"];if(!t||!x(t,d)){if(!t)throw new Error("cannot fetchVCards for undefined addressBook");throw new Error(`addressBook must have ${C(t,d)} before fetchVCards`)}const i=(null!=a?a:(await U({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{}},depth:"1",headers:u(r,s),fetchOptions:c})).map((e=>{var t;return e.ok&&null!==(t=e.href)&&void 0!==t?t:""}))).map((e=>e.startsWith("http")||!e?e:new URL(e,t.url).href)).filter(o).map((e=>new URL(e).pathname));let l=[];return i.length>0&&(l=n?await _({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CARDDAV}:address-data`]:{}},objectUrls:i,depth:"1",headers:u(r,s),fetchOptions:c}):await U({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CARDDAV}:address-data`]:{}},depth:"1",headers:u(r,s),fetchOptions:c})),l.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}}))},L=async e=>{const{addressBook:t,vCardString:r,filename:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e;return D({url:new URL(a,t.url).href,data:r,headers:u({"content-type":"text/vcard; charset=utf-8","If-None-Match":"*",...s},o),fetchOptions:n})},H=async e=>{const{vCard:t,headers:r,headersToExclude:a,fetchOptions:s={}}=e;return y({url:t.url,data:t.data,etag:t.etag,headers:u({"content-type":"text/vcard; charset=utf-8",...r},a),fetchOptions:s})},P=async e=>{const{vCard:t,headers:r,headersToExclude:a,fetchOptions:s={}}=e;return O({url:t.url,etag:t.etag,headers:u(r,a),fetchOptions:s})};var B=Object.freeze({__proto__:null,addressBookMultiGet:_,addressBookQuery:U,createVCard:L,deleteVCard:P,fetchAddressBooks:R,fetchVCards:j,updateVCard:H});const F=t("tsdav:calendar"),M=async e=>{var t,r,a;const{account:s,headers:o,headersToExclude:n,fetchOptions:c={}}=e,d=["principalUrl","rootUrl"];if(!x(s,d))throw new Error(`account must have ${C(s,d)} before fetchUserAddresses`);F(`Fetch user addresses from ${s.principalUrl}`);const l=(await v({url:s.principalUrl,props:{[`${exports.DAVNamespaceShort.CALDAV}:calendar-user-address-set`]:{}},depth:"0",headers:u(o,n),fetchOptions:c})).find((e=>i(s.principalUrl,e.href)));if(!l||!l.ok)throw new Error("cannot find calendarUserAddresses");const p=(null===(a=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===a?void 0:a.filter(Boolean))||[];return F(`Fetched calendar user addresses ${p}`),p},I=async e=>{const{url:t,props:r,filters:a,timezone:s,depth:o,headers:n,headersToExclude:c,fetchOptions:d={}}=e;return b({url:t,body:{"calendar-query":p({_attributes:l([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:u(n,c),fetchOptions:d})},z=async e=>{const{url:t,props:r,objectUrls:a,filters:s,timezone:o,depth:n,headers:c,headersToExclude:d,fetchOptions:i={}}=e;return b({url:t,body:{"calendar-multiget":p({_attributes:l([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:n,headers:u(c,d),fetchOptions:i})},Z=async e=>{const{url:t,props:r,depth:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e;return A({url:t,init:{method:"MKCALENDAR",headers:u(p({depth:a,...s}),o),namespace:exports.DAVNamespaceShort.DAV,body:{[`${exports.DAVNamespaceShort.CALDAV}:mkcalendar`]:{_attributes:l([exports.DAVNamespace.DAV,exports.DAVNamespace.CALDAV,exports.DAVNamespace.CALDAV_APPLE]),set:{prop:r}}}},fetchOptions:n})},q=async e=>{const{headers:t,account:r,props:a,projectedProps:s,headersToExclude:o,fetchOptions:c={}}=null!=e?e:{},d=["homeUrl","rootUrl"];if(!r||!x(r,d)){if(!r)throw new Error("no account for fetchCalendars");throw new Error(`account must have ${C(r,d)} 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:u(t,o),fetchOptions: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("calendar")})).filter((e=>{var t,r,a,s;return(Array.isArray(null===(t=e.props)||void 0===t?void 0:t.supportedCalendarComponentSet.comp)?null===(r=e.props)||void 0===r?void 0:r.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(s=null===(a=e.props)||void 0===a?void 0:a.supportedCalendarComponentSet.comp)||void 0===s?void 0:s._attributes.name]).some((e=>Object.values(n).includes(e)))})).map((e=>{var t,a,o,n,c,d,i,l,p,u,f,m,A,v,D,y;const O=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 O?O:"",timezone:"string"==typeof V?V:"",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===(p=e.props)||void 0===p?void 0:p.displayname,components:Array.isArray(null===(u=e.props)||void 0===u?void 0:u.supportedCalendarComponentSet.comp)?null===(f=e.props)||void 0===f?void 0:f.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(A=null===(m=e.props)||void 0===m?void 0:m.supportedCalendarComponentSet.comp)||void 0===A?void 0:A._attributes.name],resourcetype:Object.keys(null===(v=e.props)||void 0===v?void 0:v.resourcetype),syncToken:null===(D=e.props)||void 0===D?void 0:D.syncToken,...h("projectedProps",Object.fromEntries(Object.entries(null!==(y=e.props)&&void 0!==y?y:{}).filter((([e])=>null==s?void 0:s[e]))))}})).map((async e=>({...e,reports:await S({collection:e,headers:u(t,o),fetchOptions:c})}))))},Q=async e=>{const{calendar:t,objectUrls:r,filters:a,timeRange:s,headers:o,expand:n,urlFilter:c=e=>Boolean(null==e?void 0:e.includes(".ics")),useMultiGet:d=!0,headersToExclude:i,fetchOptions:l={}}=e;if(s){const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(s.start)&&e.test(s.end)||t.test(s.start)&&t.test(s.end)))throw new Error("invalid timeRange format, not in ISO8601")}F(`Fetching calendar objects from ${null==t?void 0:t.url}`);const p=["url"];if(!t||!x(t,p)){if(!t)throw new Error("cannot fetchCalendarObjects for undefined calendar");throw new Error(`calendar must have ${C(t,p)} before fetchCalendarObjects`)}const h=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`}}}:{}}}}],f=(null!=r?r:(await I({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{...n&&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:h,depth:"1",headers:u(o,i),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(c).map((e=>new URL(e).pathname));let m=[];return f.length>0&&(m=!d||n?await I({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CALDAV}:calendar-data`]:{...n&&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:h,depth:"1",headers:u(o,i),fetchOptions:l}):await z({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CALDAV}:calendar-data`]:{...n&&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:f,depth:"1",headers:u(o,i),fetchOptions:l})),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}}))},G=async e=>{const{calendar:t,iCalString:r,filename:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e;return D({url:new URL(a,t.url).href,data:r,headers:u({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*",...s},o),fetchOptions:n})},J=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={}}=e;return y({url:t.url,data:t.data,etag:t.etag,headers:u({"content-type":"text/calendar; charset=utf-8",...r},a),fetchOptions:s})},K=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={}}=e;return O({url:t.url,etag:t.etag,headers:u(r,a),fetchOptions:s})},W=async e=>{var t;const{oldCalendars:r,account:a,detailedResult:s,headers:o,headersToExclude:n,fetchOptions:c={}}=e;if(!a)throw new Error("Must have account before syncCalendars");const d=null!==(t=null!=r?r:a.calendars)&&void 0!==t?t:[],l=await q({account:a,headers:u(o,n),fetchOptions:c}),p=l.filter((e=>d.every((t=>!i(t.url,e.url)))));F(`new calendars: ${p.map((e=>e.displayName))}`);const h=d.reduce(((e,t)=>{const r=l.find((e=>i(e.url,t.url)));return r&&(r.syncToken&&`${r.syncToken}`!=`${t.syncToken}`||r.ctag&&`${r.ctag}`!=`${t.ctag}`)?[...e,r]:e}),[]);F(`updated calendars: ${h.map((e=>e.displayName))}`);const f=await Promise.all(h.map((async e=>await E({collection:{...e,objectMultiGet:z},method:"webdav",headers:u(o,n),account:a,fetchOptions:c})))),m=d.filter((e=>l.every((t=>!i(t.url,e.url)))));F(`deleted calendars: ${m.map((e=>e.displayName))}`);const A=d.filter((e=>l.some((t=>i(t.url,e.url)&&(t.syncToken&&`${t.syncToken}`!=`${e.syncToken}`||t.ctag&&`${t.ctag}`!=`${e.ctag}`)))));return s?{created:p,updated:h,deleted:m}:[...A,...p,...f]},Y=async e=>{const{url:t,timeRange:r,depth:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e;if(!r)throw new Error("timeRange is required");{const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(r.start)&&e.test(r.end)||t.test(r.start)&&t.test(r.end)))throw new Error("invalid timeRange format, not in ISO8601")}return(await b({url:t,body:{"free-busy-query":p({_attributes:l([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:u(s,o),fetchOptions:n}))[0]};var X=Object.freeze({__proto__:null,calendarMultiGet:z,calendarQuery:I,createCalendarObject:G,deleteCalendarObject:K,fetchCalendarObjects:Q,fetchCalendarUserAddresses:M,fetchCalendars:q,freeBusyQuery:Y,makeCalendar:Z,syncCalendars:W,updateCalendarObject:J});const ee=t("tsdav:account"),te=async e=>{var t,r;ee("Service discovery...");const{account:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e,c=new URL(a.serverUrl),d=new URL(`/.well-known/${a.accountType}`,c);d.protocol=null!==(t=c.protocol)&&void 0!==t?t:"http";try{const e=await fetch(d.href,{headers:u(s,o),method:"PROPFIND",redirect:"manual",...n});if(e.status>=300&&e.status<400){const t=e.headers.get("Location");if("string"==typeof t&&t.length){ee(`Service discovery redirected to ${t}`);const e=new URL(t,c);return e.hostname===d.hostname&&d.port&&!e.port&&(e.port=d.port),e.protocol=null!==(r=c.protocol)&&void 0!==r?r:"http",e.href}}}catch(e){ee(`Service discovery failed: ${e.stack}`)}return c.href},re=async e=>{var t,r,a,s,o;const{account:n,headers:c,headersToExclude:d,fetchOptions:i={}}=e,l=["rootUrl"];if(!x(n,l))throw new Error(`account must have ${C(n,l)} before fetchPrincipalUrl`);ee(`Fetching principal url from path ${n.rootUrl}`);const[p]=await v({url:n.rootUrl,props:{[`${exports.DAVNamespaceShort.DAV}:current-user-principal`]:{}},depth:"0",headers:u(c,d),fetchOptions:i});if(!p.ok&&(ee(`Fetch principal url failed: ${p.statusText}`),401===p.status))throw new Error("Invalid credentials");return ee(`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:"",n.rootUrl).href},ae=async e=>{var t,r;const{account:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e,c=["principalUrl","rootUrl"];if(!x(a,c))throw new Error(`account must have ${C(a,c)} before fetchHomeUrl`);ee(`Fetch home url from ${a.principalUrl}`);const d=(await v({url:a.principalUrl,props:"caldav"===a.accountType?{[`${exports.DAVNamespaceShort.CALDAV}:calendar-home-set`]:{}}:{[`${exports.DAVNamespaceShort.CARDDAV}:addressbook-home-set`]:{}},depth:"0",headers:u(s,o),fetchOptions:n})).find((e=>i(a.principalUrl,e.href)));if(!d||!d.ok)throw new Error("cannot find homeUrl");const l=new URL("caldav"===a.accountType?null===(t=null==d?void 0:d.props)||void 0===t?void 0:t.calendarHomeSet.href:null===(r=null==d?void 0:d.props)||void 0===r?void 0:r.addressbookHomeSet.href,a.rootUrl).href;return ee(`Fetched home url ${l}`),l},se=async e=>{const{account:t,headers:r,loadCollections:a=!1,loadObjects:s=!1,headersToExclude:o,fetchOptions:n={}}=e,c={...t};return c.rootUrl=await te({account:t,headers:u(r,o),fetchOptions:n}),c.principalUrl=await re({account:c,headers:u(r,o),fetchOptions:n}),c.homeUrl=await ae({account:c,headers:u(r,o),fetchOptions:n}),(a||s)&&("caldav"===t.accountType?c.calendars=await q({headers:u(r,o),account:c,fetchOptions:n}):"carddav"===t.accountType&&(c.addressBooks=await R({headers:u(r,o),account:c,fetchOptions:n}))),s&&("caldav"===t.accountType&&c.calendars?c.calendars=await Promise.all(c.calendars.map((async e=>({...e,objects:await Q({calendar:e,headers:u(r,o),fetchOptions:n})})))):"carddav"===t.accountType&&c.addressBooks&&(c.addressBooks=await Promise.all(c.addressBooks.map((async e=>({...e,objects:await j({addressBook:e,headers:u(r,o),fetchOptions:n})})))))),c};var oe=Object.freeze({__proto__:null,createAccount:se,fetchHomeUrl:ae,fetchPrincipalUrl:re,serviceDiscovery:te});const ne=t("tsdav:authHelper"),ce=(e,t)=>(...r)=>e({...t,...r[0]}),de=e=>(ne(`Basic auth token generated: ${a.encode(`${e.username}:${e.password}`)}`),{authorization:`Basic ${a.encode(`${e.username}:${e.password}`)}`}),ie=async(e,t)=>{const r=["authorizationCode","redirectUrl","clientId","clientSecret","tokenUrl"];if(!x(e,r))throw new Error(`Oauth credentials missing: ${C(e,r)}`);const a=new URLSearchParams({grant_type:"authorization_code",code:e.authorizationCode,redirect_uri:e.redirectUrl,client_id:e.clientId,client_secret:e.clientSecret});ne(e.tokenUrl),ne(a.toString());const s=await fetch(e.tokenUrl,{method:"POST",body:a.toString(),headers:{"content-length":`${a.toString().length}`,"content-type":"application/x-www-form-urlencoded"},...null!=t?t:{}});if(s.ok){return await s.json()}return ne(`Fetch Oauth tokens failed: ${await s.text()}`),{}},le=async(e,t)=>{const r=["refreshToken","clientId","clientSecret","tokenUrl"];if(!x(e,r))throw new Error(`Oauth credentials missing: ${C(e,r)}`);const a=new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,refresh_token:e.refreshToken,grant_type:"refresh_token"}),s=await fetch(e.tokenUrl,{method:"POST",body:a.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},...null!=t?t:{}});if(s.ok){return await s.json()}return ne(`Refresh access token failed: ${await s.text()}`),{}},pe=async(e,t)=>{var r;ne("Fetching oauth headers");let a={};return e.refreshToken?(e.refreshToken&&!e.accessToken||Date.now()>(null!==(r=e.expiration)&&void 0!==r?r:0))&&(a=await le(e,t)):a=await ie(e,t),ne(`Oauth tokens fetched: ${a.access_token}`),{tokens:a,headers:{authorization:`Bearer ${a.access_token}`}}};var he=Object.freeze({__proto__:null,defaultParam:ce,fetchOauthTokens:ie,getBasicAuthHeaders:de,getOauthHeaders:pe,refreshAccessToken:le});const ue=async e=>{var t;const{serverUrl:r,credentials:a,authMethod:s,defaultAccountType:o,authFunction:n}=e;let c={};switch(s){case"Basic":c=de(a);break;case"Oauth":c=(await pe(a)).headers;break;case"Digest":c={Authorization:`Digest ${a.digestString}`};break;case"Custom":c=null!==(t=await(null==n?void 0:n(a)))&&void 0!==t?t:{};break;default:throw new Error("Invalid auth method")}const d=o?await se({account:{serverUrl:r,credentials:a,accountType:o},headers:c}):void 0,i=ce(D,{url:r,headers:c}),l=ce(y,{headers:c,url:r}),p=ce(O,{headers:c,url:r}),h=ce(v,{headers:c}),u=ce(b,{headers:c}),f=ce(w,{headers:c}),m=ce($,{headers:c}),V=ce(S,{headers:c}),x=ce(N,{headers:c}),C=ce(E,{headers:c,account:d}),g=ce(I,{headers:c}),T=ce(z,{headers:c}),k=ce(Z,{headers:c}),B=ce(q,{headers:c,account:d}),F=ce(M,{headers:c,account:d}),Y=ce(Q,{headers:c}),X=ce(G,{headers:c}),ee=ce(J,{headers:c}),te=ce(K,{headers:c}),re=ce(W,{account:d,headers:c}),ae=ce(U,{headers:c}),oe=ce(_,{headers:c});return{davRequest:async e=>{const{init:t,...r}=e,{headers:a,...s}=t;return A({...r,init:{...s,headers:{...c,...a}}})},propfind:h,createAccount:async e=>{const{account:t,headers:s,loadCollections:o,loadObjects:n}=e;return se({account:{serverUrl:r,credentials:a,...t},headers:{...c,...s},loadCollections:o,loadObjects:n})},createObject:i,updateObject:l,deleteObject:p,calendarQuery:g,addressBookQuery:ae,collectionQuery:u,makeCollection:f,calendarMultiGet:T,makeCalendar:k,syncCollection:m,supportedReportSet:V,isCollectionDirty:x,smartCollectionSync:C,fetchCalendars:B,fetchCalendarUserAddresses:F,fetchCalendarObjects:Y,createCalendarObject:X,updateCalendarObject:ee,deleteCalendarObject:te,syncCalendars:re,fetchAddressBooks:ce(R,{account:d,headers:c}),addressBookMultiGet:oe,fetchVCards:ce(j,{headers:c}),createVCard:ce(L,{headers:c}),updateVCard:ce(H,{headers:c}),deleteVCard:ce(P,{headers:c})}};class fe{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:{}}async login(){var e;switch(this.authMethod){case"Basic":this.authHeaders=de(this.credentials);break;case"Oauth":this.authHeaders=(await pe(this.credentials,this.fetchOptions)).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 se({account:{serverUrl:this.serverUrl,credentials:this.credentials,accountType:this.accountType},headers:this.authHeaders,fetchOptions:this.fetchOptions}):void 0}async davRequest(e){const{init:t,...r}=e,{headers:a,...s}=t;return A({...r,init:{...s,headers:{...this.authHeaders,...a}},fetchOptions:this.fetchOptions})}async createObject(...e){return ce(D,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateObject(...e){return ce(y,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteObject(...e){return ce(O,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async propfind(...e){return ce(v,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createAccount(e){const{account:t,headers:r,loadCollections:a,loadObjects:s,fetchOptions:o}=e;return se({account:{serverUrl:this.serverUrl,credentials:this.credentials,...t},headers:{...this.authHeaders,...r},loadCollections:a,loadObjects:s,fetchOptions:null!=o?o:this.fetchOptions})}async collectionQuery(...e){return ce(b,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async makeCollection(...e){return ce(w,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async syncCollection(...e){return ce($,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async supportedReportSet(...e){return ce(S,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async isCollectionDirty(...e){return ce(N,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async smartCollectionSync(...e){return ce(E,{headers:this.authHeaders,fetchOptions:this.fetchOptions,account:this.account})(e[0])}async calendarQuery(...e){return ce(I,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async makeCalendar(...e){return ce(Z,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async calendarMultiGet(...e){return ce(z,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async fetchCalendars(...e){return ce(q,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(null==e?void 0:e[0])}async fetchCalendarUserAddresses(...e){return ce(M,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(null==e?void 0:e[0])}async fetchCalendarObjects(...e){return ce(Q,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createCalendarObject(...e){return ce(G,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateCalendarObject(...e){return ce(J,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteCalendarObject(...e){return ce(K,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async syncCalendars(...e){return ce(W,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(e[0])}async addressBookQuery(...e){return ce(U,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async addressBookMultiGet(...e){return ce(_,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async fetchAddressBooks(...e){return ce(R,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(null==e?void 0:e[0])}async fetchVCards(...e){return ce(j,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createVCard(...e){return ce(L,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateVCard(...e){return ce(H,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteVCard(...e){return ce(P,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}}var me=Object.freeze({__proto__:null,DAVClient:fe,createDAVClient:ue}),Ae={DAVNamespace:exports.DAVNamespace,DAVNamespaceShort:exports.DAVNamespaceShort,DAVAttributeMap:s,...me,...V,...T,...oe,...B,...X,...he,...f};exports.DAVAttributeMap=s,exports.DAVClient=fe,exports.addressBookQuery=U,exports.calendarMultiGet=z,exports.calendarQuery=I,exports.cleanupFalsy=p,exports.collectionQuery=b,exports.createAccount=se,exports.createCalendarObject=G,exports.createDAVClient=ue,exports.createObject=D,exports.createVCard=L,exports.davRequest=A,exports.default=Ae,exports.deleteCalendarObject=K,exports.deleteObject=O,exports.deleteVCard=P,exports.fetchAddressBooks=R,exports.fetchCalendarObjects=Q,exports.fetchCalendarUserAddresses=M,exports.fetchCalendars=q,exports.fetchOauthTokens=ie,exports.fetchVCards=j,exports.freeBusyQuery=Y,exports.getBasicAuthHeaders=de,exports.getDAVAttribute=l,exports.getOauthHeaders=pe,exports.isCollectionDirty=N,exports.makeCalendar=Z,exports.propfind=v,exports.refreshAccessToken=le,exports.smartCollectionSync=E,exports.supportedReportSet=S,exports.syncCalendars=W,exports.syncCollection=$,exports.updateCalendarObject=J,exports.updateObject=y,exports.updateVCard=H,exports.urlContains=i,exports.urlEquals=d; diff --git a/dist/tsdav.min.js b/dist/tsdav.min.js index bce6edba..40cfa3a0 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(e.__esModule)return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?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={exports:{}};!function(t,r){var n="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||void 0!==e&&e,i=function(){function e(){this.fetch=!1,this.DOMException=n.DOMException}return e.prototype=n,new e}();!function(e){!function(t){var r=void 0!==e&&e||"undefined"!=typeof self&&self||void 0!==r&&r,n="URLSearchParams"in r,i="Symbol"in r&&"iterator"in Symbol,a="FileReader"in r&&"Blob"in r&&function(){try{return new Blob,!0}catch(e){return!1}}(),o="FormData"in r,s="ArrayBuffer"in r;if(s)var c=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],u=ArrayBuffer.isView||function(e){return e&&c.indexOf(Object.prototype.toString.call(e))>-1};function l(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 h(e){return"string"!=typeof e&&(e=String(e)),e}function d(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return i&&(t[Symbol.iterator]=function(){return t}),t}function f(e){this.map={},e instanceof f?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function p(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));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 y(e){var t=new FileReader,r=g(t);return t.readAsArrayBuffer(e),r}function m(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function v(){return this.bodyUsed=!1,this._initBody=function(e){var t;this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:a&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:o&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:n&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():s&&a&&((t=e)&&DataView.prototype.isPrototypeOf(t))?(this._bodyArrayBuffer=m(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s&&(ArrayBuffer.prototype.isPrototypeOf(e)||u(e))?this._bodyArrayBuffer=m(e):this._bodyText=e=Object.prototype.toString.call(e):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):n&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},a&&(this.blob=function(){var e=p(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=p(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))}return this.blob().then(y)}),this.text=function(){var e,t,r,n=p(this);if(n)return n;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,r=g(t),t.readAsText(e),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,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 n=/([?&])_=[^&]*/;if(n.test(this.url))this.url=this.url.replace(n,"$1_="+(new Date).getTime());else{this.url+=(/\?/.test(this.url)?"&":"?")+"_="+(new Date).getTime()}}}function E(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 A(e,t){if(!(this instanceof A))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText=void 0===t.statusText?"":""+t.statusText,this.headers=new f(t.headers),this.url=t.url||"",this._initBody(e)}w.prototype.clone=function(){return new w(this,{body:this._bodyInit})},v.call(w.prototype),v.call(A.prototype),A.prototype.clone=function(){return new A(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new f(this.headers),url:this.url})},A.error=function(){var e=new A(null,{status:0,statusText:""});return e.type="error",e};var T=[301,302,303,307,308];A.redirect=function(e,t){if(-1===T.indexOf(t))throw new RangeError("Invalid status code");return new A(null,{status:t,headers:{location:e}})},t.DOMException=r.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function _(e,n){return new Promise((function(i,o){var c=new w(e,n);if(c.signal&&c.signal.aborted)return o(new t.DOMException("Aborted","AbortError"));var u=new XMLHttpRequest;function l(){u.abort()}u.onload=function(){var e,t,r={status:u.status,statusText:u.statusText,headers:(e=u.getAllResponseHeaders()||"",t=new f,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();t.append(n,i)}})),t)};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 A(n,r))}),0)},u.onerror=function(){setTimeout((function(){o(new TypeError("Network request failed"))}),0)},u.ontimeout=function(){setTimeout((function(){o(new TypeError("Network request failed"))}),0)},u.onabort=function(){setTimeout((function(){o(new t.DOMException("Aborted","AbortError"))}),0)},u.open(c.method,function(e){try{return""===e&&r.location.href?r.location.href:e}catch(t){return e}}(c.url),!0),"include"===c.credentials?u.withCredentials=!0:"omit"===c.credentials&&(u.withCredentials=!1),"responseType"in u&&(a?u.responseType="blob":s&&c.headers.get("Content-Type")&&-1!==c.headers.get("Content-Type").indexOf("application/octet-stream")&&(u.responseType="arraybuffer")),!n||"object"!=typeof n.headers||n.headers instanceof f?c.headers.forEach((function(e,t){u.setRequestHeader(t,e)})):Object.getOwnPropertyNames(n.headers).forEach((function(e){u.setRequestHeader(e,h(n.headers[e]))})),c.signal&&(c.signal.addEventListener("abort",l),u.onreadystatechange=function(){4===u.readyState&&c.signal.removeEventListener("abort",l)}),u.send(void 0===c._bodyInit?null:c._bodyInit)}))}_.polyfill=!0,r.fetch||(r.fetch=_,r.Headers=f,r.Request=w,r.Response=A),t.Headers=f,t.Request=w,t.Response=A,t.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}(n,n.exports);var i=n.exports,a="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function o(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}var c=o,u=s;function l(e){if(c===setTimeout)return setTimeout(e,0);if((c===o||!c)&&setTimeout)return c=setTimeout,setTimeout(e,0);try{return c(e,0)}catch(t){try{return c.call(null,e,0)}catch(t){return c.call(this,e,0)}}}"function"==typeof a.setTimeout&&(c=setTimeout),"function"==typeof a.clearTimeout&&(u=clearTimeout);var h,d=[],f=!1,p=-1;function g(){f&&h&&(f=!1,h.length?d=h.concat(d):p=-1,d.length&&y())}function y(){if(!f){var e=l(g);f=!0;for(var t=d.length;t;){for(h=d,d=[];++p1)for(var r=1;r=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}return F=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))},F}var I=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){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t{"%%"!==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")}catch(e){}!e&&"env"in N&&(e=N.env.DEBUG);return 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=I(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(L,L.exports);var U,P=t(L.exports);!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:"}(U||(U={}));const j={[U.CALDAV]:"xmlns:c",[U.CARDDAV]:"xmlns:card",[U.CALENDAR_SERVER]:"xmlns:cs",[U.CALDAV_APPLE]:"xmlns:ca",[U.DAV]:"xmlns:d"};var B,V;!function(e){e.CALDAV="c",e.CARDDAV="card",e.CALENDAR_SERVER="cs",e.CALDAV_APPLE="ca",e.DAV="d"}(B||(B={})),function(e){e.VEVENT="VEVENT",e.VTODO="VTODO",e.VJOURNAL="VJOURNAL",e.VFREEBUSY="VFREEBUSY",e.VTIMEZONE="VTIMEZONE",e.VALARM="VALARM"}(V||(V={}));var M=[],$=[],K="undefined"!=typeof Uint8Array?Uint8Array:Array,H=!1;function Y(){H=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0;t<64;++t)M[t]=e[t],$[e.charCodeAt(t)]=t;$["-".charCodeAt(0)]=62,$["_".charCodeAt(0)]=63}function q(e,t,r){for(var n,i,a=[],o=t;o>18&63]+M[i>>12&63]+M[i>>6&63]+M[63&i]);return a.join("")}function z(e){var t;H||Y();for(var r=e.length,n=r%3,i="",a=[],o=16383,s=0,c=r-n;sc?c:s+o));return 1===n?(t=e[r-1],i+=M[t>>2],i+=M[t<<4&63],i+="=="):2===n&&(t=(e[r-2]<<8)+e[r-1],i+=M[t>>10],i+=M[t>>4&63],i+=M[t<<2&63],i+="="),a.push(i),a.join("")}function G(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 W(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,g=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*g}var Q={}.toString,X=Array.isArray||function(e){return"[object Array]"==Q.call(e)};function Z(){return ee.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function J(e,t){if(Z()=Z())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Z().toString(16)+" bytes");return 0|e}function oe(e){return!(null==e||!e._isBuffer)}function se(e,t){if(oe(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 ke(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Ie(e).length;default:if(n)return ke(e).length;t=(""+t).toLowerCase(),n=!0}}function ce(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 Te(this,t,r);case"utf8":case"utf-8":return be(this,t,r);case"ascii":return Ee(this,t,r);case"latin1":case"binary":return Ae(this,t,r);case"base64":return ve(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _e(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function ue(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function le(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=ee.from(t,n)),oe(t))return 0===t.length?-1:he(e,t,r,n,i);if("number"==typeof t)return t&=255,ee.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):he(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function he(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 ve(e,t,r){return 0===t&&r===e.length?z(e):z(e.slice(t,r))}function be(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<=we)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+=" ... ")),""},ee.prototype.compare=function(e,t,r,n,i){if(!oe(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 de(this,e,t,r);case"utf8":case"utf-8":return fe(this,e,t,r);case"ascii":return pe(this,e,t,r);case"latin1":case"binary":return ge(this,e,t,r);case"base64":return ye(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return me(this,e,t,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},ee.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var we=4096;function Ee(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 Oe(e,t,r,n,i,a){if(!oe(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function De(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 xe(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 Re(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 Fe(e,t,r,n,i){return i||Re(e,0,r,4),W(e,t,r,n,23,4),r+4}function Se(e,t,r,n,i){return i||Re(e,0,r,8),W(e,t,r,n,52,8),r+8}ee.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},ee.prototype.readUInt8=function(e,t){return t||Ce(e,1,this.length),this[e]},ee.prototype.readUInt16LE=function(e,t){return t||Ce(e,2,this.length),this[e]|this[e+1]<<8},ee.prototype.readUInt16BE=function(e,t){return t||Ce(e,2,this.length),this[e]<<8|this[e+1]},ee.prototype.readUInt32LE=function(e,t){return t||Ce(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},ee.prototype.readUInt32BE=function(e,t){return t||Ce(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},ee.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||Ce(e,t,this.length);for(var n=this[e],i=1,a=0;++a=(i*=128)&&(n-=Math.pow(2,8*t)),n},ee.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||Ce(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},ee.prototype.readInt8=function(e,t){return t||Ce(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},ee.prototype.readInt16LE=function(e,t){t||Ce(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},ee.prototype.readInt16BE=function(e,t){t||Ce(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},ee.prototype.readInt32LE=function(e,t){return t||Ce(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},ee.prototype.readInt32BE=function(e,t){return t||Ce(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},ee.prototype.readFloatLE=function(e,t){return t||Ce(e,4,this.length),G(this,e,!0,23,4)},ee.prototype.readFloatBE=function(e,t){return t||Ce(e,4,this.length),G(this,e,!1,23,4)},ee.prototype.readDoubleLE=function(e,t){return t||Ce(e,8,this.length),G(this,e,!0,52,8)},ee.prototype.readDoubleBE=function(e,t){return t||Ce(e,8,this.length),G(this,e,!1,52,8)},ee.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t|=0,r|=0,n)||Oe(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},ee.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||Oe(this,e,t,1,255,0),ee.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},ee.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||Oe(this,e,t,2,65535,0),ee.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):De(this,e,t,!0),t+2},ee.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||Oe(this,e,t,2,65535,0),ee.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):De(this,e,t,!1),t+2},ee.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||Oe(this,e,t,4,4294967295,0),ee.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):xe(this,e,t,!0),t+4},ee.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||Oe(this,e,t,4,4294967295,0),ee.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):xe(this,e,t,!1),t+4},ee.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);Oe(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},ee.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||Oe(this,e,t,1,127,-128),ee.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},ee.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||Oe(this,e,t,2,32767,-32768),ee.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):De(this,e,t,!0),t+2},ee.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||Oe(this,e,t,2,32767,-32768),ee.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):De(this,e,t,!1),t+2},ee.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||Oe(this,e,t,4,2147483647,-2147483648),ee.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):xe(this,e,t,!0),t+4},ee.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||Oe(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),ee.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):xe(this,e,t,!1),t+4},ee.prototype.writeFloatLE=function(e,t,r){return Fe(this,e,t,!0,r)},ee.prototype.writeFloatBE=function(e,t,r){return Fe(this,e,t,!1,r)},ee.prototype.writeDoubleLE=function(e,t,r){return Se(this,e,t,!0,r)},ee.prototype.writeDoubleBE=function(e,t,r){return Se(this,e,t,!1,r)},ee.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||!ee.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 Ie(e){return function(e){var t,r,n,i,a,o;H||Y();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 K(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=$[e.charCodeAt(t)]<<2|$[e.charCodeAt(t+1)]>>4,o[c++]=255&i):1===a&&(i=$[e.charCodeAt(t)]<<10|$[e.charCodeAt(t+1)]<<4|$[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(Ne,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Ue(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function Pe(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}var je,Be={};function Ve(){}function Me(){Me.init.call(this)}function $e(e){return void 0===e._maxListeners?Me.defaultMaxListeners:e._maxListeners}function Ke(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 Ve,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=$e(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 He(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 Ye(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 qe(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}Ve.prototype=Object.create(null),Me.EventEmitter=Me,Me.usingDomains=!1,Me.prototype.domain=void 0,Me.prototype._events=void 0,Me.prototype._maxListeners=void 0,Me.defaultMaxListeners=10,Me.init=function(){this.domain=null,Me.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new Ve,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Me.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},Me.prototype.getMaxListeners=function(){return $e(this)},Me.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=qe(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 Ve,this;delete n[e]}else!function(e,t){for(var r=t,n=r+1,i=e.length;n0?Reflect.ownKeys(this._events):[]},je="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 ze=/%[sdj%]/g;function Ge(e){if(!ot(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]),it(t)?r.showHidden=t:t&&function(e,t){if(!t||!ut(t))return e;var r=Object.keys(t),n=r.length;for(;n--;)e[r[n]]=t[r[n]]}(r,t),st(r.showHidden)&&(r.showHidden=!1),st(r.depth)&&(r.depth=2),st(r.colors)&&(r.colors=!1),st(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=Je),tt(r,e,r.depth)}function Je(e,t){var r=Ze.styles[t];return r?"["+Ze.colors[r][0]+"m"+e+"["+Ze.colors[r][1]+"m":e}function et(e,t){return e}function tt(e,t,r){if(e.customInspect&&t&&dt(t.inspect)&&t.inspect!==Ze&&(!t.constructor||t.constructor.prototype!==t)){var n=t.inspect(r,e);return ot(n)||(n=tt(e,n,r)),n}var i=function(e,t){if(st(t))return e.stylize("undefined","undefined");if(ot(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(it(t))return e.stylize(""+t,"boolean");if(at(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)),ht(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return rt(t);if(0===a.length){if(dt(t)){var s=t.name?": "+t.name:"";return e.stylize("[Function"+s+"]","special")}if(ct(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(lt(t))return e.stylize(Date.prototype.toString.call(t),"date");if(ht(t))return rt(t)}var c,u,l="",h=!1,d=["{","}"];(c=t,Array.isArray(c)&&(h=!0,d=["[","]"]),dt(t))&&(l=" [Function"+(t.name?": "+t.name:"")+"]");return ct(t)&&(l=" "+RegExp.prototype.toString.call(t)),lt(t)&&(l=" "+Date.prototype.toUTCString.call(t)),ht(t)&&(l=" "+rt(t)),0!==a.length||h&&0!=t.length?r<0?ct(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 rt(e){return"["+Error.prototype.toString.call(e)+"]"}function nt(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")),pt(n,i)||(o="["+i+"]"),s||(e.seen.indexOf(c.value)<0?(s=at(r)?tt(e,c.value,null):tt(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")),st(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 it(e){return"boolean"==typeof e}function at(e){return null===e}function ot(e){return"string"==typeof e}function st(e){return void 0===e}function ct(e){return ut(e)&&"[object RegExp]"===ft(e)}function ut(e){return"object"==typeof e&&null!==e}function lt(e){return ut(e)&&"[object Date]"===ft(e)}function ht(e){return ut(e)&&("[object Error]"===ft(e)||e instanceof Error)}function dt(e){return"function"==typeof e}function ft(e){return Object.prototype.toString.call(e)}function pt(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function gt(){this.head=null,this.tail=null,this.length=0}Ze.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]},Ze.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},gt.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},gt.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},gt.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}},gt.prototype.clear=function(){this.head=this.tail=null,this.length=0},gt.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},gt.prototype.concat=function(e){if(0===this.length)return ee.alloc(0);if(1===this.length)return this.head.data;for(var t=ee.allocUnsafe(e>>>0),r=this.head,n=0;r;)r.data.copy(t,n),n+=r.data.length,r=r.next;return t};var yt=ee.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 mt(e){switch(this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),function(e){if(e&&!yt(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=bt;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=wt;break;default:return void(this.write=vt)}this.charBuffer=new ee(6),this.charReceived=0,this.charLength=0}function vt(e){return e.toString(this.encoding)}function bt(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function wt(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}mt.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},mt.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},mt.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};var Et=Object.freeze({__proto__:null,StringDecoder:mt});_t.ReadableState=Tt;var At=function(e){if(st(Qe)&&(Qe=N.env.NODE_DEBUG||""),e=e.toUpperCase(),!Xe[e])if(new RegExp("\\b"+e+"\\b","i").test(Qe)){Xe[e]=function(){var t=Ge.apply(null,arguments);console.error("%s %d: %s",e,0,t)}}else Xe[e]=function(){};return Xe[e]}("stream");function Tt(e,t){e=e||{},this.objectMode=!!e.objectMode,t instanceof Zt&&(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 gt,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 mt(e.encoding),this.encoding=e.encoding)}function _t(e){if(!(this instanceof _t))return new _t(e);this._readableState=new Tt(e,this),this.readable=!0,e&&"function"==typeof e.read&&(this._read=e.read),Me.call(this)}function Ct(e,t,r,n,i){var a=function(e,t){var r=null;ee.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,xt(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&&xt(e))),function(e,t){t.readingMore||(t.readingMore=!0,m(Ft,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>=Ot?e=Ot:(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 xt(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(At("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?m(Rt,e):Rt(e))}function Rt(e){At("emit readable"),e.emit("readable"),Lt(e)}function Ft(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=ee.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 It(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,m(Ut,t,e))}function Ut(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function Pt(e,t){for(var r=0,n=e.length;r=t.highWaterMark||t.ended))return At("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?It(this):xt(this),null;if(0===(e=Dt(e,t))&&t.ended)return 0===t.length&&It(this),null;var n,i=t.needReadable;return At("need readable",i),(0===t.length||t.length-e0?kt(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&It(this)),null!==n&&this.emit("data",n),n},_t.prototype._read=function(e){this.emit("error",new Error("not implemented"))},_t.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,At("pipe count=%d opts=%j",n.pipesCount,t);var i=!t||!1!==t.end?o:u;function a(e){At("onunpipe"),e===r&&u()}function o(){At("onend"),e.end()}n.endEmitted?m(i):r.once("end",i),e.on("unpipe",a);var s=function(e){return function(){var t=e._readableState;At("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&e.listeners("data").length&&(t.flowing=!0,Lt(e))}}(r);e.on("drain",s);var c=!1;function u(){At("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){At("ondata"),l=!1,!1!==e.write(t)||l||((1===n.pipesCount&&n.pipes===e||n.pipesCount>1&&-1!==Pt(n.pipes,e))&&!c&&(At("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,l=!0),r.pause())}function d(t){var r;At("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(){At("onfinish"),e.removeListener("close",f),g()}function g(){At("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||(At("pipe resume"),r.resume()),e},_t.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},Mt.prototype._write=function(e,t,r){r(new Error("not implemented"))},Mt.prototype._writev=null,Mt.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,zt(e,t),r&&(t.finished?m(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,n,r)},je(Zt,_t);for(var Wt=Object.keys(Mt.prototype),Qt=0;Qt"===a?(O(n,"onsgmldeclaration",n.sgmlDecl),n.sgmlDecl="",n.state=T.TEXT):y(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,O(n,"ondoctype",n.doctype),n.doctype=!0):(n.doctype+=a,"["===a?n.state=T.DOCTYPE_DTD:y(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):y(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&&O(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:"]"===a?n.state=T.CDATA_ENDING:n.cdata+=a;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&&O(n,"oncdata",n.cdata),O(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:g(a)?n.state=T.PROC_INST_BODY:n.procInstName+=a;continue;case T.PROC_INST_BODY:if(!n.procInstBody&&g(a))continue;"?"===a?n.state=T.PROC_INST_ENDING:n.procInstBody+=a;continue;case T.PROC_INST_ENDING:">"===a?(O(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:(g(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(g(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)):g(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(g(a))continue;S(n,"Attribute without value"),n.tag.attributes[n.attribName]="",n.attribValue="",O(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(g(a))continue;y(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:g(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":O(t,"oncdata",t.cdata),t.cdata="";break;case"script":O(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&&(O(e,"oncdata",e.cdata),e.cdata=""),""!==e.script&&(O(e,"onscript",e.script),e.script="")}};try{t=or.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){if("function"==typeof ee.isBuffer&&ee.isBuffer(e)){if(!this._decoder){var t=sr.StringDecoder;this._decoder=new t("utf8")}e=this._decoder.write(e)}return this._parser.write(e.toString()),this.emit("data",e),!0},a.prototype.end=function(e){return e&&e.length&&this.write(e),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 g(e){return" "===e||"\n"===e||"\r"===e||"\t"===e}function y(e){return'"'===e||"'"===e}function m(e){return">"===e||g(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 _ 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[_]]=_;function C(e,t,r){e[t]&&e[t](r)}function O(e,t,r){e.textNode&&D(e),C(e,t,r)}function D(e){e.textNode=x(e.opt,e.textNode),e.textNode&&C(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,C(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,C(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,O(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,O(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){O(e,"onopennamespace",{prefix:t,uri:r.ns[t]})}));for(var a=0,o=e.attribList.length;a",e.tagName="",void(e.state=T.SCRIPT);O(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,O(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];O(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?(S(e,"Invalid character entity"),"&"+e.entity+";"):String.fromCodePoint(t))}function j(e,t){"<"===t?(e.state=T.OPEN_WAKA,e.startTagPosition=e.position):g(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)}(Be);var cr,ur,lr=function(e){return Array.isArray?Array.isArray(e):"[object Array]"===Object.prototype.toString.call(e)},hr=lr,dr={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(e){"alwaysArray"in e&&("boolean"==typeof e.alwaysArray||hr(e.alwaysArray))||(e.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}},fr=Be,pr=dr,gr=lr;function yr(e){var t=Number(e);if(!isNaN(t))return t;var r=e.toLowerCase();return"true"===r||"false"!==r&&e}function mr(e,t){var r;if(cr.compact){if(!ur[cr[e+"Key"]]&&(gr(cr.alwaysArray)?-1!==cr.alwaysArray.indexOf(cr[e+"Key"]):cr.alwaysArray)&&(ur[cr[e+"Key"]]=[]),ur[cr[e+"Key"]]&&!gr(ur[cr[e+"Key"]])&&(ur[cr[e+"Key"]]=[ur[cr[e+"Key"]]]),e+"Fn"in cr&&"string"==typeof t&&(t=cr[e+"Fn"](t,ur)),"instruction"===e&&("instructionFn"in cr||"instructionNameFn"in cr))for(r in t)if(t.hasOwnProperty(r))if("instructionFn"in cr)t[r]=cr.instructionFn(t[r],r,ur);else{var n=t[r];delete t[r],t[cr.instructionNameFn(r,n,ur)]=n}gr(ur[cr[e+"Key"]])?ur[cr[e+"Key"]].push(t):ur[cr[e+"Key"]]=t}else{ur[cr.elementsKey]||(ur[cr.elementsKey]=[]);var i={};if(i[cr.typeKey]=e,"instruction"===e){for(r in t)if(t.hasOwnProperty(r))break;i[cr.nameKey]="instructionNameFn"in cr?cr.instructionNameFn(r,t,ur):r,cr.instructionHasAttributes?(i[cr.attributesKey]=t[r][cr.attributesKey],"instructionFn"in cr&&(i[cr.attributesKey]=cr.instructionFn(i[cr.attributesKey],r,ur))):("instructionFn"in cr&&(t[r]=cr.instructionFn(t[r],r,ur)),i[cr.instructionKey]=t[r])}else e+"Fn"in cr&&(t=cr[e+"Fn"](t,ur)),i[cr[e+"Key"]]=t;cr.addParent&&(i[cr.parentKey]=ur),ur[cr.elementsKey].push(i)}}function vr(e){var t;if("attributesFn"in cr&&e&&(e=cr.attributesFn(e,ur)),(cr.trim||"attributeValueFn"in cr||"attributeNameFn"in cr||cr.nativeTypeAttributes)&&e)for(t in e)if(e.hasOwnProperty(t)&&(cr.trim&&(e[t]=e[t].trim()),cr.nativeTypeAttributes&&(e[t]=yr(e[t])),"attributeValueFn"in cr&&(e[t]=cr.attributeValueFn(e[t],t,ur)),"attributeNameFn"in cr)){var r=e[t];delete e[t],e[cr.attributeNameFn(t,e[t],ur)]=r}return e}function br(e){var t={};if(e.body&&("xml"===e.name.toLowerCase()||cr.instructionHasAttributes)){for(var r,n=/([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\w+))\s*/g;null!==(r=n.exec(e.body));)t[r[1]]=r[2]||r[3]||r[4];t=vr(t)}if("xml"===e.name.toLowerCase()){if(cr.ignoreDeclaration)return;ur[cr.declarationKey]={},Object.keys(t).length&&(ur[cr.declarationKey][cr.attributesKey]=t),cr.addParent&&(ur[cr.declarationKey][cr.parentKey]=ur)}else{if(cr.ignoreInstruction)return;cr.trim&&(e.body=e.body.trim());var i={};cr.instructionHasAttributes&&Object.keys(t).length?(i[e.name]={},i[e.name][cr.attributesKey]=t):i[e.name]=e.body,mr("instruction",i)}}function wr(e,t){var r;if("object"==typeof e&&(t=e.attributes,e=e.name),t=vr(t),"elementNameFn"in cr&&(e=cr.elementNameFn(e,ur)),cr.compact){var n;if(r={},!cr.ignoreAttributes&&t&&Object.keys(t).length)for(n in r[cr.attributesKey]={},t)t.hasOwnProperty(n)&&(r[cr.attributesKey][n]=t[n]);!(e in ur)&&(gr(cr.alwaysArray)?-1!==cr.alwaysArray.indexOf(e):cr.alwaysArray)&&(ur[e]=[]),ur[e]&&!gr(ur[e])&&(ur[e]=[ur[e]]),gr(ur[e])?ur[e].push(r):ur[e]=r}else ur[cr.elementsKey]||(ur[cr.elementsKey]=[]),(r={})[cr.typeKey]="element",r[cr.nameKey]=e,!cr.ignoreAttributes&&t&&Object.keys(t).length&&(r[cr.attributesKey]=t),cr.alwaysChildren&&(r[cr.elementsKey]=[]),ur[cr.elementsKey].push(r);r[cr.parentKey]=ur,ur=r}function Er(e){cr.ignoreText||(e.trim()||cr.captureSpacesBetweenElements)&&(cr.trim&&(e=e.trim()),cr.nativeType&&(e=yr(e)),cr.sanitize&&(e=e.replace(/&/g,"&").replace(//g,">")),mr("text",e))}function Ar(e){cr.ignoreComment||(cr.trim&&(e=e.trim()),mr("comment",e))}function Tr(e){var t=ur[cr.parentKey];cr.addParent||delete ur[cr.parentKey],ur=t}function _r(e){cr.ignoreCdata||(cr.trim&&(e=e.trim()),mr("cdata",e))}function Cr(e){cr.ignoreDoctype||(e=e.replace(/^ /,""),cr.trim&&(e=e.trim()),mr("doctype",e))}function Or(e){e.note=e}var Dr=function(e,t){var r=fr.parser(!0,{}),n={};if(ur=n,cr=function(e){return cr=pr.copyOptions(e),pr.ensureFlagExists("ignoreDeclaration",cr),pr.ensureFlagExists("ignoreInstruction",cr),pr.ensureFlagExists("ignoreAttributes",cr),pr.ensureFlagExists("ignoreText",cr),pr.ensureFlagExists("ignoreComment",cr),pr.ensureFlagExists("ignoreCdata",cr),pr.ensureFlagExists("ignoreDoctype",cr),pr.ensureFlagExists("compact",cr),pr.ensureFlagExists("alwaysChildren",cr),pr.ensureFlagExists("addParent",cr),pr.ensureFlagExists("trim",cr),pr.ensureFlagExists("nativeType",cr),pr.ensureFlagExists("nativeTypeAttributes",cr),pr.ensureFlagExists("sanitize",cr),pr.ensureFlagExists("instructionHasAttributes",cr),pr.ensureFlagExists("captureSpacesBetweenElements",cr),pr.ensureAlwaysArrayExists(cr),pr.ensureKeyExists("declaration",cr),pr.ensureKeyExists("instruction",cr),pr.ensureKeyExists("attributes",cr),pr.ensureKeyExists("text",cr),pr.ensureKeyExists("comment",cr),pr.ensureKeyExists("cdata",cr),pr.ensureKeyExists("doctype",cr),pr.ensureKeyExists("type",cr),pr.ensureKeyExists("name",cr),pr.ensureKeyExists("elements",cr),pr.ensureKeyExists("parent",cr),pr.checkFnExists("doctype",cr),pr.checkFnExists("instruction",cr),pr.checkFnExists("cdata",cr),pr.checkFnExists("comment",cr),pr.checkFnExists("text",cr),pr.checkFnExists("instructionName",cr),pr.checkFnExists("elementName",cr),pr.checkFnExists("attributeName",cr),pr.checkFnExists("attributeValue",cr),pr.checkFnExists("attributes",cr),cr}(t),r.opt={strictEntities:!0},r.onopentag=wr,r.ontext=Er,r.oncomment=Ar,r.onclosetag=Tr,r.onerror=Or,r.oncdata=_r,r.ondoctype=Cr,r.onprocessinginstruction=br,r.write(e).close(),n[cr.elementsKey]){var i=n[cr.elementsKey];delete n[cr.elementsKey],n[cr.elementsKey]=i,delete n.text}return n},xr=dr,Rr=Dr;var Fr,Sr,Nr=dr,Lr=lr;function kr(e,t,r){return(!r&&e.spaces?"\n":"")+Array(t+1).join(e.spaces)}function Ir(e,t,r){if(t.ignoreAttributes)return"";"attributesFn"in t&&(e=t.attributesFn(e,Sr,Fr));var n,i,a,o,s=[];for(n in e)e.hasOwnProperty(n)&&null!==e[n]&&void 0!==e[n]&&(o=t.noQuotesForNativeAttributes&&"string"!=typeof e[n]?"":'"',i=(i=""+e[n]).replace(/"/g,"""),a="attributeNameFn"in t?t.attributeNameFn(n,i,Sr,Fr):n,s.push(t.spaces&&t.indentAttributes?kr(t,r+1,!1):" "),s.push(a+"="+o+("attributeValueFn"in t?t.attributeValueFn(i,n,Sr,Fr):i)+o));return e&&Object.keys(e).length&&t.spaces&&t.indentAttributes&&s.push(kr(t,r,!1)),s.join("")}function Ur(e,t,r){return Fr=e,Sr="xml",t.ignoreDeclaration?"":""}function Pr(e,t,r){if(t.ignoreInstruction)return"";var n;for(n in e)if(e.hasOwnProperty(n))break;var i="instructionNameFn"in t?t.instructionNameFn(n,e[n],Sr,Fr):n;if("object"==typeof e[n])return Fr=e,Sr=i,"";var a=e[n]?e[n]:"";return"instructionFn"in t&&(a=t.instructionFn(a,n,Sr,Fr)),""}function jr(e,t){return t.ignoreComment?"":"\x3c!--"+("commentFn"in t?t.commentFn(e,Sr,Fr):e)+"--\x3e"}function Br(e,t){return t.ignoreCdata?"":"","]]]]>"))+"]]>"}function Vr(e,t){return t.ignoreDoctype?"":""}function Mr(e,t){return t.ignoreText?"":(e=(e=(e=""+e).replace(/&/g,"&")).replace(/&/g,"&").replace(//g,">"),"textFn"in t?t.textFn(e,Sr,Fr):e)}function $r(e,t,r,n){return e.reduce((function(e,i){var a=kr(t,r,n&&!e);switch(i.type){case"element":return e+a+function(e,t,r){Fr=e,Sr=e.name;var n=[],i="elementNameFn"in t?t.elementNameFn(e.name,e):e.name;n.push("<"+i),e[t.attributesKey]&&n.push(Ir(e[t.attributesKey],t,r));var a=e[t.elementsKey]&&e[t.elementsKey].length||e[t.attributesKey]&&"preserve"===e[t.attributesKey]["xml:space"];return a||(a="fullTagEmptyElementFn"in t?t.fullTagEmptyElementFn(e.name,e):t.fullTagEmptyElement),a?(n.push(">"),e[t.elementsKey]&&e[t.elementsKey].length&&(n.push($r(e[t.elementsKey],t,r+1)),Fr=e,Sr=e.name),n.push(t.spaces&&function(e,t){var r;if(e.elements&&e.elements.length)for(r=0;r")):n.push("/>"),n.join("")}(i,t,r);case"comment":return e+a+jr(i[t.commentKey],t);case"doctype":return e+a+Vr(i[t.doctypeKey],t);case"cdata":return e+(t.indentCdata?a:"")+Br(i[t.cdataKey],t);case"text":return e+(t.indentText?a:"")+Mr(i[t.textKey],t);case"instruction":var o={};return o[i[t.nameKey]]=i[t.attributesKey]?i:i[t.instructionKey],e+(t.indentInstruction?a:"")+Pr(o,t,r)}}),"")}function Kr(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 Hr(e,t,r,n,i){Fr=e,Sr=t;var a="elementNameFn"in r?r.elementNameFn(t,e):t;if(null==e||""===e)return"fullTagEmptyElementFn"in r&&r.fullTagEmptyElementFn(t,e)||r.fullTagEmptyElement?"<"+a+">":"<"+a+"/>";var o=[];if(t){if(o.push("<"+a),"object"!=typeof e)return o.push(">"+Mr(e,r)+""),o.join("");e[r.attributesKey]&&o.push(Ir(e[r.attributesKey],r,n));var s=Kr(e,r,!0)||e[r.attributesKey]&&"preserve"===e[r.attributesKey]["xml:space"];if(s||(s="fullTagEmptyElementFn"in r?r.fullTagEmptyElementFn(t,e):r.fullTagEmptyElement),!s)return o.push("/>"),o.join("");o.push(">")}return o.push(Yr(e,r,n+1,!1)),Fr=e,Sr=t,t&&o.push((i?kr(r,n,!1):"")+""),o.join("")}function Yr(e,t,r,n){var i,a,o,s=[];for(a in e)if(e.hasOwnProperty(a))for(o=Lr(e[a])?e[a]:[e[a]],i=0;i{const t=Number(e);if(!Number.isNaN(t))return t;const r=e.toLowerCase();return"true"===r||"false"!==r&&e},Zr=(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)},Jr=(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)},en=e=>e.reduce(((e,t)=>({...e,[j[t]]:t})),{}),tn=e=>Object.entries(e).reduce(((e,[t,r])=>r?{...e,[t]:r}:e),{}),rn=(e,t)=>t?{[e]:t}:{},nn=(e,t)=>e?t&&0!==t.length?Object.fromEntries(Object.entries(e).filter((([e])=>!t.includes(e)))):e:{};var an=Object.freeze({__proto__:null,cleanupFalsy:tn,conditionalParam:rn,excludeHeaders:nn,getDAVAttribute:en,urlContains:Jr,urlEquals:Zr});const on=P("tsdav:request"),sn=async e=>{var t;const{url:r,init:n,convertIncoming:a=!0,parseOutgoing:o=!0,fetchOptions:s={}}=e,{headers:c={},body:u,namespace:l,method:h,attributes:d}=n,f=a?Qr.js2xml({_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}},...u,_attributes:d},{compact:!0,spaces:2,elementNameFn:e=>l&&!/^.+:.+/.test(e)?`${l}:${e}`:e}):u,p=await i.fetch(r,{headers:{"Content-Type":"text/xml;charset=UTF-8",...tn(c)},body:f,method:h,...s}),g=await p.text();if(!p.ok||!(null===(t=p.headers.get("content-type"))||void 0===t?void 0:t.includes("xml"))||!o)return[{href:p.url,ok:p.ok,status:p.status,statusText:p.statusText,raw:g}];const y=Qr.xml2js(g,{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]=Xr(e)}else r[i]=Xr(e)}catch(e){on(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(y.multistatus.response)?y.multistatus.response:[y.multistatus.response]).map((e=>{var t,r;if(!e)return{status:p.status,statusText:p.statusText,ok:p.ok};const n=/^\S+\s(?\d+)\s(?.+)$/.exec(e.status);return{raw:y,href:e.href,status:(null==n?void 0:n.groups)?Number.parseInt(null==n?void 0:n.groups.status,10):p.status,statusText:null!==(r=null===(t=null==n?void 0:n.groups)||void 0===t?void 0:t.statusText)&&void 0!==r?r:p.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})),{})}}))},cn=async e=>{const{url:t,props:r,depth:n,headers:i,headersToExclude:a,fetchOptions:o={}}=e;return sn({url:t,init:{method:"PROPFIND",headers:nn(tn({depth:n,...i}),a),namespace:B.DAV,body:{propfind:{_attributes:en([U.CALDAV,U.CALDAV_APPLE,U.CALENDAR_SERVER,U.CARDDAV,U.DAV]),prop:r}}},fetchOptions:o})},un=async e=>{const{url:t,data:r,headers:n,headersToExclude:a,fetchOptions:o={}}=e;return i.fetch(t,{method:"PUT",body:r,headers:nn(n,a),...o})},ln=async e=>{const{url:t,data:r,etag:n,headers:a,headersToExclude:o,fetchOptions:s={}}=e;return i.fetch(t,{method:"PUT",body:r,headers:nn(tn({"If-Match":n,...a}),o),...s})},hn=async e=>{const{url:t,headers:r,etag:n,headersToExclude:a,fetchOptions:o={}}=e;return i.fetch(t,{method:"DELETE",headers:nn(tn({"If-Match":n,...r}),a),...o})};var dn=Object.freeze({__proto__:null,createObject:un,davRequest:sn,deleteObject:hn,propfind:cn,updateObject:ln});function fn(e,t){const r=e=>t.every((t=>e[t]));return Array.isArray(e)?e.every((e=>r(e))):r(e)}const pn=(e,t)=>t.reduce(((t,r)=>e[r]?t:`${t.length?`${t},`:""}${r.toString()}`),""),gn=P("tsdav:collection"),yn=async e=>{const{url:t,body:r,depth:n,defaultNamespace:i=B.DAV,headers:a,headersToExclude:o,fetchOptions:s={}}=e,c=await sn({url:t,init:{method:"REPORT",headers:nn(tn({depth:n,...a}),o),namespace:i,body:r},fetchOptions:s});return 1!==c.length||c[0].raw?c:[]},mn=async e=>{const{url:t,props:r,depth:n,headers:i,headersToExclude:a,fetchOptions:o={}}=e;return sn({url:t,init:{method:"MKCOL",headers:nn(tn({depth:n,...i}),a),namespace:B.DAV,body:r?{mkcol:{set:{prop:r}}}:void 0},fetchOptions:o})},vn=async e=>{var t,r,n,i,a;const{collection:o,headers:s,headersToExclude:c,fetchOptions:u={}}=e;return null!==(a=null===(i=null===(n=null===(r=null===(t=(await cn({url:o.url,props:{[`${B.DAV}:supported-report-set`]:{}},depth:"0",headers:nn(s,c),fetchOptions:u}))[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:[]},bn=async e=>{var t,r,n;const{collection:i,headers:a,headersToExclude:o,fetchOptions:s={}}=e,c=(await cn({url:i.url,props:{[`${B.CALENDAR_SERVER}:getctag`]:{}},depth:"0",headers:nn(a,o),fetchOptions:s})).filter((e=>Jr(i.url,e.href)))[0];if(!c)throw new Error("Collection does not exist on server");return{isDirty:`${i.ctag}`!=`${null===(t=c.props)||void 0===t?void 0:t.getctag}`,newCtag:null===(n=null===(r=c.props)||void 0===r?void 0:r.getctag)||void 0===n?void 0:n.toString()}},wn=e=>{const{url:t,props:r,headers:n,syncLevel:i,syncToken:a,headersToExclude:o,fetchOptions:s}=e;return sn({url:t,init:{method:"REPORT",namespace:B.DAV,headers:nn({...n},o),body:{"sync-collection":{_attributes:en([U.CALDAV,U.CARDDAV,U.DAV]),"sync-level":i,"sync-token":a,[`${B.DAV}:prop`]:r}}},fetchOptions:s})},En=async e=>{var t,r,n,i,a,o,s,c,u,l,h;const{collection:d,method:f,headers:p,headersToExclude:g,account:y,detailedResult:m,fetchOptions:v={}}=e,b=["accountType","homeUrl"];if(!y||!fn(y,b)){if(!y)throw new Error("no account for smartCollectionSync");throw new Error(`account must have ${pn(y,b)} before smartCollectionSync`)}const w=null!=f?f:(null===(t=d.reports)||void 0===t?void 0:t.includes("syncCollection"))?"webdav":"basic";if(gn(`smart collection sync with type ${y.accountType} and method ${w}`),"webdav"===w){const e=await wn({url:d.url,props:{[`${B.DAV}:getetag`]:{},[`${"caldav"===y.accountType?B.CALDAV:B.CARDDAV}:${"caldav"===y.accountType?"calendar-data":"address-data"}`]:{},[`${B.DAV}:displayname`]:{}},syncLevel:1,syncToken:d.syncToken,headers:nn(p,g),fetchOptions:v}),t=e.filter((e=>{var t;const r="caldav"===y.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==d?void 0:d.objectMultiGet)||void 0===r?void 0:r.call(d,{url:d.url,props:{[`${B.DAV}:getetag`]:{},[`${"caldav"===y.accountType?B.CALDAV:B.CARDDAV}:${"caldav"===y.accountType?"calendar-data":"address-data"}`]:{}},objectUrls:u,depth:"1",headers:nn(p,g),fetchOptions:v})))&&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==y?void 0:y.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}})),f=null!==(i=d.objects)&&void 0!==i?i:[],b=h.filter((e=>f.every((t=>!Jr(t.url,e.url))))),w=f.reduce(((e,t)=>{const r=h.find((e=>Jr(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),E=l.map((e=>({url:e,etag:""}))),A=f.filter((e=>h.some((t=>Jr(e.url,t.url)&&t.etag===e.etag))));return{...d,objects:m?{created:b,updated:w,deleted:E}:[...A,...b,...w],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:d.syncToken}}if("basic"===w){const{isDirty:e,newCtag:t}=await bn({collection:d,headers:nn(p,g),fetchOptions:v}),r=null!==(u=d.objects)&&void 0!==u?u:[],n=null!==(h=await(null===(l=d.fetchObjects)||void 0===l?void 0:l.call(d,{collection:d,headers:nn(p,g),fetchOptions:v})))&&void 0!==h?h:[],i=n.filter((e=>r.every((t=>!Jr(t.url,e.url))))),a=r.reduce(((e,t)=>{const r=n.find((e=>Jr(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),o=r.filter((e=>n.every((t=>!Jr(t.url,e.url))))),s=r.filter((e=>n.some((t=>Jr(e.url,t.url)&&t.etag===e.etag))));if(e)return{...d,objects:m?{created:i,updated:a,deleted:o}:[...s,...i,...a],ctag:t}}return m?{...d,objects:{created:[],updated:[],deleted:[]}}:d};var An=Object.freeze({__proto__:null,collectionQuery:yn,isCollectionDirty:bn,makeCollection:mn,smartCollectionSync:En,supportedReportSet:vn,syncCollection:wn});const Tn=P("tsdav:addressBook"),_n=async e=>{const{url:t,props:r,filters:n,depth:i,headers:a,headersToExclude:o,fetchOptions:s={}}=e;return yn({url:t,body:{"addressbook-query":{_attributes:en([U.CARDDAV,U.DAV]),[`${B.DAV}:prop`]:r,filter:null!=n?n:{"prop-filter":{_attributes:{name:"FN"}}}}},defaultNamespace:B.CARDDAV,depth:i,headers:nn(a,o),fetchOptions:s})},Cn=async e=>{const{url:t,props:r,objectUrls:n,depth:i,headers:a,headersToExclude:o,fetchOptions:s={}}=e;return yn({url:t,body:{"addressbook-multiget":{_attributes:en([U.DAV,U.CARDDAV]),[`${B.DAV}:prop`]:r,[`${B.DAV}:href`]:n}},defaultNamespace:B.CARDDAV,depth:i,headers:nn(a,o),fetchOptions:s})},On=async e=>{const{account:t,headers:r,props:n,headersToExclude:i,fetchOptions:a={}}=null!=e?e:{},o=["homeUrl","rootUrl"];if(!t||!fn(t,o)){if(!t)throw new Error("no account for fetchAddressBooks");throw new Error(`account must have ${pn(t,o)} before fetchAddressBooks`)}const s=await cn({url:t.homeUrl,props:null!=n?n:{[`${B.DAV}:displayname`]:{},[`${B.CALENDAR_SERVER}:getctag`]:{},[`${B.DAV}:resourcetype`]:{},[`${B.DAV}:sync-token`]:{}},depth:"1",headers:nn(r,i),fetchOptions:a});return Promise.all(s.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 Tn(`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 vn({collection:e,headers:nn(r,i),fetchOptions:a})}))))},Dn=async e=>{const{addressBook:t,headers:r,objectUrls:n,headersToExclude:i,urlFilter:a=e=>e,useMultiGet:o=!0,fetchOptions:s={}}=e;Tn(`Fetching vcards from ${null==t?void 0:t.url}`);const c=["url"];if(!t||!fn(t,c)){if(!t)throw new Error("cannot fetchVCards for undefined addressBook");throw new Error(`addressBook must have ${pn(t,c)} before fetchVCards`)}const u=(null!=n?n:(await _n({url:t.url,props:{[`${B.DAV}:getetag`]:{}},depth:"1",headers:nn(r,i),fetchOptions:s})).map((e=>{var t;return e.ok&&null!==(t=e.href)&&void 0!==t?t:""}))).map((e=>e.startsWith("http")||!e?e:new URL(e,t.url).href)).filter(a).map((e=>new URL(e).pathname));let l=[];return u.length>0&&(l=o?await Cn({url:t.url,props:{[`${B.DAV}:getetag`]:{},[`${B.CARDDAV}:address-data`]:{}},objectUrls:u,depth:"1",headers:nn(r,i),fetchOptions:s}):await _n({url:t.url,props:{[`${B.DAV}:getetag`]:{},[`${B.CARDDAV}:address-data`]:{}},depth:"1",headers:nn(r,i),fetchOptions:s})),l.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}}))},xn=async e=>{const{addressBook:t,vCardString:r,filename:n,headers:i,headersToExclude:a,fetchOptions:o={}}=e;return un({url:new URL(n,t.url).href,data:r,headers:nn({"content-type":"text/vcard; charset=utf-8","If-None-Match":"*",...i},a),fetchOptions:o})},Rn=async e=>{const{vCard:t,headers:r,headersToExclude:n,fetchOptions:i={}}=e;return ln({url:t.url,data:t.data,etag:t.etag,headers:nn({"content-type":"text/vcard; charset=utf-8",...r},n),fetchOptions:i})},Fn=async e=>{const{vCard:t,headers:r,headersToExclude:n,fetchOptions:i={}}=e;return hn({url:t.url,etag:t.etag,headers:nn(r,n),fetchOptions:i})};var Sn=Object.freeze({__proto__:null,addressBookMultiGet:Cn,addressBookQuery:_n,createVCard:xn,deleteVCard:Fn,fetchAddressBooks:On,fetchVCards:Dn,updateVCard:Rn});const Nn=P("tsdav:calendar"),Ln=async e=>{var t,r,n;const{account:i,headers:a,headersToExclude:o,fetchOptions:s={}}=e,c=["principalUrl","rootUrl"];if(!fn(i,c))throw new Error(`account must have ${pn(i,c)} before fetchUserAddresses`);Nn(`Fetch user addresses from ${i.principalUrl}`);const u=(await cn({url:i.principalUrl,props:{[`${B.CALDAV}:calendar-user-address-set`]:{}},depth:"0",headers:nn(a,o),fetchOptions:s})).find((e=>Jr(i.principalUrl,e.href)));if(!u||!u.ok)throw new Error("cannot find calendarUserAddresses");const l=(null===(n=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===n?void 0:n.filter(Boolean))||[];return Nn(`Fetched calendar user addresses ${l}`),l},kn=async e=>{const{url:t,props:r,filters:n,timezone:i,depth:a,headers:o,headersToExclude:s,fetchOptions:c={}}=e;return yn({url:t,body:{"calendar-query":tn({_attributes:en([U.CALDAV,U.CALENDAR_SERVER,U.CALDAV_APPLE,U.DAV]),[`${B.DAV}:prop`]:r,filter:n,timezone:i})},defaultNamespace:B.CALDAV,depth:a,headers:nn(o,s),fetchOptions:c})},In=async e=>{const{url:t,props:r,objectUrls:n,filters:i,timezone:a,depth:o,headers:s,headersToExclude:c,fetchOptions:u={}}=e;return yn({url:t,body:{"calendar-multiget":{_attributes:en([U.DAV,U.CALDAV]),[`${B.DAV}:prop`]:r,[`${B.DAV}:href`]:n,...rn("filter",i),timezone:a}},defaultNamespace:B.CALDAV,depth:o,headers:nn(s,c),fetchOptions:u})},Un=async e=>{const{url:t,props:r,depth:n,headers:i,headersToExclude:a,fetchOptions:o={}}=e;return sn({url:t,init:{method:"MKCALENDAR",headers:nn(tn({depth:n,...i}),a),namespace:B.DAV,body:{[`${B.CALDAV}:mkcalendar`]:{_attributes:en([U.DAV,U.CALDAV,U.CALDAV_APPLE]),set:{prop:r}}}},fetchOptions:o})},Pn=async e=>{const{headers:t,account:r,props:n,projectedProps:i,headersToExclude:a,fetchOptions:o={}}=null!=e?e:{},s=["homeUrl","rootUrl"];if(!r||!fn(r,s)){if(!r)throw new Error("no account for fetchCalendars");throw new Error(`account must have ${pn(r,s)} before fetchCalendars`)}const c=await cn({url:r.homeUrl,props:null!=n?n:{[`${B.CALDAV}:calendar-description`]:{},[`${B.CALDAV}:calendar-timezone`]:{},[`${B.DAV}:displayname`]:{},[`${B.CALDAV_APPLE}:calendar-color`]:{},[`${B.CALENDAR_SERVER}:getctag`]:{},[`${B.DAV}:resourcetype`]:{},[`${B.CALDAV}:supported-calendar-component-set`]:{},[`${B.DAV}:sync-token`]:{}},depth:"1",headers:nn(t,a),fetchOptions: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("calendar")})).filter((e=>{var t,r,n,i;return(Array.isArray(null===(t=e.props)||void 0===t?void 0:t.supportedCalendarComponentSet.comp)?null===(r=e.props)||void 0===r?void 0:r.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(i=null===(n=e.props)||void 0===n?void 0:n.supportedCalendarComponentSet.comp)||void 0===i?void 0:i._attributes.name]).some((e=>Object.values(V).includes(e)))})).map((e=>{var t,n,a,o,s,c,u,l,h,d,f,p,g,y,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===(g=null===(p=e.props)||void 0===p?void 0:p.supportedCalendarComponentSet.comp)||void 0===g?void 0:g._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,...rn("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 vn({collection:e,headers:nn(t,a),fetchOptions:o})}))))},jn=async e=>{const{calendar:t,objectUrls:r,filters:n,timeRange:i,headers:a,expand:o,urlFilter:s=e=>Boolean(null==e?void 0:e.includes(".ics")),useMultiGet:c=!0,headersToExclude:u,fetchOptions:l={}}=e;if(i){const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(i.start)&&e.test(i.end)||t.test(i.start)&&t.test(i.end)))throw new Error("invalid timeRange format, not in ISO8601")}Nn(`Fetching calendar objects from ${null==t?void 0:t.url}`);const h=["url"];if(!t||!fn(t,h)){if(!t)throw new Error("cannot fetchCalendarObjects for undefined calendar");throw new Error(`calendar must have ${pn(t,h)} before fetchCalendarObjects`)}const d=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`}}}:{}}}}],f=(null!=r?r:(await kn({url:t.url,props:{[`${B.DAV}:getetag`]:{...o&&i?{[`${B.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:d,depth:"1",headers:nn(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:{[`${B.DAV}:getetag`]:{},[`${B.CALDAV}:calendar-data`]:{...o&&i?{[`${B.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:d,depth:"1",headers:nn(a,u),fetchOptions:l}):await In({url:t.url,props:{[`${B.DAV}:getetag`]:{},[`${B.CALDAV}:calendar-data`]:{...o&&i?{[`${B.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:f,depth:"1",headers:nn(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}}))},Bn=async e=>{const{calendar:t,iCalString:r,filename:n,headers:i,headersToExclude:a,fetchOptions:o={}}=e;return un({url:new URL(n,t.url).href,data:r,headers:nn({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*",...i},a),fetchOptions:o})},Vn=async e=>{const{calendarObject:t,headers:r,headersToExclude:n,fetchOptions:i={}}=e;return ln({url:t.url,data:t.data,etag:t.etag,headers:nn({"content-type":"text/calendar; charset=utf-8",...r},n),fetchOptions:i})},Mn=async e=>{const{calendarObject:t,headers:r,headersToExclude:n,fetchOptions:i={}}=e;return hn({url:t.url,etag:t.etag,headers:nn(r,n),fetchOptions:i})},$n=async e=>{var t;const{oldCalendars:r,account:n,detailedResult:i,headers:a,headersToExclude:o,fetchOptions:s={}}=e;if(!n)throw new Error("Must have account before syncCalendars");const c=null!==(t=null!=r?r:n.calendars)&&void 0!==t?t:[],u=await Pn({account:n,headers:nn(a,o),fetchOptions:s}),l=u.filter((e=>c.every((t=>!Jr(t.url,e.url)))));Nn(`new calendars: ${l.map((e=>e.displayName))}`);const h=c.reduce(((e,t)=>{const r=u.find((e=>Jr(e.url,t.url)));return r&&(r.syncToken&&`${r.syncToken}`!=`${t.syncToken}`||r.ctag&&`${r.ctag}`!=`${t.ctag}`)?[...e,r]:e}),[]);Nn(`updated calendars: ${h.map((e=>e.displayName))}`);const d=await Promise.all(h.map((async e=>await En({collection:{...e,objectMultiGet:In},method:"webdav",headers:nn(a,o),account:n,fetchOptions:s})))),f=c.filter((e=>u.every((t=>!Jr(t.url,e.url)))));Nn(`deleted calendars: ${f.map((e=>e.displayName))}`);const p=c.filter((e=>u.some((t=>Jr(t.url,e.url)&&(t.syncToken&&`${t.syncToken}`!=`${e.syncToken}`||t.ctag&&`${t.ctag}`!=`${e.ctag}`)))));return i?{created:l,updated:h,deleted:f}:[...p,...l,...d]},Kn=async e=>{const{url:t,timeRange:r,depth:n,headers:i,headersToExclude:a,fetchOptions:o={}}=e;if(!r)throw new Error("timeRange is required");{const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(r.start)&&e.test(r.end)||t.test(r.start)&&t.test(r.end)))throw new Error("invalid timeRange format, not in ISO8601")}return(await yn({url:t,body:{"free-busy-query":tn({_attributes:en([U.CALDAV]),[`${B.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:B.CALDAV,depth:n,headers:nn(i,a),fetchOptions:o}))[0]};var Hn=Object.freeze({__proto__:null,calendarMultiGet:In,calendarQuery:kn,createCalendarObject:Bn,deleteCalendarObject:Mn,fetchCalendarObjects:jn,fetchCalendarUserAddresses:Ln,fetchCalendars:Pn,freeBusyQuery:Kn,makeCalendar:Un,syncCalendars:$n,updateCalendarObject:Vn});const Yn=P("tsdav:account"),qn=async e=>{var t,r;Yn("Service discovery...");const{account:n,headers:a,headersToExclude:o,fetchOptions:s={}}=e,c=new URL(n.serverUrl),u=new URL(`/.well-known/${n.accountType}`,c);u.protocol=null!==(t=c.protocol)&&void 0!==t?t:"http";try{const e=await i.fetch(u.href,{headers:nn(a,o),method:"PROPFIND",redirect:"manual",...s});if(e.status>=300&&e.status<400){const t=e.headers.get("Location");if("string"==typeof t&&t.length){Yn(`Service discovery redirected to ${t}`);const e=new URL(t,c);return e.hostname===u.hostname&&u.port&&!e.port&&(e.port=u.port),e.protocol=null!==(r=c.protocol)&&void 0!==r?r:"http",e.href}}}catch(e){Yn(`Service discovery failed: ${e.stack}`)}return c.href},zn=async e=>{var t,r,n,i,a;const{account:o,headers:s,headersToExclude:c,fetchOptions:u={}}=e,l=["rootUrl"];if(!fn(o,l))throw new Error(`account must have ${pn(o,l)} before fetchPrincipalUrl`);Yn(`Fetching principal url from path ${o.rootUrl}`);const[h]=await cn({url:o.rootUrl,props:{[`${B.DAV}:current-user-principal`]:{}},depth:"0",headers:nn(s,c),fetchOptions:u});if(!h.ok&&(Yn(`Fetch principal url failed: ${h.statusText}`),401===h.status))throw new Error("Invalid credentials");return Yn(`Fetched principal url ${null===(r=null===(t=h.props)||void 0===t?void 0:t.currentUserPrincipal)||void 0===r?void 0:r.href}`),new URL(null!==(a=null===(i=null===(n=h.props)||void 0===n?void 0:n.currentUserPrincipal)||void 0===i?void 0:i.href)&&void 0!==a?a:"",o.rootUrl).href},Gn=async e=>{var t,r;const{account:n,headers:i,headersToExclude:a,fetchOptions:o={}}=e,s=["principalUrl","rootUrl"];if(!fn(n,s))throw new Error(`account must have ${pn(n,s)} before fetchHomeUrl`);Yn(`Fetch home url from ${n.principalUrl}`);const c=(await cn({url:n.principalUrl,props:"caldav"===n.accountType?{[`${B.CALDAV}:calendar-home-set`]:{}}:{[`${B.CARDDAV}:addressbook-home-set`]:{}},depth:"0",headers:nn(i,a),fetchOptions:o})).find((e=>Jr(n.principalUrl,e.href)));if(!c||!c.ok)throw new Error("cannot find homeUrl");const u=new URL("caldav"===n.accountType?null===(t=null==c?void 0:c.props)||void 0===t?void 0:t.calendarHomeSet.href:null===(r=null==c?void 0:c.props)||void 0===r?void 0:r.addressbookHomeSet.href,n.rootUrl).href;return Yn(`Fetched home url ${u}`),u},Wn=async e=>{const{account:t,headers:r,loadCollections:n=!1,loadObjects:i=!1,headersToExclude:a,fetchOptions:o={}}=e,s={...t};return s.rootUrl=await qn({account:t,headers:nn(r,a),fetchOptions:o}),s.principalUrl=await zn({account:s,headers:nn(r,a),fetchOptions:o}),s.homeUrl=await Gn({account:s,headers:nn(r,a),fetchOptions:o}),(n||i)&&("caldav"===t.accountType?s.calendars=await Pn({headers:nn(r,a),account:s,fetchOptions:o}):"carddav"===t.accountType&&(s.addressBooks=await On({headers:nn(r,a),account:s,fetchOptions:o}))),i&&("caldav"===t.accountType&&s.calendars?s.calendars=await Promise.all(s.calendars.map((async e=>({...e,objects:await jn({calendar:e,headers:nn(r,a),fetchOptions:o})})))):"carddav"===t.accountType&&s.addressBooks&&(s.addressBooks=await Promise.all(s.addressBooks.map((async e=>({...e,objects:await Dn({addressBook:e,headers:nn(r,a),fetchOptions:o})})))))),s};var Qn,Xn,Zn=Object.freeze({__proto__:null,createAccount:Wn,fetchHomeUrl:Gn,fetchPrincipalUrl:zn,serviceDiscovery:qn}),Jn={exports:{}};Qn=Jn,Xn=Jn.exports,function(t){var r=Xn,n=Qn&&Qn.exports==r&&Qn,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}(e);var ei=Jn.exports;const ti=P("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=async(e,t)=>{const r=["authorizationCode","redirectUrl","clientId","clientSecret","tokenUrl"];if(!fn(e,r))throw new Error(`Oauth credentials missing: ${pn(e,r)}`);const n=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(n.toString());const a=await i.fetch(e.tokenUrl,{method:"POST",body:n.toString(),headers:{"content-length":`${n.toString().length}`,"content-type":"application/x-www-form-urlencoded"},...null!=t?t:{}});if(a.ok){return await a.json()}return ti(`Fetch Oauth tokens failed: ${await a.text()}`),{}},ai=async(e,t)=>{const r=["refreshToken","clientId","clientSecret","tokenUrl"];if(!fn(e,r))throw new Error(`Oauth credentials missing: ${pn(e,r)}`);const n=new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,refresh_token:e.refreshToken,grant_type:"refresh_token"}),a=await i.fetch(e.tokenUrl,{method:"POST",body:n.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},...null!=t?t:{}});if(a.ok){return await a.json()}return ti(`Refresh access token failed: ${await a.text()}`),{}},oi=async(e,t)=>{var r;ti("Fetching oauth headers");let n={};return e.refreshToken?(e.refreshToken&&!e.accessToken||Date.now()>(null!==(r=e.expiration)&&void 0!==r?r:0))&&(n=await ai(e,t)):n=await ii(e,t),ti(`Oauth tokens fetched: ${n.access_token}`),{tokens:n,headers:{authorization:`Bearer ${n.access_token}`}}};var si=Object.freeze({__proto__:null,defaultParam:ri,fetchOauthTokens:ii,getBasicAuthHeaders:ni,getOauthHeaders:oi,refreshAccessToken:ai});const ci=async e=>{var t;const{serverUrl:r,credentials:n,authMethod:i,defaultAccountType:a,authFunction:o}=e;let s={};switch(i){case"Basic":s=ni(n);break;case"Oauth":s=(await oi(n)).headers;break;case"Digest":s={Authorization:`Digest ${n.digestString}`};break;case"Custom":s=null!==(t=await(null==o?void 0:o(n)))&&void 0!==t?t:{};break;default:throw new Error("Invalid auth method")}const c=a?await Wn({account:{serverUrl:r,credentials:n,accountType:a},headers:s}):void 0,u=ri(un,{url:r,headers:s}),l=ri(ln,{headers:s,url:r}),h=ri(hn,{headers:s,url:r}),d=ri(cn,{headers:s}),f=ri(yn,{headers:s}),p=ri(mn,{headers:s}),g=ri(wn,{headers:s}),y=ri(vn,{headers:s}),m=ri(bn,{headers:s}),v=ri(En,{headers:s,account:c}),b=ri(kn,{headers:s}),w=ri(In,{headers:s}),E=ri(Un,{headers:s}),A=ri(Pn,{headers:s,account:c}),T=ri(Ln,{headers:s,account:c}),_=ri(jn,{headers:s}),C=ri(Bn,{headers:s}),O=ri(Vn,{headers:s}),D=ri(Mn,{headers:s}),x=ri($n,{account:c,headers:s}),R=ri(_n,{headers:s}),F=ri(Cn,{headers:s});return{davRequest:async e=>{const{init:t,...r}=e,{headers:n,...i}=t;return sn({...r,init:{...i,headers:{...s,...n}}})},propfind:d,createAccount:async e=>{const{account:t,headers:i,loadCollections:a,loadObjects:o}=e;return Wn({account:{serverUrl:r,credentials:n,...t},headers:{...s,...i},loadCollections:a,loadObjects:o})},createObject:u,updateObject:l,deleteObject:h,calendarQuery:b,addressBookQuery:R,collectionQuery:f,makeCollection:p,calendarMultiGet:w,makeCalendar:E,syncCollection:g,supportedReportSet:y,isCollectionDirty:m,smartCollectionSync:v,fetchCalendars:A,fetchCalendarUserAddresses:T,fetchCalendarObjects:_,createCalendarObject:C,updateCalendarObject:O,deleteCalendarObject:D,syncCalendars:x,fetchAddressBooks:ri(On,{account:c,headers:s}),addressBookMultiGet:F,fetchVCards:ri(Dn,{headers:s}),createVCard:ri(xn,{headers:s}),updateVCard:ri(Rn,{headers:s}),deleteVCard:ri(Fn,{headers:s})}};class ui{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:{}}async login(){var e;switch(this.authMethod){case"Basic":this.authHeaders=ni(this.credentials);break;case"Oauth":this.authHeaders=(await oi(this.credentials,this.fetchOptions)).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 Wn({account:{serverUrl:this.serverUrl,credentials:this.credentials,accountType:this.accountType},headers:this.authHeaders,fetchOptions:this.fetchOptions}):void 0}async davRequest(e){const{init:t,...r}=e,{headers:n,...i}=t;return sn({...r,init:{...i,headers:{...this.authHeaders,...n}},fetchOptions:this.fetchOptions})}async createObject(...e){return ri(un,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateObject(...e){return ri(ln,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteObject(...e){return ri(hn,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async propfind(...e){return ri(cn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createAccount(e){const{account:t,headers:r,loadCollections:n,loadObjects:i,fetchOptions:a}=e;return Wn({account:{serverUrl:this.serverUrl,credentials:this.credentials,...t},headers:{...this.authHeaders,...r},loadCollections:n,loadObjects:i,fetchOptions:null!=a?a:this.fetchOptions})}async collectionQuery(...e){return ri(yn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async makeCollection(...e){return ri(mn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async syncCollection(...e){return ri(wn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async supportedReportSet(...e){return ri(vn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async isCollectionDirty(...e){return ri(bn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async smartCollectionSync(...e){return ri(En,{headers:this.authHeaders,fetchOptions:this.fetchOptions,account:this.account})(e[0])}async calendarQuery(...e){return ri(kn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async makeCalendar(...e){return ri(Un,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async calendarMultiGet(...e){return ri(In,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async fetchCalendars(...e){return ri(Pn,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(null==e?void 0:e[0])}async fetchCalendarUserAddresses(...e){return ri(Ln,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(null==e?void 0:e[0])}async fetchCalendarObjects(...e){return ri(jn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createCalendarObject(...e){return ri(Bn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateCalendarObject(...e){return ri(Vn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteCalendarObject(...e){return ri(Mn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async syncCalendars(...e){return ri($n,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(e[0])}async addressBookQuery(...e){return ri(_n,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async addressBookMultiGet(...e){return ri(Cn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async fetchAddressBooks(...e){return ri(On,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(null==e?void 0:e[0])}async fetchVCards(...e){return ri(Dn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createVCard(...e){return ri(xn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateVCard(...e){return ri(Rn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteVCard(...e){return ri(Fn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}}var li={DAVNamespace:U,DAVNamespaceShort:B,DAVAttributeMap:j,...Object.freeze({__proto__:null,DAVClient:ui,createDAVClient:ci}),...dn,...An,...Zn,...Sn,...Hn,...si,...an};export{j as DAVAttributeMap,ui as DAVClient,U as DAVNamespace,B as DAVNamespaceShort,_n as addressBookQuery,In as calendarMultiGet,kn as calendarQuery,tn as cleanupFalsy,yn as collectionQuery,Wn as createAccount,Bn as createCalendarObject,ci as createDAVClient,un as createObject,xn as createVCard,sn as davRequest,li as default,Mn as deleteCalendarObject,hn as deleteObject,Fn as deleteVCard,On as fetchAddressBooks,jn as fetchCalendarObjects,Ln as fetchCalendarUserAddresses,Pn as fetchCalendars,ii as fetchOauthTokens,Dn as fetchVCards,Kn as freeBusyQuery,ni as getBasicAuthHeaders,en as getDAVAttribute,oi as getOauthHeaders,bn as isCollectionDirty,Un as makeCalendar,cn as propfind,ai as refreshAccessToken,En as smartCollectionSync,vn as supportedReportSet,$n as syncCalendars,wn as syncCollection,Vn as updateCalendarObject,ln as updateObject,Rn as updateVCard,Jr as urlContains,Zr as urlEquals}; +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(e.__esModule)return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?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}!function(e){!function(t){var r="undefined"!=typeof globalThis&&globalThis||void 0!==e&&e||void 0!==r&&r,n="URLSearchParams"in r,i="Symbol"in r&&"iterator"in Symbol,a="FileReader"in r&&"Blob"in r&&function(){try{return new Blob,!0}catch(e){return!1}}(),o="FormData"in r,s="ArrayBuffer"in r;if(s)var c=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],u=ArrayBuffer.isView||function(e){return e&&c.indexOf(Object.prototype.toString.call(e))>-1};function l(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 h(e){return"string"!=typeof e&&(e=String(e)),e}function d(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return i&&(t[Symbol.iterator]=function(){return t}),t}function f(e){this.map={},e instanceof f?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function p(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));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 y(e){var t=new FileReader,r=g(t);return t.readAsArrayBuffer(e),r}function m(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function v(){return this.bodyUsed=!1,this._initBody=function(e){var t;this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:a&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:o&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:n&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():s&&a&&((t=e)&&DataView.prototype.isPrototypeOf(t))?(this._bodyArrayBuffer=m(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s&&(ArrayBuffer.prototype.isPrototypeOf(e)||u(e))?this._bodyArrayBuffer=m(e):this._bodyText=e=Object.prototype.toString.call(e):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):n&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},a&&(this.blob=function(){var e=p(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=p(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))}return this.blob().then(y)}),this.text=function(){var e,t,r,n=p(this);if(n)return n;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,r=g(t),t.readAsText(e),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,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 n=/([?&])_=[^&]*/;if(n.test(this.url))this.url=this.url.replace(n,"$1_="+(new Date).getTime());else{this.url+=(/\?/.test(this.url)?"&":"?")+"_="+(new Date).getTime()}}}function E(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 A(e,t){if(!(this instanceof A))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText=void 0===t.statusText?"":""+t.statusText,this.headers=new f(t.headers),this.url=t.url||"",this._initBody(e)}w.prototype.clone=function(){return new w(this,{body:this._bodyInit})},v.call(w.prototype),v.call(A.prototype),A.prototype.clone=function(){return new A(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new f(this.headers),url:this.url})},A.error=function(){var e=new A(null,{status:0,statusText:""});return e.type="error",e};var T=[301,302,303,307,308];A.redirect=function(e,t){if(-1===T.indexOf(t))throw new RangeError("Invalid status code");return new A(null,{status:t,headers:{location:e}})},t.DOMException=r.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function _(e,n){return new Promise((function(i,o){var c=new w(e,n);if(c.signal&&c.signal.aborted)return o(new t.DOMException("Aborted","AbortError"));var u=new XMLHttpRequest;function l(){u.abort()}u.onload=function(){var e,t,r={status:u.status,statusText:u.statusText,headers:(e=u.getAllResponseHeaders()||"",t=new f,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();t.append(n,i)}})),t)};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 A(n,r))}),0)},u.onerror=function(){setTimeout((function(){o(new TypeError("Network request failed"))}),0)},u.ontimeout=function(){setTimeout((function(){o(new TypeError("Network request failed"))}),0)},u.onabort=function(){setTimeout((function(){o(new t.DOMException("Aborted","AbortError"))}),0)},u.open(c.method,function(e){try{return""===e&&r.location.href?r.location.href:e}catch(t){return e}}(c.url),!0),"include"===c.credentials?u.withCredentials=!0:"omit"===c.credentials&&(u.withCredentials=!1),"responseType"in u&&(a?u.responseType="blob":s&&c.headers.get("Content-Type")&&-1!==c.headers.get("Content-Type").indexOf("application/octet-stream")&&(u.responseType="arraybuffer")),!n||"object"!=typeof n.headers||n.headers instanceof f?c.headers.forEach((function(e,t){u.setRequestHeader(t,e)})):Object.getOwnPropertyNames(n.headers).forEach((function(e){u.setRequestHeader(e,h(n.headers[e]))})),c.signal&&(c.signal.addEventListener("abort",l),u.onreadystatechange=function(){4===u.readyState&&c.signal.removeEventListener("abort",l)}),u.send(void 0===c._bodyInit?null:c._bodyInit)}))}_.polyfill=!0,r.fetch||(r.fetch=_,r.Headers=f,r.Request=w,r.Response=A),t.Headers=f,t.Request=w,t.Response=A,t.fetch=_}({})}("undefined"!=typeof self?self:e);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))},x}var L=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){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t{"%%"!==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")}catch(e){}!e&&void 0!==F&&"env"in F&&(e=F.env.DEBUG);return 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=L(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(S,S.exports);var k,I=t(S.exports);!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:"}(k||(k={}));const U={[k.CALDAV]:"xmlns:c",[k.CARDDAV]:"xmlns:card",[k.CALENDAR_SERVER]:"xmlns:cs",[k.CALDAV_APPLE]:"xmlns:ca",[k.DAV]:"xmlns:d"};var P,j;!function(e){e.CALDAV="c",e.CARDDAV="card",e.CALENDAR_SERVER="cs",e.CALDAV_APPLE="ca",e.DAV="d"}(P||(P={})),function(e){e.VEVENT="VEVENT",e.VTODO="VTODO",e.VJOURNAL="VJOURNAL",e.VFREEBUSY="VFREEBUSY",e.VTIMEZONE="VTIMEZONE",e.VALARM="VALARM"}(j||(j={}));var B=[],V=[],M="undefined"!=typeof Uint8Array?Uint8Array:Array,$=!1;function K(){$=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0;t<64;++t)B[t]=e[t],V[e.charCodeAt(t)]=t;V["-".charCodeAt(0)]=62,V["_".charCodeAt(0)]=63}function H(e,t,r){for(var n,i,a=[],o=t;o>18&63]+B[i>>12&63]+B[i>>6&63]+B[63&i]);return a.join("")}function Y(e){var t;$||K();for(var r=e.length,n=r%3,i="",a=[],o=16383,s=0,c=r-n;sc?c:s+o));return 1===n?(t=e[r-1],i+=B[t>>2],i+=B[t<<4&63],i+="=="):2===n&&(t=(e[r-2]<<8)+e[r-1],i+=B[t>>10],i+=B[t>>4&63],i+=B[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 z(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,g=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*g}var G={}.toString,W=Array.isArray||function(e){return"[object Array]"==G.call(e)};function Q(){return Z.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function X(e,t){if(Q()=Q())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Q().toString(16)+" bytes");return 0|e}function ie(e){return!(null==e||!e._isBuffer)}function ae(e,t){if(ie(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 Ne(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Le(e).length;default:if(n)return Ne(e).length;t=(""+t).toLowerCase(),n=!0}}function oe(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 Ee(this,t,r);case"utf8":case"utf-8":return me(this,t,r);case"ascii":return be(this,t,r);case"latin1":case"binary":return we(this,t,r);case"base64":return ye(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ae(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function se(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function ce(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=Z.from(t,n)),ie(t))return 0===t.length?-1:ue(e,t,r,n,i);if("number"==typeof t)return t&=255,Z.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):ue(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function ue(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 ye(e,t,r){return 0===t&&r===e.length?Y(e):Y(e.slice(t,r))}function me(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<=ve)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+=" ... ")),""},Z.prototype.compare=function(e,t,r,n,i){if(!ie(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 le(this,e,t,r);case"utf8":case"utf-8":return he(this,e,t,r);case"ascii":return de(this,e,t,r);case"latin1":case"binary":return fe(this,e,t,r);case"base64":return pe(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ge(this,e,t,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},Z.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var ve=4096;function be(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 _e(e,t,r,n,i,a){if(!ie(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function Ce(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 Oe(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 De(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 xe(e,t,r,n,i){return i||De(e,0,r,4),z(e,t,r,n,23,4),r+4}function Re(e,t,r,n,i){return i||De(e,0,r,8),z(e,t,r,n,52,8),r+8}Z.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},Z.prototype.readUInt8=function(e,t){return t||Te(e,1,this.length),this[e]},Z.prototype.readUInt16LE=function(e,t){return t||Te(e,2,this.length),this[e]|this[e+1]<<8},Z.prototype.readUInt16BE=function(e,t){return t||Te(e,2,this.length),this[e]<<8|this[e+1]},Z.prototype.readUInt32LE=function(e,t){return t||Te(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},Z.prototype.readUInt32BE=function(e,t){return t||Te(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},Z.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||Te(e,t,this.length);for(var n=this[e],i=1,a=0;++a=(i*=128)&&(n-=Math.pow(2,8*t)),n},Z.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||Te(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},Z.prototype.readInt8=function(e,t){return t||Te(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},Z.prototype.readInt16LE=function(e,t){t||Te(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},Z.prototype.readInt16BE=function(e,t){t||Te(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},Z.prototype.readInt32LE=function(e,t){return t||Te(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},Z.prototype.readInt32BE=function(e,t){return t||Te(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},Z.prototype.readFloatLE=function(e,t){return t||Te(e,4,this.length),q(this,e,!0,23,4)},Z.prototype.readFloatBE=function(e,t){return t||Te(e,4,this.length),q(this,e,!1,23,4)},Z.prototype.readDoubleLE=function(e,t){return t||Te(e,8,this.length),q(this,e,!0,52,8)},Z.prototype.readDoubleBE=function(e,t){return t||Te(e,8,this.length),q(this,e,!1,52,8)},Z.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t|=0,r|=0,n)||_e(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},Z.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||_e(this,e,t,1,255,0),Z.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},Z.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||_e(this,e,t,2,65535,0),Z.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Ce(this,e,t,!0),t+2},Z.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||_e(this,e,t,2,65535,0),Z.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Ce(this,e,t,!1),t+2},Z.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||_e(this,e,t,4,4294967295,0),Z.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):Oe(this,e,t,!0),t+4},Z.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||_e(this,e,t,4,4294967295,0),Z.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Oe(this,e,t,!1),t+4},Z.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);_e(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},Z.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||_e(this,e,t,1,127,-128),Z.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},Z.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||_e(this,e,t,2,32767,-32768),Z.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Ce(this,e,t,!0),t+2},Z.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||_e(this,e,t,2,32767,-32768),Z.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Ce(this,e,t,!1),t+2},Z.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||_e(this,e,t,4,2147483647,-2147483648),Z.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):Oe(this,e,t,!0),t+4},Z.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||_e(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),Z.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Oe(this,e,t,!1),t+4},Z.prototype.writeFloatLE=function(e,t,r){return xe(this,e,t,!0,r)},Z.prototype.writeFloatBE=function(e,t,r){return xe(this,e,t,!1,r)},Z.prototype.writeDoubleLE=function(e,t,r){return Re(this,e,t,!0,r)},Z.prototype.writeDoubleBE=function(e,t,r){return Re(this,e,t,!1,r)},Z.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||!Z.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 Le(e){return function(e){var t,r,n,i,a,o;$||K();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 M(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=V[e.charCodeAt(t)]<<2|V[e.charCodeAt(t+1)]>>4,o[c++]=255&i):1===a&&(i=V[e.charCodeAt(t)]<<10|V[e.charCodeAt(t+1)]<<4|V[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(Fe,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function ke(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function Ie(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}var Ue,Pe={};function je(){}function Be(){Be.init.call(this)}function Ve(e){return void 0===e._maxListeners?Be.defaultMaxListeners:e._maxListeners}function Me(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 je,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=Ve(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 $e(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 Ke(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 He(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}je.prototype=Object.create(null),Be.EventEmitter=Be,Be.usingDomains=!1,Be.prototype.domain=void 0,Be.prototype._events=void 0,Be.prototype._maxListeners=void 0,Be.defaultMaxListeners=10,Be.init=function(){this.domain=null,Be.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new je,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Be.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},Be.prototype.getMaxListeners=function(){return Ve(this)},Be.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=He(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 je,this;delete n[e]}else!function(e,t){for(var r=t,n=r+1,i=e.length;n0?Reflect.ownKeys(this._events):[]},Ue="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 Ye=/%[sdj%]/g;function qe(e){if(!it(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]),rt(t)?r.showHidden=t:t&&function(e,t){if(!t||!st(t))return e;var r=Object.keys(t),n=r.length;for(;n--;)e[r[n]]=t[r[n]]}(r,t),at(r.showHidden)&&(r.showHidden=!1),at(r.depth)&&(r.depth=2),at(r.colors)&&(r.colors=!1),at(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=Xe),Je(r,e,r.depth)}function Xe(e,t){var r=Qe.styles[t];return r?"["+Qe.colors[r][0]+"m"+e+"["+Qe.colors[r][1]+"m":e}function Ze(e,t){return e}function Je(e,t,r){if(e.customInspect&&t&<(t.inspect)&&t.inspect!==Qe&&(!t.constructor||t.constructor.prototype!==t)){var n=t.inspect(r,e);return it(n)||(n=Je(e,n,r)),n}var i=function(e,t){if(at(t))return e.stylize("undefined","undefined");if(it(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(rt(t))return e.stylize(""+t,"boolean");if(nt(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)),ut(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return et(t);if(0===a.length){if(lt(t)){var s=t.name?": "+t.name:"";return e.stylize("[Function"+s+"]","special")}if(ot(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(ct(t))return e.stylize(Date.prototype.toString.call(t),"date");if(ut(t))return et(t)}var c,u,l="",h=!1,d=["{","}"];(c=t,Array.isArray(c)&&(h=!0,d=["[","]"]),lt(t))&&(l=" [Function"+(t.name?": "+t.name:"")+"]");return ot(t)&&(l=" "+RegExp.prototype.toString.call(t)),ct(t)&&(l=" "+Date.prototype.toUTCString.call(t)),ut(t)&&(l=" "+et(t)),0!==a.length||h&&0!=t.length?r<0?ot(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 et(e){return"["+Error.prototype.toString.call(e)+"]"}function tt(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")),dt(n,i)||(o="["+i+"]"),s||(e.seen.indexOf(c.value)<0?(s=nt(r)?Je(e,c.value,null):Je(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")),at(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 rt(e){return"boolean"==typeof e}function nt(e){return null===e}function it(e){return"string"==typeof e}function at(e){return void 0===e}function ot(e){return st(e)&&"[object RegExp]"===ht(e)}function st(e){return"object"==typeof e&&null!==e}function ct(e){return st(e)&&"[object Date]"===ht(e)}function ut(e){return st(e)&&("[object Error]"===ht(e)||e instanceof Error)}function lt(e){return"function"==typeof e}function ht(e){return Object.prototype.toString.call(e)}function dt(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ft(){this.head=null,this.tail=null,this.length=0}Qe.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]},Qe.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},ft.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},ft.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},ft.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}},ft.prototype.clear=function(){this.head=this.tail=null,this.length=0},ft.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},ft.prototype.concat=function(e){if(0===this.length)return Z.alloc(0);if(1===this.length)return this.head.data;for(var t=Z.allocUnsafe(e>>>0),r=this.head,n=0;r;)r.data.copy(t,n),n+=r.data.length,r=r.next;return t};var pt=Z.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 gt(e){switch(this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),function(e){if(e&&!pt(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=mt;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=vt;break;default:return void(this.write=yt)}this.charBuffer=new Z(6),this.charReceived=0,this.charLength=0}function yt(e){return e.toString(this.encoding)}function mt(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function vt(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}gt.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},gt.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},gt.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};var bt=Object.freeze({__proto__:null,StringDecoder:gt});At.ReadableState=Et;var wt=function(e){if(at(Ge)&&(Ge=F.env.NODE_DEBUG||""),e=e.toUpperCase(),!We[e])if(new RegExp("\\b"+e+"\\b","i").test(Ge)){We[e]=function(){var t=qe.apply(null,arguments);console.error("%s %d: %s",e,0,t)}}else We[e]=function(){};return We[e]}("stream");function Et(e,t){e=e||{},this.objectMode=!!e.objectMode,t instanceof Qt&&(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 ft,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 gt(e.encoding),this.encoding=e.encoding)}function At(e){if(!(this instanceof At))return new At(e);this._readableState=new Et(e,this),this.readable=!0,e&&"function"==typeof e.read&&(this._read=e.read),Be.call(this)}function Tt(e,t,r,n,i){var a=function(e,t){var r=null;Z.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,Ot(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&&Ot(e))),function(e,t){t.readingMore||(t.readingMore=!0,g(xt,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>=_t?e=_t:(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 Ot(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(wt("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?g(Dt,e):Dt(e))}function Dt(e){wt("emit readable"),e.emit("readable"),St(e)}function xt(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=Z.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 Lt(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,g(kt,t,e))}function kt(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function It(e,t){for(var r=0,n=e.length;r=t.highWaterMark||t.ended))return wt("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?Lt(this):Ot(this),null;if(0===(e=Ct(e,t))&&t.ended)return 0===t.length&&Lt(this),null;var n,i=t.needReadable;return wt("need readable",i),(0===t.length||t.length-e0?Nt(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&Lt(this)),null!==n&&this.emit("data",n),n},At.prototype._read=function(e){this.emit("error",new Error("not implemented"))},At.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,wt("pipe count=%d opts=%j",n.pipesCount,t);var i=!t||!1!==t.end?o:u;function a(e){wt("onunpipe"),e===r&&u()}function o(){wt("onend"),e.end()}n.endEmitted?g(i):r.once("end",i),e.on("unpipe",a);var s=function(e){return function(){var t=e._readableState;wt("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&e.listeners("data").length&&(t.flowing=!0,St(e))}}(r);e.on("drain",s);var c=!1;function u(){wt("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){wt("ondata"),l=!1,!1!==e.write(t)||l||((1===n.pipesCount&&n.pipes===e||n.pipesCount>1&&-1!==It(n.pipes,e))&&!c&&(wt("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,l=!0),r.pause())}function d(t){var r;wt("onerror",t),y(),e.removeListener("error",d),0===(r="error",e.listeners(r).length)&&e.emit("error",t)}function f(){e.removeListener("finish",p),y()}function p(){wt("onfinish"),e.removeListener("close",f),y()}function y(){wt("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||(wt("pipe resume"),r.resume()),e},At.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},Bt.prototype._write=function(e,t,r){r(new Error("not implemented"))},Bt.prototype._writev=null,Bt.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,Yt(e,t),r&&(t.finished?g(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,n,r)},Ue(Qt,At);for(var zt=Object.keys(Bt.prototype),Gt=0;Gt"===a?(O(n,"onsgmldeclaration",n.sgmlDecl),n.sgmlDecl="",n.state=T.TEXT):y(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,O(n,"ondoctype",n.doctype),n.doctype=!0):(n.doctype+=a,"["===a?n.state=T.DOCTYPE_DTD:y(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):y(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&&O(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:"]"===a?n.state=T.CDATA_ENDING:n.cdata+=a;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&&O(n,"oncdata",n.cdata),O(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:g(a)?n.state=T.PROC_INST_BODY:n.procInstName+=a;continue;case T.PROC_INST_BODY:if(!n.procInstBody&&g(a))continue;"?"===a?n.state=T.PROC_INST_ENDING:n.procInstBody+=a;continue;case T.PROC_INST_ENDING:">"===a?(O(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:(g(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(g(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)):g(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(g(a))continue;S(n,"Attribute without value"),n.tag.attributes[n.attribName]="",n.attribValue="",O(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(g(a))continue;y(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:g(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":O(t,"oncdata",t.cdata),t.cdata="";break;case"script":O(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&&(O(e,"oncdata",e.cdata),e.cdata=""),""!==e.script&&(O(e,"onscript",e.script),e.script="")}};try{t=ir.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){if("function"==typeof Z.isBuffer&&Z.isBuffer(e)){if(!this._decoder){var t=ar.StringDecoder;this._decoder=new t("utf8")}e=this._decoder.write(e)}return this._parser.write(e.toString()),this.emit("data",e),!0},a.prototype.end=function(e){return e&&e.length&&this.write(e),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 g(e){return" "===e||"\n"===e||"\r"===e||"\t"===e}function y(e){return'"'===e||"'"===e}function m(e){return">"===e||g(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 _ 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[_]]=_;function C(e,t,r){e[t]&&e[t](r)}function O(e,t,r){e.textNode&&D(e),C(e,t,r)}function D(e){e.textNode=x(e.opt,e.textNode),e.textNode&&C(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,C(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,C(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,O(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,O(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){O(e,"onopennamespace",{prefix:t,uri:r.ns[t]})}));for(var a=0,o=e.attribList.length;a",e.tagName="",void(e.state=T.SCRIPT);O(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,O(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];O(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?(S(e,"Invalid character entity"),"&"+e.entity+";"):String.fromCodePoint(t))}function j(e,t){"<"===t?(e.state=T.OPEN_WAKA,e.startTagPosition=e.position):g(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)}(Pe);var or,sr,cr=function(e){return Array.isArray?Array.isArray(e):"[object Array]"===Object.prototype.toString.call(e)},ur=cr,lr={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(e){"alwaysArray"in e&&("boolean"==typeof e.alwaysArray||ur(e.alwaysArray))||(e.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}},hr=Pe,dr=lr,fr=cr;function pr(e){var t=Number(e);if(!isNaN(t))return t;var r=e.toLowerCase();return"true"===r||"false"!==r&&e}function gr(e,t){var r;if(or.compact){if(!sr[or[e+"Key"]]&&(fr(or.alwaysArray)?-1!==or.alwaysArray.indexOf(or[e+"Key"]):or.alwaysArray)&&(sr[or[e+"Key"]]=[]),sr[or[e+"Key"]]&&!fr(sr[or[e+"Key"]])&&(sr[or[e+"Key"]]=[sr[or[e+"Key"]]]),e+"Fn"in or&&"string"==typeof t&&(t=or[e+"Fn"](t,sr)),"instruction"===e&&("instructionFn"in or||"instructionNameFn"in or))for(r in t)if(t.hasOwnProperty(r))if("instructionFn"in or)t[r]=or.instructionFn(t[r],r,sr);else{var n=t[r];delete t[r],t[or.instructionNameFn(r,n,sr)]=n}fr(sr[or[e+"Key"]])?sr[or[e+"Key"]].push(t):sr[or[e+"Key"]]=t}else{sr[or.elementsKey]||(sr[or.elementsKey]=[]);var i={};if(i[or.typeKey]=e,"instruction"===e){for(r in t)if(t.hasOwnProperty(r))break;i[or.nameKey]="instructionNameFn"in or?or.instructionNameFn(r,t,sr):r,or.instructionHasAttributes?(i[or.attributesKey]=t[r][or.attributesKey],"instructionFn"in or&&(i[or.attributesKey]=or.instructionFn(i[or.attributesKey],r,sr))):("instructionFn"in or&&(t[r]=or.instructionFn(t[r],r,sr)),i[or.instructionKey]=t[r])}else e+"Fn"in or&&(t=or[e+"Fn"](t,sr)),i[or[e+"Key"]]=t;or.addParent&&(i[or.parentKey]=sr),sr[or.elementsKey].push(i)}}function yr(e){var t;if("attributesFn"in or&&e&&(e=or.attributesFn(e,sr)),(or.trim||"attributeValueFn"in or||"attributeNameFn"in or||or.nativeTypeAttributes)&&e)for(t in e)if(e.hasOwnProperty(t)&&(or.trim&&(e[t]=e[t].trim()),or.nativeTypeAttributes&&(e[t]=pr(e[t])),"attributeValueFn"in or&&(e[t]=or.attributeValueFn(e[t],t,sr)),"attributeNameFn"in or)){var r=e[t];delete e[t],e[or.attributeNameFn(t,e[t],sr)]=r}return e}function mr(e){var t={};if(e.body&&("xml"===e.name.toLowerCase()||or.instructionHasAttributes)){for(var r,n=/([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\w+))\s*/g;null!==(r=n.exec(e.body));)t[r[1]]=r[2]||r[3]||r[4];t=yr(t)}if("xml"===e.name.toLowerCase()){if(or.ignoreDeclaration)return;sr[or.declarationKey]={},Object.keys(t).length&&(sr[or.declarationKey][or.attributesKey]=t),or.addParent&&(sr[or.declarationKey][or.parentKey]=sr)}else{if(or.ignoreInstruction)return;or.trim&&(e.body=e.body.trim());var i={};or.instructionHasAttributes&&Object.keys(t).length?(i[e.name]={},i[e.name][or.attributesKey]=t):i[e.name]=e.body,gr("instruction",i)}}function vr(e,t){var r;if("object"==typeof e&&(t=e.attributes,e=e.name),t=yr(t),"elementNameFn"in or&&(e=or.elementNameFn(e,sr)),or.compact){var n;if(r={},!or.ignoreAttributes&&t&&Object.keys(t).length)for(n in r[or.attributesKey]={},t)t.hasOwnProperty(n)&&(r[or.attributesKey][n]=t[n]);!(e in sr)&&(fr(or.alwaysArray)?-1!==or.alwaysArray.indexOf(e):or.alwaysArray)&&(sr[e]=[]),sr[e]&&!fr(sr[e])&&(sr[e]=[sr[e]]),fr(sr[e])?sr[e].push(r):sr[e]=r}else sr[or.elementsKey]||(sr[or.elementsKey]=[]),(r={})[or.typeKey]="element",r[or.nameKey]=e,!or.ignoreAttributes&&t&&Object.keys(t).length&&(r[or.attributesKey]=t),or.alwaysChildren&&(r[or.elementsKey]=[]),sr[or.elementsKey].push(r);r[or.parentKey]=sr,sr=r}function br(e){or.ignoreText||(e.trim()||or.captureSpacesBetweenElements)&&(or.trim&&(e=e.trim()),or.nativeType&&(e=pr(e)),or.sanitize&&(e=e.replace(/&/g,"&").replace(//g,">")),gr("text",e))}function wr(e){or.ignoreComment||(or.trim&&(e=e.trim()),gr("comment",e))}function Er(e){var t=sr[or.parentKey];or.addParent||delete sr[or.parentKey],sr=t}function Ar(e){or.ignoreCdata||(or.trim&&(e=e.trim()),gr("cdata",e))}function Tr(e){or.ignoreDoctype||(e=e.replace(/^ /,""),or.trim&&(e=e.trim()),gr("doctype",e))}function _r(e){e.note=e}var Cr=function(e,t){var r=hr.parser(!0,{}),n={};if(sr=n,or=function(e){return or=dr.copyOptions(e),dr.ensureFlagExists("ignoreDeclaration",or),dr.ensureFlagExists("ignoreInstruction",or),dr.ensureFlagExists("ignoreAttributes",or),dr.ensureFlagExists("ignoreText",or),dr.ensureFlagExists("ignoreComment",or),dr.ensureFlagExists("ignoreCdata",or),dr.ensureFlagExists("ignoreDoctype",or),dr.ensureFlagExists("compact",or),dr.ensureFlagExists("alwaysChildren",or),dr.ensureFlagExists("addParent",or),dr.ensureFlagExists("trim",or),dr.ensureFlagExists("nativeType",or),dr.ensureFlagExists("nativeTypeAttributes",or),dr.ensureFlagExists("sanitize",or),dr.ensureFlagExists("instructionHasAttributes",or),dr.ensureFlagExists("captureSpacesBetweenElements",or),dr.ensureAlwaysArrayExists(or),dr.ensureKeyExists("declaration",or),dr.ensureKeyExists("instruction",or),dr.ensureKeyExists("attributes",or),dr.ensureKeyExists("text",or),dr.ensureKeyExists("comment",or),dr.ensureKeyExists("cdata",or),dr.ensureKeyExists("doctype",or),dr.ensureKeyExists("type",or),dr.ensureKeyExists("name",or),dr.ensureKeyExists("elements",or),dr.ensureKeyExists("parent",or),dr.checkFnExists("doctype",or),dr.checkFnExists("instruction",or),dr.checkFnExists("cdata",or),dr.checkFnExists("comment",or),dr.checkFnExists("text",or),dr.checkFnExists("instructionName",or),dr.checkFnExists("elementName",or),dr.checkFnExists("attributeName",or),dr.checkFnExists("attributeValue",or),dr.checkFnExists("attributes",or),or}(t),r.opt={strictEntities:!0},r.onopentag=vr,r.ontext=br,r.oncomment=wr,r.onclosetag=Er,r.onerror=_r,r.oncdata=Ar,r.ondoctype=Tr,r.onprocessinginstruction=mr,r.write(e).close(),n[or.elementsKey]){var i=n[or.elementsKey];delete n[or.elementsKey],n[or.elementsKey]=i,delete n.text}return n},Or=lr,Dr=Cr;var xr,Rr,Fr=lr,Sr=cr;function Nr(e,t,r){return(!r&&e.spaces?"\n":"")+Array(t+1).join(e.spaces)}function Lr(e,t,r){if(t.ignoreAttributes)return"";"attributesFn"in t&&(e=t.attributesFn(e,Rr,xr));var n,i,a,o,s=[];for(n in e)e.hasOwnProperty(n)&&null!==e[n]&&void 0!==e[n]&&(o=t.noQuotesForNativeAttributes&&"string"!=typeof e[n]?"":'"',i=(i=""+e[n]).replace(/"/g,"""),a="attributeNameFn"in t?t.attributeNameFn(n,i,Rr,xr):n,s.push(t.spaces&&t.indentAttributes?Nr(t,r+1,!1):" "),s.push(a+"="+o+("attributeValueFn"in t?t.attributeValueFn(i,n,Rr,xr):i)+o));return e&&Object.keys(e).length&&t.spaces&&t.indentAttributes&&s.push(Nr(t,r,!1)),s.join("")}function kr(e,t,r){return xr=e,Rr="xml",t.ignoreDeclaration?"":""}function Ir(e,t,r){if(t.ignoreInstruction)return"";var n;for(n in e)if(e.hasOwnProperty(n))break;var i="instructionNameFn"in t?t.instructionNameFn(n,e[n],Rr,xr):n;if("object"==typeof e[n])return xr=e,Rr=i,"";var a=e[n]?e[n]:"";return"instructionFn"in t&&(a=t.instructionFn(a,n,Rr,xr)),""}function Ur(e,t){return t.ignoreComment?"":"\x3c!--"+("commentFn"in t?t.commentFn(e,Rr,xr):e)+"--\x3e"}function Pr(e,t){return t.ignoreCdata?"":"","]]]]>"))+"]]>"}function jr(e,t){return t.ignoreDoctype?"":""}function Br(e,t){return t.ignoreText?"":(e=(e=(e=""+e).replace(/&/g,"&")).replace(/&/g,"&").replace(//g,">"),"textFn"in t?t.textFn(e,Rr,xr):e)}function Vr(e,t,r,n){return e.reduce((function(e,i){var a=Nr(t,r,n&&!e);switch(i.type){case"element":return e+a+function(e,t,r){xr=e,Rr=e.name;var n=[],i="elementNameFn"in t?t.elementNameFn(e.name,e):e.name;n.push("<"+i),e[t.attributesKey]&&n.push(Lr(e[t.attributesKey],t,r));var a=e[t.elementsKey]&&e[t.elementsKey].length||e[t.attributesKey]&&"preserve"===e[t.attributesKey]["xml:space"];return a||(a="fullTagEmptyElementFn"in t?t.fullTagEmptyElementFn(e.name,e):t.fullTagEmptyElement),a?(n.push(">"),e[t.elementsKey]&&e[t.elementsKey].length&&(n.push(Vr(e[t.elementsKey],t,r+1)),xr=e,Rr=e.name),n.push(t.spaces&&function(e,t){var r;if(e.elements&&e.elements.length)for(r=0;r")):n.push("/>"),n.join("")}(i,t,r);case"comment":return e+a+Ur(i[t.commentKey],t);case"doctype":return e+a+jr(i[t.doctypeKey],t);case"cdata":return e+(t.indentCdata?a:"")+Pr(i[t.cdataKey],t);case"text":return e+(t.indentText?a:"")+Br(i[t.textKey],t);case"instruction":var o={};return o[i[t.nameKey]]=i[t.attributesKey]?i:i[t.instructionKey],e+(t.indentInstruction?a:"")+Ir(o,t,r)}}),"")}function Mr(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 $r(e,t,r,n,i){xr=e,Rr=t;var a="elementNameFn"in r?r.elementNameFn(t,e):t;if(null==e||""===e)return"fullTagEmptyElementFn"in r&&r.fullTagEmptyElementFn(t,e)||r.fullTagEmptyElement?"<"+a+">":"<"+a+"/>";var o=[];if(t){if(o.push("<"+a),"object"!=typeof e)return o.push(">"+Br(e,r)+""),o.join("");e[r.attributesKey]&&o.push(Lr(e[r.attributesKey],r,n));var s=Mr(e,r,!0)||e[r.attributesKey]&&"preserve"===e[r.attributesKey]["xml:space"];if(s||(s="fullTagEmptyElementFn"in r?r.fullTagEmptyElementFn(t,e):r.fullTagEmptyElement),!s)return o.push("/>"),o.join("");o.push(">")}return o.push(Kr(e,r,n+1,!1)),xr=e,Rr=t,t&&o.push((i?Nr(r,n,!1):"")+""),o.join("")}function Kr(e,t,r,n){var i,a,o,s=[];for(a in e)if(e.hasOwnProperty(a))for(o=Sr(e[a])?e[a]:[e[a]],i=0;i{const t=Number(e);if(!Number.isNaN(t))return t;const r=e.toLowerCase();return"true"===r||"false"!==r&&e},Qr=(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)},Xr=(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)},Zr=e=>e.reduce(((e,t)=>({...e,[U[t]]:t})),{}),Jr=e=>Object.entries(e).reduce(((e,[t,r])=>r?{...e,[t]:r}:e),{}),en=(e,t)=>t?{[e]:t}:{},tn=(e,t)=>e?t&&0!==t.length?Object.fromEntries(Object.entries(e).filter((([e])=>!t.includes(e)))):e:{};var rn=Object.freeze({__proto__:null,cleanupFalsy:Jr,conditionalParam:en,excludeHeaders:tn,getDAVAttribute:Zr,urlContains:Xr,urlEquals:Qr});const nn=I("tsdav:request"),an=async e=>{var t;const{url:r,init:n,convertIncoming:i=!0,parseOutgoing:a=!0,fetchOptions:o={}}=e,{headers:s={},body:c,namespace:u,method:l,attributes:h}=n,d=i?Gr.js2xml({_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}},...c,_attributes:h},{compact:!0,spaces:2,elementNameFn:e=>u&&!/^.+:.+/.test(e)?`${u}:${e}`:e}):c,f=await fetch(r,{headers:{"Content-Type":"text/xml;charset=UTF-8",...Jr(s)},body:d,method:l,...o}),p=await f.text();if(!f.ok||!(null===(t=f.headers.get("content-type"))||void 0===t?void 0:t.includes("xml"))||!a)return[{href:f.url,ok:f.ok,status:f.status,statusText:f.statusText,raw:p}];const g=Gr.xml2js(p,{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]=Wr(e)}else r[i]=Wr(e)}catch(e){nn(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:f.status,statusText:f.statusText,ok:f.ok};const n=/^\S+\s(?\d+)\s(?.+)$/.exec(e.status);return{raw:g,href:e.href,status:(null==n?void 0:n.groups)?Number.parseInt(null==n?void 0:n.groups.status,10):f.status,statusText:null!==(r=null===(t=null==n?void 0:n.groups)||void 0===t?void 0:t.statusText)&&void 0!==r?r:f.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})),{})}}))},on=async e=>{const{url:t,props:r,depth:n,headers:i,headersToExclude:a,fetchOptions:o={}}=e;return an({url:t,init:{method:"PROPFIND",headers:tn(Jr({depth:n,...i}),a),namespace:P.DAV,body:{propfind:{_attributes:Zr([k.CALDAV,k.CALDAV_APPLE,k.CALENDAR_SERVER,k.CARDDAV,k.DAV]),prop:r}}},fetchOptions:o})},sn=async e=>{const{url:t,data:r,headers:n,headersToExclude:i,fetchOptions:a={}}=e;return fetch(t,{method:"PUT",body:r,headers:tn(n,i),...a})},cn=async e=>{const{url:t,data:r,etag:n,headers:i,headersToExclude:a,fetchOptions:o={}}=e;return fetch(t,{method:"PUT",body:r,headers:tn(Jr({"If-Match":n,...i}),a),...o})},un=async e=>{const{url:t,headers:r,etag:n,headersToExclude:i,fetchOptions:a={}}=e;return fetch(t,{method:"DELETE",headers:tn(Jr({"If-Match":n,...r}),i),...a})};var ln=Object.freeze({__proto__:null,createObject:sn,davRequest:an,deleteObject:un,propfind:on,updateObject:cn});function hn(e,t){const r=e=>t.every((t=>e[t]));return Array.isArray(e)?e.every((e=>r(e))):r(e)}const dn=(e,t)=>t.reduce(((t,r)=>e[r]?t:`${t.length?`${t},`:""}${r.toString()}`),""),fn=I("tsdav:collection"),pn=async e=>{const{url:t,body:r,depth:n,defaultNamespace:i=P.DAV,headers:a,headersToExclude:o,fetchOptions:s={}}=e,c=await an({url:t,init:{method:"REPORT",headers:tn(Jr({depth:n,...a}),o),namespace:i,body:r},fetchOptions:s});return 1!==c.length||c[0].raw?c:[]},gn=async e=>{const{url:t,props:r,depth:n,headers:i,headersToExclude:a,fetchOptions:o={}}=e;return an({url:t,init:{method:"MKCOL",headers:tn(Jr({depth:n,...i}),a),namespace:P.DAV,body:r?{mkcol:{set:{prop:r}}}:void 0},fetchOptions:o})},yn=async e=>{var t,r,n,i,a;const{collection:o,headers:s,headersToExclude:c,fetchOptions:u={}}=e;return null!==(a=null===(i=null===(n=null===(r=null===(t=(await on({url:o.url,props:{[`${P.DAV}:supported-report-set`]:{}},depth:"0",headers:tn(s,c),fetchOptions:u}))[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:[]},mn=async e=>{var t,r,n;const{collection:i,headers:a,headersToExclude:o,fetchOptions:s={}}=e,c=(await on({url:i.url,props:{[`${P.CALENDAR_SERVER}:getctag`]:{}},depth:"0",headers:tn(a,o),fetchOptions:s})).filter((e=>Xr(i.url,e.href)))[0];if(!c)throw new Error("Collection does not exist on server");return{isDirty:`${i.ctag}`!=`${null===(t=c.props)||void 0===t?void 0:t.getctag}`,newCtag:null===(n=null===(r=c.props)||void 0===r?void 0:r.getctag)||void 0===n?void 0:n.toString()}},vn=e=>{const{url:t,props:r,headers:n,syncLevel:i,syncToken:a,headersToExclude:o,fetchOptions:s}=e;return an({url:t,init:{method:"REPORT",namespace:P.DAV,headers:tn({...n},o),body:{"sync-collection":{_attributes:Zr([k.CALDAV,k.CARDDAV,k.DAV]),"sync-level":i,"sync-token":a,[`${P.DAV}:prop`]:r}}},fetchOptions:s})},bn=async e=>{var t,r,n,i,a,o,s,c,u,l,h;const{collection:d,method:f,headers:p,headersToExclude:g,account:y,detailedResult:m,fetchOptions:v={}}=e,b=["accountType","homeUrl"];if(!y||!hn(y,b)){if(!y)throw new Error("no account for smartCollectionSync");throw new Error(`account must have ${dn(y,b)} before smartCollectionSync`)}const w=null!=f?f:(null===(t=d.reports)||void 0===t?void 0:t.includes("syncCollection"))?"webdav":"basic";if(fn(`smart collection sync with type ${y.accountType} and method ${w}`),"webdav"===w){const e=await vn({url:d.url,props:{[`${P.DAV}:getetag`]:{},[`${"caldav"===y.accountType?P.CALDAV:P.CARDDAV}:${"caldav"===y.accountType?"calendar-data":"address-data"}`]:{},[`${P.DAV}:displayname`]:{}},syncLevel:1,syncToken:d.syncToken,headers:tn(p,g),fetchOptions:v}),t=e.filter((e=>{var t;const r="caldav"===y.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==d?void 0:d.objectMultiGet)||void 0===r?void 0:r.call(d,{url:d.url,props:{[`${P.DAV}:getetag`]:{},[`${"caldav"===y.accountType?P.CALDAV:P.CARDDAV}:${"caldav"===y.accountType?"calendar-data":"address-data"}`]:{}},objectUrls:u,depth:"1",headers:tn(p,g),fetchOptions:v})))&&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==y?void 0:y.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}})),f=null!==(i=d.objects)&&void 0!==i?i:[],b=h.filter((e=>f.every((t=>!Xr(t.url,e.url))))),w=f.reduce(((e,t)=>{const r=h.find((e=>Xr(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),E=l.map((e=>({url:e,etag:""}))),A=f.filter((e=>h.some((t=>Xr(e.url,t.url)&&t.etag===e.etag))));return{...d,objects:m?{created:b,updated:w,deleted:E}:[...A,...b,...w],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:d.syncToken}}if("basic"===w){const{isDirty:e,newCtag:t}=await mn({collection:d,headers:tn(p,g),fetchOptions:v}),r=null!==(u=d.objects)&&void 0!==u?u:[],n=null!==(h=await(null===(l=d.fetchObjects)||void 0===l?void 0:l.call(d,{collection:d,headers:tn(p,g),fetchOptions:v})))&&void 0!==h?h:[],i=n.filter((e=>r.every((t=>!Xr(t.url,e.url))))),a=r.reduce(((e,t)=>{const r=n.find((e=>Xr(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),o=r.filter((e=>n.every((t=>!Xr(t.url,e.url))))),s=r.filter((e=>n.some((t=>Xr(e.url,t.url)&&t.etag===e.etag))));if(e)return{...d,objects:m?{created:i,updated:a,deleted:o}:[...s,...i,...a],ctag:t}}return m?{...d,objects:{created:[],updated:[],deleted:[]}}:d};var wn=Object.freeze({__proto__:null,collectionQuery:pn,isCollectionDirty:mn,makeCollection:gn,smartCollectionSync:bn,supportedReportSet:yn,syncCollection:vn});const En=I("tsdav:addressBook"),An=async e=>{const{url:t,props:r,filters:n,depth:i,headers:a,headersToExclude:o,fetchOptions:s={}}=e;return pn({url:t,body:{"addressbook-query":Jr({_attributes:Zr([k.CARDDAV,k.DAV]),[`${P.DAV}:prop`]:r,filter:null!=n?n:{"prop-filter":{_attributes:{name:"FN"}}}})},defaultNamespace:P.CARDDAV,depth:i,headers:tn(a,o),fetchOptions:s})},Tn=async e=>{const{url:t,props:r,objectUrls:n,depth:i,headers:a,headersToExclude:o,fetchOptions:s={}}=e;return pn({url:t,body:{"addressbook-multiget":Jr({_attributes:Zr([k.DAV,k.CARDDAV]),[`${P.DAV}:prop`]:r,[`${P.DAV}:href`]:n})},defaultNamespace:P.CARDDAV,depth:i,headers:tn(a,o),fetchOptions:s})},_n=async e=>{const{account:t,headers:r,props:n,headersToExclude:i,fetchOptions:a={}}=null!=e?e:{},o=["homeUrl","rootUrl"];if(!t||!hn(t,o)){if(!t)throw new Error("no account for fetchAddressBooks");throw new Error(`account must have ${dn(t,o)} before fetchAddressBooks`)}const s=await on({url:t.homeUrl,props:null!=n?n:{[`${P.DAV}:displayname`]:{},[`${P.CALENDAR_SERVER}:getctag`]:{},[`${P.DAV}:resourcetype`]:{},[`${P.DAV}:sync-token`]:{}},depth:"1",headers:tn(r,i),fetchOptions:a});return Promise.all(s.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 En(`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 yn({collection:e,headers:tn(r,i),fetchOptions:a})}))))},Cn=async e=>{const{addressBook:t,headers:r,objectUrls:n,headersToExclude:i,urlFilter:a=e=>e,useMultiGet:o=!0,fetchOptions:s={}}=e;En(`Fetching vcards from ${null==t?void 0:t.url}`);const c=["url"];if(!t||!hn(t,c)){if(!t)throw new Error("cannot fetchVCards for undefined addressBook");throw new Error(`addressBook must have ${dn(t,c)} before fetchVCards`)}const u=(null!=n?n:(await An({url:t.url,props:{[`${P.DAV}:getetag`]:{}},depth:"1",headers:tn(r,i),fetchOptions:s})).map((e=>{var t;return e.ok&&null!==(t=e.href)&&void 0!==t?t:""}))).map((e=>e.startsWith("http")||!e?e:new URL(e,t.url).href)).filter(a).map((e=>new URL(e).pathname));let l=[];return u.length>0&&(l=o?await Tn({url:t.url,props:{[`${P.DAV}:getetag`]:{},[`${P.CARDDAV}:address-data`]:{}},objectUrls:u,depth:"1",headers:tn(r,i),fetchOptions:s}):await An({url:t.url,props:{[`${P.DAV}:getetag`]:{},[`${P.CARDDAV}:address-data`]:{}},depth:"1",headers:tn(r,i),fetchOptions:s})),l.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}}))},On=async e=>{const{addressBook:t,vCardString:r,filename:n,headers:i,headersToExclude:a,fetchOptions:o={}}=e;return sn({url:new URL(n,t.url).href,data:r,headers:tn({"content-type":"text/vcard; charset=utf-8","If-None-Match":"*",...i},a),fetchOptions:o})},Dn=async e=>{const{vCard:t,headers:r,headersToExclude:n,fetchOptions:i={}}=e;return cn({url:t.url,data:t.data,etag:t.etag,headers:tn({"content-type":"text/vcard; charset=utf-8",...r},n),fetchOptions:i})},xn=async e=>{const{vCard:t,headers:r,headersToExclude:n,fetchOptions:i={}}=e;return un({url:t.url,etag:t.etag,headers:tn(r,n),fetchOptions:i})};var Rn=Object.freeze({__proto__:null,addressBookMultiGet:Tn,addressBookQuery:An,createVCard:On,deleteVCard:xn,fetchAddressBooks:_n,fetchVCards:Cn,updateVCard:Dn});const Fn=I("tsdav:calendar"),Sn=async e=>{var t,r,n;const{account:i,headers:a,headersToExclude:o,fetchOptions:s={}}=e,c=["principalUrl","rootUrl"];if(!hn(i,c))throw new Error(`account must have ${dn(i,c)} before fetchUserAddresses`);Fn(`Fetch user addresses from ${i.principalUrl}`);const u=(await on({url:i.principalUrl,props:{[`${P.CALDAV}:calendar-user-address-set`]:{}},depth:"0",headers:tn(a,o),fetchOptions:s})).find((e=>Xr(i.principalUrl,e.href)));if(!u||!u.ok)throw new Error("cannot find calendarUserAddresses");const l=(null===(n=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===n?void 0:n.filter(Boolean))||[];return Fn(`Fetched calendar user addresses ${l}`),l},Nn=async e=>{const{url:t,props:r,filters:n,timezone:i,depth:a,headers:o,headersToExclude:s,fetchOptions:c={}}=e;return pn({url:t,body:{"calendar-query":Jr({_attributes:Zr([k.CALDAV,k.CALENDAR_SERVER,k.CALDAV_APPLE,k.DAV]),[`${P.DAV}:prop`]:r,filter:n,timezone:i})},defaultNamespace:P.CALDAV,depth:a,headers:tn(o,s),fetchOptions:c})},Ln=async e=>{const{url:t,props:r,objectUrls:n,filters:i,timezone:a,depth:o,headers:s,headersToExclude:c,fetchOptions:u={}}=e;return pn({url:t,body:{"calendar-multiget":Jr({_attributes:Zr([k.DAV,k.CALDAV]),[`${P.DAV}:prop`]:r,[`${P.DAV}:href`]:n,filter:i,timezone:a})},defaultNamespace:P.CALDAV,depth:o,headers:tn(s,c),fetchOptions:u})},kn=async e=>{const{url:t,props:r,depth:n,headers:i,headersToExclude:a,fetchOptions:o={}}=e;return an({url:t,init:{method:"MKCALENDAR",headers:tn(Jr({depth:n,...i}),a),namespace:P.DAV,body:{[`${P.CALDAV}:mkcalendar`]:{_attributes:Zr([k.DAV,k.CALDAV,k.CALDAV_APPLE]),set:{prop:r}}}},fetchOptions:o})},In=async e=>{const{headers:t,account:r,props:n,projectedProps:i,headersToExclude:a,fetchOptions:o={}}=null!=e?e:{},s=["homeUrl","rootUrl"];if(!r||!hn(r,s)){if(!r)throw new Error("no account for fetchCalendars");throw new Error(`account must have ${dn(r,s)} before fetchCalendars`)}const c=await on({url:r.homeUrl,props:null!=n?n:{[`${P.CALDAV}:calendar-description`]:{},[`${P.CALDAV}:calendar-timezone`]:{},[`${P.DAV}:displayname`]:{},[`${P.CALDAV_APPLE}:calendar-color`]:{},[`${P.CALENDAR_SERVER}:getctag`]:{},[`${P.DAV}:resourcetype`]:{},[`${P.CALDAV}:supported-calendar-component-set`]:{},[`${P.DAV}:sync-token`]:{}},depth:"1",headers:tn(t,a),fetchOptions: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("calendar")})).filter((e=>{var t,r,n,i;return(Array.isArray(null===(t=e.props)||void 0===t?void 0:t.supportedCalendarComponentSet.comp)?null===(r=e.props)||void 0===r?void 0:r.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(i=null===(n=e.props)||void 0===n?void 0:n.supportedCalendarComponentSet.comp)||void 0===i?void 0:i._attributes.name]).some((e=>Object.values(j).includes(e)))})).map((e=>{var t,n,a,o,s,c,u,l,h,d,f,p,g,y,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===(g=null===(p=e.props)||void 0===p?void 0:p.supportedCalendarComponentSet.comp)||void 0===g?void 0:g._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,...en("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 yn({collection:e,headers:tn(t,a),fetchOptions:o})}))))},Un=async e=>{const{calendar:t,objectUrls:r,filters:n,timeRange:i,headers:a,expand:o,urlFilter:s=e=>Boolean(null==e?void 0:e.includes(".ics")),useMultiGet:c=!0,headersToExclude:u,fetchOptions:l={}}=e;if(i){const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(i.start)&&e.test(i.end)||t.test(i.start)&&t.test(i.end)))throw new Error("invalid timeRange format, not in ISO8601")}Fn(`Fetching calendar objects from ${null==t?void 0:t.url}`);const h=["url"];if(!t||!hn(t,h)){if(!t)throw new Error("cannot fetchCalendarObjects for undefined calendar");throw new Error(`calendar must have ${dn(t,h)} before fetchCalendarObjects`)}const d=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`}}}:{}}}}],f=(null!=r?r:(await Nn({url:t.url,props:{[`${P.DAV}:getetag`]:{...o&&i?{[`${P.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:d,depth:"1",headers:tn(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 Nn({url:t.url,props:{[`${P.DAV}:getetag`]:{},[`${P.CALDAV}:calendar-data`]:{...o&&i?{[`${P.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:d,depth:"1",headers:tn(a,u),fetchOptions:l}):await Ln({url:t.url,props:{[`${P.DAV}:getetag`]:{},[`${P.CALDAV}:calendar-data`]:{...o&&i?{[`${P.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:f,depth:"1",headers:tn(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}}))},Pn=async e=>{const{calendar:t,iCalString:r,filename:n,headers:i,headersToExclude:a,fetchOptions:o={}}=e;return sn({url:new URL(n,t.url).href,data:r,headers:tn({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*",...i},a),fetchOptions:o})},jn=async e=>{const{calendarObject:t,headers:r,headersToExclude:n,fetchOptions:i={}}=e;return cn({url:t.url,data:t.data,etag:t.etag,headers:tn({"content-type":"text/calendar; charset=utf-8",...r},n),fetchOptions:i})},Bn=async e=>{const{calendarObject:t,headers:r,headersToExclude:n,fetchOptions:i={}}=e;return un({url:t.url,etag:t.etag,headers:tn(r,n),fetchOptions:i})},Vn=async e=>{var t;const{oldCalendars:r,account:n,detailedResult:i,headers:a,headersToExclude:o,fetchOptions:s={}}=e;if(!n)throw new Error("Must have account before syncCalendars");const c=null!==(t=null!=r?r:n.calendars)&&void 0!==t?t:[],u=await In({account:n,headers:tn(a,o),fetchOptions:s}),l=u.filter((e=>c.every((t=>!Xr(t.url,e.url)))));Fn(`new calendars: ${l.map((e=>e.displayName))}`);const h=c.reduce(((e,t)=>{const r=u.find((e=>Xr(e.url,t.url)));return r&&(r.syncToken&&`${r.syncToken}`!=`${t.syncToken}`||r.ctag&&`${r.ctag}`!=`${t.ctag}`)?[...e,r]:e}),[]);Fn(`updated calendars: ${h.map((e=>e.displayName))}`);const d=await Promise.all(h.map((async e=>await bn({collection:{...e,objectMultiGet:Ln},method:"webdav",headers:tn(a,o),account:n,fetchOptions:s})))),f=c.filter((e=>u.every((t=>!Xr(t.url,e.url)))));Fn(`deleted calendars: ${f.map((e=>e.displayName))}`);const p=c.filter((e=>u.some((t=>Xr(t.url,e.url)&&(t.syncToken&&`${t.syncToken}`!=`${e.syncToken}`||t.ctag&&`${t.ctag}`!=`${e.ctag}`)))));return i?{created:l,updated:h,deleted:f}:[...p,...l,...d]},Mn=async e=>{const{url:t,timeRange:r,depth:n,headers:i,headersToExclude:a,fetchOptions:o={}}=e;if(!r)throw new Error("timeRange is required");{const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(r.start)&&e.test(r.end)||t.test(r.start)&&t.test(r.end)))throw new Error("invalid timeRange format, not in ISO8601")}return(await pn({url:t,body:{"free-busy-query":Jr({_attributes:Zr([k.CALDAV]),[`${P.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:P.CALDAV,depth:n,headers:tn(i,a),fetchOptions:o}))[0]};var $n=Object.freeze({__proto__:null,calendarMultiGet:Ln,calendarQuery:Nn,createCalendarObject:Pn,deleteCalendarObject:Bn,fetchCalendarObjects:Un,fetchCalendarUserAddresses:Sn,fetchCalendars:In,freeBusyQuery:Mn,makeCalendar:kn,syncCalendars:Vn,updateCalendarObject:jn});const Kn=I("tsdav:account"),Hn=async e=>{var t,r;Kn("Service discovery...");const{account:n,headers:i,headersToExclude:a,fetchOptions:o={}}=e,s=new URL(n.serverUrl),c=new URL(`/.well-known/${n.accountType}`,s);c.protocol=null!==(t=s.protocol)&&void 0!==t?t:"http";try{const e=await fetch(c.href,{headers:tn(i,a),method:"PROPFIND",redirect:"manual",...o});if(e.status>=300&&e.status<400){const t=e.headers.get("Location");if("string"==typeof t&&t.length){Kn(`Service discovery redirected to ${t}`);const e=new URL(t,s);return e.hostname===c.hostname&&c.port&&!e.port&&(e.port=c.port),e.protocol=null!==(r=s.protocol)&&void 0!==r?r:"http",e.href}}}catch(e){Kn(`Service discovery failed: ${e.stack}`)}return s.href},Yn=async e=>{var t,r,n,i,a;const{account:o,headers:s,headersToExclude:c,fetchOptions:u={}}=e,l=["rootUrl"];if(!hn(o,l))throw new Error(`account must have ${dn(o,l)} before fetchPrincipalUrl`);Kn(`Fetching principal url from path ${o.rootUrl}`);const[h]=await on({url:o.rootUrl,props:{[`${P.DAV}:current-user-principal`]:{}},depth:"0",headers:tn(s,c),fetchOptions:u});if(!h.ok&&(Kn(`Fetch principal url failed: ${h.statusText}`),401===h.status))throw new Error("Invalid credentials");return Kn(`Fetched principal url ${null===(r=null===(t=h.props)||void 0===t?void 0:t.currentUserPrincipal)||void 0===r?void 0:r.href}`),new URL(null!==(a=null===(i=null===(n=h.props)||void 0===n?void 0:n.currentUserPrincipal)||void 0===i?void 0:i.href)&&void 0!==a?a:"",o.rootUrl).href},qn=async e=>{var t,r;const{account:n,headers:i,headersToExclude:a,fetchOptions:o={}}=e,s=["principalUrl","rootUrl"];if(!hn(n,s))throw new Error(`account must have ${dn(n,s)} before fetchHomeUrl`);Kn(`Fetch home url from ${n.principalUrl}`);const c=(await on({url:n.principalUrl,props:"caldav"===n.accountType?{[`${P.CALDAV}:calendar-home-set`]:{}}:{[`${P.CARDDAV}:addressbook-home-set`]:{}},depth:"0",headers:tn(i,a),fetchOptions:o})).find((e=>Xr(n.principalUrl,e.href)));if(!c||!c.ok)throw new Error("cannot find homeUrl");const u=new URL("caldav"===n.accountType?null===(t=null==c?void 0:c.props)||void 0===t?void 0:t.calendarHomeSet.href:null===(r=null==c?void 0:c.props)||void 0===r?void 0:r.addressbookHomeSet.href,n.rootUrl).href;return Kn(`Fetched home url ${u}`),u},zn=async e=>{const{account:t,headers:r,loadCollections:n=!1,loadObjects:i=!1,headersToExclude:a,fetchOptions:o={}}=e,s={...t};return s.rootUrl=await Hn({account:t,headers:tn(r,a),fetchOptions:o}),s.principalUrl=await Yn({account:s,headers:tn(r,a),fetchOptions:o}),s.homeUrl=await qn({account:s,headers:tn(r,a),fetchOptions:o}),(n||i)&&("caldav"===t.accountType?s.calendars=await In({headers:tn(r,a),account:s,fetchOptions:o}):"carddav"===t.accountType&&(s.addressBooks=await _n({headers:tn(r,a),account:s,fetchOptions:o}))),i&&("caldav"===t.accountType&&s.calendars?s.calendars=await Promise.all(s.calendars.map((async e=>({...e,objects:await Un({calendar:e,headers:tn(r,a),fetchOptions:o})})))):"carddav"===t.accountType&&s.addressBooks&&(s.addressBooks=await Promise.all(s.addressBooks.map((async e=>({...e,objects:await Cn({addressBook:e,headers:tn(r,a),fetchOptions:o})})))))),s};var Gn,Wn,Qn=Object.freeze({__proto__:null,createAccount:zn,fetchHomeUrl:qn,fetchPrincipalUrl:Yn,serviceDiscovery:Hn}),Xn={exports:{}};Gn=Xn,Wn=Xn.exports,function(t){var r=Wn,n=Gn&&Gn.exports==r&&Gn,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}(e);var Zn=Xn.exports;const Jn=I("tsdav:authHelper"),ei=(e,t)=>(...r)=>e({...t,...r[0]}),ti=e=>(Jn(`Basic auth token generated: ${Zn.encode(`${e.username}:${e.password}`)}`),{authorization:`Basic ${Zn.encode(`${e.username}:${e.password}`)}`}),ri=async(e,t)=>{const r=["authorizationCode","redirectUrl","clientId","clientSecret","tokenUrl"];if(!hn(e,r))throw new Error(`Oauth credentials missing: ${dn(e,r)}`);const n=new URLSearchParams({grant_type:"authorization_code",code:e.authorizationCode,redirect_uri:e.redirectUrl,client_id:e.clientId,client_secret:e.clientSecret});Jn(e.tokenUrl),Jn(n.toString());const i=await fetch(e.tokenUrl,{method:"POST",body:n.toString(),headers:{"content-length":`${n.toString().length}`,"content-type":"application/x-www-form-urlencoded"},...null!=t?t:{}});if(i.ok){return await i.json()}return Jn(`Fetch Oauth tokens failed: ${await i.text()}`),{}},ni=async(e,t)=>{const r=["refreshToken","clientId","clientSecret","tokenUrl"];if(!hn(e,r))throw new Error(`Oauth credentials missing: ${dn(e,r)}`);const n=new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,refresh_token:e.refreshToken,grant_type:"refresh_token"}),i=await fetch(e.tokenUrl,{method:"POST",body:n.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},...null!=t?t:{}});if(i.ok){return await i.json()}return Jn(`Refresh access token failed: ${await i.text()}`),{}},ii=async(e,t)=>{var r;Jn("Fetching oauth headers");let n={};return e.refreshToken?(e.refreshToken&&!e.accessToken||Date.now()>(null!==(r=e.expiration)&&void 0!==r?r:0))&&(n=await ni(e,t)):n=await ri(e,t),Jn(`Oauth tokens fetched: ${n.access_token}`),{tokens:n,headers:{authorization:`Bearer ${n.access_token}`}}};var ai=Object.freeze({__proto__:null,defaultParam:ei,fetchOauthTokens:ri,getBasicAuthHeaders:ti,getOauthHeaders:ii,refreshAccessToken:ni});const oi=async e=>{var t;const{serverUrl:r,credentials:n,authMethod:i,defaultAccountType:a,authFunction:o}=e;let s={};switch(i){case"Basic":s=ti(n);break;case"Oauth":s=(await ii(n)).headers;break;case"Digest":s={Authorization:`Digest ${n.digestString}`};break;case"Custom":s=null!==(t=await(null==o?void 0:o(n)))&&void 0!==t?t:{};break;default:throw new Error("Invalid auth method")}const c=a?await zn({account:{serverUrl:r,credentials:n,accountType:a},headers:s}):void 0,u=ei(sn,{url:r,headers:s}),l=ei(cn,{headers:s,url:r}),h=ei(un,{headers:s,url:r}),d=ei(on,{headers:s}),f=ei(pn,{headers:s}),p=ei(gn,{headers:s}),g=ei(vn,{headers:s}),y=ei(yn,{headers:s}),m=ei(mn,{headers:s}),v=ei(bn,{headers:s,account:c}),b=ei(Nn,{headers:s}),w=ei(Ln,{headers:s}),E=ei(kn,{headers:s}),A=ei(In,{headers:s,account:c}),T=ei(Sn,{headers:s,account:c}),_=ei(Un,{headers:s}),C=ei(Pn,{headers:s}),O=ei(jn,{headers:s}),D=ei(Bn,{headers:s}),x=ei(Vn,{account:c,headers:s}),R=ei(An,{headers:s}),F=ei(Tn,{headers:s});return{davRequest:async e=>{const{init:t,...r}=e,{headers:n,...i}=t;return an({...r,init:{...i,headers:{...s,...n}}})},propfind:d,createAccount:async e=>{const{account:t,headers:i,loadCollections:a,loadObjects:o}=e;return zn({account:{serverUrl:r,credentials:n,...t},headers:{...s,...i},loadCollections:a,loadObjects:o})},createObject:u,updateObject:l,deleteObject:h,calendarQuery:b,addressBookQuery:R,collectionQuery:f,makeCollection:p,calendarMultiGet:w,makeCalendar:E,syncCollection:g,supportedReportSet:y,isCollectionDirty:m,smartCollectionSync:v,fetchCalendars:A,fetchCalendarUserAddresses:T,fetchCalendarObjects:_,createCalendarObject:C,updateCalendarObject:O,deleteCalendarObject:D,syncCalendars:x,fetchAddressBooks:ei(_n,{account:c,headers:s}),addressBookMultiGet:F,fetchVCards:ei(Cn,{headers:s}),createVCard:ei(On,{headers:s}),updateVCard:ei(Dn,{headers:s}),deleteVCard:ei(xn,{headers:s})}};class si{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:{}}async login(){var e;switch(this.authMethod){case"Basic":this.authHeaders=ti(this.credentials);break;case"Oauth":this.authHeaders=(await ii(this.credentials,this.fetchOptions)).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 zn({account:{serverUrl:this.serverUrl,credentials:this.credentials,accountType:this.accountType},headers:this.authHeaders,fetchOptions:this.fetchOptions}):void 0}async davRequest(e){const{init:t,...r}=e,{headers:n,...i}=t;return an({...r,init:{...i,headers:{...this.authHeaders,...n}},fetchOptions:this.fetchOptions})}async createObject(...e){return ei(sn,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateObject(...e){return ei(cn,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteObject(...e){return ei(un,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async propfind(...e){return ei(on,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createAccount(e){const{account:t,headers:r,loadCollections:n,loadObjects:i,fetchOptions:a}=e;return zn({account:{serverUrl:this.serverUrl,credentials:this.credentials,...t},headers:{...this.authHeaders,...r},loadCollections:n,loadObjects:i,fetchOptions:null!=a?a:this.fetchOptions})}async collectionQuery(...e){return ei(pn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async makeCollection(...e){return ei(gn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async syncCollection(...e){return ei(vn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async supportedReportSet(...e){return ei(yn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async isCollectionDirty(...e){return ei(mn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async smartCollectionSync(...e){return ei(bn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,account:this.account})(e[0])}async calendarQuery(...e){return ei(Nn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async makeCalendar(...e){return ei(kn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async calendarMultiGet(...e){return ei(Ln,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async fetchCalendars(...e){return ei(In,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(null==e?void 0:e[0])}async fetchCalendarUserAddresses(...e){return ei(Sn,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(null==e?void 0:e[0])}async fetchCalendarObjects(...e){return ei(Un,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createCalendarObject(...e){return ei(Pn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateCalendarObject(...e){return ei(jn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteCalendarObject(...e){return ei(Bn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async syncCalendars(...e){return ei(Vn,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(e[0])}async addressBookQuery(...e){return ei(An,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async addressBookMultiGet(...e){return ei(Tn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async fetchAddressBooks(...e){return ei(_n,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(null==e?void 0:e[0])}async fetchVCards(...e){return ei(Cn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createVCard(...e){return ei(On,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateVCard(...e){return ei(Dn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteVCard(...e){return ei(xn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}}var ci={DAVNamespace:k,DAVNamespaceShort:P,DAVAttributeMap:U,...Object.freeze({__proto__:null,DAVClient:si,createDAVClient:oi}),...ln,...wn,...Qn,...Rn,...$n,...ai,...rn};export{U as DAVAttributeMap,si as DAVClient,k as DAVNamespace,P as DAVNamespaceShort,An as addressBookQuery,Ln as calendarMultiGet,Nn as calendarQuery,Jr as cleanupFalsy,pn as collectionQuery,zn as createAccount,Pn as createCalendarObject,oi as createDAVClient,sn as createObject,On as createVCard,an as davRequest,ci as default,Bn as deleteCalendarObject,un as deleteObject,xn as deleteVCard,_n as fetchAddressBooks,Un as fetchCalendarObjects,Sn as fetchCalendarUserAddresses,In as fetchCalendars,ri as fetchOauthTokens,Cn as fetchVCards,Mn as freeBusyQuery,ti as getBasicAuthHeaders,Zr as getDAVAttribute,ii as getOauthHeaders,mn as isCollectionDirty,kn as makeCalendar,on as propfind,ni as refreshAccessToken,bn as smartCollectionSync,yn as supportedReportSet,Vn as syncCalendars,vn as syncCollection,jn as updateCalendarObject,cn as updateObject,Dn as updateVCard,Xr as urlContains,Qr as urlEquals}; diff --git a/dist/tsdav.min.mjs b/dist/tsdav.min.mjs index cbdc70f0..6ee38406 100644 --- a/dist/tsdav.min.mjs +++ b/dist/tsdav.min.mjs @@ -1 +1 @@ -import{fetch as e}from"cross-fetch";import t from"debug";import r from"xml-js";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=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)},u=e=>e.reduce(((e,t)=>({...e,[o[t]]:t})),{}),h=e=>Object.entries(e).reduce(((e,[t,r])=>r?{...e,[t]:r}:e),{}),p=(e,t)=>t?{[e]:t}:{},f=(e,t)=>e?t&&0!==t.length?Object.fromEntries(Object.entries(e).filter((([e])=>!t.includes(e)))):e:{};var v=Object.freeze({__proto__:null,cleanupFalsy:h,conditionalParam:p,excludeHeaders:f,getDAVAttribute:u,urlContains:l,urlEquals:i});const y=t("tsdav:request"),O=async t=>{var a;const{url:s,init:o,convertIncoming:n=!0,parseOutgoing:c=!0,fetchOptions:i={}}=t,{headers:l={},body:u,namespace:p,method:f,attributes:v}=o,O=n?r.js2xml({_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}},...u,_attributes:v},{compact:!0,spaces:2,elementNameFn:e=>p&&!/^.+:.+/.test(e)?`${p}:${e}`:e}):u,m=await e(s,{headers:{"Content-Type":"text/xml;charset=UTF-8",...h(l)},body:O,method:f,...i}),A=await m.text();if(!m.ok||!(null===(a=m.headers.get("content-type"))||void 0===a?void 0:a.includes("xml"))||!c)return[{href:m.url,ok:m.ok,status:m.status,statusText:m.statusText,raw:A}];const g=r.xml2js(A,{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]=d(e)}else r[s]=d(e)}catch(e){y(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:m.status,statusText:m.statusText,ok:m.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):m.status,statusText:null!==(r=null===(t=null==a?void 0:a.groups)||void 0===t?void 0:t.statusText)&&void 0!==r?r:m.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})),{})}}))},m=async e=>{const{url:t,props:r,depth:a,headers:o,headersToExclude:c,fetchOptions:d={}}=e;return O({url:t,init:{method:"PROPFIND",headers:f(h({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})},A=async t=>{const{url:r,data:a,headers:s,headersToExclude:o,fetchOptions:n={}}=t;return e(r,{method:"PUT",body:a,headers:f(s,o),...n})},g=async t=>{const{url:r,data:a,etag:s,headers:o,headersToExclude:n,fetchOptions:c={}}=t;return e(r,{method:"PUT",body:a,headers:f(h({"If-Match":s,...o}),n),...c})},C=async t=>{const{url:r,headers:a,etag:s,headersToExclude:o,fetchOptions:n={}}=t;return e(r,{method:"DELETE",headers:f(h({"If-Match":s,...a}),o),...n})};var w=Object.freeze({__proto__:null,createObject:A,davRequest:O,deleteObject:C,propfind:m,updateObject:g});function D(e,t){const r=e=>t.every((t=>e[t]));return Array.isArray(e)?e.every((e=>r(e))):r(e)}const b=(e,t)=>t.reduce(((t,r)=>e[r]?t:`${t.length?`${t},`:""}${r.toString()}`),""),V=t("tsdav:collection"),$=async e=>{const{url:t,body:r,depth:a,defaultNamespace:s=n.DAV,headers:o,headersToExclude:c,fetchOptions:d={}}=e,i=await O({url:t,init:{method:"REPORT",headers:f(h({depth:a,...o}),c),namespace:s,body:r},fetchOptions:d});return 1!==i.length||i[0].raw?i:[]},E=async e=>{const{url:t,props:r,depth:a,headers:s,headersToExclude:o,fetchOptions:c={}}=e;return O({url:t,init:{method:"MKCOL",headers:f(h({depth:a,...s}),o),namespace:n.DAV,body:r?{mkcol:{set:{prop:r}}}:void 0},fetchOptions:c})},T=async e=>{var t,r,a,s,o;const{collection:c,headers:d,headersToExclude:i,fetchOptions:l={}}=e;return null!==(o=null===(s=null===(a=null===(r=null===(t=(await m({url:c.url,props:{[`${n.DAV}:supported-report-set`]:{}},depth:"0",headers:f(d,i),fetchOptions: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:[]},k=async e=>{var t,r,a;const{collection:s,headers:o,headersToExclude:c,fetchOptions:d={}}=e,i=(await m({url:s.url,props:{[`${n.CALENDAR_SERVER}:getctag`]:{}},depth:"0",headers:f(o,c),fetchOptions: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()}},U=e=>{const{url:t,props:r,headers:a,syncLevel:o,syncToken:c,headersToExclude:d,fetchOptions:i}=e;return O({url:t,init:{method:"REPORT",namespace:n.DAV,headers:f({...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})},_=async e=>{var t,r,a,s,o,c,d,i,u,h,p;const{collection:v,method:y,headers:O,headersToExclude:m,account:A,detailedResult:g,fetchOptions:C={}}=e,w=["accountType","homeUrl"];if(!A||!D(A,w)){if(!A)throw new Error("no account for smartCollectionSync");throw new Error(`account must have ${b(A,w)} before smartCollectionSync`)}const $=null!=y?y:(null===(t=v.reports)||void 0===t?void 0:t.includes("syncCollection"))?"webdav":"basic";if(V(`smart collection sync with type ${A.accountType} and method ${$}`),"webdav"===$){const e=await U({url:v.url,props:{[`${n.DAV}:getetag`]:{},[`${"caldav"===A.accountType?n.CALDAV:n.CARDDAV}:${"caldav"===A.accountType?"calendar-data":"address-data"}`]:{},[`${n.DAV}:displayname`]:{}},syncLevel:1,syncToken:v.syncToken,headers:f(O,m),fetchOptions:C}),t=e.filter((e=>{var t;const r="caldav"===A.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)),h=t.filter((e=>404===e.status)).map((e=>e.href)),p=(u.length&&null!==(a=await(null===(r=null==v?void 0:v.objectMultiGet)||void 0===r?void 0:r.call(v,{url:v.url,props:{[`${n.DAV}:getetag`]:{},[`${"caldav"===A.accountType?n.CALDAV:n.CARDDAV}:${"caldav"===A.accountType?"calendar-data":"address-data"}`]:{}},objectUrls:u,depth:"1",headers:f(O,m),fetchOptions:C})))&&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==A?void 0:A.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}})),y=null!==(s=v.objects)&&void 0!==s?s:[],w=p.filter((e=>y.every((t=>!l(t.url,e.url))))),D=y.reduce(((e,t)=>{const r=p.find((e=>l(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),b=h.map((e=>({url:e,etag:""}))),V=y.filter((e=>p.some((t=>l(e.url,t.url)&&t.etag===e.etag))));return{...v,objects:g?{created:w,updated:D,deleted:b}:[...V,...w,...D],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:v.syncToken}}if("basic"===$){const{isDirty:e,newCtag:t}=await k({collection:v,headers:f(O,m),fetchOptions:C}),r=null!==(u=v.objects)&&void 0!==u?u:[],a=null!==(p=await(null===(h=v.fetchObjects)||void 0===h?void 0:h.call(v,{collection:v,headers:f(O,m),fetchOptions:C})))&&void 0!==p?p:[],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{...v,objects:g?{created:s,updated:o,deleted:n}:[...c,...s,...o],ctag:t}}return g?{...v,objects:{created:[],updated:[],deleted:[]}}:v};var R=Object.freeze({__proto__:null,collectionQuery:$,isCollectionDirty:k,makeCollection:E,smartCollectionSync:_,supportedReportSet:T,syncCollection:U});const L=t("tsdav:addressBook"),j=async e=>{const{url:t,props:r,filters:a,depth:o,headers:c,headersToExclude:d,fetchOptions:i={}}=e;return $({url:t,body:{"addressbook-query":{_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:f(c,d),fetchOptions:i})},x=async e=>{const{url:t,props:r,objectUrls:a,depth:o,headers:c,headersToExclude:d,fetchOptions:i={}}=e;return $({url:t,body:{"addressbook-multiget":{_attributes:u([s.DAV,s.CARDDAV]),[`${n.DAV}:prop`]:r,[`${n.DAV}:href`]:a}},defaultNamespace:n.CARDDAV,depth:o,headers:f(c,d),fetchOptions:i})},S=async e=>{const{account:t,headers:r,props:a,headersToExclude:s,fetchOptions:o={}}=null!=e?e:{},c=["homeUrl","rootUrl"];if(!t||!D(t,c)){if(!t)throw new Error("no account for fetchAddressBooks");throw new Error(`account must have ${b(t,c)} before fetchAddressBooks`)}const d=await m({url:t.homeUrl,props:null!=a?a:{[`${n.DAV}:displayname`]:{},[`${n.CALENDAR_SERVER}:getctag`]:{},[`${n.DAV}:resourcetype`]:{},[`${n.DAV}:sync-token`]:{}},depth:"1",headers:f(r,s),fetchOptions:o});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,n,c,d,i,l;const u=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 u?u:""},\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 u?u:"",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 T({collection:e,headers:f(r,s),fetchOptions:o})}))))},N=async e=>{const{addressBook:t,headers:r,objectUrls:a,headersToExclude:s,urlFilter:o=e=>e,useMultiGet:c=!0,fetchOptions:d={}}=e;L(`Fetching vcards from ${null==t?void 0:t.url}`);const i=["url"];if(!t||!D(t,i)){if(!t)throw new Error("cannot fetchVCards for undefined addressBook");throw new Error(`addressBook must have ${b(t,i)} before fetchVCards`)}const l=(null!=a?a:(await j({url:t.url,props:{[`${n.DAV}:getetag`]:{}},depth:"1",headers:f(r,s),fetchOptions:d})).map((e=>{var t;return e.ok&&null!==(t=e.href)&&void 0!==t?t:""}))).map((e=>e.startsWith("http")||!e?e:new URL(e,t.url).href)).filter(o).map((e=>new URL(e).pathname));let u=[];return l.length>0&&(u=c?await x({url:t.url,props:{[`${n.DAV}:getetag`]:{},[`${n.CARDDAV}:address-data`]:{}},objectUrls:l,depth:"1",headers:f(r,s),fetchOptions:d}):await j({url:t.url,props:{[`${n.DAV}:getetag`]:{},[`${n.CARDDAV}:address-data`]:{}},depth:"1",headers:f(r,s),fetchOptions:d})),u.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}}))},H=async e=>{const{addressBook:t,vCardString:r,filename:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e;return A({url:new URL(a,t.url).href,data:r,headers:f({"content-type":"text/vcard; charset=utf-8","If-None-Match":"*",...s},o),fetchOptions:n})},P=async e=>{const{vCard:t,headers:r,headersToExclude:a,fetchOptions:s={}}=e;return g({url:t.url,data:t.data,etag:t.etag,headers:f({"content-type":"text/vcard; charset=utf-8",...r},a),fetchOptions:s})},B=async e=>{const{vCard:t,headers:r,headersToExclude:a,fetchOptions:s={}}=e;return C({url:t.url,etag:t.etag,headers:f(r,a),fetchOptions:s})};var F=Object.freeze({__proto__:null,addressBookMultiGet:x,addressBookQuery:j,createVCard:H,deleteVCard:B,fetchAddressBooks:S,fetchVCards:N,updateVCard:P});const I=t("tsdav:calendar"),M=async e=>{var t,r,a;const{account:s,headers:o,headersToExclude:c,fetchOptions:d={}}=e,i=["principalUrl","rootUrl"];if(!D(s,i))throw new Error(`account must have ${b(s,i)} before fetchUserAddresses`);I(`Fetch user addresses from ${s.principalUrl}`);const u=(await m({url:s.principalUrl,props:{[`${n.CALDAV}:calendar-user-address-set`]:{}},depth:"0",headers:f(o,c),fetchOptions:d})).find((e=>l(s.principalUrl,e.href)));if(!u||!u.ok)throw new Error("cannot find calendarUserAddresses");const h=(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 I(`Fetched calendar user addresses ${h}`),h},z=async e=>{const{url:t,props:r,filters:a,timezone:o,depth:c,headers:d,headersToExclude:i,fetchOptions:l={}}=e;return $({url:t,body:{"calendar-query":h({_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:f(d,i),fetchOptions:l})},Z=async e=>{const{url:t,props:r,objectUrls:a,filters:o,timezone:c,depth:d,headers:i,headersToExclude:l,fetchOptions:h={}}=e;return $({url:t,body:{"calendar-multiget":{_attributes:u([s.DAV,s.CALDAV]),[`${n.DAV}:prop`]:r,[`${n.DAV}:href`]:a,...p("filter",o),timezone:c}},defaultNamespace:n.CALDAV,depth:d,headers:f(i,l),fetchOptions:h})},G=async e=>{const{url:t,props:r,depth:a,headers:o,headersToExclude:c,fetchOptions:d={}}=e;return O({url:t,init:{method:"MKCALENDAR",headers:f(h({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})},Q=async e=>{const{headers:t,account:r,props:a,projectedProps:s,headersToExclude:o,fetchOptions:d={}}=null!=e?e:{},i=["homeUrl","rootUrl"];if(!r||!D(r,i)){if(!r)throw new Error("no account for fetchCalendars");throw new Error(`account must have ${b(r,i)} before fetchCalendars`)}const l=await m({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:f(t,o),fetchOptions:d});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;return(Array.isArray(null===(t=e.props)||void 0===t?void 0:t.supportedCalendarComponentSet.comp)?null===(r=e.props)||void 0===r?void 0:r.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(s=null===(a=e.props)||void 0===a?void 0:a.supportedCalendarComponentSet.comp)||void 0===s?void 0:s._attributes.name]).some((e=>Object.values(c).includes(e)))})).map((e=>{var t,a,o,n,c,d,i,l,u,h,f,v,y,O,m,A;const g=null===(t=e.props)||void 0===t?void 0:t.calendarDescription,C=null===(a=e.props)||void 0===a?void 0:a.calendarTimezone;return{description:"string"==typeof g?g:"",timezone:"string"==typeof C?C:"",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===(u=e.props)||void 0===u?void 0:u.displayname,components:Array.isArray(null===(h=e.props)||void 0===h?void 0:h.supportedCalendarComponentSet.comp)?null===(f=e.props)||void 0===f?void 0:f.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(y=null===(v=e.props)||void 0===v?void 0:v.supportedCalendarComponentSet.comp)||void 0===y?void 0:y._attributes.name],resourcetype:Object.keys(null===(O=e.props)||void 0===O?void 0:O.resourcetype),syncToken:null===(m=e.props)||void 0===m?void 0:m.syncToken,...p("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 T({collection:e,headers:f(t,o),fetchOptions:d})}))))},q=async e=>{const{calendar:t,objectUrls:r,filters:a,timeRange:s,headers:o,expand:c,urlFilter:d=e=>Boolean(null==e?void 0:e.includes(".ics")),useMultiGet:i=!0,headersToExclude:l,fetchOptions:u={}}=e;if(s){const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(s.start)&&e.test(s.end)||t.test(s.start)&&t.test(s.end)))throw new Error("invalid timeRange format, not in ISO8601")}I(`Fetching calendar objects from ${null==t?void 0:t.url}`);const h=["url"];if(!t||!D(t,h)){if(!t)throw new Error("cannot fetchCalendarObjects for undefined calendar");throw new Error(`calendar must have ${b(t,h)} before fetchCalendarObjects`)}const p=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`}}}:{}}}}],v=(null!=r?r:(await z({url:t.url,props:{[`${n.DAV}:getetag`]:{...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:p,depth:"1",headers:f(o,l),fetchOptions: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 y=[];return v.length>0&&(y=!i||c?await z({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:p,depth:"1",headers:f(o,l),fetchOptions:u}):await Z({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:v,depth:"1",headers:f(o,l),fetchOptions:u})),y.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}}))},J=async e=>{const{calendar:t,iCalString:r,filename:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e;return A({url:new URL(a,t.url).href,data:r,headers:f({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*",...s},o),fetchOptions:n})},K=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={}}=e;return g({url:t.url,data:t.data,etag:t.etag,headers:f({"content-type":"text/calendar; charset=utf-8",...r},a),fetchOptions:s})},W=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={}}=e;return C({url:t.url,etag:t.etag,headers:f(r,a),fetchOptions:s})},Y=async e=>{var t;const{oldCalendars:r,account:a,detailedResult:s,headers:o,headersToExclude:n,fetchOptions:c={}}=e;if(!a)throw new Error("Must have account before syncCalendars");const d=null!==(t=null!=r?r:a.calendars)&&void 0!==t?t:[],i=await Q({account:a,headers:f(o,n),fetchOptions:c}),u=i.filter((e=>d.every((t=>!l(t.url,e.url)))));I(`new calendars: ${u.map((e=>e.displayName))}`);const h=d.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}),[]);I(`updated calendars: ${h.map((e=>e.displayName))}`);const p=await Promise.all(h.map((async e=>await _({collection:{...e,objectMultiGet:Z},method:"webdav",headers:f(o,n),account:a,fetchOptions:c})))),v=d.filter((e=>i.every((t=>!l(t.url,e.url)))));I(`deleted calendars: ${v.map((e=>e.displayName))}`);const y=d.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:u,updated:h,deleted:v}:[...y,...u,...p]},X=async e=>{const{url:t,timeRange:r,depth:a,headers:o,headersToExclude:c,fetchOptions:d={}}=e;if(!r)throw new Error("timeRange is required");{const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(r.start)&&e.test(r.end)||t.test(r.start)&&t.test(r.end)))throw new Error("invalid timeRange format, not in ISO8601")}return(await $({url:t,body:{"free-busy-query":h({_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:f(o,c),fetchOptions:d}))[0]};var ee=Object.freeze({__proto__:null,calendarMultiGet:Z,calendarQuery:z,createCalendarObject:J,deleteCalendarObject:W,fetchCalendarObjects:q,fetchCalendarUserAddresses:M,fetchCalendars:Q,freeBusyQuery:X,makeCalendar:G,syncCalendars:Y,updateCalendarObject:K});const te=t("tsdav:account"),re=async t=>{var r,a;te("Service discovery...");const{account:s,headers:o,headersToExclude:n,fetchOptions:c={}}=t,d=new URL(s.serverUrl),i=new URL(`/.well-known/${s.accountType}`,d);i.protocol=null!==(r=d.protocol)&&void 0!==r?r:"http";try{const t=await e(i.href,{headers:f(o,n),method:"PROPFIND",redirect:"manual",...c});if(t.status>=300&&t.status<400){const e=t.headers.get("Location");if("string"==typeof e&&e.length){te(`Service discovery redirected to ${e}`);const t=new URL(e,d);return t.hostname===i.hostname&&i.port&&!t.port&&(t.port=i.port),t.protocol=null!==(a=d.protocol)&&void 0!==a?a:"http",t.href}}}catch(e){te(`Service discovery failed: ${e.stack}`)}return d.href},ae=async e=>{var t,r,a,s,o;const{account:c,headers:d,headersToExclude:i,fetchOptions:l={}}=e,u=["rootUrl"];if(!D(c,u))throw new Error(`account must have ${b(c,u)} before fetchPrincipalUrl`);te(`Fetching principal url from path ${c.rootUrl}`);const[h]=await m({url:c.rootUrl,props:{[`${n.DAV}:current-user-principal`]:{}},depth:"0",headers:f(d,i),fetchOptions:l});if(!h.ok&&(te(`Fetch principal url failed: ${h.statusText}`),401===h.status))throw new Error("Invalid credentials");return te(`Fetched principal url ${null===(r=null===(t=h.props)||void 0===t?void 0:t.currentUserPrincipal)||void 0===r?void 0:r.href}`),new URL(null!==(o=null===(s=null===(a=h.props)||void 0===a?void 0:a.currentUserPrincipal)||void 0===s?void 0:s.href)&&void 0!==o?o:"",c.rootUrl).href},se=async e=>{var t,r;const{account:a,headers:s,headersToExclude:o,fetchOptions:c={}}=e,d=["principalUrl","rootUrl"];if(!D(a,d))throw new Error(`account must have ${b(a,d)} before fetchHomeUrl`);te(`Fetch home url from ${a.principalUrl}`);const i=(await m({url:a.principalUrl,props:"caldav"===a.accountType?{[`${n.CALDAV}:calendar-home-set`]:{}}:{[`${n.CARDDAV}:addressbook-home-set`]:{}},depth:"0",headers:f(s,o),fetchOptions:c})).find((e=>l(a.principalUrl,e.href)));if(!i||!i.ok)throw new Error("cannot find homeUrl");const u=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 te(`Fetched home url ${u}`),u},oe=async e=>{const{account:t,headers:r,loadCollections:a=!1,loadObjects:s=!1,headersToExclude:o,fetchOptions:n={}}=e,c={...t};return c.rootUrl=await re({account:t,headers:f(r,o),fetchOptions:n}),c.principalUrl=await ae({account:c,headers:f(r,o),fetchOptions:n}),c.homeUrl=await se({account:c,headers:f(r,o),fetchOptions:n}),(a||s)&&("caldav"===t.accountType?c.calendars=await Q({headers:f(r,o),account:c,fetchOptions:n}):"carddav"===t.accountType&&(c.addressBooks=await S({headers:f(r,o),account:c,fetchOptions:n}))),s&&("caldav"===t.accountType&&c.calendars?c.calendars=await Promise.all(c.calendars.map((async e=>({...e,objects:await q({calendar:e,headers:f(r,o),fetchOptions:n})})))):"carddav"===t.accountType&&c.addressBooks&&(c.addressBooks=await Promise.all(c.addressBooks.map((async e=>({...e,objects:await N({addressBook:e,headers:f(r,o),fetchOptions:n})})))))),c};var ne=Object.freeze({__proto__:null,createAccount:oe,fetchHomeUrl:se,fetchPrincipalUrl:ae,serviceDiscovery:re});const ce=t("tsdav:authHelper"),de=(e,t)=>(...r)=>e({...t,...r[0]}),ie=e=>(ce(`Basic auth token generated: ${a(`${e.username}:${e.password}`)}`),{authorization:`Basic ${a(`${e.username}:${e.password}`)}`}),le=async(t,r)=>{const a=["authorizationCode","redirectUrl","clientId","clientSecret","tokenUrl"];if(!D(t,a))throw new Error(`Oauth credentials missing: ${b(t,a)}`);const s=new URLSearchParams({grant_type:"authorization_code",code:t.authorizationCode,redirect_uri:t.redirectUrl,client_id:t.clientId,client_secret:t.clientSecret});ce(t.tokenUrl),ce(s.toString());const o=await e(t.tokenUrl,{method:"POST",body:s.toString(),headers:{"content-length":`${s.toString().length}`,"content-type":"application/x-www-form-urlencoded"},...null!=r?r:{}});if(o.ok){return await o.json()}return ce(`Fetch Oauth tokens failed: ${await o.text()}`),{}},ue=async(t,r)=>{const a=["refreshToken","clientId","clientSecret","tokenUrl"];if(!D(t,a))throw new Error(`Oauth credentials missing: ${b(t,a)}`);const s=new URLSearchParams({client_id:t.clientId,client_secret:t.clientSecret,refresh_token:t.refreshToken,grant_type:"refresh_token"}),o=await e(t.tokenUrl,{method:"POST",body:s.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},...null!=r?r:{}});if(o.ok){return await o.json()}return ce(`Refresh access token failed: ${await o.text()}`),{}},he=async(e,t)=>{var r;ce("Fetching oauth headers");let a={};return e.refreshToken?(e.refreshToken&&!e.accessToken||Date.now()>(null!==(r=e.expiration)&&void 0!==r?r:0))&&(a=await ue(e,t)):a=await le(e,t),ce(`Oauth tokens fetched: ${a.access_token}`),{tokens:a,headers:{authorization:`Bearer ${a.access_token}`}}};var pe=Object.freeze({__proto__:null,defaultParam:de,fetchOauthTokens:le,getBasicAuthHeaders:ie,getOauthHeaders:he,refreshAccessToken:ue});const fe=async e=>{var t;const{serverUrl:r,credentials:a,authMethod:s,defaultAccountType:o,authFunction:n}=e;let c={};switch(s){case"Basic":c=ie(a);break;case"Oauth":c=(await he(a)).headers;break;case"Digest":c={Authorization:`Digest ${a.digestString}`};break;case"Custom":c=null!==(t=await(null==n?void 0:n(a)))&&void 0!==t?t:{};break;default:throw new Error("Invalid auth method")}const d=o?await oe({account:{serverUrl:r,credentials:a,accountType:o},headers:c}):void 0,i=de(A,{url:r,headers:c}),l=de(g,{headers:c,url:r}),u=de(C,{headers:c,url:r}),h=de(m,{headers:c}),p=de($,{headers:c}),f=de(E,{headers:c}),v=de(U,{headers:c}),y=de(T,{headers:c}),w=de(k,{headers:c}),D=de(_,{headers:c,account:d}),b=de(z,{headers:c}),V=de(Z,{headers:c}),R=de(G,{headers:c}),L=de(Q,{headers:c,account:d}),F=de(M,{headers:c,account:d}),I=de(q,{headers:c}),X=de(J,{headers:c}),ee=de(K,{headers:c}),te=de(W,{headers:c}),re=de(Y,{account:d,headers:c}),ae=de(j,{headers:c}),se=de(x,{headers:c});return{davRequest:async e=>{const{init:t,...r}=e,{headers:a,...s}=t;return O({...r,init:{...s,headers:{...c,...a}}})},propfind:h,createAccount:async e=>{const{account:t,headers:s,loadCollections:o,loadObjects:n}=e;return oe({account:{serverUrl:r,credentials:a,...t},headers:{...c,...s},loadCollections:o,loadObjects:n})},createObject:i,updateObject:l,deleteObject:u,calendarQuery:b,addressBookQuery:ae,collectionQuery:p,makeCollection:f,calendarMultiGet:V,makeCalendar:R,syncCollection:v,supportedReportSet:y,isCollectionDirty:w,smartCollectionSync:D,fetchCalendars:L,fetchCalendarUserAddresses:F,fetchCalendarObjects:I,createCalendarObject:X,updateCalendarObject:ee,deleteCalendarObject:te,syncCalendars:re,fetchAddressBooks:de(S,{account:d,headers:c}),addressBookMultiGet:se,fetchVCards:de(N,{headers:c}),createVCard:de(H,{headers:c}),updateVCard:de(P,{headers:c}),deleteVCard:de(B,{headers:c})}};class ve{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:{}}async login(){var e;switch(this.authMethod){case"Basic":this.authHeaders=ie(this.credentials);break;case"Oauth":this.authHeaders=(await he(this.credentials,this.fetchOptions)).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 oe({account:{serverUrl:this.serverUrl,credentials:this.credentials,accountType:this.accountType},headers:this.authHeaders,fetchOptions:this.fetchOptions}):void 0}async davRequest(e){const{init:t,...r}=e,{headers:a,...s}=t;return O({...r,init:{...s,headers:{...this.authHeaders,...a}},fetchOptions:this.fetchOptions})}async createObject(...e){return de(A,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateObject(...e){return de(g,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteObject(...e){return de(C,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async propfind(...e){return de(m,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createAccount(e){const{account:t,headers:r,loadCollections:a,loadObjects:s,fetchOptions:o}=e;return oe({account:{serverUrl:this.serverUrl,credentials:this.credentials,...t},headers:{...this.authHeaders,...r},loadCollections:a,loadObjects:s,fetchOptions:null!=o?o:this.fetchOptions})}async collectionQuery(...e){return de($,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async makeCollection(...e){return de(E,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async syncCollection(...e){return de(U,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async supportedReportSet(...e){return de(T,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async isCollectionDirty(...e){return de(k,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async smartCollectionSync(...e){return de(_,{headers:this.authHeaders,fetchOptions:this.fetchOptions,account:this.account})(e[0])}async calendarQuery(...e){return de(z,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async makeCalendar(...e){return de(G,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async calendarMultiGet(...e){return de(Z,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async fetchCalendars(...e){return de(Q,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(null==e?void 0:e[0])}async fetchCalendarUserAddresses(...e){return de(M,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(null==e?void 0:e[0])}async fetchCalendarObjects(...e){return de(q,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createCalendarObject(...e){return de(J,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateCalendarObject(...e){return de(K,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteCalendarObject(...e){return de(W,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async syncCalendars(...e){return de(Y,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(e[0])}async addressBookQuery(...e){return de(j,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async addressBookMultiGet(...e){return de(x,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async fetchAddressBooks(...e){return de(S,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(null==e?void 0:e[0])}async fetchVCards(...e){return de(N,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createVCard(...e){return de(H,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateVCard(...e){return de(P,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteVCard(...e){return de(B,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}}var ye={DAVNamespace:s,DAVNamespaceShort:n,DAVAttributeMap:o,...Object.freeze({__proto__:null,DAVClient:ve,createDAVClient:fe}),...w,...R,...ne,...F,...ee,...pe,...v};export{o as DAVAttributeMap,ve as DAVClient,s as DAVNamespace,n as DAVNamespaceShort,j as addressBookQuery,Z as calendarMultiGet,z as calendarQuery,h as cleanupFalsy,$ as collectionQuery,oe as createAccount,J as createCalendarObject,fe as createDAVClient,A as createObject,H as createVCard,O as davRequest,ye as default,W as deleteCalendarObject,C as deleteObject,B as deleteVCard,S as fetchAddressBooks,q as fetchCalendarObjects,M as fetchCalendarUserAddresses,Q as fetchCalendars,le as fetchOauthTokens,N as fetchVCards,X as freeBusyQuery,ie as getBasicAuthHeaders,u as getDAVAttribute,he as getOauthHeaders,k as isCollectionDirty,G as makeCalendar,m as propfind,ue as refreshAccessToken,_ as smartCollectionSync,T as supportedReportSet,Y as syncCalendars,U as syncCollection,K as updateCalendarObject,g as updateObject,P as updateVCard,l as urlContains,i as urlEquals}; +import"cross-fetch/polyfill";import e from"debug";import t from"xml-js";import{encode as r}from"base-64";var a;!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:"}(a||(a={}));const s={[a.CALDAV]:"xmlns:c",[a.CARDDAV]:"xmlns:card",[a.CALENDAR_SERVER]:"xmlns:cs",[a.CALDAV_APPLE]:"xmlns:ca",[a.DAV]:"xmlns:d"};var o,n;!function(e){e.CALDAV="c",e.CARDDAV="card",e.CALENDAR_SERVER="cs",e.CALDAV_APPLE="ca",e.DAV="d"}(o||(o={})),function(e){e.VEVENT="VEVENT",e.VTODO="VTODO",e.VJOURNAL="VJOURNAL",e.VFREEBUSY="VFREEBUSY",e.VTIMEZONE="VTIMEZONE",e.VALARM="VALARM"}(n||(n={}));const c=e=>{const t=Number(e);if(!Number.isNaN(t))return t;const r=e.toLowerCase();return"true"===r||"false"!==r&&e},d=(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)},i=(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)},l=e=>e.reduce(((e,t)=>({...e,[s[t]]:t})),{}),u=e=>Object.entries(e).reduce(((e,[t,r])=>r?{...e,[t]:r}:e),{}),h=(e,t)=>t?{[e]:t}:{},p=(e,t)=>e?t&&0!==t.length?Object.fromEntries(Object.entries(e).filter((([e])=>!t.includes(e)))):e:{};var f=Object.freeze({__proto__:null,cleanupFalsy:u,conditionalParam:h,excludeHeaders:p,getDAVAttribute:l,urlContains:i,urlEquals:d});const v=e("tsdav:request"),y=async e=>{var r;const{url:a,init:s,convertIncoming:o=!0,parseOutgoing:n=!0,fetchOptions:d={}}=e,{headers:i={},body:l,namespace:h,method:p,attributes:f}=s,y=o?t.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,O=await fetch(a,{headers:{"Content-Type":"text/xml;charset=UTF-8",...u(i)},body:y,method:p,...d}),m=await O.text();if(!O.ok||!(null===(r=O.headers.get("content-type"))||void 0===r?void 0:r.includes("xml"))||!n)return[{href:O.url,ok:O.ok,status:O.status,statusText:O.statusText,raw:m}];const A=t.xml2js(m,{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]=c(e)}else r[s]=c(e)}catch(e){v(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(A.multistatus.response)?A.multistatus.response:[A.multistatus.response]).map((e=>{var t,r;if(!e)return{status:O.status,statusText:O.statusText,ok:O.ok};const a=/^\S+\s(?\d+)\s(?.+)$/.exec(e.status);return{raw:A,href:e.href,status:(null==a?void 0:a.groups)?Number.parseInt(null==a?void 0:a.groups.status,10):O.status,statusText:null!==(r=null===(t=null==a?void 0:a.groups)||void 0===t?void 0:t.statusText)&&void 0!==r?r:O.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})),{})}}))},O=async e=>{const{url:t,props:r,depth:s,headers:n,headersToExclude:c,fetchOptions:d={}}=e;return y({url:t,init:{method:"PROPFIND",headers:p(u({depth:s,...n}),c),namespace:o.DAV,body:{propfind:{_attributes:l([a.CALDAV,a.CALDAV_APPLE,a.CALENDAR_SERVER,a.CARDDAV,a.DAV]),prop:r}}},fetchOptions:d})},m=async e=>{const{url:t,data:r,headers:a,headersToExclude:s,fetchOptions:o={}}=e;return fetch(t,{method:"PUT",body:r,headers:p(a,s),...o})},A=async e=>{const{url:t,data:r,etag:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e;return fetch(t,{method:"PUT",body:r,headers:p(u({"If-Match":a,...s}),o),...n})},g=async e=>{const{url:t,headers:r,etag:a,headersToExclude:s,fetchOptions:o={}}=e;return fetch(t,{method:"DELETE",headers:p(u({"If-Match":a,...r}),s),...o})};var C=Object.freeze({__proto__:null,createObject:m,davRequest:y,deleteObject:g,propfind:O,updateObject:A});function w(e,t){const r=e=>t.every((t=>e[t]));return Array.isArray(e)?e.every((e=>r(e))):r(e)}const D=(e,t)=>t.reduce(((t,r)=>e[r]?t:`${t.length?`${t},`:""}${r.toString()}`),""),b=e("tsdav:collection"),V=async e=>{const{url:t,body:r,depth:a,defaultNamespace:s=o.DAV,headers:n,headersToExclude:c,fetchOptions:d={}}=e,i=await y({url:t,init:{method:"REPORT",headers:p(u({depth:a,...n}),c),namespace:s,body:r},fetchOptions:d});return 1!==i.length||i[0].raw?i:[]},$=async e=>{const{url:t,props:r,depth:a,headers:s,headersToExclude:n,fetchOptions:c={}}=e;return y({url:t,init:{method:"MKCOL",headers:p(u({depth:a,...s}),n),namespace:o.DAV,body:r?{mkcol:{set:{prop:r}}}:void 0},fetchOptions:c})},E=async e=>{var t,r,a,s,n;const{collection:c,headers:d,headersToExclude:i,fetchOptions:l={}}=e;return null!==(n=null===(s=null===(a=null===(r=null===(t=(await O({url:c.url,props:{[`${o.DAV}:supported-report-set`]:{}},depth:"0",headers:p(d,i),fetchOptions: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!==n?n:[]},T=async e=>{var t,r,a;const{collection:s,headers:n,headersToExclude:c,fetchOptions:d={}}=e,l=(await O({url:s.url,props:{[`${o.CALENDAR_SERVER}:getctag`]:{}},depth:"0",headers:p(n,c),fetchOptions:d})).filter((e=>i(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()}},k=e=>{const{url:t,props:r,headers:s,syncLevel:n,syncToken:c,headersToExclude:d,fetchOptions:i}=e;return y({url:t,init:{method:"REPORT",namespace:o.DAV,headers:p({...s},d),body:{"sync-collection":{_attributes:l([a.CALDAV,a.CARDDAV,a.DAV]),"sync-level":n,"sync-token":c,[`${o.DAV}:prop`]:r}}},fetchOptions:i})},U=async e=>{var t,r,a,s,n,c,d,l,u,h,f;const{collection:v,method:y,headers:O,headersToExclude:m,account:A,detailedResult:g,fetchOptions:C={}}=e,V=["accountType","homeUrl"];if(!A||!w(A,V)){if(!A)throw new Error("no account for smartCollectionSync");throw new Error(`account must have ${D(A,V)} before smartCollectionSync`)}const $=null!=y?y:(null===(t=v.reports)||void 0===t?void 0:t.includes("syncCollection"))?"webdav":"basic";if(b(`smart collection sync with type ${A.accountType} and method ${$}`),"webdav"===$){const e=await k({url:v.url,props:{[`${o.DAV}:getetag`]:{},[`${"caldav"===A.accountType?o.CALDAV:o.CARDDAV}:${"caldav"===A.accountType?"calendar-data":"address-data"}`]:{},[`${o.DAV}:displayname`]:{}},syncLevel:1,syncToken:v.syncToken,headers:p(O,m),fetchOptions:C}),t=e.filter((e=>{var t;const r="caldav"===A.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)),h=t.filter((e=>404===e.status)).map((e=>e.href)),f=(u.length&&null!==(a=await(null===(r=null==v?void 0:v.objectMultiGet)||void 0===r?void 0:r.call(v,{url:v.url,props:{[`${o.DAV}:getetag`]:{},[`${"caldav"===A.accountType?o.CALDAV:o.CARDDAV}:${"caldav"===A.accountType?"calendar-data":"address-data"}`]:{}},objectUrls:u,depth:"1",headers:p(O,m),fetchOptions:C})))&&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==A?void 0:A.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}})),y=null!==(s=v.objects)&&void 0!==s?s:[],w=f.filter((e=>y.every((t=>!i(t.url,e.url))))),D=y.reduce(((e,t)=>{const r=f.find((e=>i(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),b=h.map((e=>({url:e,etag:""}))),V=y.filter((e=>f.some((t=>i(e.url,t.url)&&t.etag===e.etag))));return{...v,objects:g?{created:w,updated:D,deleted:b}:[...V,...w,...D],syncToken:null!==(l=null===(d=null===(c=null===(n=e[0])||void 0===n?void 0:n.raw)||void 0===c?void 0:c.multistatus)||void 0===d?void 0:d.syncToken)&&void 0!==l?l:v.syncToken}}if("basic"===$){const{isDirty:e,newCtag:t}=await T({collection:v,headers:p(O,m),fetchOptions:C}),r=null!==(u=v.objects)&&void 0!==u?u:[],a=null!==(f=await(null===(h=v.fetchObjects)||void 0===h?void 0:h.call(v,{collection:v,headers:p(O,m),fetchOptions:C})))&&void 0!==f?f:[],s=a.filter((e=>r.every((t=>!i(t.url,e.url))))),o=r.reduce(((e,t)=>{const r=a.find((e=>i(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),n=r.filter((e=>a.every((t=>!i(t.url,e.url))))),c=r.filter((e=>a.some((t=>i(e.url,t.url)&&t.etag===e.etag))));if(e)return{...v,objects:g?{created:s,updated:o,deleted:n}:[...c,...s,...o],ctag:t}}return g?{...v,objects:{created:[],updated:[],deleted:[]}}:v};var _=Object.freeze({__proto__:null,collectionQuery:V,isCollectionDirty:T,makeCollection:$,smartCollectionSync:U,supportedReportSet:E,syncCollection:k});const R=e("tsdav:addressBook"),L=async e=>{const{url:t,props:r,filters:s,depth:n,headers:c,headersToExclude:d,fetchOptions:i={}}=e;return V({url:t,body:{"addressbook-query":u({_attributes:l([a.CARDDAV,a.DAV]),[`${o.DAV}:prop`]:r,filter:null!=s?s:{"prop-filter":{_attributes:{name:"FN"}}}})},defaultNamespace:o.CARDDAV,depth:n,headers:p(c,d),fetchOptions:i})},j=async e=>{const{url:t,props:r,objectUrls:s,depth:n,headers:c,headersToExclude:d,fetchOptions:i={}}=e;return V({url:t,body:{"addressbook-multiget":u({_attributes:l([a.DAV,a.CARDDAV]),[`${o.DAV}:prop`]:r,[`${o.DAV}:href`]:s})},defaultNamespace:o.CARDDAV,depth:n,headers:p(c,d),fetchOptions:i})},x=async e=>{const{account:t,headers:r,props:a,headersToExclude:s,fetchOptions:n={}}=null!=e?e:{},c=["homeUrl","rootUrl"];if(!t||!w(t,c)){if(!t)throw new Error("no account for fetchAddressBooks");throw new Error(`account must have ${D(t,c)} before fetchAddressBooks`)}const d=await O({url:t.homeUrl,props:null!=a?a:{[`${o.DAV}:displayname`]:{},[`${o.CALENDAR_SERVER}:getctag`]:{},[`${o.DAV}:resourcetype`]:{},[`${o.DAV}:sync-token`]:{}},depth:"1",headers:p(r,s),fetchOptions:n});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,n,c,d,i,l;const u=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 R(`Found address book named ${"string"==typeof u?u:""},\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 u?u:"",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 E({collection:e,headers:p(r,s),fetchOptions:n})}))))},S=async e=>{const{addressBook:t,headers:r,objectUrls:a,headersToExclude:s,urlFilter:n=e=>e,useMultiGet:c=!0,fetchOptions:d={}}=e;R(`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 ${D(t,i)} before fetchVCards`)}const l=(null!=a?a:(await L({url:t.url,props:{[`${o.DAV}:getetag`]:{}},depth:"1",headers:p(r,s),fetchOptions:d})).map((e=>{var t;return e.ok&&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 u=[];return l.length>0&&(u=c?await j({url:t.url,props:{[`${o.DAV}:getetag`]:{},[`${o.CARDDAV}:address-data`]:{}},objectUrls:l,depth:"1",headers:p(r,s),fetchOptions:d}):await L({url:t.url,props:{[`${o.DAV}:getetag`]:{},[`${o.CARDDAV}:address-data`]:{}},depth:"1",headers:p(r,s),fetchOptions:d})),u.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}}))},N=async e=>{const{addressBook:t,vCardString:r,filename:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e;return m({url:new URL(a,t.url).href,data:r,headers:p({"content-type":"text/vcard; charset=utf-8","If-None-Match":"*",...s},o),fetchOptions:n})},H=async e=>{const{vCard:t,headers:r,headersToExclude:a,fetchOptions:s={}}=e;return A({url:t.url,data:t.data,etag:t.etag,headers:p({"content-type":"text/vcard; charset=utf-8",...r},a),fetchOptions:s})},P=async e=>{const{vCard:t,headers:r,headersToExclude:a,fetchOptions:s={}}=e;return g({url:t.url,etag:t.etag,headers:p(r,a),fetchOptions:s})};var B=Object.freeze({__proto__:null,addressBookMultiGet:j,addressBookQuery:L,createVCard:N,deleteVCard:P,fetchAddressBooks:x,fetchVCards:S,updateVCard:H});const F=e("tsdav:calendar"),I=async e=>{var t,r,a;const{account:s,headers:n,headersToExclude:c,fetchOptions:d={}}=e,l=["principalUrl","rootUrl"];if(!w(s,l))throw new Error(`account must have ${D(s,l)} before fetchUserAddresses`);F(`Fetch user addresses from ${s.principalUrl}`);const u=(await O({url:s.principalUrl,props:{[`${o.CALDAV}:calendar-user-address-set`]:{}},depth:"0",headers:p(n,c),fetchOptions:d})).find((e=>i(s.principalUrl,e.href)));if(!u||!u.ok)throw new Error("cannot find calendarUserAddresses");const h=(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 F(`Fetched calendar user addresses ${h}`),h},M=async e=>{const{url:t,props:r,filters:s,timezone:n,depth:c,headers:d,headersToExclude:i,fetchOptions:h={}}=e;return V({url:t,body:{"calendar-query":u({_attributes:l([a.CALDAV,a.CALENDAR_SERVER,a.CALDAV_APPLE,a.DAV]),[`${o.DAV}:prop`]:r,filter:s,timezone:n})},defaultNamespace:o.CALDAV,depth:c,headers:p(d,i),fetchOptions:h})},z=async e=>{const{url:t,props:r,objectUrls:s,filters:n,timezone:c,depth:d,headers:i,headersToExclude:h,fetchOptions:f={}}=e;return V({url:t,body:{"calendar-multiget":u({_attributes:l([a.DAV,a.CALDAV]),[`${o.DAV}:prop`]:r,[`${o.DAV}:href`]:s,filter:n,timezone:c})},defaultNamespace:o.CALDAV,depth:d,headers:p(i,h),fetchOptions:f})},Z=async e=>{const{url:t,props:r,depth:s,headers:n,headersToExclude:c,fetchOptions:d={}}=e;return y({url:t,init:{method:"MKCALENDAR",headers:p(u({depth:s,...n}),c),namespace:o.DAV,body:{[`${o.CALDAV}:mkcalendar`]:{_attributes:l([a.DAV,a.CALDAV,a.CALDAV_APPLE]),set:{prop:r}}}},fetchOptions:d})},G=async e=>{const{headers:t,account:r,props:a,projectedProps:s,headersToExclude:c,fetchOptions: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 ${D(r,i)} before fetchCalendars`)}const l=await O({url:r.homeUrl,props:null!=a?a:{[`${o.CALDAV}:calendar-description`]:{},[`${o.CALDAV}:calendar-timezone`]:{},[`${o.DAV}:displayname`]:{},[`${o.CALDAV_APPLE}:calendar-color`]:{},[`${o.CALENDAR_SERVER}:getctag`]:{},[`${o.DAV}:resourcetype`]:{},[`${o.CALDAV}:supported-calendar-component-set`]:{},[`${o.DAV}:sync-token`]:{}},depth:"1",headers:p(t,c),fetchOptions:d});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;return(Array.isArray(null===(t=e.props)||void 0===t?void 0:t.supportedCalendarComponentSet.comp)?null===(r=e.props)||void 0===r?void 0:r.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(s=null===(a=e.props)||void 0===a?void 0:a.supportedCalendarComponentSet.comp)||void 0===s?void 0:s._attributes.name]).some((e=>Object.values(n).includes(e)))})).map((e=>{var t,a,o,n,c,d,i,l,u,p,f,v,y,O,m,A;const g=null===(t=e.props)||void 0===t?void 0:t.calendarDescription,C=null===(a=e.props)||void 0===a?void 0:a.calendarTimezone;return{description:"string"==typeof g?g:"",timezone:"string"==typeof C?C:"",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===(u=e.props)||void 0===u?void 0:u.displayname,components:Array.isArray(null===(p=e.props)||void 0===p?void 0:p.supportedCalendarComponentSet.comp)?null===(f=e.props)||void 0===f?void 0:f.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(y=null===(v=e.props)||void 0===v?void 0:v.supportedCalendarComponentSet.comp)||void 0===y?void 0:y._attributes.name],resourcetype:Object.keys(null===(O=e.props)||void 0===O?void 0:O.resourcetype),syncToken:null===(m=e.props)||void 0===m?void 0:m.syncToken,...h("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 E({collection:e,headers:p(t,c),fetchOptions:d})}))))},Q=async e=>{const{calendar:t,objectUrls:r,filters:a,timeRange:s,headers:n,expand:c,urlFilter:d=e=>Boolean(null==e?void 0:e.includes(".ics")),useMultiGet:i=!0,headersToExclude:l,fetchOptions:u={}}=e;if(s){const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(s.start)&&e.test(s.end)||t.test(s.start)&&t.test(s.end)))throw new Error("invalid timeRange format, not in ISO8601")}F(`Fetching calendar objects from ${null==t?void 0:t.url}`);const h=["url"];if(!t||!w(t,h)){if(!t)throw new Error("cannot fetchCalendarObjects for undefined calendar");throw new Error(`calendar must have ${D(t,h)} 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`}}}:{}}}}],v=(null!=r?r:(await M({url:t.url,props:{[`${o.DAV}:getetag`]:{...c&&s?{[`${o.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:p(n,l),fetchOptions: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 y=[];return v.length>0&&(y=!i||c?await M({url:t.url,props:{[`${o.DAV}:getetag`]:{},[`${o.CALDAV}:calendar-data`]:{...c&&s?{[`${o.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:p(n,l),fetchOptions:u}):await z({url:t.url,props:{[`${o.DAV}:getetag`]:{},[`${o.CALDAV}:calendar-data`]:{...c&&s?{[`${o.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:v,depth:"1",headers:p(n,l),fetchOptions:u})),y.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}}))},q=async e=>{const{calendar:t,iCalString:r,filename:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e;return m({url:new URL(a,t.url).href,data:r,headers:p({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*",...s},o),fetchOptions:n})},J=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={}}=e;return A({url:t.url,data:t.data,etag:t.etag,headers:p({"content-type":"text/calendar; charset=utf-8",...r},a),fetchOptions:s})},K=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={}}=e;return g({url:t.url,etag:t.etag,headers:p(r,a),fetchOptions:s})},W=async e=>{var t;const{oldCalendars:r,account:a,detailedResult:s,headers:o,headersToExclude:n,fetchOptions:c={}}=e;if(!a)throw new Error("Must have account before syncCalendars");const d=null!==(t=null!=r?r:a.calendars)&&void 0!==t?t:[],l=await G({account:a,headers:p(o,n),fetchOptions:c}),u=l.filter((e=>d.every((t=>!i(t.url,e.url)))));F(`new calendars: ${u.map((e=>e.displayName))}`);const h=d.reduce(((e,t)=>{const r=l.find((e=>i(e.url,t.url)));return r&&(r.syncToken&&`${r.syncToken}`!=`${t.syncToken}`||r.ctag&&`${r.ctag}`!=`${t.ctag}`)?[...e,r]:e}),[]);F(`updated calendars: ${h.map((e=>e.displayName))}`);const f=await Promise.all(h.map((async e=>await U({collection:{...e,objectMultiGet:z},method:"webdav",headers:p(o,n),account:a,fetchOptions:c})))),v=d.filter((e=>l.every((t=>!i(t.url,e.url)))));F(`deleted calendars: ${v.map((e=>e.displayName))}`);const y=d.filter((e=>l.some((t=>i(t.url,e.url)&&(t.syncToken&&`${t.syncToken}`!=`${e.syncToken}`||t.ctag&&`${t.ctag}`!=`${e.ctag}`)))));return s?{created:u,updated:h,deleted:v}:[...y,...u,...f]},Y=async e=>{const{url:t,timeRange:r,depth:s,headers:n,headersToExclude:c,fetchOptions:d={}}=e;if(!r)throw new Error("timeRange is required");{const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(r.start)&&e.test(r.end)||t.test(r.start)&&t.test(r.end)))throw new Error("invalid timeRange format, not in ISO8601")}return(await V({url:t,body:{"free-busy-query":u({_attributes:l([a.CALDAV]),[`${o.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:o.CALDAV,depth:s,headers:p(n,c),fetchOptions:d}))[0]};var X=Object.freeze({__proto__:null,calendarMultiGet:z,calendarQuery:M,createCalendarObject:q,deleteCalendarObject:K,fetchCalendarObjects:Q,fetchCalendarUserAddresses:I,fetchCalendars:G,freeBusyQuery:Y,makeCalendar:Z,syncCalendars:W,updateCalendarObject:J});const ee=e("tsdav:account"),te=async e=>{var t,r;ee("Service discovery...");const{account:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e,c=new URL(a.serverUrl),d=new URL(`/.well-known/${a.accountType}`,c);d.protocol=null!==(t=c.protocol)&&void 0!==t?t:"http";try{const e=await fetch(d.href,{headers:p(s,o),method:"PROPFIND",redirect:"manual",...n});if(e.status>=300&&e.status<400){const t=e.headers.get("Location");if("string"==typeof t&&t.length){ee(`Service discovery redirected to ${t}`);const e=new URL(t,c);return e.hostname===d.hostname&&d.port&&!e.port&&(e.port=d.port),e.protocol=null!==(r=c.protocol)&&void 0!==r?r:"http",e.href}}}catch(e){ee(`Service discovery failed: ${e.stack}`)}return c.href},re=async e=>{var t,r,a,s,n;const{account:c,headers:d,headersToExclude:i,fetchOptions:l={}}=e,u=["rootUrl"];if(!w(c,u))throw new Error(`account must have ${D(c,u)} before fetchPrincipalUrl`);ee(`Fetching principal url from path ${c.rootUrl}`);const[h]=await O({url:c.rootUrl,props:{[`${o.DAV}:current-user-principal`]:{}},depth:"0",headers:p(d,i),fetchOptions:l});if(!h.ok&&(ee(`Fetch principal url failed: ${h.statusText}`),401===h.status))throw new Error("Invalid credentials");return ee(`Fetched principal url ${null===(r=null===(t=h.props)||void 0===t?void 0:t.currentUserPrincipal)||void 0===r?void 0:r.href}`),new URL(null!==(n=null===(s=null===(a=h.props)||void 0===a?void 0:a.currentUserPrincipal)||void 0===s?void 0:s.href)&&void 0!==n?n:"",c.rootUrl).href},ae=async e=>{var t,r;const{account:a,headers:s,headersToExclude:n,fetchOptions:c={}}=e,d=["principalUrl","rootUrl"];if(!w(a,d))throw new Error(`account must have ${D(a,d)} before fetchHomeUrl`);ee(`Fetch home url from ${a.principalUrl}`);const l=(await O({url:a.principalUrl,props:"caldav"===a.accountType?{[`${o.CALDAV}:calendar-home-set`]:{}}:{[`${o.CARDDAV}:addressbook-home-set`]:{}},depth:"0",headers:p(s,n),fetchOptions:c})).find((e=>i(a.principalUrl,e.href)));if(!l||!l.ok)throw new Error("cannot find homeUrl");const u=new URL("caldav"===a.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,a.rootUrl).href;return ee(`Fetched home url ${u}`),u},se=async e=>{const{account:t,headers:r,loadCollections:a=!1,loadObjects:s=!1,headersToExclude:o,fetchOptions:n={}}=e,c={...t};return c.rootUrl=await te({account:t,headers:p(r,o),fetchOptions:n}),c.principalUrl=await re({account:c,headers:p(r,o),fetchOptions:n}),c.homeUrl=await ae({account:c,headers:p(r,o),fetchOptions:n}),(a||s)&&("caldav"===t.accountType?c.calendars=await G({headers:p(r,o),account:c,fetchOptions:n}):"carddav"===t.accountType&&(c.addressBooks=await x({headers:p(r,o),account:c,fetchOptions:n}))),s&&("caldav"===t.accountType&&c.calendars?c.calendars=await Promise.all(c.calendars.map((async e=>({...e,objects:await Q({calendar:e,headers:p(r,o),fetchOptions:n})})))):"carddav"===t.accountType&&c.addressBooks&&(c.addressBooks=await Promise.all(c.addressBooks.map((async e=>({...e,objects:await S({addressBook:e,headers:p(r,o),fetchOptions:n})})))))),c};var oe=Object.freeze({__proto__:null,createAccount:se,fetchHomeUrl:ae,fetchPrincipalUrl:re,serviceDiscovery:te});const ne=e("tsdav:authHelper"),ce=(e,t)=>(...r)=>e({...t,...r[0]}),de=e=>(ne(`Basic auth token generated: ${r(`${e.username}:${e.password}`)}`),{authorization:`Basic ${r(`${e.username}:${e.password}`)}`}),ie=async(e,t)=>{const r=["authorizationCode","redirectUrl","clientId","clientSecret","tokenUrl"];if(!w(e,r))throw new Error(`Oauth credentials missing: ${D(e,r)}`);const a=new URLSearchParams({grant_type:"authorization_code",code:e.authorizationCode,redirect_uri:e.redirectUrl,client_id:e.clientId,client_secret:e.clientSecret});ne(e.tokenUrl),ne(a.toString());const s=await fetch(e.tokenUrl,{method:"POST",body:a.toString(),headers:{"content-length":`${a.toString().length}`,"content-type":"application/x-www-form-urlencoded"},...null!=t?t:{}});if(s.ok){return await s.json()}return ne(`Fetch Oauth tokens failed: ${await s.text()}`),{}},le=async(e,t)=>{const r=["refreshToken","clientId","clientSecret","tokenUrl"];if(!w(e,r))throw new Error(`Oauth credentials missing: ${D(e,r)}`);const a=new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,refresh_token:e.refreshToken,grant_type:"refresh_token"}),s=await fetch(e.tokenUrl,{method:"POST",body:a.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},...null!=t?t:{}});if(s.ok){return await s.json()}return ne(`Refresh access token failed: ${await s.text()}`),{}},ue=async(e,t)=>{var r;ne("Fetching oauth headers");let a={};return e.refreshToken?(e.refreshToken&&!e.accessToken||Date.now()>(null!==(r=e.expiration)&&void 0!==r?r:0))&&(a=await le(e,t)):a=await ie(e,t),ne(`Oauth tokens fetched: ${a.access_token}`),{tokens:a,headers:{authorization:`Bearer ${a.access_token}`}}};var he=Object.freeze({__proto__:null,defaultParam:ce,fetchOauthTokens:ie,getBasicAuthHeaders:de,getOauthHeaders:ue,refreshAccessToken:le});const pe=async e=>{var t;const{serverUrl:r,credentials:a,authMethod:s,defaultAccountType:o,authFunction:n}=e;let c={};switch(s){case"Basic":c=de(a);break;case"Oauth":c=(await ue(a)).headers;break;case"Digest":c={Authorization:`Digest ${a.digestString}`};break;case"Custom":c=null!==(t=await(null==n?void 0:n(a)))&&void 0!==t?t:{};break;default:throw new Error("Invalid auth method")}const d=o?await se({account:{serverUrl:r,credentials:a,accountType:o},headers:c}):void 0,i=ce(m,{url:r,headers:c}),l=ce(A,{headers:c,url:r}),u=ce(g,{headers:c,url:r}),h=ce(O,{headers:c}),p=ce(V,{headers:c}),f=ce($,{headers:c}),v=ce(k,{headers:c}),C=ce(E,{headers:c}),w=ce(T,{headers:c}),D=ce(U,{headers:c,account:d}),b=ce(M,{headers:c}),_=ce(z,{headers:c}),R=ce(Z,{headers:c}),B=ce(G,{headers:c,account:d}),F=ce(I,{headers:c,account:d}),Y=ce(Q,{headers:c}),X=ce(q,{headers:c}),ee=ce(J,{headers:c}),te=ce(K,{headers:c}),re=ce(W,{account:d,headers:c}),ae=ce(L,{headers:c}),oe=ce(j,{headers:c});return{davRequest:async e=>{const{init:t,...r}=e,{headers:a,...s}=t;return y({...r,init:{...s,headers:{...c,...a}}})},propfind:h,createAccount:async e=>{const{account:t,headers:s,loadCollections:o,loadObjects:n}=e;return se({account:{serverUrl:r,credentials:a,...t},headers:{...c,...s},loadCollections:o,loadObjects:n})},createObject:i,updateObject:l,deleteObject:u,calendarQuery:b,addressBookQuery:ae,collectionQuery:p,makeCollection:f,calendarMultiGet:_,makeCalendar:R,syncCollection:v,supportedReportSet:C,isCollectionDirty:w,smartCollectionSync:D,fetchCalendars:B,fetchCalendarUserAddresses:F,fetchCalendarObjects:Y,createCalendarObject:X,updateCalendarObject:ee,deleteCalendarObject:te,syncCalendars:re,fetchAddressBooks:ce(x,{account:d,headers:c}),addressBookMultiGet:oe,fetchVCards:ce(S,{headers:c}),createVCard:ce(N,{headers:c}),updateVCard:ce(H,{headers:c}),deleteVCard:ce(P,{headers:c})}};class fe{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:{}}async login(){var e;switch(this.authMethod){case"Basic":this.authHeaders=de(this.credentials);break;case"Oauth":this.authHeaders=(await ue(this.credentials,this.fetchOptions)).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 se({account:{serverUrl:this.serverUrl,credentials:this.credentials,accountType:this.accountType},headers:this.authHeaders,fetchOptions:this.fetchOptions}):void 0}async davRequest(e){const{init:t,...r}=e,{headers:a,...s}=t;return y({...r,init:{...s,headers:{...this.authHeaders,...a}},fetchOptions:this.fetchOptions})}async createObject(...e){return ce(m,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateObject(...e){return ce(A,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteObject(...e){return ce(g,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async propfind(...e){return ce(O,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createAccount(e){const{account:t,headers:r,loadCollections:a,loadObjects:s,fetchOptions:o}=e;return se({account:{serverUrl:this.serverUrl,credentials:this.credentials,...t},headers:{...this.authHeaders,...r},loadCollections:a,loadObjects:s,fetchOptions:null!=o?o:this.fetchOptions})}async collectionQuery(...e){return ce(V,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async makeCollection(...e){return ce($,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async syncCollection(...e){return ce(k,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async supportedReportSet(...e){return ce(E,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async isCollectionDirty(...e){return ce(T,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async smartCollectionSync(...e){return ce(U,{headers:this.authHeaders,fetchOptions:this.fetchOptions,account:this.account})(e[0])}async calendarQuery(...e){return ce(M,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async makeCalendar(...e){return ce(Z,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async calendarMultiGet(...e){return ce(z,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async fetchCalendars(...e){return ce(G,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(null==e?void 0:e[0])}async fetchCalendarUserAddresses(...e){return ce(I,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(null==e?void 0:e[0])}async fetchCalendarObjects(...e){return ce(Q,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createCalendarObject(...e){return ce(q,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateCalendarObject(...e){return ce(J,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteCalendarObject(...e){return ce(K,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async syncCalendars(...e){return ce(W,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(e[0])}async addressBookQuery(...e){return ce(L,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async addressBookMultiGet(...e){return ce(j,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async fetchAddressBooks(...e){return ce(x,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions})(null==e?void 0:e[0])}async fetchVCards(...e){return ce(S,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createVCard(...e){return ce(N,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateVCard(...e){return ce(H,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteVCard(...e){return ce(P,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}}var ve={DAVNamespace:a,DAVNamespaceShort:o,DAVAttributeMap:s,...Object.freeze({__proto__:null,DAVClient:fe,createDAVClient:pe}),...C,..._,...oe,...B,...X,...he,...f};export{s as DAVAttributeMap,fe as DAVClient,a as DAVNamespace,o as DAVNamespaceShort,L as addressBookQuery,z as calendarMultiGet,M as calendarQuery,u as cleanupFalsy,V as collectionQuery,se as createAccount,q as createCalendarObject,pe as createDAVClient,m as createObject,N as createVCard,y as davRequest,ve as default,K as deleteCalendarObject,g as deleteObject,P as deleteVCard,x as fetchAddressBooks,Q as fetchCalendarObjects,I as fetchCalendarUserAddresses,G as fetchCalendars,ie as fetchOauthTokens,S as fetchVCards,Y as freeBusyQuery,de as getBasicAuthHeaders,l as getDAVAttribute,ue as getOauthHeaders,T as isCollectionDirty,Z as makeCalendar,O as propfind,le as refreshAccessToken,U as smartCollectionSync,E as supportedReportSet,W as syncCalendars,k as syncCollection,J as updateCalendarObject,A as updateObject,H as updateVCard,i as urlContains,d as urlEquals}; diff --git a/dist/tsdav.mjs b/dist/tsdav.mjs index b1af53ce..3f4ea415 100644 --- a/dist/tsdav.mjs +++ b/dist/tsdav.mjs @@ -1,4 +1,4 @@ -import { fetch } from 'cross-fetch'; +import 'cross-fetch/polyfill'; import getLogger from 'debug'; import convert from 'xml-js'; import { encode } from 'base-64'; @@ -293,7 +293,7 @@ const deleteObject = async (params) => { return fetch(url, { method: 'DELETE', headers: excludeHeaders(cleanupFalsy({ 'If-Match': etag, ...headers }), headersToExclude), - ...fetchOptions + ...fetchOptions, }); }; @@ -567,11 +567,11 @@ var collection = /*#__PURE__*/Object.freeze({ /* eslint-disable no-underscore-dangle */ const debug$3 = getLogger('tsdav:addressBook'); const addressBookQuery = async (params) => { - const { url, props, filters, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, filters, depth, headers, headersToExclude, fetchOptions = {} } = params; return collectionQuery({ url, body: { - 'addressbook-query': { + 'addressbook-query': cleanupFalsy({ _attributes: getDAVAttribute([DAVNamespace.CARDDAV, DAVNamespace.DAV]), [`${DAVNamespaceShort.DAV}:prop`]: props, filter: filters !== null && filters !== void 0 ? filters : { @@ -581,24 +581,24 @@ const addressBookQuery = async (params) => { }, }, }, - }, + }), }, defaultNamespace: DAVNamespaceShort.CARDDAV, depth, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); }; const addressBookMultiGet = async (params) => { - const { url, props, objectUrls, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, objectUrls, depth, headers, headersToExclude, fetchOptions = {} } = params; return collectionQuery({ url, body: { - 'addressbook-multiget': { + 'addressbook-multiget': cleanupFalsy({ _attributes: getDAVAttribute([DAVNamespace.DAV, DAVNamespace.CARDDAV]), [`${DAVNamespaceShort.DAV}:prop`]: props, [`${DAVNamespaceShort.DAV}:href`]: objectUrls, - }, + }), }, defaultNamespace: DAVNamespaceShort.CARDDAV, depth, @@ -607,7 +607,7 @@ const addressBookMultiGet = async (params) => { }); }; const fetchAddressBooks = async (params) => { - const { account, headers, props: customProps, headersToExclude, fetchOptions = {} } = params !== null && params !== void 0 ? params : {}; + const { account, headers, props: customProps, headersToExclude, fetchOptions = {}, } = params !== null && params !== void 0 ? params : {}; const requiredFields = ['homeUrl', 'rootUrl']; if (!account || !hasFields(account, requiredFields)) { if (!account) { @@ -644,11 +644,15 @@ const fetchAddressBooks = async (params) => { }) .map(async (addr) => ({ ...addr, - reports: await supportedReportSet({ collection: addr, headers: excludeHeaders(headers, headersToExclude), fetchOptions }), + reports: await supportedReportSet({ + collection: addr, + headers: excludeHeaders(headers, headersToExclude), + fetchOptions, + }), }))); }; const fetchVCards = async (params) => { - const { addressBook, headers, objectUrls, headersToExclude, urlFilter = (url) => url, useMultiGet = true, fetchOptions = {} } = params; + const { addressBook, headers, objectUrls, headersToExclude, urlFilter = (url) => url, useMultiGet = true, fetchOptions = {}, } = params; debug$3(`Fetching vcards from ${addressBook === null || addressBook === void 0 ? void 0 : addressBook.url}`); const requiredFields = ['url']; if (!addressBook || !hasFields(addressBook, requiredFields)) { @@ -665,7 +669,7 @@ const fetchVCards = async (params) => { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, - })).map((res) => { var _a; return (res.ok ? (_a = res.href) !== null && _a !== void 0 ? _a : '' : ''); })) + })).map((res) => { var _a; return (res.ok ? ((_a = res.href) !== null && _a !== void 0 ? _a : '') : ''); })) .map((url) => (url.startsWith('http') || !url ? url : new URL(url, addressBook.url).href)) .filter(urlFilter) .map((url) => new URL(url).pathname); @@ -681,7 +685,7 @@ const fetchVCards = async (params) => { objectUrls: vcardUrls, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } else { @@ -693,7 +697,7 @@ const fetchVCards = async (params) => { }, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } } @@ -707,7 +711,7 @@ const fetchVCards = async (params) => { }); }; const createVCard = async (params) => { - const { addressBook, vCardString, filename, headers, headersToExclude, fetchOptions = {} } = params; + const { addressBook, vCardString, filename, headers, headersToExclude, fetchOptions = {}, } = params; return createObject({ url: new URL(filename, addressBook.url).href, data: vCardString, @@ -716,7 +720,7 @@ const createVCard = async (params) => { 'If-None-Match': '*', ...headers, }, headersToExclude), - fetchOptions + fetchOptions, }); }; const updateVCard = async (params) => { @@ -738,7 +742,7 @@ const deleteVCard = async (params) => { url: vCard.url, etag: vCard.etag, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); }; @@ -779,7 +783,7 @@ const fetchCalendarUserAddresses = async (params) => { return addresses; }; const calendarQuery = async (params) => { - const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {} } = params; + const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, } = params; return collectionQuery({ url, body: { @@ -802,17 +806,17 @@ const calendarQuery = async (params) => { }); }; const calendarMultiGet = async (params) => { - const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {} } = params; + const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, } = params; return collectionQuery({ url, body: { - 'calendar-multiget': { + 'calendar-multiget': cleanupFalsy({ _attributes: getDAVAttribute([DAVNamespace.DAV, DAVNamespace.CALDAV]), [`${DAVNamespaceShort.DAV}:prop`]: props, [`${DAVNamespaceShort.DAV}:href`]: objectUrls, - ...conditionalParam('filter', filters), + filter: filters, timezone, - }, + }), }, defaultNamespace: DAVNamespaceShort.CALDAV, depth, @@ -841,11 +845,11 @@ const makeCalendar = async (params) => { }, }, }, - fetchOptions + fetchOptions, }); }; const fetchCalendars = async (params) => { - const { headers, account, props: customProps, projectedProps, headersToExclude, fetchOptions = {} } = params !== null && params !== void 0 ? params : {}; + const { headers, account, props: customProps, projectedProps, headersToExclude, fetchOptions = {}, } = params !== null && params !== void 0 ? params : {}; const requiredFields = ['homeUrl', 'rootUrl']; if (!account || !hasFields(account, requiredFields)) { if (!account) { @@ -985,7 +989,7 @@ const fetchCalendarObjects = async (params) => { filters, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, })).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)) // patch up to full url if url is not full .filter(urlFilter) // custom filter function on calendar objects @@ -1019,7 +1023,7 @@ const fetchCalendarObjects = async (params) => { filters, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } else { @@ -1049,7 +1053,7 @@ const fetchCalendarObjects = async (params) => { objectUrls: calendarObjectUrls, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } } @@ -1072,7 +1076,7 @@ const createCalendarObject = async (params) => { 'If-None-Match': '*', ...headers, }, headersToExclude), - fetchOptions + fetchOptions, }); }; const updateCalendarObject = async (params) => { @@ -1085,7 +1089,7 @@ const updateCalendarObject = async (params) => { 'content-type': 'text/calendar; charset=utf-8', ...headers, }, headersToExclude), - fetchOptions + fetchOptions, }); }; const deleteCalendarObject = async (params) => { @@ -1094,7 +1098,7 @@ const deleteCalendarObject = async (params) => { url: calendarObject.url, etag: calendarObject.etag, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); }; /** @@ -1102,7 +1106,7 @@ const deleteCalendarObject = async (params) => { */ const syncCalendars = async (params) => { var _a; - const { oldCalendars, account, detailedResult, headers, headersToExclude, fetchOptions = {} } = params; + const { oldCalendars, account, detailedResult, headers, headersToExclude, fetchOptions = {}, } = params; if (!account) { throw new Error('Must have account before syncCalendars'); } @@ -1110,7 +1114,7 @@ const syncCalendars = async (params) => { const remoteCalendars = await fetchCalendars({ account, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); // no existing url const created = remoteCalendars.filter((rc) => localCalendars.every((lc) => !urlContains(lc.url, rc.url))); @@ -1181,7 +1185,7 @@ const freeBusyQuery = async (params) => { defaultNamespace: DAVNamespaceShort.CALDAV, depth, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); return result[0]; }; diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index 9cbb48cc..e1127f33 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -59,7 +59,7 @@ module.exports = { lastVersion: 'current', versions: { current: { - label: '2.1.2', + label: '2.1.3', }, '1.1.6': { label: '1.1.6', diff --git a/docs/package.json b/docs/package.json index bc69a522..9c80e785 100644 --- a/docs/package.json +++ b/docs/package.json @@ -27,15 +27,15 @@ ] }, "dependencies": { - "@docusaurus/core": "3.4.0", - "@docusaurus/preset-classic": "3.4.0", + "@docusaurus/core": "3.6.3", + "@docusaurus/preset-classic": "3.6.3", "@easyops-cn/docusaurus-search-local": "0.44.4", - "@mdx-js/react": "3.0.1", + "@mdx-js/react": "3.1.0", "@svgr/webpack": "8.1.0", "buffer": "6.0.3", "clsx": "2.1.1", "file-loader": "6.2.0", - "prism-react-renderer": "2.3.1", + "prism-react-renderer": "2.4.0", "react": "18.3.1", "react-dom": "18.3.1", "stream-browserify": "3.0.0", @@ -43,11 +43,11 @@ "xml-js": "1.6.11" }, "devDependencies": { - "@docusaurus/module-type-aliases": "3.4.0", + "@docusaurus/module-type-aliases": "3.6.3", "@tsconfig/docusaurus": "2.0.3", "@types/react": "18.3.3", "@types/react-helmet": "6.1.11", "@types/react-router-dom": "5.3.3", - "typescript": "5.5.4" + "typescript": "5.7.2" } } diff --git a/package.json b/package.json index 3b73c778..bdf3142b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "tsdav", - "version": "2.1.2", + "version": "2.1.3", "description": "WebDAV, CALDAV, and CARDDAV client for Nodejs and the Browser", "keywords": [ "dav", @@ -48,41 +48,41 @@ "dependencies": { "base-64": "1.0.0", "cross-fetch": "4.0.0", - "debug": "4.3.7", + "debug": "4.4.0", "xml-js": "1.6.11" }, "devDependencies": { - "@rollup/plugin-commonjs": "26.0.1", - "@rollup/plugin-node-resolve": "15.2.3", + "@rollup/plugin-commonjs": "28.0.1", + "@rollup/plugin-node-resolve": "15.3.0", "@rollup/plugin-terser": "0.4.4", - "@rollup/plugin-typescript": "11.1.6", + "@rollup/plugin-typescript": "12.1.1", "@types/base-64": "1.0.2", "@types/debug": "4.1.12", - "@types/jest": "29.5.12", + "@types/jest": "29.5.14", "@types/node": "22.5.4", "@typescript-eslint/eslint-plugin": "8.5.0", - "@typescript-eslint/parser": "8.5.0", + "@typescript-eslint/parser": "8.17.0", "copyfiles": "2.4.1", "cross-env": "7.0.3", - "dotenv": "16.4.5", - "eslint": "9.10.0", + "dotenv": "16.4.7", + "eslint": "9.16.0", "eslint-config-airbnb": "19.0.4", "eslint-config-airbnb-typescript": "18.0.0", "eslint-config-prettier": "9.1.0", - "eslint-module-utils": "2.11.0", - "eslint-plugin-import": "2.30.0", - "eslint-plugin-prettier": "5.1.3", + "eslint-module-utils": "2.12.0", + "eslint-plugin-import": "2.31.0", + "eslint-plugin-prettier": "5.2.1", "jest": "29.7.0", - "prettier": "3.3.3", + "prettier": "3.4.2", "rimraf": "6.0.1", - "rollup": "4.21.2", + "rollup": "4.28.1", "rollup-plugin-dts": "6.1.1", "rollup-plugin-node-builtins": "2.1.2", "rollup-plugin-polyfill-node": "0.13.0", - "sort-package-json": "2.10.1", + "sort-package-json": "2.12.0", "ts-jest": "29.2.5", - "tslib": "2.7.0", - "typescript": "5.6.2" + "tslib": "2.8.1", + "typescript": "5.7.2" }, "engines": { "node": ">=10" diff --git a/src/account.ts b/src/account.ts index 76690e46..287bcbc0 100644 --- a/src/account.ts +++ b/src/account.ts @@ -1,4 +1,5 @@ -import { fetch } from 'cross-fetch'; +import 'cross-fetch/polyfill'; + import getLogger from 'debug'; import { fetchAddressBooks, fetchVCards } from './addressBook'; diff --git a/src/addressBook.ts b/src/addressBook.ts index f1bcf24a..fb430a27 100644 --- a/src/addressBook.ts +++ b/src/addressBook.ts @@ -7,7 +7,7 @@ import { DAVNamespace, DAVNamespaceShort } from './consts'; import { createObject, deleteObject, propfind, updateObject } from './request'; import { DAVDepth, DAVResponse } from './types/DAVTypes'; import { DAVAccount, DAVAddressBook, DAVVCard } from './types/models'; -import { excludeHeaders, getDAVAttribute } from './util/requestHelpers'; +import { cleanupFalsy, excludeHeaders, getDAVAttribute } from './util/requestHelpers'; import { findMissingFieldNames, hasFields } from './util/typeHelpers'; const debug = getLogger('tsdav:addressBook'); @@ -21,11 +21,11 @@ export const addressBookQuery = async (params: { headersToExclude?: string[]; fetchOptions?: RequestInit; }): Promise => { - const { url, props, filters, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, filters, depth, headers, headersToExclude, fetchOptions = {} } = params; return collectionQuery({ url, body: { - 'addressbook-query': { + 'addressbook-query': cleanupFalsy({ _attributes: getDAVAttribute([DAVNamespace.CARDDAV, DAVNamespace.DAV]), [`${DAVNamespaceShort.DAV}:prop`]: props, filter: filters ?? { @@ -35,12 +35,12 @@ export const addressBookQuery = async (params: { }, }, }, - }, + }), }, defaultNamespace: DAVNamespaceShort.CARDDAV, depth, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); }; @@ -53,15 +53,15 @@ export const addressBookMultiGet = async (params: { headersToExclude?: string[]; fetchOptions?: RequestInit; }): Promise => { - const { url, props, objectUrls, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, objectUrls, depth, headers, headersToExclude, fetchOptions = {} } = params; return collectionQuery({ url, body: { - 'addressbook-multiget': { + 'addressbook-multiget': cleanupFalsy({ _attributes: getDAVAttribute([DAVNamespace.DAV, DAVNamespace.CARDDAV]), [`${DAVNamespaceShort.DAV}:prop`]: props, [`${DAVNamespaceShort.DAV}:href`]: objectUrls, - }, + }), }, defaultNamespace: DAVNamespaceShort.CARDDAV, depth, @@ -77,7 +77,13 @@ export const fetchAddressBooks = async (params?: { headersToExclude?: string[]; fetchOptions?: RequestInit; }): Promise => { - const { account, headers, props: customProps, headersToExclude, fetchOptions = {} } = params ?? {}; + const { + account, + headers, + props: customProps, + headersToExclude, + fetchOptions = {}, + } = params ?? {}; const requiredFields: Array = ['homeUrl', 'rootUrl']; if (!account || !hasFields(account, requiredFields)) { if (!account) { @@ -119,7 +125,11 @@ export const fetchAddressBooks = async (params?: { }) .map(async (addr) => ({ ...addr, - reports: await supportedReportSet({ collection: addr, headers: excludeHeaders(headers, headersToExclude), fetchOptions }), + reports: await supportedReportSet({ + collection: addr, + headers: excludeHeaders(headers, headersToExclude), + fetchOptions, + }), })), ); }; @@ -140,7 +150,7 @@ export const fetchVCards = async (params: { headersToExclude, urlFilter = (url) => url, useMultiGet = true, - fetchOptions = {} + fetchOptions = {}, } = params; debug(`Fetching vcards from ${addressBook?.url}`); const requiredFields: Array<'url'> = ['url']; @@ -167,7 +177,7 @@ export const fetchVCards = async (params: { headers: excludeHeaders(headers, headersToExclude), fetchOptions, }) - ).map((res) => (res.ok ? res.href ?? '' : '')) + ).map((res) => (res.ok ? (res.href ?? '') : '')) ) .map((url) => (url.startsWith('http') || !url ? url : new URL(url, addressBook.url).href)) .filter(urlFilter) @@ -185,7 +195,7 @@ export const fetchVCards = async (params: { objectUrls: vcardUrls, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } else { vCardResults = await addressBookQuery({ @@ -196,7 +206,7 @@ export const fetchVCards = async (params: { }, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } } @@ -216,7 +226,14 @@ export const createVCard = async (params: { headersToExclude?: string[]; fetchOptions?: RequestInit; }): Promise => { - const { addressBook, vCardString, filename, headers, headersToExclude, fetchOptions = {} } = params; + const { + addressBook, + vCardString, + filename, + headers, + headersToExclude, + fetchOptions = {}, + } = params; return createObject({ url: new URL(filename, addressBook.url).href, data: vCardString, @@ -228,7 +245,7 @@ export const createVCard = async (params: { }, headersToExclude, ), - fetchOptions + fetchOptions, }); }; @@ -265,6 +282,6 @@ export const deleteVCard = async (params: { url: vCard.url, etag: vCard.etag, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); }; diff --git a/src/calendar.ts b/src/calendar.ts index 3963ee18..388b69db 100644 --- a/src/calendar.ts +++ b/src/calendar.ts @@ -63,7 +63,16 @@ export const calendarQuery = async (params: { headersToExclude?: string[]; fetchOptions?: RequestInit; }): Promise => { - const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {} } = params; + const { + url, + props, + filters, + timezone, + depth, + headers, + headersToExclude, + fetchOptions = {}, + } = params; return collectionQuery({ url, body: { @@ -97,17 +106,27 @@ export const calendarMultiGet = async (params: { headersToExclude?: string[]; fetchOptions?: RequestInit; }): Promise => { - const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {} } = params; + const { + url, + props, + objectUrls, + filters, + timezone, + depth, + headers, + headersToExclude, + fetchOptions = {}, + } = params; return collectionQuery({ url, body: { - 'calendar-multiget': { + 'calendar-multiget': cleanupFalsy({ _attributes: getDAVAttribute([DAVNamespace.DAV, DAVNamespace.CALDAV]), [`${DAVNamespaceShort.DAV}:prop`]: props, [`${DAVNamespaceShort.DAV}:href`]: objectUrls, - ...conditionalParam('filter', filters), + filter: filters, timezone, - }, + }), }, defaultNamespace: DAVNamespaceShort.CALDAV, depth, @@ -144,7 +163,7 @@ export const makeCalendar = async (params: { }, }, }, - fetchOptions + fetchOptions, }); }; @@ -156,7 +175,14 @@ export const fetchCalendars = async (params?: { headersToExclude?: string[]; fetchOptions?: RequestInit; }): Promise => { - const { headers, account, props: customProps, projectedProps, headersToExclude, fetchOptions = {} } = params ?? {}; + const { + headers, + account, + props: customProps, + projectedProps, + headersToExclude, + fetchOptions = {}, + } = params ?? {}; const requiredFields: Array<'homeUrl' | 'rootUrl'> = ['homeUrl', 'rootUrl']; if (!account || !hasFields(account, requiredFields)) { if (!account) { @@ -342,7 +368,7 @@ export const fetchCalendarObjects = async (params: { filters, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }) ).map((res) => res.href ?? '') ) @@ -380,7 +406,7 @@ export const fetchCalendarObjects = async (params: { filters, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } else { calendarObjectResults = await calendarMultiGet({ @@ -409,7 +435,7 @@ export const fetchCalendarObjects = async (params: { objectUrls: calendarObjectUrls, depth: '1', headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); } } @@ -442,7 +468,7 @@ export const createCalendarObject = async (params: { }, headersToExclude, ), - fetchOptions + fetchOptions, }); }; @@ -464,7 +490,7 @@ export const updateCalendarObject = async (params: { }, headersToExclude, ), - fetchOptions + fetchOptions, }); }; @@ -479,7 +505,7 @@ export const deleteCalendarObject = async (params: { url: calendarObject.url, etag: calendarObject.etag, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); }; @@ -494,7 +520,14 @@ export const syncCalendars: SyncCalendars = async (params: { detailedResult?: boolean; fetchOptions?: RequestInit; }): Promise => { - const { oldCalendars, account, detailedResult, headers, headersToExclude, fetchOptions = {} } = params; + const { + oldCalendars, + account, + detailedResult, + headers, + headersToExclude, + fetchOptions = {}, + } = params; if (!account) { throw new Error('Must have account before syncCalendars'); } @@ -503,7 +536,7 @@ export const syncCalendars: SyncCalendars = async (params: { const remoteCalendars = await fetchCalendars({ account, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); // no existing url @@ -603,7 +636,7 @@ export const freeBusyQuery = async (params: { defaultNamespace: DAVNamespaceShort.CALDAV, depth, headers: excludeHeaders(headers, headersToExclude), - fetchOptions + fetchOptions, }); return result[0]; }; diff --git a/src/request.ts b/src/request.ts index 9e9d27dc..c8790667 100644 --- a/src/request.ts +++ b/src/request.ts @@ -1,4 +1,5 @@ -import { fetch } from 'cross-fetch'; +import 'cross-fetch/polyfill'; + import getLogger from 'debug'; import convert, { ElementCompact } from 'xml-js'; @@ -243,6 +244,6 @@ export const deleteObject = async (params: { return fetch(url, { method: 'DELETE', headers: excludeHeaders(cleanupFalsy({ 'If-Match': etag, ...headers }), headersToExclude), - ...fetchOptions + ...fetchOptions, }); }; diff --git a/src/util/authHelpers.ts b/src/util/authHelpers.ts index 666ee5f0..c206e001 100644 --- a/src/util/authHelpers.ts +++ b/src/util/authHelpers.ts @@ -1,5 +1,6 @@ +import 'cross-fetch/polyfill'; + import { encode } from 'base-64'; -import { fetch } from 'cross-fetch'; import getLogger from 'debug'; import { DAVTokens } from '../types/DAVTypes'; @@ -27,7 +28,10 @@ export const getBasicAuthHeaders = (credentials: DAVCredentials): { authorizatio }; }; -export const fetchOauthTokens = async (credentials: DAVCredentials, fetchOptions?: RequestInit): Promise => { +export const fetchOauthTokens = async ( + credentials: DAVCredentials, + fetchOptions?: RequestInit, +): Promise => { const requireFields: Array = [ 'authorizationCode', 'redirectUrl',