Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

tsdav

Package Overview
Dependencies
Maintainers
1
Versions
31
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

tsdav - npm Package Compare versions

Comparing version 1.0.6 to 1.1.0

CHANGELOG.md

12

dist/account.d.ts
import { DAVAccount } from './types/models';
export declare const serviceDiscovery: (params: {
account: DAVAccount;
headers?: Record<string, string> | undefined;
headers?: Record<string, string>;
}) => Promise<string>;
export declare const fetchPrincipalUrl: (params: {
account: DAVAccount;
headers?: Record<string, string> | undefined;
headers?: Record<string, string>;
}) => Promise<string>;
export declare const fetchHomeUrl: (params: {
account: DAVAccount;
headers?: Record<string, string> | undefined;
headers?: Record<string, string>;
}) => Promise<string>;
export declare const createAccount: (params: {
account: DAVAccount;
headers?: Record<string, string> | undefined;
loadCollections?: boolean | undefined;
loadObjects?: boolean | undefined;
headers?: Record<string, string>;
loadCollections?: boolean;
loadObjects?: boolean;
}) => Promise<DAVAccount>;
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -22,29 +11,2 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -55,197 +17,124 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.createAccount = exports.fetchHomeUrl = exports.fetchPrincipalUrl = exports.serviceDiscovery = void 0;
var cross_fetch_1 = require("cross-fetch");
var debug_1 = __importDefault(require("debug"));
var addressBook_1 = require("./addressBook");
var calendar_1 = require("./calendar");
var consts_1 = require("./consts");
var request_1 = require("./request");
var requestHelpers_1 = require("./util/requestHelpers");
var typeHelper_1 = require("./util/typeHelper");
var debug = debug_1.default('tsdav:account');
var serviceDiscovery = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var account, headers, endpoint, uri, response, location_1, serviceURL, err_1;
const cross_fetch_1 = require("cross-fetch");
const debug_1 = __importDefault(require("debug"));
const addressBook_1 = require("./addressBook");
const calendar_1 = require("./calendar");
const consts_1 = require("./consts");
const request_1 = require("./request");
const requestHelpers_1 = require("./util/requestHelpers");
const typeHelpers_1 = require("./util/typeHelpers");
const debug = debug_1.default('tsdav:account');
const serviceDiscovery = (params) => __awaiter(void 0, void 0, void 0, function* () {
var _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
debug('Service discovery...');
account = params.account, headers = params.headers;
endpoint = new URL(account.serverUrl);
uri = new URL("/.well-known/" + account.accountType, endpoint);
uri.protocol = (_a = endpoint.protocol) !== null && _a !== void 0 ? _a : 'http';
_c.label = 1;
case 1:
_c.trys.push([1, 3, , 4]);
return [4 /*yield*/, cross_fetch_1.fetch(uri.href, {
headers: headers,
method: 'GET',
redirect: 'manual',
})];
case 2:
response = _c.sent();
if (response.status >= 300 && response.status < 400) {
location_1 = response.headers.get('Location');
if (typeof location_1 === 'string' && location_1.length) {
debug("Service discovery redirected to " + location_1);
serviceURL = new URL(location_1, endpoint);
serviceURL.protocol = (_b = endpoint.protocol) !== null && _b !== void 0 ? _b : 'http';
return [2 /*return*/, serviceURL.href];
}
}
return [3 /*break*/, 4];
case 3:
err_1 = _c.sent();
debug("Service discovery failed: " + err_1.stack);
return [3 /*break*/, 4];
case 4: return [2 /*return*/, endpoint.href];
debug('Service discovery...');
const { account, headers } = params;
const endpoint = new URL(account.serverUrl);
const uri = new URL(`/.well-known/${account.accountType}`, endpoint);
uri.protocol = (_a = endpoint.protocol) !== null && _a !== void 0 ? _a : 'http';
try {
const response = yield cross_fetch_1.fetch(uri.href, {
headers,
method: 'GET',
redirect: 'manual',
});
if (response.status >= 300 && response.status < 400) {
// http redirect.
const location = response.headers.get('Location');
if (typeof location === 'string' && location.length) {
debug(`Service discovery redirected to ${location}`);
const serviceURL = new URL(location, endpoint);
serviceURL.protocol = (_b = endpoint.protocol) !== null && _b !== void 0 ? _b : 'http';
return serviceURL.href;
}
}
}
catch (err) {
debug(`Service discovery failed: ${err.stack}`);
}
return endpoint.href;
});
exports.serviceDiscovery = serviceDiscovery;
const fetchPrincipalUrl = (params) => __awaiter(void 0, void 0, void 0, function* () {
var _c, _d, _e;
const { account, headers } = params;
const requiredFields = ['rootUrl'];
if (!typeHelpers_1.hasFields(account, requiredFields)) {
throw new Error(`account must have ${typeHelpers_1.findMissingFieldNames(account, requiredFields)} before fetchPrincipalUrl`);
}
debug(`Fetching principal url from path ${account.rootUrl}`);
const [response] = yield request_1.propfind({
url: account.rootUrl,
props: [{ name: 'current-user-principal', namespace: consts_1.DAVNamespace.DAV }],
depth: '0',
headers,
});
}); };
exports.serviceDiscovery = serviceDiscovery;
var fetchPrincipalUrl = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var account, headers, requiredFields, response;
var _a, _b, _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
account = params.account, headers = params.headers;
requiredFields = ['rootUrl'];
if (!typeHelper_1.hasFields(account, requiredFields)) {
throw new Error("account must have " + typeHelper_1.findMissingFieldNames(account, requiredFields) + " before fetchPrincipalUrl");
}
debug("Fetching principal url from path " + account.rootUrl);
return [4 /*yield*/, request_1.propfind({
url: account.rootUrl,
props: [{ name: 'current-user-principal', namespace: consts_1.DAVNamespace.DAV }],
depth: '0',
headers: headers,
})];
case 1:
response = (_d.sent())[0];
if (!response.ok) {
debug("Fetch principal url failed: " + response.statusText);
if (response.status === 401) {
throw new Error('Invalid credentials');
}
}
debug("Fetched principal url " + ((_a = response.props) === null || _a === void 0 ? void 0 : _a.currentUserPrincipal.href));
return [2 /*return*/, new URL((_c = (_b = response.props) === null || _b === void 0 ? void 0 : _b.currentUserPrincipal.href) !== null && _c !== void 0 ? _c : '', account.rootUrl).href];
if (!response.ok) {
debug(`Fetch principal url failed: ${response.statusText}`);
if (response.status === 401) {
throw new Error('Invalid credentials');
}
});
}); };
}
debug(`Fetched principal url ${(_c = response.props) === null || _c === void 0 ? void 0 : _c.currentUserPrincipal.href}`);
return new URL((_e = (_d = response.props) === null || _d === void 0 ? void 0 : _d.currentUserPrincipal.href) !== null && _e !== void 0 ? _e : '', account.rootUrl).href;
});
exports.fetchPrincipalUrl = fetchPrincipalUrl;
var fetchHomeUrl = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var account, headers, requiredFields, responses, matched, result;
var _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
account = params.account, headers = params.headers;
requiredFields = ['principalUrl', 'rootUrl'];
if (!typeHelper_1.hasFields(account, requiredFields)) {
throw new Error("account must have " + typeHelper_1.findMissingFieldNames(account, requiredFields) + " before fetchHomeUrl");
}
debug("Fetch home url from " + account.principalUrl);
return [4 /*yield*/, request_1.propfind({
url: account.principalUrl,
props: [
account.accountType === 'caldav'
? { name: 'calendar-home-set', namespace: consts_1.DAVNamespace.CALDAV }
: { name: 'addressbook-home-set', namespace: consts_1.DAVNamespace.CARDDAV },
],
depth: '0',
headers: headers,
})];
case 1:
responses = _c.sent();
matched = responses.find(function (r) { return requestHelpers_1.urlContains(account.principalUrl, r.href); });
if (!matched || !matched.ok) {
throw new Error('cannot find homeUrl');
}
result = new URL(account.accountType === 'caldav'
? (_a = matched === null || matched === void 0 ? void 0 : matched.props) === null || _a === void 0 ? void 0 : _a.calendarHomeSet.href
: (_b = matched === null || matched === void 0 ? void 0 : matched.props) === null || _b === void 0 ? void 0 : _b.addressbookHomeSet.href, account.rootUrl).href;
debug("Fetched home url " + result);
return [2 /*return*/, result];
}
const fetchHomeUrl = (params) => __awaiter(void 0, void 0, void 0, function* () {
var _f, _g;
const { account, headers } = params;
const requiredFields = ['principalUrl', 'rootUrl'];
if (!typeHelpers_1.hasFields(account, requiredFields)) {
throw new Error(`account must have ${typeHelpers_1.findMissingFieldNames(account, requiredFields)} before fetchHomeUrl`);
}
debug(`Fetch home url from ${account.principalUrl}`);
const responses = yield request_1.propfind({
url: account.principalUrl,
props: [
account.accountType === 'caldav'
? { name: 'calendar-home-set', namespace: consts_1.DAVNamespace.CALDAV }
: { name: 'addressbook-home-set', namespace: consts_1.DAVNamespace.CARDDAV },
],
depth: '0',
headers,
});
}); };
const matched = responses.find((r) => requestHelpers_1.urlContains(account.principalUrl, r.href));
if (!matched || !matched.ok) {
throw new Error('cannot find homeUrl');
}
const result = new URL(account.accountType === 'caldav'
? (_f = matched === null || matched === void 0 ? void 0 : matched.props) === null || _f === void 0 ? void 0 : _f.calendarHomeSet.href
: (_g = matched === null || matched === void 0 ? void 0 : matched.props) === null || _g === void 0 ? void 0 : _g.addressbookHomeSet.href, account.rootUrl).href;
debug(`Fetched home url ${result}`);
return result;
});
exports.fetchHomeUrl = fetchHomeUrl;
var createAccount = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var account, headers, _a, loadCollections, _b, loadObjects, newAccount, _c, _d, _e, _f, _g, _h, _j;
return __generator(this, function (_k) {
switch (_k.label) {
case 0:
account = params.account, headers = params.headers, _a = params.loadCollections, loadCollections = _a === void 0 ? false : _a, _b = params.loadObjects, loadObjects = _b === void 0 ? false : _b;
newAccount = __assign({}, account);
_c = newAccount;
return [4 /*yield*/, exports.serviceDiscovery({ account: account, headers: headers })];
case 1:
_c.rootUrl = _k.sent();
_d = newAccount;
return [4 /*yield*/, exports.fetchPrincipalUrl({ account: newAccount, headers: headers })];
case 2:
_d.principalUrl = _k.sent();
_e = newAccount;
return [4 /*yield*/, exports.fetchHomeUrl({ account: newAccount, headers: headers })];
case 3:
_e.homeUrl = _k.sent();
if (!(loadCollections || loadObjects)) return [3 /*break*/, 7];
if (!(account.accountType === 'caldav')) return [3 /*break*/, 5];
_f = newAccount;
return [4 /*yield*/, calendar_1.fetchCalendars({ headers: headers, account: newAccount })];
case 4:
_f.calendars = _k.sent();
return [3 /*break*/, 7];
case 5:
if (!(account.accountType === 'carddav')) return [3 /*break*/, 7];
_g = newAccount;
return [4 /*yield*/, addressBook_1.fetchAddressBooks({ headers: headers, account: newAccount })];
case 6:
_g.addressBooks = _k.sent();
_k.label = 7;
case 7:
if (!loadObjects) return [3 /*break*/, 11];
if (!(account.accountType === 'caldav' && newAccount.calendars)) return [3 /*break*/, 9];
_h = newAccount;
return [4 /*yield*/, Promise.all(newAccount.calendars.map(function (cal) { return __awaiter(void 0, void 0, void 0, function () {
var _a;
var _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_a = [__assign({}, cal)];
_b = {};
return [4 /*yield*/, calendar_1.fetchCalendarObjects({ calendar: cal, headers: headers })];
case 1: return [2 /*return*/, (__assign.apply(void 0, _a.concat([(_b.objects = _c.sent(), _b)])))];
}
});
}); }))];
case 8:
_h.calendars = _k.sent();
return [3 /*break*/, 11];
case 9:
if (!(account.accountType === 'carddav' && newAccount.addressBooks)) return [3 /*break*/, 11];
_j = newAccount;
return [4 /*yield*/, Promise.all(newAccount.addressBooks.map(function (addr) { return __awaiter(void 0, void 0, void 0, function () {
var _a;
var _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_a = [__assign({}, addr)];
_b = {};
return [4 /*yield*/, addressBook_1.fetchVCards({ addressBook: addr, headers: headers })];
case 1: return [2 /*return*/, (__assign.apply(void 0, _a.concat([(_b.objects = _c.sent(), _b)])))];
}
});
}); }))];
case 10:
_j.addressBooks = _k.sent();
_k.label = 11;
case 11: return [2 /*return*/, newAccount];
const createAccount = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { account, headers, loadCollections = false, loadObjects = false } = params;
const newAccount = Object.assign({}, account);
newAccount.rootUrl = yield exports.serviceDiscovery({ account, headers });
newAccount.principalUrl = yield exports.fetchPrincipalUrl({ account: newAccount, headers });
newAccount.homeUrl = yield exports.fetchHomeUrl({ account: newAccount, headers });
// to load objects you must first load collections
if (loadCollections || loadObjects) {
if (account.accountType === 'caldav') {
newAccount.calendars = yield calendar_1.fetchCalendars({ headers, account: newAccount });
}
});
}); };
else if (account.accountType === 'carddav') {
newAccount.addressBooks = yield addressBook_1.fetchAddressBooks({ headers, account: newAccount });
}
}
if (loadObjects) {
if (account.accountType === 'caldav' && newAccount.calendars) {
newAccount.calendars = yield Promise.all(newAccount.calendars.map((cal) => __awaiter(void 0, void 0, void 0, function* () {
return (Object.assign(Object.assign({}, cal), { objects: yield calendar_1.fetchCalendarObjects({ calendar: cal, headers }) }));
})));
}
else if (account.accountType === 'carddav' && newAccount.addressBooks) {
newAccount.addressBooks = yield Promise.all(newAccount.addressBooks.map((addr) => __awaiter(void 0, void 0, void 0, function* () {
return (Object.assign(Object.assign({}, addr), { objects: yield addressBook_1.fetchVCards({ addressBook: addr, headers }) }));
})));
}
}
return newAccount;
});
exports.createAccount = createAccount;
//# sourceMappingURL=account.js.map

@@ -6,4 +6,4 @@ import { DAVDepth, DAVFilter, DAVProp, DAVResponse } from './types/DAVTypes';

props: DAVProp[];
depth?: DAVDepth | undefined;
headers?: Record<string, string> | undefined;
depth?: DAVDepth;
headers?: Record<string, string>;
}) => Promise<DAVResponse[]>;

@@ -14,5 +14,5 @@ export declare const addressBookMultiGet: (params: {

objectUrls: string[];
filters?: DAVFilter[] | undefined;
filters?: DAVFilter[];
depth: DAVDepth;
headers?: Record<string, string> | undefined;
headers?: Record<string, string>;
}) => Promise<DAVResponse[]>;

@@ -25,4 +25,4 @@ export declare const fetchAddressBooks: (params?: {

addressBook: DAVAddressBook;
headers?: Record<string, string> | undefined;
objectUrls?: string[] | undefined;
headers?: Record<string, string>;
objectUrls?: string[];
}) => Promise<DAVVCard[]>;

@@ -33,11 +33,11 @@ export declare const createVCard: (params: {

filename: string;
headers?: Record<string, string> | undefined;
headers?: Record<string, string>;
}) => Promise<Response>;
export declare const updateVCard: (params: {
vCard: DAVVCard;
headers?: Record<string, string> | undefined;
headers?: Record<string, string>;
}) => Promise<Response>;
export declare const deleteVCard: (params: {
vCard: DAVVCard;
headers?: Record<string, string> | undefined;
headers?: Record<string, string>;
}) => Promise<Response>;
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -22,29 +11,2 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -56,210 +18,159 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

/* eslint-disable no-underscore-dangle */
var debug_1 = __importDefault(require("debug"));
var collection_1 = require("./collection");
var consts_1 = require("./consts");
var request_1 = require("./request");
var requestHelpers_1 = require("./util/requestHelpers");
var typeHelper_1 = require("./util/typeHelper");
var debug = debug_1.default('tsdav:addressBook');
var addressBookQuery = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var url, props, depth, headers;
var _a;
return __generator(this, function (_b) {
url = params.url, props = params.props, depth = params.depth, headers = params.headers;
return [2 /*return*/, collection_1.collectionQuery({
url: url,
body: {
'addressbook-query': (_a = {
_attributes: requestHelpers_1.getDAVAttribute([consts_1.DAVNamespace.CARDDAV, consts_1.DAVNamespace.DAV])
const debug_1 = __importDefault(require("debug"));
const collection_1 = require("./collection");
const consts_1 = require("./consts");
const request_1 = require("./request");
const requestHelpers_1 = require("./util/requestHelpers");
const typeHelpers_1 = require("./util/typeHelpers");
const debug = debug_1.default('tsdav:addressBook');
const addressBookQuery = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { url, props, depth, headers } = params;
return collection_1.collectionQuery({
url,
body: {
'addressbook-query': {
_attributes: requestHelpers_1.getDAVAttribute([consts_1.DAVNamespace.CARDDAV, consts_1.DAVNamespace.DAV]),
[`${consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV]}:prop`]: requestHelpers_1.formatProps(props),
filter: {
'prop-filter': {
_attributes: {
name: 'FN',
},
_a[consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV] + ":prop"] = requestHelpers_1.formatProps(props),
_a.filter = {
'prop-filter': {
_attributes: {
name: 'FN',
},
},
},
_a),
},
},
defaultNamespace: consts_1.DAVNamespace.CARDDAV,
depth: depth,
headers: headers,
})];
},
},
defaultNamespace: consts_1.DAVNamespace.CARDDAV,
depth,
headers,
});
}); };
});
exports.addressBookQuery = addressBookQuery;
var addressBookMultiGet = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var url, props, objectUrls, filters, depth, headers;
var _a;
return __generator(this, function (_b) {
url = params.url, props = params.props, objectUrls = params.objectUrls, filters = params.filters, depth = params.depth, headers = params.headers;
return [2 /*return*/, collection_1.collectionQuery({
url: url,
body: {
'addressbook-multiget': (_a = {
_attributes: requestHelpers_1.getDAVAttribute([consts_1.DAVNamespace.DAV, consts_1.DAVNamespace.CARDDAV])
},
_a[consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV] + ":prop"] = requestHelpers_1.formatProps(props),
_a[consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV] + ":href"] = objectUrls,
_a.filter = requestHelpers_1.formatFilters(filters),
_a),
},
defaultNamespace: consts_1.DAVNamespace.CARDDAV,
depth: depth,
headers: headers,
})];
const addressBookMultiGet = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { url, props, objectUrls, filters, depth, headers } = params;
return collection_1.collectionQuery({
url,
body: {
'addressbook-multiget': {
_attributes: requestHelpers_1.getDAVAttribute([consts_1.DAVNamespace.DAV, consts_1.DAVNamespace.CARDDAV]),
[`${consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV]}:prop`]: requestHelpers_1.formatProps(props),
[`${consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV]}:href`]: objectUrls,
filter: requestHelpers_1.formatFilters(filters),
},
},
defaultNamespace: consts_1.DAVNamespace.CARDDAV,
depth,
headers,
});
}); };
});
exports.addressBookMultiGet = addressBookMultiGet;
var fetchAddressBooks = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var _a, account, headers, requiredFields, res;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = params !== null && params !== void 0 ? params : {}, account = _a.account, headers = _a.headers;
requiredFields = ['homeUrl', 'rootUrl'];
if (!account || !typeHelper_1.hasFields(account, requiredFields)) {
if (!account) {
throw new Error('no account for fetchAddressBooks');
}
throw new Error("account must have " + typeHelper_1.findMissingFieldNames(account, requiredFields) + " before fetchAddressBooks");
}
return [4 /*yield*/, request_1.propfind({
url: account.homeUrl,
props: [
{ name: 'displayname', namespace: consts_1.DAVNamespace.DAV },
{ name: 'getctag', namespace: consts_1.DAVNamespace.CALENDAR_SERVER },
{ name: 'resourcetype', namespace: consts_1.DAVNamespace.DAV },
{ name: 'sync-token', namespace: consts_1.DAVNamespace.DAV },
],
depth: '1',
headers: headers,
})];
case 1:
res = _b.sent();
return [2 /*return*/, Promise.all(res
.filter(function (r) { var _a, _b; return Object.keys((_b = (_a = r.props) === null || _a === void 0 ? void 0 : _a.resourcetype) !== null && _b !== void 0 ? _b : {}).includes('addressbook'); })
.map(function (rs) {
var _a, _b, _c, _d, _e, _f;
var displayName = (_a = rs.props) === null || _a === void 0 ? void 0 : _a.displayname;
debug("Found address book named " + (typeof displayName === 'string' ? displayName : '') + ",\n props: " + JSON.stringify(rs.props));
return {
url: new URL((_b = rs.href) !== null && _b !== void 0 ? _b : '', (_c = account.rootUrl) !== null && _c !== void 0 ? _c : '').href,
ctag: (_d = rs.props) === null || _d === void 0 ? void 0 : _d.getctag,
displayName: typeof displayName === 'string' ? displayName : '',
resourcetype: Object.keys((_e = rs.props) === null || _e === void 0 ? void 0 : _e.resourcetype),
syncToken: (_f = rs.props) === null || _f === void 0 ? void 0 : _f.syncToken,
};
})
.map(function (addr) { return __awaiter(void 0, void 0, void 0, function () {
var _a;
var _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_a = [__assign({}, addr)];
_b = {};
return [4 /*yield*/, collection_1.supportedReportSet({ collection: addr, headers: headers })];
case 1: return [2 /*return*/, (__assign.apply(void 0, _a.concat([(_b.reports = _c.sent(), _b)])))];
}
});
}); }))];
const fetchAddressBooks = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { account, headers } = params !== null && params !== void 0 ? params : {};
const requiredFields = ['homeUrl', 'rootUrl'];
if (!account || !typeHelpers_1.hasFields(account, requiredFields)) {
if (!account) {
throw new Error('no account for fetchAddressBooks');
}
throw new Error(`account must have ${typeHelpers_1.findMissingFieldNames(account, requiredFields)} before fetchAddressBooks`);
}
const res = yield request_1.propfind({
url: account.homeUrl,
props: [
{ name: 'displayname', namespace: consts_1.DAVNamespace.DAV },
{ name: 'getctag', namespace: consts_1.DAVNamespace.CALENDAR_SERVER },
{ name: 'resourcetype', namespace: consts_1.DAVNamespace.DAV },
{ name: 'sync-token', namespace: consts_1.DAVNamespace.DAV },
],
depth: '1',
headers,
});
}); };
return Promise.all(res
.filter((r) => { var _a, _b; return Object.keys((_b = (_a = r.props) === null || _a === void 0 ? void 0 : _a.resourcetype) !== null && _b !== void 0 ? _b : {}).includes('addressbook'); })
.map((rs) => {
var _a, _b, _c, _d, _e, _f;
const displayName = (_a = rs.props) === null || _a === void 0 ? void 0 : _a.displayname;
debug(`Found address book named ${typeof displayName === 'string' ? displayName : ''},
props: ${JSON.stringify(rs.props)}`);
return {
url: new URL((_b = rs.href) !== null && _b !== void 0 ? _b : '', (_c = account.rootUrl) !== null && _c !== void 0 ? _c : '').href,
ctag: (_d = rs.props) === null || _d === void 0 ? void 0 : _d.getctag,
displayName: typeof displayName === 'string' ? displayName : '',
resourcetype: Object.keys((_e = rs.props) === null || _e === void 0 ? void 0 : _e.resourcetype),
syncToken: (_f = rs.props) === null || _f === void 0 ? void 0 : _f.syncToken,
};
})
.map((addr) => __awaiter(void 0, void 0, void 0, function* () {
return (Object.assign(Object.assign({}, addr), { reports: yield collection_1.supportedReportSet({ collection: addr, headers }) }));
})));
});
exports.fetchAddressBooks = fetchAddressBooks;
var fetchVCards = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var addressBook, headers, objectUrls, requiredFields, vcardUrls, _a, vCardResults;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
addressBook = params.addressBook, headers = params.headers, objectUrls = params.objectUrls;
debug("Fetching vcards from " + (addressBook === null || addressBook === void 0 ? void 0 : addressBook.url));
requiredFields = ['url'];
if (!addressBook || !typeHelper_1.hasFields(addressBook, requiredFields)) {
if (!addressBook) {
throw new Error('cannot fetchVCards for undefined addressBook');
}
throw new Error("addressBook must have " + typeHelper_1.findMissingFieldNames(addressBook, requiredFields) + " before fetchVCards");
}
if (!(objectUrls !== null && objectUrls !== void 0)) return [3 /*break*/, 1];
_a = objectUrls;
return [3 /*break*/, 3];
case 1: return [4 /*yield*/, exports.addressBookQuery({
url: addressBook.url,
props: [{ name: 'getetag', namespace: consts_1.DAVNamespace.DAV }],
depth: '1',
headers: headers,
})];
case 2:
// fetch all objects of the calendar
_a = (_b.sent()).map(function (res) { var _a; return (_a = res.href) !== null && _a !== void 0 ? _a : ''; });
_b.label = 3;
case 3:
vcardUrls = (_a)
.map(function (url) { return (url.includes('http') ? url : new URL(url, addressBook.url).href); })
.map(function (url) { return new URL(url).pathname; })
.filter(function (url) { return Boolean(url === null || url === void 0 ? void 0 : url.includes('.vcf')); });
return [4 /*yield*/, exports.addressBookMultiGet({
url: addressBook.url,
props: [
{ name: 'getetag', namespace: consts_1.DAVNamespace.DAV },
{ name: 'address-data', namespace: consts_1.DAVNamespace.CARDDAV },
],
objectUrls: vcardUrls,
depth: '1',
headers: headers,
})];
case 4:
vCardResults = _b.sent();
return [2 /*return*/, vCardResults.map(function (res) {
var _a, _b, _c, _d, _e, _f;
return ({
url: new URL((_a = res.href) !== null && _a !== void 0 ? _a : '', addressBook.url).href,
etag: (_b = res.props) === null || _b === void 0 ? void 0 : _b.getetag,
data: (_e = (_d = (_c = res.props) === null || _c === void 0 ? void 0 : _c.addressData) === null || _d === void 0 ? void 0 : _d._cdata) !== null && _e !== void 0 ? _e : (_f = res.props) === null || _f === void 0 ? void 0 : _f.addressData,
});
})];
const fetchVCards = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { addressBook, headers, objectUrls } = params;
debug(`Fetching vcards from ${addressBook === null || addressBook === void 0 ? void 0 : addressBook.url}`);
const requiredFields = ['url'];
if (!addressBook || !typeHelpers_1.hasFields(addressBook, requiredFields)) {
if (!addressBook) {
throw new Error('cannot fetchVCards for undefined addressBook');
}
throw new Error(`addressBook must have ${typeHelpers_1.findMissingFieldNames(addressBook, requiredFields)} before fetchVCards`);
}
const vcardUrls = (objectUrls !== null && objectUrls !== void 0 ? objectUrls :
// fetch all objects of the calendar
(yield exports.addressBookQuery({
url: addressBook.url,
props: [{ name: 'getetag', namespace: consts_1.DAVNamespace.DAV }],
depth: '1',
headers,
})).map((res) => { var _a; return (_a = res.href) !== null && _a !== void 0 ? _a : ''; }))
.map((url) => (url.includes('http') ? url : new URL(url, addressBook.url).href))
.map((url) => new URL(url).pathname)
.filter((url) => Boolean(url === null || url === void 0 ? void 0 : url.includes('.vcf')));
const vCardResults = yield exports.addressBookMultiGet({
url: addressBook.url,
props: [
{ name: 'getetag', namespace: consts_1.DAVNamespace.DAV },
{ name: 'address-data', namespace: consts_1.DAVNamespace.CARDDAV },
],
objectUrls: vcardUrls,
depth: '1',
headers,
});
}); };
return vCardResults.map((res) => {
var _a, _b, _c, _d, _e, _f;
return ({
url: new URL((_a = res.href) !== null && _a !== void 0 ? _a : '', addressBook.url).href,
etag: (_b = res.props) === null || _b === void 0 ? void 0 : _b.getetag,
data: (_e = (_d = (_c = res.props) === null || _c === void 0 ? void 0 : _c.addressData) === null || _d === void 0 ? void 0 : _d._cdata) !== null && _e !== void 0 ? _e : (_f = res.props) === null || _f === void 0 ? void 0 : _f.addressData,
});
});
});
exports.fetchVCards = fetchVCards;
var createVCard = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var addressBook, vCardString, filename, headers;
return __generator(this, function (_a) {
addressBook = params.addressBook, vCardString = params.vCardString, filename = params.filename, headers = params.headers;
return [2 /*return*/, request_1.createObject({
url: new URL(filename, addressBook.url).href,
data: vCardString,
headers: __assign({ 'content-type': 'text/vcard; charset=utf-8' }, headers),
})];
const createVCard = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { addressBook, vCardString, filename, headers } = params;
return request_1.createObject({
url: new URL(filename, addressBook.url).href,
data: vCardString,
headers: Object.assign({ 'content-type': 'text/vcard; charset=utf-8' }, headers),
});
}); };
});
exports.createVCard = createVCard;
var updateVCard = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var vCard, headers;
return __generator(this, function (_a) {
vCard = params.vCard, headers = params.headers;
return [2 /*return*/, request_1.updateObject({
url: vCard.url,
data: vCard.data,
etag: vCard.etag,
headers: __assign({ 'content-type': 'text/vcard; charset=utf-8' }, headers),
})];
const updateVCard = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { vCard, headers } = params;
return request_1.updateObject({
url: vCard.url,
data: vCard.data,
etag: vCard.etag,
headers: Object.assign({ 'content-type': 'text/vcard; charset=utf-8' }, headers),
});
}); };
});
exports.updateVCard = updateVCard;
var deleteVCard = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var vCard, headers;
return __generator(this, function (_a) {
vCard = params.vCard, headers = params.headers;
return [2 /*return*/, request_1.deleteObject({
url: vCard.url,
etag: vCard.etag,
headers: headers,
})];
const deleteVCard = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { vCard, headers } = params;
return request_1.deleteObject({
url: vCard.url,
etag: vCard.etag,
headers,
});
}); };
});
exports.deleteVCard = deleteVCard;
//# sourceMappingURL=addressBook.js.map

@@ -7,6 +7,6 @@ import { DAVDepth, DAVFilter, DAVProp, DAVResponse } from './types/DAVTypes';

props: DAVProp[];
filters?: DAVFilter[] | undefined;
timezone?: string | undefined;
depth?: DAVDepth | undefined;
headers?: Record<string, string> | undefined;
filters?: DAVFilter[];
timezone?: string;
depth?: DAVDepth;
headers?: Record<string, string>;
}) => Promise<DAVResponse[]>;

@@ -16,7 +16,7 @@ export declare const calendarMultiGet: (params: {

props: DAVProp[];
objectUrls?: string[] | undefined;
filters?: DAVFilter[] | undefined;
timezone?: string | undefined;
objectUrls?: string[];
filters?: DAVFilter[];
timezone?: string;
depth: DAVDepth;
headers?: Record<string, string> | undefined;
headers?: Record<string, string>;
}) => Promise<DAVResponse[]>;

@@ -26,4 +26,4 @@ export declare const makeCalendar: (params: {

props: DAVProp[];
depth?: DAVDepth | undefined;
headers?: Record<string, string> | undefined;
depth?: DAVDepth;
headers?: Record<string, string>;
}) => Promise<DAVResponse[]>;

@@ -36,9 +36,9 @@ export declare const fetchCalendars: (params?: {

calendar: DAVCalendar;
objectUrls?: string[] | undefined;
filters?: DAVFilter[] | undefined;
objectUrls?: string[];
filters?: DAVFilter[];
timeRange?: {
start: string;
end: string;
} | undefined;
headers?: Record<string, string> | undefined;
};
headers?: Record<string, string>;
}) => Promise<DAVCalendarObject[]>;

@@ -49,11 +49,11 @@ export declare const createCalendarObject: (params: {

filename: string;
headers?: Record<string, string> | undefined;
headers?: Record<string, string>;
}) => Promise<Response>;
export declare const updateCalendarObject: (params: {
calendarObject: DAVCalendarObject;
headers?: Record<string, string> | undefined;
headers?: Record<string, string>;
}) => Promise<Response>;
export declare const deleteCalendarObject: (params: {
calendarObject: DAVCalendarObject;
headers?: Record<string, string> | undefined;
headers?: Record<string, string>;
}) => Promise<Response>;

@@ -60,0 +60,0 @@ /**

"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -22,34 +11,2 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -61,271 +18,225 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

/* eslint-disable no-underscore-dangle */
var debug_1 = __importDefault(require("debug"));
var collection_1 = require("./collection");
var consts_1 = require("./consts");
var request_1 = require("./request");
var requestHelpers_1 = require("./util/requestHelpers");
var typeHelper_1 = require("./util/typeHelper");
var debug = debug_1.default('tsdav:calendar');
var calendarQuery = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var url, props, filters, timezone, depth, headers;
var _a;
return __generator(this, function (_b) {
url = params.url, props = params.props, filters = params.filters, timezone = params.timezone, depth = params.depth, headers = params.headers;
return [2 /*return*/, collection_1.collectionQuery({
url: url,
body: {
'calendar-query': (_a = {
_attributes: requestHelpers_1.getDAVAttribute([
consts_1.DAVNamespace.CALDAV,
consts_1.DAVNamespace.CALENDAR_SERVER,
consts_1.DAVNamespace.CALDAV_APPLE,
consts_1.DAVNamespace.DAV,
])
},
_a[consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV] + ":prop"] = requestHelpers_1.formatProps(props),
_a.filter = requestHelpers_1.formatFilters(filters),
_a.timezone = timezone,
_a),
},
defaultNamespace: consts_1.DAVNamespace.CALDAV,
depth: depth,
headers: headers,
})];
const debug_1 = __importDefault(require("debug"));
const collection_1 = require("./collection");
const consts_1 = require("./consts");
const request_1 = require("./request");
const requestHelpers_1 = require("./util/requestHelpers");
const typeHelpers_1 = require("./util/typeHelpers");
const debug = debug_1.default('tsdav:calendar');
const calendarQuery = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { url, props, filters, timezone, depth, headers } = params;
return collection_1.collectionQuery({
url,
body: {
'calendar-query': {
_attributes: requestHelpers_1.getDAVAttribute([
consts_1.DAVNamespace.CALDAV,
consts_1.DAVNamespace.CALENDAR_SERVER,
consts_1.DAVNamespace.CALDAV_APPLE,
consts_1.DAVNamespace.DAV,
]),
[`${consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV]}:prop`]: requestHelpers_1.formatProps(props),
filter: requestHelpers_1.formatFilters(filters),
timezone,
},
},
defaultNamespace: consts_1.DAVNamespace.CALDAV,
depth,
headers,
});
}); };
});
exports.calendarQuery = calendarQuery;
var calendarMultiGet = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var url, props, objectUrls, filters, timezone, depth, headers;
var _a;
return __generator(this, function (_b) {
url = params.url, props = params.props, objectUrls = params.objectUrls, filters = params.filters, timezone = params.timezone, depth = params.depth, headers = params.headers;
return [2 /*return*/, collection_1.collectionQuery({
url: url,
body: {
'calendar-multiget': (_a = {
_attributes: requestHelpers_1.getDAVAttribute([consts_1.DAVNamespace.DAV, consts_1.DAVNamespace.CALDAV])
},
_a[consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV] + ":prop"] = requestHelpers_1.formatProps(props),
_a[consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV] + ":href"] = objectUrls,
_a.filter = requestHelpers_1.formatFilters(filters),
_a.timezone = timezone,
_a),
},
defaultNamespace: consts_1.DAVNamespace.CALDAV,
depth: depth,
headers: headers,
})];
const calendarMultiGet = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { url, props, objectUrls, filters, timezone, depth, headers } = params;
return collection_1.collectionQuery({
url,
body: {
'calendar-multiget': {
_attributes: requestHelpers_1.getDAVAttribute([consts_1.DAVNamespace.DAV, consts_1.DAVNamespace.CALDAV]),
[`${consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV]}:prop`]: requestHelpers_1.formatProps(props),
[`${consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV]}:href`]: objectUrls,
filter: requestHelpers_1.formatFilters(filters),
timezone,
},
},
defaultNamespace: consts_1.DAVNamespace.CALDAV,
depth,
headers,
});
}); };
});
exports.calendarMultiGet = calendarMultiGet;
var makeCalendar = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var url, props, depth, headers;
var _a;
return __generator(this, function (_b) {
url = params.url, props = params.props, depth = params.depth, headers = params.headers;
return [2 /*return*/, request_1.davRequest({
url: url,
init: {
method: 'MKCALENDAR',
headers: requestHelpers_1.cleanupFalsy(__assign(__assign({}, headers), { depth: depth })),
namespace: consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV],
body: (_a = {},
_a[consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.CALDAV] + ":mkcalendar"] = {
_attributes: requestHelpers_1.getDAVAttribute([consts_1.DAVNamespace.DAV, consts_1.DAVNamespace.CALDAV]),
set: {
prop: requestHelpers_1.formatProps(props),
},
},
_a),
const makeCalendar = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { url, props, depth, headers } = params;
return request_1.davRequest({
url,
init: {
method: 'MKCALENDAR',
headers: requestHelpers_1.cleanupFalsy(Object.assign(Object.assign({}, headers), { depth })),
namespace: consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV],
body: {
[`${consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.CALDAV]}:mkcalendar`]: {
_attributes: requestHelpers_1.getDAVAttribute([consts_1.DAVNamespace.DAV, consts_1.DAVNamespace.CALDAV]),
set: {
prop: requestHelpers_1.formatProps(props),
},
},
})];
},
},
});
}); };
});
exports.makeCalendar = makeCalendar;
var fetchCalendars = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var _a, headers, account, requiredFields, res;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = params !== null && params !== void 0 ? params : {}, headers = _a.headers, account = _a.account;
requiredFields = ['homeUrl', 'rootUrl'];
if (!account || !typeHelper_1.hasFields(account, requiredFields)) {
if (!account) {
throw new Error('no account for fetchCalendars');
}
throw new Error("account must have " + typeHelper_1.findMissingFieldNames(account, requiredFields) + " before fetchCalendars");
}
return [4 /*yield*/, request_1.propfind({
url: account.homeUrl,
props: [
{ name: 'calendar-description', namespace: consts_1.DAVNamespace.CALDAV },
{ name: 'calendar-timezone', namespace: consts_1.DAVNamespace.CALDAV },
{ name: 'displayname', namespace: consts_1.DAVNamespace.DAV },
{ name: 'getctag', namespace: consts_1.DAVNamespace.CALENDAR_SERVER },
{ name: 'resourcetype', namespace: consts_1.DAVNamespace.DAV },
{ name: 'supported-calendar-component-set', namespace: consts_1.DAVNamespace.CALDAV },
{ name: 'sync-token', namespace: consts_1.DAVNamespace.DAV },
],
depth: '1',
headers: headers,
})];
case 1:
res = _b.sent();
return [2 /*return*/, Promise.all(res
.filter(function (r) { var _a, _b; return Object.keys((_b = (_a = r.props) === null || _a === void 0 ? void 0 : _a.resourcetype) !== null && _b !== void 0 ? _b : {}).includes('calendar'); })
.filter(function (rc) {
var _a, _b, _c;
// filter out none iCal format calendars.
var components = Array.isArray((_a = rc.props) === null || _a === void 0 ? void 0 : _a.supportedCalendarComponentSet.comp)
? (_b = rc.props) === null || _b === void 0 ? void 0 : _b.supportedCalendarComponentSet.comp.map(function (sc) { return sc._attributes.name; })
: [(_c = rc.props) === null || _c === void 0 ? void 0 : _c.supportedCalendarComponentSet.comp._attributes.name] || [];
return components.some(function (c) { return Object.values(consts_1.ICALObjects).includes(c); });
})
.map(function (rs) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
// debug(`Found calendar ${rs.props?.displayname}`);
var description = (_a = rs.props) === null || _a === void 0 ? void 0 : _a.calendarDescription;
var timezone = (_b = rs.props) === null || _b === void 0 ? void 0 : _b.calendarTimezon;
return {
description: typeof description === 'string' ? description : '',
timezone: typeof timezone === 'string' ? timezone : '',
url: new URL((_c = rs.href) !== null && _c !== void 0 ? _c : '', (_d = account.rootUrl) !== null && _d !== void 0 ? _d : '').href,
ctag: (_e = rs.props) === null || _e === void 0 ? void 0 : _e.getctag,
displayName: (_f = rs.props) === null || _f === void 0 ? void 0 : _f.displayname,
components: Array.isArray((_g = rs.props) === null || _g === void 0 ? void 0 : _g.supportedCalendarComponentSet.comp)
? (_h = rs.props) === null || _h === void 0 ? void 0 : _h.supportedCalendarComponentSet.comp.map(function (sc) { return sc._attributes.name; })
: [(_j = rs.props) === null || _j === void 0 ? void 0 : _j.supportedCalendarComponentSet.comp._attributes.name],
resourcetype: Object.keys((_k = rs.props) === null || _k === void 0 ? void 0 : _k.resourcetype),
syncToken: (_l = rs.props) === null || _l === void 0 ? void 0 : _l.syncToken,
};
})
.map(function (cal) { return __awaiter(void 0, void 0, void 0, function () {
var _a;
var _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_a = [__assign({}, cal)];
_b = {};
return [4 /*yield*/, collection_1.supportedReportSet({ collection: cal, headers: headers })];
case 1: return [2 /*return*/, (__assign.apply(void 0, _a.concat([(_b.reports = _c.sent(), _b)])))];
}
});
}); }))];
const fetchCalendars = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { headers, account } = params !== null && params !== void 0 ? params : {};
const requiredFields = ['homeUrl', 'rootUrl'];
if (!account || !typeHelpers_1.hasFields(account, requiredFields)) {
if (!account) {
throw new Error('no account for fetchCalendars');
}
throw new Error(`account must have ${typeHelpers_1.findMissingFieldNames(account, requiredFields)} before fetchCalendars`);
}
const res = yield request_1.propfind({
url: account.homeUrl,
props: [
{ name: 'calendar-description', namespace: consts_1.DAVNamespace.CALDAV },
{ name: 'calendar-timezone', namespace: consts_1.DAVNamespace.CALDAV },
{ name: 'displayname', namespace: consts_1.DAVNamespace.DAV },
{ name: 'getctag', namespace: consts_1.DAVNamespace.CALENDAR_SERVER },
{ name: 'resourcetype', namespace: consts_1.DAVNamespace.DAV },
{ name: 'supported-calendar-component-set', namespace: consts_1.DAVNamespace.CALDAV },
{ name: 'sync-token', namespace: consts_1.DAVNamespace.DAV },
],
depth: '1',
headers,
});
}); };
return Promise.all(res
.filter((r) => { var _a, _b; return Object.keys((_b = (_a = r.props) === null || _a === void 0 ? void 0 : _a.resourcetype) !== null && _b !== void 0 ? _b : {}).includes('calendar'); })
.filter((rc) => {
var _a, _b, _c;
// filter out none iCal format calendars.
const components = Array.isArray((_a = rc.props) === null || _a === void 0 ? void 0 : _a.supportedCalendarComponentSet.comp)
? (_b = rc.props) === null || _b === void 0 ? void 0 : _b.supportedCalendarComponentSet.comp.map((sc) => sc._attributes.name)
: [(_c = rc.props) === null || _c === void 0 ? void 0 : _c.supportedCalendarComponentSet.comp._attributes.name] || [];
return components.some((c) => Object.values(consts_1.ICALObjects).includes(c));
})
.map((rs) => {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
// debug(`Found calendar ${rs.props?.displayname}`);
const description = (_a = rs.props) === null || _a === void 0 ? void 0 : _a.calendarDescription;
const timezone = (_b = rs.props) === null || _b === void 0 ? void 0 : _b.calendarTimezon;
return {
description: typeof description === 'string' ? description : '',
timezone: typeof timezone === 'string' ? timezone : '',
url: new URL((_c = rs.href) !== null && _c !== void 0 ? _c : '', (_d = account.rootUrl) !== null && _d !== void 0 ? _d : '').href,
ctag: (_e = rs.props) === null || _e === void 0 ? void 0 : _e.getctag,
displayName: (_f = rs.props) === null || _f === void 0 ? void 0 : _f.displayname,
components: Array.isArray((_g = rs.props) === null || _g === void 0 ? void 0 : _g.supportedCalendarComponentSet.comp)
? (_h = rs.props) === null || _h === void 0 ? void 0 : _h.supportedCalendarComponentSet.comp.map((sc) => sc._attributes.name)
: [(_j = rs.props) === null || _j === void 0 ? void 0 : _j.supportedCalendarComponentSet.comp._attributes.name],
resourcetype: Object.keys((_k = rs.props) === null || _k === void 0 ? void 0 : _k.resourcetype),
syncToken: (_l = rs.props) === null || _l === void 0 ? void 0 : _l.syncToken,
};
})
.map((cal) => __awaiter(void 0, void 0, void 0, function* () {
return (Object.assign(Object.assign({}, cal), { reports: yield collection_1.supportedReportSet({ collection: cal, headers }) }));
})));
});
exports.fetchCalendars = fetchCalendars;
var fetchCalendarObjects = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var calendar, objectUrls, defaultFilters, timeRange, headers, requiredFields, filters, calendarObjectUrls, _a, calendarObjectResults;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
calendar = params.calendar, objectUrls = params.objectUrls, defaultFilters = params.filters, timeRange = params.timeRange, headers = params.headers;
debug("Fetching calendar objects from " + (calendar === null || calendar === void 0 ? void 0 : calendar.url));
requiredFields = ['url'];
if (!calendar || !typeHelper_1.hasFields(calendar, requiredFields)) {
if (!calendar) {
throw new Error('cannot fetchCalendarObjects for undefined calendar');
}
throw new Error("calendar must have " + typeHelper_1.findMissingFieldNames(calendar, requiredFields) + " before fetchCalendarObjects");
}
filters = defaultFilters !== null && defaultFilters !== void 0 ? defaultFilters : [
{
type: 'comp-filter',
attributes: { name: 'VCALENDAR' },
children: [
const fetchCalendarObjects = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { calendar, objectUrls, filters: defaultFilters, timeRange, headers } = params;
if (timeRange) {
// validate timeRange
const ISO_8601 = /^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i;
const ISO_8601_FULL = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;
if ((!ISO_8601.test(timeRange.start) || !ISO_8601.test(timeRange.end)) &&
(!ISO_8601_FULL.test(timeRange.start) || !ISO_8601_FULL.test(timeRange.end))) {
throw new Error('invalid timeRange format, not in ISO8601');
}
}
debug(`Fetching calendar objects from ${calendar === null || calendar === void 0 ? void 0 : calendar.url}`);
const requiredFields = ['url'];
if (!calendar || !typeHelpers_1.hasFields(calendar, requiredFields)) {
if (!calendar) {
throw new Error('cannot fetchCalendarObjects for undefined calendar');
}
throw new Error(`calendar must have ${typeHelpers_1.findMissingFieldNames(calendar, requiredFields)} before fetchCalendarObjects`);
}
// default to fetch all
const filters = defaultFilters !== null && defaultFilters !== void 0 ? defaultFilters : [
{
type: 'comp-filter',
attributes: { name: 'VCALENDAR' },
children: [
{
type: 'comp-filter',
attributes: { name: 'VEVENT' },
children: timeRange
? [
{
type: 'comp-filter',
attributes: { name: 'VEVENT' },
children: timeRange
? [
{
type: 'time-range',
attributes: {
start: timeRange === null || timeRange === void 0 ? void 0 : timeRange.start.replace(/[-:.]/g, ''),
end: timeRange === null || timeRange === void 0 ? void 0 : timeRange.end.replace(/[-:.]/g, ''),
},
},
]
: undefined,
type: 'time-range',
attributes: {
start: new Date(timeRange.start).toISOString().replace(/[-:.]/g, ''),
end: new Date(timeRange.end).toISOString().replace(/[-:.]/g, ''),
},
},
],
},
];
if (!(objectUrls !== null && objectUrls !== void 0)) return [3 /*break*/, 1];
_a = objectUrls;
return [3 /*break*/, 3];
case 1: return [4 /*yield*/, exports.calendarQuery({
url: calendar.url,
props: [{ name: 'getetag', namespace: consts_1.DAVNamespace.DAV }],
filters: filters,
depth: '1',
headers: headers,
})];
case 2:
// fetch all objects of the calendar
_a = (_b.sent()).map(function (res) { var _a; return (_a = res.href) !== null && _a !== void 0 ? _a : ''; });
_b.label = 3;
case 3:
calendarObjectUrls = (_a)
.map(function (url) { return (url.startsWith('http') ? url : new URL(url, calendar.url).href); }) // patch up to full url if url is not full
.map(function (url) { return new URL(url).pathname; }) // obtain pathname of the url
.filter(function (url) { return Boolean(url === null || url === void 0 ? void 0 : url.includes('.ics')); });
return [4 /*yield*/, exports.calendarMultiGet({
url: calendar.url,
props: [
{ name: 'getetag', namespace: consts_1.DAVNamespace.DAV },
{ name: 'calendar-data', namespace: consts_1.DAVNamespace.CALDAV },
],
objectUrls: calendarObjectUrls,
depth: '1',
headers: headers,
})];
case 4:
calendarObjectResults = _b.sent();
return [2 /*return*/, calendarObjectResults.map(function (res) {
var _a, _b, _c, _d, _e, _f;
return ({
url: new URL((_a = res.href) !== null && _a !== void 0 ? _a : '', calendar.url).href,
etag: (_b = res.props) === null || _b === void 0 ? void 0 : _b.getetag,
data: (_e = (_d = (_c = res.props) === null || _c === void 0 ? void 0 : _c.calendarData) === null || _d === void 0 ? void 0 : _d._cdata) !== null && _e !== void 0 ? _e : (_f = res.props) === null || _f === void 0 ? void 0 : _f.calendarData,
});
})];
}
]
: undefined,
},
],
},
];
const calendarObjectUrls = (objectUrls !== null && objectUrls !== void 0 ? objectUrls :
// fetch all objects of the calendar
(yield exports.calendarQuery({
url: calendar.url,
props: [{ name: 'getetag', namespace: consts_1.DAVNamespace.DAV }],
filters,
depth: '1',
headers,
})).map((res) => { var _a; return (_a = res.href) !== null && _a !== void 0 ? _a : ''; }))
.map((url) => (url.startsWith('http') ? url : new URL(url, calendar.url).href)) // patch up to full url if url is not full
.map((url) => new URL(url).pathname) // obtain pathname of the url
.filter((url) => Boolean(url === null || url === void 0 ? void 0 : url.includes('.ics'))); // filter out non ics calendar objects since apple calendar might have those
const calendarObjectResults = yield exports.calendarMultiGet({
url: calendar.url,
props: [
{ name: 'getetag', namespace: consts_1.DAVNamespace.DAV },
{ name: 'calendar-data', namespace: consts_1.DAVNamespace.CALDAV },
],
objectUrls: calendarObjectUrls,
depth: '1',
headers,
});
}); };
return calendarObjectResults.map((res) => {
var _a, _b, _c, _d, _e, _f;
return ({
url: new URL((_a = res.href) !== null && _a !== void 0 ? _a : '', calendar.url).href,
etag: (_b = res.props) === null || _b === void 0 ? void 0 : _b.getetag,
data: (_e = (_d = (_c = res.props) === null || _c === void 0 ? void 0 : _c.calendarData) === null || _d === void 0 ? void 0 : _d._cdata) !== null && _e !== void 0 ? _e : (_f = res.props) === null || _f === void 0 ? void 0 : _f.calendarData,
});
});
});
exports.fetchCalendarObjects = fetchCalendarObjects;
var createCalendarObject = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var calendar, iCalString, filename, headers;
return __generator(this, function (_a) {
calendar = params.calendar, iCalString = params.iCalString, filename = params.filename, headers = params.headers;
return [2 /*return*/, request_1.createObject({
url: new URL(filename, calendar.url).href,
data: iCalString,
headers: __assign({ 'content-type': 'text/calendar; charset=utf-8' }, headers),
})];
const createCalendarObject = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { calendar, iCalString, filename, headers } = params;
return request_1.createObject({
url: new URL(filename, calendar.url).href,
data: iCalString,
headers: Object.assign({ 'content-type': 'text/calendar; charset=utf-8' }, headers),
});
}); };
});
exports.createCalendarObject = createCalendarObject;
var updateCalendarObject = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var calendarObject, headers;
return __generator(this, function (_a) {
calendarObject = params.calendarObject, headers = params.headers;
return [2 /*return*/, request_1.updateObject({
url: calendarObject.url,
data: calendarObject.data,
etag: calendarObject.etag,
headers: __assign({ 'content-type': 'text/calendar; charset=utf-8' }, headers),
})];
const updateCalendarObject = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { calendarObject, headers } = params;
return request_1.updateObject({
url: calendarObject.url,
data: calendarObject.data,
etag: calendarObject.etag,
headers: Object.assign({ 'content-type': 'text/calendar; charset=utf-8' }, headers),
});
}); };
});
exports.updateCalendarObject = updateCalendarObject;
var deleteCalendarObject = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var calendarObject, headers;
return __generator(this, function (_a) {
calendarObject = params.calendarObject, headers = params.headers;
return [2 /*return*/, request_1.deleteObject({ url: calendarObject.url, etag: calendarObject.etag, headers: headers })];
});
}); };
const deleteCalendarObject = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { calendarObject, headers } = params;
return request_1.deleteObject({ url: calendarObject.url, etag: calendarObject.etag, headers });
});
exports.deleteCalendarObject = deleteCalendarObject;

@@ -335,70 +246,48 @@ /**

*/
var syncCalendars = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var oldCalendars, account, detailedResult, headers, localCalendars, remoteCalendars, created, updated, updatedWithObjects, deleted, unchanged;
const syncCalendars = (params) => __awaiter(void 0, void 0, void 0, function* () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
oldCalendars = params.oldCalendars, account = params.account, detailedResult = params.detailedResult, headers = params.headers;
if (!account) {
throw new Error('Must have account before syncCalendars');
}
localCalendars = (_a = oldCalendars !== null && oldCalendars !== void 0 ? oldCalendars : account.calendars) !== null && _a !== void 0 ? _a : [];
return [4 /*yield*/, exports.fetchCalendars({ account: account, headers: headers })];
case 1:
remoteCalendars = _b.sent();
created = remoteCalendars.filter(function (rc) {
return localCalendars.every(function (lc) { return !requestHelpers_1.urlContains(lc.url, rc.url); });
});
debug("new calendars: " + created.map(function (cc) { return cc.displayName; }));
updated = localCalendars.reduce(function (prev, curr) {
var found = remoteCalendars.find(function (rc) { return requestHelpers_1.urlContains(rc.url, curr.url); });
if (found &&
((found.syncToken && found.syncToken !== curr.syncToken) ||
(found.ctag && found.ctag !== curr.ctag))) {
return __spreadArray(__spreadArray([], prev), [found]);
}
return prev;
}, []);
debug("updated calendars: " + updated.map(function (cc) { return cc.displayName; }));
return [4 /*yield*/, Promise.all(updated.map(function (u) { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, collection_1.smartCollectionSync({
collection: __assign(__assign({}, u), { objectMultiGet: exports.calendarMultiGet }),
method: 'webdav',
headers: headers,
account: account,
})];
case 1:
result = _a.sent();
return [2 /*return*/, result];
}
});
}); }))];
case 2:
updatedWithObjects = _b.sent();
deleted = localCalendars.filter(function (cal) {
return remoteCalendars.every(function (rc) { return !requestHelpers_1.urlContains(rc.url, cal.url); });
});
debug("deleted calendars: " + deleted.map(function (cc) { return cc.displayName; }));
unchanged = localCalendars.filter(function (cal) {
return remoteCalendars.some(function (rc) {
return requestHelpers_1.urlContains(rc.url, cal.url) &&
((rc.syncToken && rc.syncToken !== cal.syncToken) || (rc.ctag && rc.ctag !== cal.ctag));
});
});
// debug(`unchanged calendars: ${unchanged.map((cc) => cc.displayName)}`);
return [2 /*return*/, detailedResult
? {
created: created,
updated: updated,
deleted: deleted,
}
: __spreadArray(__spreadArray(__spreadArray([], unchanged), created), updatedWithObjects)];
const { oldCalendars, account, detailedResult, headers } = params;
if (!account) {
throw new Error('Must have account before syncCalendars');
}
const localCalendars = (_a = oldCalendars !== null && oldCalendars !== void 0 ? oldCalendars : account.calendars) !== null && _a !== void 0 ? _a : [];
const remoteCalendars = yield exports.fetchCalendars({ account, headers });
// no existing url
const created = remoteCalendars.filter((rc) => localCalendars.every((lc) => !requestHelpers_1.urlContains(lc.url, rc.url)));
debug(`new calendars: ${created.map((cc) => cc.displayName)}`);
// have same url, but syncToken/ctag different
const updated = localCalendars.reduce((prev, curr) => {
const found = remoteCalendars.find((rc) => requestHelpers_1.urlContains(rc.url, curr.url));
if (found &&
((found.syncToken && found.syncToken !== curr.syncToken) ||
(found.ctag && found.ctag !== curr.ctag))) {
return [...prev, found];
}
});
}); };
return prev;
}, []);
debug(`updated calendars: ${updated.map((cc) => cc.displayName)}`);
const updatedWithObjects = yield Promise.all(updated.map((u) => __awaiter(void 0, void 0, void 0, function* () {
const result = yield collection_1.smartCollectionSync({
collection: Object.assign(Object.assign({}, u), { objectMultiGet: exports.calendarMultiGet }),
method: 'webdav',
headers,
account,
});
return result;
})));
// does not present in remote
const deleted = localCalendars.filter((cal) => remoteCalendars.every((rc) => !requestHelpers_1.urlContains(rc.url, cal.url)));
debug(`deleted calendars: ${deleted.map((cc) => cc.displayName)}`);
const unchanged = localCalendars.filter((cal) => remoteCalendars.some((rc) => requestHelpers_1.urlContains(rc.url, cal.url) &&
((rc.syncToken && rc.syncToken !== cal.syncToken) || (rc.ctag && rc.ctag !== cal.ctag))));
// debug(`unchanged calendars: ${unchanged.map((cc) => cc.displayName)}`);
return detailedResult
? {
created,
updated,
deleted,
}
: [...unchanged, ...created, ...updatedWithObjects];
});
exports.syncCalendars = syncCalendars;
//# sourceMappingURL=calendar.js.map

@@ -0,9 +1,13 @@

import { addressBookMultiGet as rawAddressBookMultiGet, addressBookQuery as rawAddressBookQuery, createVCard as rawCreateVCard, deleteVCard as rawDeleteVCard, fetchAddressBooks as rawFetchAddressBooks, fetchVCards as rawFetchVCards, updateVCard as rawUpdateVCard } from './addressBook';
import { calendarMultiGet as rawCalendarMultiGet, calendarQuery as rawCalendarQuery, createCalendarObject as rawCreateCalendarObject, deleteCalendarObject as rawDeleteCalendarObject, fetchCalendarObjects as rawFetchCalendarObjects, fetchCalendars as rawFetchCalendars, makeCalendar as rawMakeCalendar, updateCalendarObject as rawUpdateCalendarObject } from './calendar';
import { collectionQuery as rawCollectionQuery, isCollectionDirty as rawIsCollectionDirty, makeCollection as rawMakeCollection, supportedReportSet as rawSupportedReportSet, syncCollection as rawSyncCollection } from './collection';
import { createObject as rawCreateObject, deleteObject as rawDeleteObject, propfind as rawPropfind, updateObject as rawUpdateObject } from './request';
import { DAVRequest, DAVResponse } from './types/DAVTypes';
import { SmartCollectionSync, SyncCalendars } from './types/functionsOverloads';
import { DAVAccount, DAVCredentials } from './types/models';
import { Await, Optional } from './util/typeHelper';
import { DAVAccount, DAVAddressBook, DAVCalendar, DAVCalendarObject, DAVCredentials, DAVVCard } from './types/models';
import { Optional } from './util/typeHelpers';
export declare const createDAVClient: (params: {
serverUrl: string;
credentials: DAVCredentials;
authMethod?: "Basic" | "Oauth" | undefined;
authMethod?: 'Basic' | 'Oauth';
defaultAccountType?: DAVAccount['accountType'] | undefined;

@@ -14,4 +18,4 @@ }) => Promise<{

init: DAVRequest;
convertIncoming?: boolean | undefined;
parseOutgoing?: boolean | undefined;
convertIncoming?: boolean;
parseOutgoing?: boolean;
}) => Promise<DAVResponse[]>;

@@ -26,5 +30,5 @@ propfind: (params: {

account: Optional<DAVAccount, 'serverUrl'>;
headers?: Record<string, string> | undefined;
loadCollections?: boolean | undefined;
loadObjects?: boolean | undefined;
headers?: Record<string, string>;
loadCollections?: boolean;
loadObjects?: boolean;
}) => Promise<DAVAccount>;

@@ -111,5 +115,5 @@ createObject: (params: {

headers?: Record<string, string> | undefined;
} | undefined) => Promise<import("./types/models").DAVCalendar[]>;
} | undefined) => Promise<DAVCalendar[]>;
fetchCalendarObjects: (params: {
calendar: import("./types/models").DAVCalendar;
calendar: DAVCalendar;
objectUrls?: string[] | undefined;

@@ -124,3 +128,3 @@ filters?: import("./types/DAVTypes").DAVFilter[] | undefined;

createCalendarObject: (params: {
calendar: import("./types/models").DAVCalendar;
calendar: DAVCalendar;
iCalString: string;

@@ -171,2 +175,57 @@ filename: string;

}>;
export declare type DAVClient = Await<ReturnType<typeof createDAVClient>>;
export declare class DAVClient {
serverUrl: string;
credentials: DAVCredentials;
authMethod: 'Basic' | 'Oauth';
accountType: DAVAccount['accountType'];
authHeaders?: Record<string, string>;
account?: DAVAccount;
constructor(params: {
serverUrl: string;
credentials: DAVCredentials;
authMethod?: 'Basic' | 'Oauth';
defaultAccountType?: DAVAccount['accountType'] | undefined;
});
login(): Promise<void>;
davRequest(params0: {
url: string;
init: DAVRequest;
convertIncoming?: boolean;
parseOutgoing?: boolean;
}): Promise<DAVResponse[]>;
createObject(params: Parameters<typeof rawCreateObject>): Promise<Response>;
updateObject(params: Parameters<typeof rawUpdateObject>): Promise<Response>;
deleteObject(params: Parameters<typeof rawDeleteObject>): Promise<Response>;
propfind(params: Parameters<typeof rawPropfind>): Promise<DAVResponse[]>;
createAccount(params0: {
account: Optional<DAVAccount, 'serverUrl'>;
headers?: Record<string, string>;
loadCollections?: boolean;
loadObjects?: boolean;
}): Promise<DAVAccount>;
collectionQuery(params: Parameters<typeof rawCollectionQuery>): Promise<DAVResponse[]>;
makeCollection(params: Parameters<typeof rawMakeCollection>): Promise<DAVResponse[]>;
syncCollection(params: Parameters<typeof rawSyncCollection>): Promise<DAVResponse[]>;
supportedReportSet(params: Parameters<typeof rawSupportedReportSet>): Promise<string[]>;
isCollectionDirty(params: Parameters<typeof rawIsCollectionDirty>): Promise<{
isDirty: boolean;
newCtag: string;
}>;
smartCollectionSync(params: Parameters<SmartCollectionSync>): ReturnType<SmartCollectionSync>;
calendarQuery(params: Parameters<typeof rawCalendarQuery>): Promise<DAVResponse[]>;
makeCalendar(params: Parameters<typeof rawMakeCalendar>): Promise<DAVResponse[]>;
calendarMultiGet(params: Parameters<typeof rawCalendarMultiGet>): Promise<DAVResponse[]>;
fetchCalendars(params?: Parameters<typeof rawFetchCalendars>): Promise<DAVCalendar[]>;
fetchCalendarObjects(params: Parameters<typeof rawFetchCalendarObjects>): Promise<DAVCalendarObject[]>;
createCalendarObject(params: Parameters<typeof rawCreateCalendarObject>): Promise<Response>;
updateCalendarObject(params: Parameters<typeof rawUpdateCalendarObject>): Promise<Response>;
deleteCalendarObject(params: Parameters<typeof rawDeleteCalendarObject>): Promise<Response>;
syncCalendars(params: Parameters<SyncCalendars>): Promise<ReturnType<SyncCalendars>>;
addressBookQuery(params: Parameters<typeof rawAddressBookQuery>): Promise<DAVResponse[]>;
addressBookMultiGet(params: Parameters<typeof rawAddressBookMultiGet>): Promise<DAVResponse[]>;
fetchAddressBooks(params?: Parameters<typeof rawFetchAddressBooks>): Promise<DAVAddressBook[]>;
fetchVCards(params: Parameters<typeof rawFetchVCards>): Promise<DAVVCard[]>;
createVCard(params: Parameters<typeof rawCreateVCard>): Promise<Response>;
updateVCard(params: Parameters<typeof rawUpdateVCard>): Promise<Response>;
deleteVCard(params: Parameters<typeof rawDeleteVCard>): Promise<Response>;
}
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -22,29 +11,2 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __rest = (this && this.__rest) || function (s, e) {

@@ -62,157 +24,316 @@ var t = {};

Object.defineProperty(exports, "__esModule", { value: true });
exports.createDAVClient = void 0;
var account_1 = require("./account");
var addressBook_1 = require("./addressBook");
var calendar_1 = require("./calendar");
var collection_1 = require("./collection");
var request_1 = require("./request");
var authHelper_1 = require("./util/authHelper");
exports.DAVClient = exports.createDAVClient = void 0;
const account_1 = require("./account");
const addressBook_1 = require("./addressBook");
const calendar_1 = require("./calendar");
const collection_1 = require("./collection");
const request_1 = require("./request");
const authHelpers_1 = require("./util/authHelpers");
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
var createDAVClient = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var serverUrl, credentials, authMethod, defaultAccountType, authHeaders, _a, _b, defaultAccount, _c, davRequest, createObject, updateObject, deleteObject, propfind, createAccount, collectionQuery, makeCollection, syncCollection, supportedReportSet, isCollectionDirty, smartCollectionSync, calendarQuery, calendarMultiGet, makeCalendar, fetchCalendars, fetchCalendarObjects, createCalendarObject, updateCalendarObject, deleteCalendarObject, syncCalendars, addressBookQuery, addressBookMultiGet, fetchAddressBooks, fetchVCards, createVCard, updateVCard, deleteVCard;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
serverUrl = params.serverUrl, credentials = params.credentials, authMethod = params.authMethod, defaultAccountType = params.defaultAccountType;
if (!
// eslint-disable-next-line no-nested-ternary
(authMethod === 'Basic'))
// eslint-disable-next-line no-nested-ternary
return [3 /*break*/, 1];
_a = authHelper_1.getBasicAuthHeaders(credentials);
return [3 /*break*/, 5];
case 1:
if (!(authMethod === 'Oauth')) return [3 /*break*/, 3];
return [4 /*yield*/, authHelper_1.getOauthHeaders(credentials)];
case 2:
_b = (_d.sent()).headers;
return [3 /*break*/, 4];
case 3:
_b = {};
_d.label = 4;
case 4:
_a = _b;
_d.label = 5;
case 5:
authHeaders = _a;
if (!defaultAccountType) return [3 /*break*/, 7];
return [4 /*yield*/, account_1.createAccount({
account: { serverUrl: serverUrl, credentials: credentials, accountType: defaultAccountType },
headers: authHeaders,
})];
case 6:
_c = _d.sent();
return [3 /*break*/, 8];
case 7:
_c = undefined;
_d.label = 8;
case 8:
defaultAccount = _c;
davRequest = function (params0) { return __awaiter(void 0, void 0, void 0, function () {
var init, rest, headers, restInit;
return __generator(this, function (_a) {
init = params0.init, rest = __rest(params0, ["init"]);
headers = init.headers, restInit = __rest(init, ["headers"]);
return [2 /*return*/, request_1.davRequest(__assign(__assign({}, rest), { init: __assign(__assign({}, restInit), { headers: __assign(__assign({}, authHeaders), headers) }) }))];
});
}); };
createObject = authHelper_1.defaultParam(request_1.createObject, {
url: serverUrl,
headers: authHeaders,
});
updateObject = authHelper_1.defaultParam(request_1.updateObject, { headers: authHeaders, url: serverUrl });
deleteObject = authHelper_1.defaultParam(request_1.deleteObject, { headers: authHeaders, url: serverUrl });
propfind = authHelper_1.defaultParam(request_1.propfind, { headers: authHeaders });
createAccount = function (params0) { return __awaiter(void 0, void 0, void 0, function () {
var account, headers, loadCollections, loadObjects;
return __generator(this, function (_a) {
account = params0.account, headers = params0.headers, loadCollections = params0.loadCollections, loadObjects = params0.loadObjects;
return [2 /*return*/, account_1.createAccount({
account: __assign({ serverUrl: serverUrl, credentials: credentials }, account),
headers: __assign(__assign({}, authHeaders), headers),
loadCollections: loadCollections,
loadObjects: loadObjects,
})];
});
}); };
collectionQuery = authHelper_1.defaultParam(collection_1.collectionQuery, { headers: authHeaders });
makeCollection = authHelper_1.defaultParam(collection_1.makeCollection, { headers: authHeaders });
syncCollection = authHelper_1.defaultParam(collection_1.syncCollection, { headers: authHeaders });
supportedReportSet = authHelper_1.defaultParam(collection_1.supportedReportSet, {
headers: authHeaders,
});
isCollectionDirty = authHelper_1.defaultParam(collection_1.isCollectionDirty, {
headers: authHeaders,
});
smartCollectionSync = authHelper_1.defaultParam(collection_1.smartCollectionSync, {
headers: authHeaders,
account: defaultAccount,
});
calendarQuery = authHelper_1.defaultParam(calendar_1.calendarQuery, { headers: authHeaders });
calendarMultiGet = authHelper_1.defaultParam(calendar_1.calendarMultiGet, { headers: authHeaders });
makeCalendar = authHelper_1.defaultParam(calendar_1.makeCalendar, { headers: authHeaders });
fetchCalendars = authHelper_1.defaultParam(calendar_1.fetchCalendars, {
headers: authHeaders,
account: defaultAccount,
});
fetchCalendarObjects = authHelper_1.defaultParam(calendar_1.fetchCalendarObjects, {
headers: authHeaders,
});
createCalendarObject = authHelper_1.defaultParam(calendar_1.createCalendarObject, {
headers: authHeaders,
});
updateCalendarObject = authHelper_1.defaultParam(calendar_1.updateCalendarObject, {
headers: authHeaders,
});
deleteCalendarObject = authHelper_1.defaultParam(calendar_1.deleteCalendarObject, {
headers: authHeaders,
});
syncCalendars = authHelper_1.defaultParam(calendar_1.syncCalendars, {
account: defaultAccount,
headers: authHeaders,
});
addressBookQuery = authHelper_1.defaultParam(addressBook_1.addressBookQuery, { headers: authHeaders });
addressBookMultiGet = authHelper_1.defaultParam(addressBook_1.addressBookMultiGet, { headers: authHeaders });
fetchAddressBooks = authHelper_1.defaultParam(addressBook_1.fetchAddressBooks, {
account: defaultAccount,
headers: authHeaders,
});
fetchVCards = authHelper_1.defaultParam(addressBook_1.fetchVCards, { headers: authHeaders });
createVCard = authHelper_1.defaultParam(addressBook_1.createVCard, { headers: authHeaders });
updateVCard = authHelper_1.defaultParam(addressBook_1.updateVCard, { headers: authHeaders });
deleteVCard = authHelper_1.defaultParam(addressBook_1.deleteVCard, { headers: authHeaders });
return [2 /*return*/, {
davRequest: davRequest,
propfind: propfind,
createAccount: createAccount,
createObject: createObject,
updateObject: updateObject,
deleteObject: deleteObject,
calendarQuery: calendarQuery,
addressBookQuery: addressBookQuery,
collectionQuery: collectionQuery,
makeCollection: makeCollection,
calendarMultiGet: calendarMultiGet,
makeCalendar: makeCalendar,
syncCollection: syncCollection,
supportedReportSet: supportedReportSet,
isCollectionDirty: isCollectionDirty,
smartCollectionSync: smartCollectionSync,
fetchCalendars: fetchCalendars,
fetchCalendarObjects: fetchCalendarObjects,
createCalendarObject: createCalendarObject,
updateCalendarObject: updateCalendarObject,
deleteCalendarObject: deleteCalendarObject,
syncCalendars: syncCalendars,
fetchAddressBooks: fetchAddressBooks,
addressBookMultiGet: addressBookMultiGet,
fetchVCards: fetchVCards,
createVCard: createVCard,
updateVCard: updateVCard,
deleteVCard: deleteVCard,
}];
}
const createDAVClient = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { serverUrl, credentials, authMethod, defaultAccountType } = params;
const authHeaders =
// eslint-disable-next-line no-nested-ternary
authMethod === 'Basic'
? authHelpers_1.getBasicAuthHeaders(credentials)
: authMethod === 'Oauth'
? (yield authHelpers_1.getOauthHeaders(credentials)).headers
: {};
const defaultAccount = defaultAccountType
? yield account_1.createAccount({
account: { serverUrl, credentials, accountType: defaultAccountType },
headers: authHeaders,
})
: undefined;
const davRequest = (params0) => __awaiter(void 0, void 0, void 0, function* () {
const { init } = params0, rest = __rest(params0, ["init"]);
const { headers } = init, restInit = __rest(init, ["headers"]);
return request_1.davRequest(Object.assign(Object.assign({}, rest), { init: Object.assign(Object.assign({}, restInit), { headers: Object.assign(Object.assign({}, authHeaders), headers) }) }));
});
}); };
const createObject = authHelpers_1.defaultParam(request_1.createObject, {
url: serverUrl,
headers: authHeaders,
});
const updateObject = authHelpers_1.defaultParam(request_1.updateObject, { headers: authHeaders, url: serverUrl });
const deleteObject = authHelpers_1.defaultParam(request_1.deleteObject, { headers: authHeaders, url: serverUrl });
const propfind = authHelpers_1.defaultParam(request_1.propfind, { headers: authHeaders });
// account
const createAccount = (params0) => __awaiter(void 0, void 0, void 0, function* () {
const { account, headers, loadCollections, loadObjects } = params0;
return account_1.createAccount({
account: Object.assign({ serverUrl, credentials }, account),
headers: Object.assign(Object.assign({}, authHeaders), headers),
loadCollections,
loadObjects,
});
});
// collection
const collectionQuery = authHelpers_1.defaultParam(collection_1.collectionQuery, { headers: authHeaders });
const makeCollection = authHelpers_1.defaultParam(collection_1.makeCollection, { headers: authHeaders });
const syncCollection = authHelpers_1.defaultParam(collection_1.syncCollection, { headers: authHeaders });
const supportedReportSet = authHelpers_1.defaultParam(collection_1.supportedReportSet, {
headers: authHeaders,
});
const isCollectionDirty = authHelpers_1.defaultParam(collection_1.isCollectionDirty, {
headers: authHeaders,
});
const smartCollectionSync = authHelpers_1.defaultParam(collection_1.smartCollectionSync, {
headers: authHeaders,
account: defaultAccount,
});
// calendar
const calendarQuery = authHelpers_1.defaultParam(calendar_1.calendarQuery, { headers: authHeaders });
const calendarMultiGet = authHelpers_1.defaultParam(calendar_1.calendarMultiGet, { headers: authHeaders });
const makeCalendar = authHelpers_1.defaultParam(calendar_1.makeCalendar, { headers: authHeaders });
const fetchCalendars = authHelpers_1.defaultParam(calendar_1.fetchCalendars, {
headers: authHeaders,
account: defaultAccount,
});
const fetchCalendarObjects = authHelpers_1.defaultParam(calendar_1.fetchCalendarObjects, {
headers: authHeaders,
});
const createCalendarObject = authHelpers_1.defaultParam(calendar_1.createCalendarObject, {
headers: authHeaders,
});
const updateCalendarObject = authHelpers_1.defaultParam(calendar_1.updateCalendarObject, {
headers: authHeaders,
});
const deleteCalendarObject = authHelpers_1.defaultParam(calendar_1.deleteCalendarObject, {
headers: authHeaders,
});
const syncCalendars = authHelpers_1.defaultParam(calendar_1.syncCalendars, {
account: defaultAccount,
headers: authHeaders,
});
// addressBook
const addressBookQuery = authHelpers_1.defaultParam(addressBook_1.addressBookQuery, { headers: authHeaders });
const addressBookMultiGet = authHelpers_1.defaultParam(addressBook_1.addressBookMultiGet, { headers: authHeaders });
const fetchAddressBooks = authHelpers_1.defaultParam(addressBook_1.fetchAddressBooks, {
account: defaultAccount,
headers: authHeaders,
});
const fetchVCards = authHelpers_1.defaultParam(addressBook_1.fetchVCards, { headers: authHeaders });
const createVCard = authHelpers_1.defaultParam(addressBook_1.createVCard, { headers: authHeaders });
const updateVCard = authHelpers_1.defaultParam(addressBook_1.updateVCard, { headers: authHeaders });
const deleteVCard = authHelpers_1.defaultParam(addressBook_1.deleteVCard, { headers: authHeaders });
return {
davRequest,
propfind,
createAccount,
createObject,
updateObject,
deleteObject,
calendarQuery,
addressBookQuery,
collectionQuery,
makeCollection,
calendarMultiGet,
makeCalendar,
syncCollection,
supportedReportSet,
isCollectionDirty,
smartCollectionSync,
fetchCalendars,
fetchCalendarObjects,
createCalendarObject,
updateCalendarObject,
deleteCalendarObject,
syncCalendars,
fetchAddressBooks,
addressBookMultiGet,
fetchVCards,
createVCard,
updateVCard,
deleteVCard,
};
});
exports.createDAVClient = createDAVClient;
class DAVClient {
constructor(params) {
var _a, _b;
this.serverUrl = params.serverUrl;
this.credentials = params.credentials;
this.authMethod = (_a = params.authMethod) !== null && _a !== void 0 ? _a : 'Basic';
this.accountType = (_b = params.defaultAccountType) !== null && _b !== void 0 ? _b : 'caldav';
}
login() {
return __awaiter(this, void 0, void 0, function* () {
this.authHeaders =
// eslint-disable-next-line no-nested-ternary
this.authMethod === 'Basic'
? authHelpers_1.getBasicAuthHeaders(this.credentials)
: this.authMethod === 'Oauth'
? (yield authHelpers_1.getOauthHeaders(this.credentials)).headers
: {};
this.account = this.accountType
? yield account_1.createAccount({
account: {
serverUrl: this.serverUrl,
credentials: this.credentials,
accountType: this.accountType,
},
headers: this.authHeaders,
})
: undefined;
});
}
davRequest(params0) {
return __awaiter(this, void 0, void 0, function* () {
const { init } = params0, rest = __rest(params0, ["init"]);
const { headers } = init, restInit = __rest(init, ["headers"]);
return request_1.davRequest(Object.assign(Object.assign({}, rest), { init: Object.assign(Object.assign({}, restInit), { headers: Object.assign(Object.assign({}, this.authHeaders), headers) }) }));
});
}
createObject(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(request_1.createObject, {
url: this.serverUrl,
headers: this.authHeaders,
})(params[0]);
});
}
updateObject(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(request_1.updateObject, { headers: this.authHeaders, url: this.serverUrl })(params[0]);
});
}
deleteObject(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(request_1.deleteObject, { headers: this.authHeaders, url: this.serverUrl })(params[0]);
});
}
propfind(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(request_1.propfind, { headers: this.authHeaders })(params[0]);
});
}
createAccount(params0) {
return __awaiter(this, void 0, void 0, function* () {
const { account, headers, loadCollections, loadObjects } = params0;
return account_1.createAccount({
account: Object.assign({ serverUrl: this.serverUrl, credentials: this.credentials }, account),
headers: Object.assign(Object.assign({}, this.authHeaders), headers),
loadCollections,
loadObjects,
});
});
}
collectionQuery(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(collection_1.collectionQuery, { headers: this.authHeaders })(params[0]);
});
}
makeCollection(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(collection_1.makeCollection, { headers: this.authHeaders })(params[0]);
});
}
syncCollection(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(collection_1.syncCollection, { headers: this.authHeaders })(params[0]);
});
}
supportedReportSet(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(collection_1.supportedReportSet, { headers: this.authHeaders })(params[0]);
});
}
isCollectionDirty(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(collection_1.isCollectionDirty, { headers: this.authHeaders })(params[0]);
});
}
smartCollectionSync(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(collection_1.smartCollectionSync, {
headers: this.authHeaders,
account: this.account,
})(params[0]);
});
}
calendarQuery(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(calendar_1.calendarQuery, { headers: this.authHeaders })(params[0]);
});
}
makeCalendar(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(calendar_1.makeCalendar, { headers: this.authHeaders })(params[0]);
});
}
calendarMultiGet(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(calendar_1.calendarMultiGet, { headers: this.authHeaders })(params[0]);
});
}
fetchCalendars(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(calendar_1.fetchCalendars, { headers: this.authHeaders, account: this.account })(params === null || params === void 0 ? void 0 : params[0]);
});
}
fetchCalendarObjects(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(calendar_1.fetchCalendarObjects, { headers: this.authHeaders })(params[0]);
});
}
createCalendarObject(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(calendar_1.createCalendarObject, { headers: this.authHeaders })(params[0]);
});
}
updateCalendarObject(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(calendar_1.updateCalendarObject, { headers: this.authHeaders })(params[0]);
});
}
deleteCalendarObject(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(calendar_1.deleteCalendarObject, { headers: this.authHeaders })(params[0]);
});
}
syncCalendars(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(calendar_1.syncCalendars, {
headers: this.authHeaders,
account: this.account,
})(params[0]);
});
}
addressBookQuery(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(addressBook_1.addressBookQuery, { headers: this.authHeaders })(params[0]);
});
}
addressBookMultiGet(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(addressBook_1.addressBookMultiGet, { headers: this.authHeaders })(params[0]);
});
}
fetchAddressBooks(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(addressBook_1.fetchAddressBooks, { headers: this.authHeaders, account: this.account })(params === null || params === void 0 ? void 0 : params[0]);
});
}
fetchVCards(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(addressBook_1.fetchVCards, { headers: this.authHeaders })(params[0]);
});
}
createVCard(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(addressBook_1.createVCard, { headers: this.authHeaders })(params[0]);
});
}
updateVCard(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(addressBook_1.updateVCard, { headers: this.authHeaders })(params[0]);
});
}
deleteVCard(params) {
return __awaiter(this, void 0, void 0, function* () {
return authHelpers_1.defaultParam(addressBook_1.deleteVCard, { headers: this.authHeaders })(params[0]);
});
}
}
exports.DAVClient = DAVClient;
//# sourceMappingURL=client.js.map

@@ -8,19 +8,19 @@ import { DAVNamespace } from './consts';

body: any;
depth?: DAVDepth | undefined;
defaultNamespace?: DAVNamespace | undefined;
headers?: Record<string, string> | undefined;
depth?: DAVDepth;
defaultNamespace?: DAVNamespace;
headers?: Record<string, string>;
}) => Promise<DAVResponse[]>;
export declare const makeCollection: (params: {
url: string;
props?: DAVProp[] | undefined;
depth?: DAVDepth | undefined;
headers?: Record<string, string> | undefined;
props?: DAVProp[];
depth?: DAVDepth;
headers?: Record<string, string>;
}) => Promise<DAVResponse[]>;
export declare const supportedReportSet: (params: {
collection: DAVCollection;
headers?: Record<string, string> | undefined;
headers?: Record<string, string>;
}) => Promise<string[]>;
export declare const isCollectionDirty: (params: {
collection: DAVCollection;
headers?: Record<string, string> | undefined;
headers?: Record<string, string>;
}) => Promise<{

@@ -36,7 +36,7 @@ isDirty: boolean;

props: DAVProp[];
headers?: Record<string, string> | undefined;
syncLevel?: number | undefined;
syncToken?: string | undefined;
headers?: Record<string, string>;
syncLevel?: number;
syncToken?: string;
}) => Promise<DAVResponse[]>;
/** remote collection to local */
export declare const smartCollectionSync: SmartCollectionSync;
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -22,34 +11,2 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -61,91 +18,69 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

/* eslint-disable no-underscore-dangle */
var debug_1 = __importDefault(require("debug"));
var consts_1 = require("./consts");
var request_1 = require("./request");
var requestHelpers_1 = require("./util/requestHelpers");
var typeHelper_1 = require("./util/typeHelper");
var debug = debug_1.default('tsdav:collection');
var collectionQuery = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var url, body, depth, _a, defaultNamespace, headers;
return __generator(this, function (_b) {
url = params.url, body = params.body, depth = params.depth, _a = params.defaultNamespace, defaultNamespace = _a === void 0 ? consts_1.DAVNamespace.DAV : _a, headers = params.headers;
return [2 /*return*/, request_1.davRequest({
url: url,
init: {
method: 'REPORT',
headers: requestHelpers_1.cleanupFalsy(__assign(__assign({}, headers), { depth: depth })),
namespace: consts_1.DAVNamespaceShorthandMap[defaultNamespace],
body: body,
},
})];
const debug_1 = __importDefault(require("debug"));
const consts_1 = require("./consts");
const request_1 = require("./request");
const requestHelpers_1 = require("./util/requestHelpers");
const typeHelpers_1 = require("./util/typeHelpers");
const debug = debug_1.default('tsdav:collection');
const collectionQuery = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { url, body, depth, defaultNamespace = consts_1.DAVNamespace.DAV, headers } = params;
return request_1.davRequest({
url,
init: {
method: 'REPORT',
headers: requestHelpers_1.cleanupFalsy(Object.assign(Object.assign({}, headers), { depth })),
namespace: consts_1.DAVNamespaceShorthandMap[defaultNamespace],
body,
},
});
}); };
});
exports.collectionQuery = collectionQuery;
var makeCollection = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var url, props, depth, headers;
return __generator(this, function (_a) {
url = params.url, props = params.props, depth = params.depth, headers = params.headers;
return [2 /*return*/, request_1.davRequest({
url: url,
init: {
method: 'MKCOL',
headers: requestHelpers_1.cleanupFalsy(__assign(__assign({}, headers), { depth: depth })),
namespace: consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV],
body: props
? {
mkcol: {
set: {
prop: requestHelpers_1.formatProps(props),
},
},
}
: undefined,
},
})];
const makeCollection = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { url, props, depth, headers } = params;
return request_1.davRequest({
url,
init: {
method: 'MKCOL',
headers: requestHelpers_1.cleanupFalsy(Object.assign(Object.assign({}, headers), { depth })),
namespace: consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV],
body: props
? {
mkcol: {
set: {
prop: requestHelpers_1.formatProps(props),
},
},
}
: undefined,
},
});
}); };
});
exports.makeCollection = makeCollection;
var supportedReportSet = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var collection, headers, res;
const supportedReportSet = (params) => __awaiter(void 0, void 0, void 0, function* () {
var _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
collection = params.collection, headers = params.headers;
return [4 /*yield*/, request_1.propfind({
url: collection.url,
props: [{ name: 'supported-report-set', namespace: consts_1.DAVNamespace.DAV }],
depth: '1',
headers: headers,
})];
case 1:
res = _c.sent();
return [2 /*return*/, (_b = (_a = res[0]) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.supportedReportSet.supportedReport.map(function (sr) { return Object.keys(sr.report)[0]; })];
}
const { collection, headers } = params;
const res = yield request_1.propfind({
url: collection.url,
props: [{ name: 'supported-report-set', namespace: consts_1.DAVNamespace.DAV }],
depth: '1',
headers,
});
}); };
return (_b = (_a = res[0]) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.supportedReportSet.supportedReport.map((sr) => Object.keys(sr.report)[0]);
});
exports.supportedReportSet = supportedReportSet;
var isCollectionDirty = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var collection, headers, responses, res;
var _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
collection = params.collection, headers = params.headers;
return [4 /*yield*/, request_1.propfind({
url: collection.url,
props: [{ name: 'getctag', namespace: consts_1.DAVNamespace.CALENDAR_SERVER }],
depth: '0',
headers: headers,
})];
case 1:
responses = _c.sent();
res = responses.filter(function (r) { return requestHelpers_1.urlContains(collection.url, r.href); })[0];
if (!res) {
throw new Error('Collection does not exist on server');
}
return [2 /*return*/, { isDirty: collection.ctag !== ((_a = res.props) === null || _a === void 0 ? void 0 : _a.getctag), newCtag: (_b = res.props) === null || _b === void 0 ? void 0 : _b.getctag }];
}
const isCollectionDirty = (params) => __awaiter(void 0, void 0, void 0, function* () {
var _c, _d;
const { collection, headers } = params;
const responses = yield request_1.propfind({
url: collection.url,
props: [{ name: 'getctag', namespace: consts_1.DAVNamespace.CALENDAR_SERVER }],
depth: '0',
headers,
});
}); };
const res = responses.filter((r) => requestHelpers_1.urlContains(collection.url, r.href))[0];
if (!res) {
throw new Error('Collection does not exist on server');
}
return { isDirty: collection.ctag !== ((_c = res.props) === null || _c === void 0 ? void 0 : _c.getctag), newCtag: (_d = res.props) === null || _d === void 0 ? void 0 : _d.getctag };
});
exports.isCollectionDirty = isCollectionDirty;

@@ -155,23 +90,21 @@ /**

*/
var syncCollection = function (params) {
var _a;
var url = params.url, props = params.props, headers = params.headers, syncLevel = params.syncLevel, syncToken = params.syncToken;
const syncCollection = (params) => {
const { url, props, headers, syncLevel, syncToken } = params;
return request_1.davRequest({
url: url,
url,
init: {
method: 'REPORT',
namespace: consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV],
headers: __assign({}, headers),
headers: Object.assign({}, headers),
body: {
'sync-collection': (_a = {
_attributes: requestHelpers_1.getDAVAttribute([
consts_1.DAVNamespace.CALDAV,
consts_1.DAVNamespace.CARDDAV,
consts_1.DAVNamespace.DAV,
]),
'sync-level': syncLevel,
'sync-token': syncToken
},
_a[consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV] + ":prop"] = requestHelpers_1.formatProps(props),
_a),
'sync-collection': {
_attributes: requestHelpers_1.getDAVAttribute([
consts_1.DAVNamespace.CALDAV,
consts_1.DAVNamespace.CARDDAV,
consts_1.DAVNamespace.DAV,
]),
'sync-level': syncLevel,
'sync-token': syncToken,
[`${consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV]}:prop`]: requestHelpers_1.formatProps(props),
},
},

@@ -183,144 +116,126 @@ },

/** remote collection to local */
var smartCollectionSync = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var collection, method, headers, account, detailedResult, requiredFields, syncMethod, result, objectResponses, changedObjectUrls, deletedObjectUrls, multiGetObjectResponse, _a, remoteObjects_1, localObjects_1, created, updated, deleted, unchanged, _b, isDirty, newCtag, localObjects_2, remoteObjects_2, created, updated, deleted, unchanged;
var _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
return __generator(this, function (_p) {
switch (_p.label) {
case 0:
collection = params.collection, method = params.method, headers = params.headers, account = params.account, detailedResult = params.detailedResult;
requiredFields = ['accountType', 'homeUrl'];
if (!account || !typeHelper_1.hasFields(account, requiredFields)) {
if (!account) {
throw new Error('no account for smartCollectionSync');
}
throw new Error("account must have " + typeHelper_1.findMissingFieldNames(account, requiredFields) + " before smartCollectionSync");
}
syncMethod = method !== null && method !== void 0 ? method : (((_c = collection.reports) === null || _c === void 0 ? void 0 : _c.includes('syncCollection')) ? 'webdav' : 'basic');
debug("smart collection sync with type " + account.accountType + " and method " + syncMethod);
if (!(syncMethod === 'webdav')) return [3 /*break*/, 5];
return [4 /*yield*/, exports.syncCollection({
url: collection.url,
props: [
{ name: 'getetag', namespace: consts_1.DAVNamespace.DAV },
{
name: account.accountType === 'caldav' ? 'calendar-data' : 'address-data',
namespace: account.accountType === 'caldav' ? consts_1.DAVNamespace.CALDAV : consts_1.DAVNamespace.CARDDAV,
},
{
name: 'displayname',
namespace: consts_1.DAVNamespace.DAV,
},
],
syncLevel: 1,
syncToken: collection.syncToken,
headers: headers,
})];
case 1:
result = _p.sent();
objectResponses = result.filter(function (r) {
var _a;
var extName = account.accountType === 'caldav' ? '.ics' : '.vcf';
return ((_a = r.href) === null || _a === void 0 ? void 0 : _a.slice(-4)) === extName;
});
changedObjectUrls = objectResponses.filter(function (o) { return o.status !== 404; }).map(function (r) { return r.href; });
deletedObjectUrls = objectResponses.filter(function (o) { return o.status === 404; }).map(function (r) { return r.href; });
if (!changedObjectUrls.length) return [3 /*break*/, 3];
return [4 /*yield*/, ((_d = collection === null || collection === void 0 ? void 0 : collection.objectMultiGet) === null || _d === void 0 ? void 0 : _d.call(collection, {
url: collection.url,
props: [
{ name: 'getetag', namespace: consts_1.DAVNamespace.DAV },
{
name: account.accountType === 'caldav' ? 'calendar-data' : 'address-data',
namespace: account.accountType === 'caldav' ? consts_1.DAVNamespace.CALDAV : consts_1.DAVNamespace.CARDDAV,
},
],
objectUrls: changedObjectUrls,
depth: '1',
headers: headers,
}))];
case 2:
_a = (_e = (_p.sent())) !== null && _e !== void 0 ? _e : [];
return [3 /*break*/, 4];
case 3:
_a = [];
_p.label = 4;
case 4:
multiGetObjectResponse = _a;
remoteObjects_1 = multiGetObjectResponse.map(function (res) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
return {
url: (_a = res.href) !== null && _a !== void 0 ? _a : '',
etag: (_b = res.props) === null || _b === void 0 ? void 0 : _b.getetag,
data: (account === null || account === void 0 ? void 0 : account.accountType) === 'caldav'
? (_e = (_d = (_c = res.props) === null || _c === void 0 ? void 0 : _c.calendarData) === null || _d === void 0 ? void 0 : _d._cdata) !== null && _e !== void 0 ? _e : (_f = res.props) === null || _f === void 0 ? void 0 : _f.calendarData
: (_j = (_h = (_g = res.props) === null || _g === void 0 ? void 0 : _g.addressData) === null || _h === void 0 ? void 0 : _h._cdata) !== null && _j !== void 0 ? _j : (_k = res.props) === null || _k === void 0 ? void 0 : _k.addressData,
};
});
localObjects_1 = (_f = collection.objects) !== null && _f !== void 0 ? _f : [];
created = remoteObjects_1.filter(function (o) {
return localObjects_1.every(function (lo) { return !requestHelpers_1.urlContains(lo.url, o.url); });
});
updated = localObjects_1.reduce(function (prev, curr) {
var found = remoteObjects_1.find(function (ro) { return requestHelpers_1.urlContains(ro.url, curr.url); });
if (found && found.etag && found.etag !== curr.etag) {
return __spreadArray(__spreadArray([], prev), [found]);
}
return prev;
}, []);
deleted = deletedObjectUrls.map(function (o) { return ({
url: o,
etag: '',
}); });
unchanged = localObjects_1.filter(function (lo) {
return remoteObjects_1.some(function (ro) { return requestHelpers_1.urlContains(lo.url, ro.url) && ro.etag === lo.etag; });
});
return [2 /*return*/, __assign(__assign({}, collection), { objects: detailedResult
? { created: created, updated: updated, deleted: deleted }
: __spreadArray(__spreadArray(__spreadArray([], unchanged), created), updated),
// all syncToken in the results are the same so we use the first one here
syncToken: (_k = (_j = (_h = (_g = result[0]) === null || _g === void 0 ? void 0 : _g.raw) === null || _h === void 0 ? void 0 : _h.multistatus) === null || _j === void 0 ? void 0 : _j.syncToken) !== null && _k !== void 0 ? _k : collection.syncToken })];
case 5:
if (!(syncMethod === 'basic')) return [3 /*break*/, 8];
return [4 /*yield*/, exports.isCollectionDirty({
collection: collection,
headers: headers,
})];
case 6:
_b = _p.sent(), isDirty = _b.isDirty, newCtag = _b.newCtag;
localObjects_2 = (_l = collection.objects) !== null && _l !== void 0 ? _l : [];
return [4 /*yield*/, ((_m = collection.fetchObjects) === null || _m === void 0 ? void 0 : _m.call(collection, { collection: collection, headers: headers }))];
case 7:
remoteObjects_2 = (_o = (_p.sent())) !== null && _o !== void 0 ? _o : [];
created = remoteObjects_2.filter(function (ro) {
return localObjects_2.every(function (lo) { return !requestHelpers_1.urlContains(lo.url, ro.url); });
});
updated = localObjects_2.reduce(function (prev, curr) {
var found = remoteObjects_2.find(function (ro) { return requestHelpers_1.urlContains(ro.url, curr.url); });
if (found && found.etag && found.etag !== curr.etag) {
return __spreadArray(__spreadArray([], prev), [found]);
}
return prev;
}, []);
deleted = localObjects_2.filter(function (cal) {
return remoteObjects_2.every(function (ro) { return !requestHelpers_1.urlContains(ro.url, cal.url); });
});
unchanged = localObjects_2.filter(function (lo) {
return remoteObjects_2.some(function (ro) { return requestHelpers_1.urlContains(lo.url, ro.url) && ro.etag === lo.etag; });
});
if (isDirty) {
return [2 /*return*/, __assign(__assign({}, collection), { objects: detailedResult
? { created: created, updated: updated, deleted: deleted }
: __spreadArray(__spreadArray(__spreadArray([], unchanged), created), updated), ctag: newCtag })];
}
_p.label = 8;
case 8: return [2 /*return*/, detailedResult
? __assign(__assign({}, collection), { objects: {
created: [],
updated: [],
deleted: [],
} }) : collection];
const smartCollectionSync = (params) => __awaiter(void 0, void 0, void 0, function* () {
var _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
const { collection, method, headers, account, detailedResult } = params;
const requiredFields = ['accountType', 'homeUrl'];
if (!account || !typeHelpers_1.hasFields(account, requiredFields)) {
if (!account) {
throw new Error('no account for smartCollectionSync');
}
});
}); };
throw new Error(`account must have ${typeHelpers_1.findMissingFieldNames(account, requiredFields)} before smartCollectionSync`);
}
const syncMethod = method !== null && method !== void 0 ? method : (((_e = collection.reports) === null || _e === void 0 ? void 0 : _e.includes('syncCollection')) ? 'webdav' : 'basic');
debug(`smart collection sync with type ${account.accountType} and method ${syncMethod}`);
if (syncMethod === 'webdav') {
const result = yield exports.syncCollection({
url: collection.url,
props: [
{ name: 'getetag', namespace: consts_1.DAVNamespace.DAV },
{
name: account.accountType === 'caldav' ? 'calendar-data' : 'address-data',
namespace: account.accountType === 'caldav' ? consts_1.DAVNamespace.CALDAV : consts_1.DAVNamespace.CARDDAV,
},
{
name: 'displayname',
namespace: consts_1.DAVNamespace.DAV,
},
],
syncLevel: 1,
syncToken: collection.syncToken,
headers,
});
const objectResponses = result.filter((r) => {
var _a;
const extName = account.accountType === 'caldav' ? '.ics' : '.vcf';
return ((_a = r.href) === null || _a === void 0 ? void 0 : _a.slice(-4)) === extName;
});
const changedObjectUrls = objectResponses.filter((o) => o.status !== 404).map((r) => r.href);
const deletedObjectUrls = objectResponses.filter((o) => o.status === 404).map((r) => r.href);
const multiGetObjectResponse = changedObjectUrls.length
? (_g = (yield ((_f = collection === null || collection === void 0 ? void 0 : collection.objectMultiGet) === null || _f === void 0 ? void 0 : _f.call(collection, {
url: collection.url,
props: [
{ name: 'getetag', namespace: consts_1.DAVNamespace.DAV },
{
name: account.accountType === 'caldav' ? 'calendar-data' : 'address-data',
namespace: account.accountType === 'caldav' ? consts_1.DAVNamespace.CALDAV : consts_1.DAVNamespace.CARDDAV,
},
],
objectUrls: changedObjectUrls,
depth: '1',
headers,
})))) !== null && _g !== void 0 ? _g : []
: [];
const remoteObjects = multiGetObjectResponse.map((res) => {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
return {
url: (_a = res.href) !== null && _a !== void 0 ? _a : '',
etag: (_b = res.props) === null || _b === void 0 ? void 0 : _b.getetag,
data: (account === null || account === void 0 ? void 0 : account.accountType) === 'caldav'
? (_e = (_d = (_c = res.props) === null || _c === void 0 ? void 0 : _c.calendarData) === null || _d === void 0 ? void 0 : _d._cdata) !== null && _e !== void 0 ? _e : (_f = res.props) === null || _f === void 0 ? void 0 : _f.calendarData
: (_j = (_h = (_g = res.props) === null || _g === void 0 ? void 0 : _g.addressData) === null || _h === void 0 ? void 0 : _h._cdata) !== null && _j !== void 0 ? _j : (_k = res.props) === null || _k === void 0 ? void 0 : _k.addressData,
};
});
const localObjects = (_h = collection.objects) !== null && _h !== void 0 ? _h : [];
// no existing url
const created = remoteObjects.filter((o) => localObjects.every((lo) => !requestHelpers_1.urlContains(lo.url, o.url)));
// debug(`created objects: ${created.map((o) => o.url).join('\n')}`);
// have same url, but etag different
const updated = localObjects.reduce((prev, curr) => {
const found = remoteObjects.find((ro) => requestHelpers_1.urlContains(ro.url, curr.url));
if (found && found.etag && found.etag !== curr.etag) {
return [...prev, found];
}
return prev;
}, []);
// debug(`updated objects: ${updated.map((o) => o.url).join('\n')}`);
const deleted = deletedObjectUrls.map((o) => ({
url: o,
etag: '',
}));
// debug(`deleted objects: ${deleted.map((o) => o.url).join('\n')}`);
const unchanged = localObjects.filter((lo) => remoteObjects.some((ro) => requestHelpers_1.urlContains(lo.url, ro.url) && ro.etag === lo.etag));
return Object.assign(Object.assign({}, collection), { objects: detailedResult
? { created, updated, deleted }
: [...unchanged, ...created, ...updated],
// all syncToken in the results are the same so we use the first one here
syncToken: (_m = (_l = (_k = (_j = result[0]) === null || _j === void 0 ? void 0 : _j.raw) === null || _k === void 0 ? void 0 : _k.multistatus) === null || _l === void 0 ? void 0 : _l.syncToken) !== null && _m !== void 0 ? _m : collection.syncToken });
}
if (syncMethod === 'basic') {
const { isDirty, newCtag } = yield exports.isCollectionDirty({
collection,
headers,
});
const localObjects = (_o = collection.objects) !== null && _o !== void 0 ? _o : [];
const remoteObjects = (_q = (yield ((_p = collection.fetchObjects) === null || _p === void 0 ? void 0 : _p.call(collection, { collection, headers })))) !== null && _q !== void 0 ? _q : [];
// no existing url
const created = remoteObjects.filter((ro) => localObjects.every((lo) => !requestHelpers_1.urlContains(lo.url, ro.url)));
// debug(`created objects: ${created.map((o) => o.url).join('\n')}`);
// have same url, but etag different
const updated = localObjects.reduce((prev, curr) => {
const found = remoteObjects.find((ro) => requestHelpers_1.urlContains(ro.url, curr.url));
if (found && found.etag && found.etag !== curr.etag) {
return [...prev, found];
}
return prev;
}, []);
// debug(`updated objects: ${updated.map((o) => o.url).join('\n')}`);
// does not present in remote
const deleted = localObjects.filter((cal) => remoteObjects.every((ro) => !requestHelpers_1.urlContains(ro.url, cal.url)));
// debug(`deleted objects: ${deleted.map((o) => o.url).join('\n')}`);
const unchanged = localObjects.filter((lo) => remoteObjects.some((ro) => requestHelpers_1.urlContains(lo.url, ro.url) && ro.etag === lo.etag));
if (isDirty) {
return Object.assign(Object.assign({}, collection), { objects: detailedResult
? { created, updated, deleted }
: [...unchanged, ...created, ...updated], ctag: newCtag });
}
}
return detailedResult
? Object.assign(Object.assign({}, collection), { objects: {
created: [],
updated: [],
deleted: [],
} }) : collection;
});
exports.smartCollectionSync = smartCollectionSync;
//# sourceMappingURL=collection.js.map
"use strict";
var _a, _b;
Object.defineProperty(exports, "__esModule", { value: true });

@@ -13,16 +12,16 @@ exports.ICALObjects = exports.DAVNamespaceShorthandMap = exports.DAVAttributeMap = exports.DAVNamespace = void 0;

})(DAVNamespace = exports.DAVNamespace || (exports.DAVNamespace = {}));
exports.DAVAttributeMap = (_a = {},
_a[DAVNamespace.CALDAV] = 'xmlns:c',
_a[DAVNamespace.CARDDAV] = 'xmlns:card',
_a[DAVNamespace.CALENDAR_SERVER] = 'xmlns:cs',
_a[DAVNamespace.CALDAV_APPLE] = 'xmlns:ca',
_a[DAVNamespace.DAV] = 'xmlns:d',
_a);
exports.DAVNamespaceShorthandMap = (_b = {},
_b[DAVNamespace.CALDAV] = 'c',
_b[DAVNamespace.CARDDAV] = 'card',
_b[DAVNamespace.CALENDAR_SERVER] = 'cs',
_b[DAVNamespace.CALDAV_APPLE] = 'ca',
_b[DAVNamespace.DAV] = 'd',
_b);
exports.DAVAttributeMap = {
[DAVNamespace.CALDAV]: 'xmlns:c',
[DAVNamespace.CARDDAV]: 'xmlns:card',
[DAVNamespace.CALENDAR_SERVER]: 'xmlns:cs',
[DAVNamespace.CALDAV_APPLE]: 'xmlns:ca',
[DAVNamespace.DAV]: 'xmlns:d',
};
exports.DAVNamespaceShorthandMap = {
[DAVNamespace.CALDAV]: 'c',
[DAVNamespace.CARDDAV]: 'card',
[DAVNamespace.CALENDAR_SERVER]: 'cs',
[DAVNamespace.CALDAV_APPLE]: 'ca',
[DAVNamespace.DAV]: 'd',
};
var ICALObjects;

@@ -29,0 +28,0 @@ (function (ICALObjects) {

@@ -0,5 +1,6 @@

import * as client from './client';
import { DAVNamespace } from './consts';
export type { DAVProp, DAVFilter, DAVDepth, DAVMethods, DAVRequest, DAVResponse, DAVTokens, } from './types/DAVTypes';
export type { DAVAccount, DAVAddressBook, DAVCalendar, DAVCalendarObject, DAVCollection, DAVCredentials, DAVObject, DAVVCard, } from './types/models';
export type { DAVClient } from './client';
export { DAVClient } from './client';
export { createDAVClient } from './client';

@@ -11,8 +12,28 @@ export { createAccount } from './account';

export { addressBookQuery, fetchAddressBooks, fetchVCards, createVCard, updateVCard, deleteVCard, } from './addressBook';
export { getBasicAuthHeaders, getOauthHeaders, fetchOauthTokens, refreshAccessToken, } from './util/authHelper';
export { getBasicAuthHeaders, getOauthHeaders, fetchOauthTokens, refreshAccessToken, } from './util/authHelpers';
export { mergeObjectDupKeyArray, urlContains, urlEquals, getDAVAttribute, formatFilters, formatProps, cleanupFalsy, } from './util/requestHelpers';
export { DAVNamespace, DAVNamespaceShorthandMap, DAVAttributeMap } from './consts';
declare const _default: {
urlEquals: (urlA?: string | undefined, urlB?: string | undefined) => boolean;
urlContains: (urlA?: string | undefined, urlB?: string | undefined) => boolean;
mergeObjectDupKeyArray: <A, B>(objA: A, objB: B) => { [key in keyof A | keyof B]: key extends keyof A & keyof B ? (A[key] | B[key])[] : key extends keyof A ? A[key] : key extends keyof B ? B[key] : never; };
getDAVAttribute: (nsArr: DAVNamespace[]) => {
[key: string]: DAVNamespace;
};
formatProps: (props?: import("./types/DAVTypes").DAVProp[] | undefined) => {
[key: string]: any;
} | undefined;
formatFilters: (filters?: import("./types/DAVTypes").DAVFilter[] | undefined) => {
[key: string]: any;
} | undefined;
cleanupFalsy: <T = unknown>(obj: T) => import("./util/typeHelpers").NoUndefinedField<T>;
defaultParam: <F extends (...args: any[]) => any>(fn: F, params: Partial<Parameters<F>[0]>) => (...args: Parameters<F>) => ReturnType<F>;
getBasicAuthHeaders: (credentials: import("./types/models").DAVCredentials) => {
authorization?: string | undefined;
};
fetchOauthTokens: (credentials: import("./types/models").DAVCredentials) => Promise<import("./types/DAVTypes").DAVTokens>;
refreshAccessToken: (credentials: import("./types/models").DAVCredentials) => Promise<{
access_token?: string | undefined;
expires_in?: number | undefined;
}>;
getOauthHeaders: (credentials: import("./types/models").DAVCredentials) => Promise<{

@@ -24,7 +45,2 @@ tokens: import("./types/DAVTypes").DAVTokens;

}>;
fetchOauthTokens: (credentials: import("./types/models").DAVCredentials) => Promise<import("./types/DAVTypes").DAVTokens>;
refreshAccessToken: (credentials: import("./types/models").DAVCredentials) => Promise<{
access_token?: string | undefined;
expires_in?: number | undefined;
}>;
calendarQuery: (params: {

@@ -216,3 +232,3 @@ url: string;

createAccount: (params0: {
account: import("./util/typeHelper").Optional<import("./types/models").DAVAccount, "serverUrl">;
account: import("./util/typeHelpers").Optional<import("./types/models").DAVAccount, "serverUrl">;
headers?: Record<string, string> | undefined;

@@ -360,2 +376,3 @@ loadCollections?: boolean | undefined;

}>;
DAVClient: typeof client.DAVClient;
DAVNamespace: typeof DAVNamespace;

@@ -362,0 +379,0 @@ DAVNamespaceShorthandMap: {

"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {

@@ -33,13 +22,16 @@ if (k2 === undefined) k2 = k;

Object.defineProperty(exports, "__esModule", { value: true });
exports.DAVAttributeMap = exports.DAVNamespaceShorthandMap = exports.DAVNamespace = exports.refreshAccessToken = exports.fetchOauthTokens = exports.getOauthHeaders = exports.getBasicAuthHeaders = exports.deleteVCard = exports.updateVCard = exports.createVCard = exports.fetchVCards = exports.fetchAddressBooks = exports.addressBookQuery = exports.syncCalendars = exports.deleteCalendarObject = exports.updateCalendarObject = exports.createCalendarObject = exports.fetchCalendarObjects = exports.fetchCalendars = exports.makeCalendar = exports.calendarMultiGet = exports.calendarQuery = exports.smartCollectionSync = exports.syncCollection = exports.isCollectionDirty = exports.supportedReportSet = exports.collectionQuery = exports.deleteObject = exports.updateObject = exports.createObject = exports.propfind = exports.davRequest = exports.createAccount = exports.createDAVClient = void 0;
var account = __importStar(require("./account"));
var addressBook = __importStar(require("./addressBook"));
var calendar = __importStar(require("./calendar"));
var client = __importStar(require("./client"));
var collection = __importStar(require("./collection"));
var consts_1 = require("./consts");
var request = __importStar(require("./request"));
var authHelper = __importStar(require("./util/authHelper"));
exports.DAVAttributeMap = exports.DAVNamespaceShorthandMap = exports.DAVNamespace = exports.cleanupFalsy = exports.formatProps = exports.formatFilters = exports.getDAVAttribute = exports.urlEquals = exports.urlContains = exports.mergeObjectDupKeyArray = exports.refreshAccessToken = exports.fetchOauthTokens = exports.getOauthHeaders = exports.getBasicAuthHeaders = exports.deleteVCard = exports.updateVCard = exports.createVCard = exports.fetchVCards = exports.fetchAddressBooks = exports.addressBookQuery = exports.syncCalendars = exports.deleteCalendarObject = exports.updateCalendarObject = exports.createCalendarObject = exports.fetchCalendarObjects = exports.fetchCalendars = exports.makeCalendar = exports.calendarMultiGet = exports.calendarQuery = exports.smartCollectionSync = exports.syncCollection = exports.isCollectionDirty = exports.supportedReportSet = exports.collectionQuery = exports.deleteObject = exports.updateObject = exports.createObject = exports.propfind = exports.davRequest = exports.createAccount = exports.createDAVClient = exports.DAVClient = void 0;
const account = __importStar(require("./account"));
const addressBook = __importStar(require("./addressBook"));
const calendar = __importStar(require("./calendar"));
const client = __importStar(require("./client"));
const collection = __importStar(require("./collection"));
const consts_1 = require("./consts");
const request = __importStar(require("./request"));
const authHelpers = __importStar(require("./util/authHelpers"));
const requestHelpers = __importStar(require("./util/requestHelpers"));
var client_1 = require("./client");
Object.defineProperty(exports, "createDAVClient", { enumerable: true, get: function () { return client_1.createDAVClient; } });
Object.defineProperty(exports, "DAVClient", { enumerable: true, get: function () { return client_1.DAVClient; } });
var client_2 = require("./client");
Object.defineProperty(exports, "createDAVClient", { enumerable: true, get: function () { return client_2.createDAVClient; } });
var account_1 = require("./account");

@@ -76,7 +68,15 @@ Object.defineProperty(exports, "createAccount", { enumerable: true, get: function () { return account_1.createAccount; } });

Object.defineProperty(exports, "deleteVCard", { enumerable: true, get: function () { return addressBook_1.deleteVCard; } });
var authHelper_1 = require("./util/authHelper");
Object.defineProperty(exports, "getBasicAuthHeaders", { enumerable: true, get: function () { return authHelper_1.getBasicAuthHeaders; } });
Object.defineProperty(exports, "getOauthHeaders", { enumerable: true, get: function () { return authHelper_1.getOauthHeaders; } });
Object.defineProperty(exports, "fetchOauthTokens", { enumerable: true, get: function () { return authHelper_1.fetchOauthTokens; } });
Object.defineProperty(exports, "refreshAccessToken", { enumerable: true, get: function () { return authHelper_1.refreshAccessToken; } });
var authHelpers_1 = require("./util/authHelpers");
Object.defineProperty(exports, "getBasicAuthHeaders", { enumerable: true, get: function () { return authHelpers_1.getBasicAuthHeaders; } });
Object.defineProperty(exports, "getOauthHeaders", { enumerable: true, get: function () { return authHelpers_1.getOauthHeaders; } });
Object.defineProperty(exports, "fetchOauthTokens", { enumerable: true, get: function () { return authHelpers_1.fetchOauthTokens; } });
Object.defineProperty(exports, "refreshAccessToken", { enumerable: true, get: function () { return authHelpers_1.refreshAccessToken; } });
var requestHelpers_1 = require("./util/requestHelpers");
Object.defineProperty(exports, "mergeObjectDupKeyArray", { enumerable: true, get: function () { return requestHelpers_1.mergeObjectDupKeyArray; } });
Object.defineProperty(exports, "urlContains", { enumerable: true, get: function () { return requestHelpers_1.urlContains; } });
Object.defineProperty(exports, "urlEquals", { enumerable: true, get: function () { return requestHelpers_1.urlEquals; } });
Object.defineProperty(exports, "getDAVAttribute", { enumerable: true, get: function () { return requestHelpers_1.getDAVAttribute; } });
Object.defineProperty(exports, "formatFilters", { enumerable: true, get: function () { return requestHelpers_1.formatFilters; } });
Object.defineProperty(exports, "formatProps", { enumerable: true, get: function () { return requestHelpers_1.formatProps; } });
Object.defineProperty(exports, "cleanupFalsy", { enumerable: true, get: function () { return requestHelpers_1.cleanupFalsy; } });
var consts_2 = require("./consts");

@@ -86,3 +86,5 @@ Object.defineProperty(exports, "DAVNamespace", { enumerable: true, get: function () { return consts_2.DAVNamespace; } });

Object.defineProperty(exports, "DAVAttributeMap", { enumerable: true, get: function () { return consts_2.DAVAttributeMap; } });
exports.default = __assign(__assign(__assign(__assign(__assign(__assign(__assign({ DAVNamespace: consts_1.DAVNamespace, DAVNamespaceShorthandMap: consts_1.DAVNamespaceShorthandMap, DAVAttributeMap: consts_1.DAVAttributeMap }, client), request), collection), account), addressBook), calendar), { getBasicAuthHeaders: authHelper.getBasicAuthHeaders, getOauthHeaders: authHelper.getOauthHeaders, fetchOauthTokens: authHelper.fetchOauthTokens, refreshAccessToken: authHelper.refreshAccessToken });
exports.default = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ DAVNamespace: consts_1.DAVNamespace,
DAVNamespaceShorthandMap: consts_1.DAVNamespaceShorthandMap,
DAVAttributeMap: consts_1.DAVAttributeMap }, client), request), collection), account), addressBook), calendar), authHelpers), requestHelpers);
//# sourceMappingURL=index.js.map
{
"name": "tsdav",
"version": "1.0.6",
"version": "1.1.0",
"description": "WebDAV, CALDAV, and CARDDAV client for Nodejs and the Browser",

@@ -26,15 +26,18 @@ "keywords": [

"author": "linlilulll@gmail.com",
"main": "dist/index.js",
"module": "dist/index.js",
"main": "dist",
"module": "dist-esm",
"types": "dist/index.d.ts",
"files": [
"dist",
"dist-esm",
"package.json"
],
"scripts": {
"clean": "rimraf dist*",
"typecheck": "tsc --noEmit",
"lint": "eslint src",
"lint": "eslint src --ext .ts",
"lintFix": "eslint src --ext .ts --fix",
"test": "jest",
"prepublishOnly": "yarn build",
"build": "rimraf dist && tsc -p ./tsconfig.build.json && copyfiles package.json LICENSE README.md ./dist",
"build": "yarn -s clean && tsc -p tsconfig.cjs.json && tsc -p tsconfig.esm.json && copyfiles package.json LICENSE README.md ./dist && copyfiles package.json LICENSE README.md ./dist-esm",
"watch": "tsc --watch --outDir ./dist"

@@ -51,7 +54,7 @@ },

"@types/debug": "^4.1.7",
"@types/jest": "^26.0.24",
"@types/node": "^16.4.13",
"@typescript-eslint/eslint-plugin": "^4.29.0",
"@typescript-eslint/parser": "^4.29.0",
"concurrently": "^6.2.0",
"@types/jest": "^27.0.1",
"@types/node": "^16.7.1",
"@typescript-eslint/eslint-plugin": "^4.29.2",
"@typescript-eslint/parser": "4.29.2",
"concurrently": "^6.2.1",
"copyfiles": "^2.4.1",

@@ -61,6 +64,7 @@ "cross-env": "^7.0.3",

"eslint": "^7.32.0",
"eslint-config-airbnb-typescript": "^12.3.1",
"eslint-config-airbnb": "18.2.1",
"eslint-config-airbnb-typescript": "^13.0.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-import": "^2.23.4",
"eslint-plugin-prettier": "^3.4.0",
"eslint-plugin-import": "^2.24.1",
"eslint-plugin-prettier": "^3.4.1",
"jest": "^27.0.6",

@@ -70,3 +74,3 @@ "prettier": "^2.3.2",

"sort-package-json": "1.50.0",
"ts-jest": "27.0.4",
"ts-jest": "27.0.5",
"typescript": "^4.3.5"

@@ -73,0 +77,0 @@ },

@@ -27,2 +27,3 @@ <p align="center">

- Works in both `Browsers` and `Node.js`
- Supports Both `commonjs` and `esm`
- OAuth2 & Basic Auth helpers built-in

@@ -53,3 +54,3 @@ - Native typescript, fully linted and well tested

(async () => {
const googleClient = await createDAVClient({
const client = await createDAVClient({
serverUrl: 'https://apidata.googleusercontent.com/caldav/v2/',

@@ -95,2 +96,55 @@ credentials: {

After `v1.1.0`, you have a new way of creating clients.
##### Google CALDAV
```ts
import { DAVClient } from 'tsdav';
const client = new DAVClient({
serverUrl: 'https://apidata.googleusercontent.com/caldav/v2/',
credentials: {
refreshToken: 'YOUR_REFRESH_TOKEN_WITH_CALDAV_PERMISSION',
},
authMethod: 'Oauth',
defaultAccountType: 'caldav',
});
(async () => {
await googleClient.login();
const calendars = await client.fetchCalendars();
const calendarObjects = await client.fetchCalendarObjects({
calendar: calendars[0],
});
})();
```
##### Apple CARDDAV
```ts
import { DAVClient } from 'tsdav';
const client = new DAVClient({
serverUrl: 'https://contacts.icloud.com',
credentials: {
username: 'YOUR_APPLE_ID',
password: 'YOUR_APP_SPECIFIC_PASSWORD',
},
authMethod: 'Basic',
defaultAccountType: 'carddav',
});
(async () => {
await client.login();
const addressBooks = await client.fetchAddressBooks();
const vcards = await client.fetchVCards({
addressBook: addressBooks[0],
});
})();
```
### Documentation

@@ -106,10 +160,9 @@

### RELEASE NOTES
### Changelog
##### v1.0.6
refers to [Changelog](./CHANGELOG.md)
Fixed a bug where timeRange filter sometimes might be in the wrong format.
### Debugging
##### v1.0.3
Fixed a bug where calendar objects with `http` in its id would cause operations on it to fail.
this package uses `debug` package,
add `tsdav:*` to `DEBUG` env variable to enable debug logs

@@ -5,4 +5,4 @@ import { DAVDepth, DAVProp, DAVRequest, DAVResponse } from './types/DAVTypes';

init: DAVRequest;
convertIncoming?: boolean | undefined;
parseOutgoing?: boolean | undefined;
convertIncoming?: boolean;
parseOutgoing?: boolean;
}) => Promise<DAVResponse[]>;

@@ -12,4 +12,4 @@ export declare const propfind: (params: {

props: DAVProp[];
depth?: DAVDepth | undefined;
headers?: Record<string, string> | undefined;
depth?: DAVDepth;
headers?: Record<string, string>;
}) => Promise<DAVResponse[]>;

@@ -19,3 +19,3 @@ export declare const createObject: (params: {

data: BodyInit;
headers?: Record<string, string> | undefined;
headers?: Record<string, string>;
}) => Promise<Response>;

@@ -26,8 +26,8 @@ export declare const updateObject: (params: {

etag: string;
headers?: Record<string, string> | undefined;
headers?: Record<string, string>;
}) => Promise<Response>;
export declare const deleteObject: (params: {
url: string;
etag?: string | undefined;
headers?: Record<string, string> | undefined;
etag?: string;
headers?: Record<string, string>;
}) => Promise<Response>;
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -22,29 +11,2 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -55,184 +17,164 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.deleteObject = exports.updateObject = exports.createObject = exports.propfind = exports.davRequest = void 0;
var cross_fetch_1 = require("cross-fetch");
var debug_1 = __importDefault(require("debug"));
var xml_js_1 = __importDefault(require("xml-js"));
var consts_1 = require("./consts");
var camelCase_1 = require("./util/camelCase");
var nativeType_1 = require("./util/nativeType");
var requestHelpers_1 = require("./util/requestHelpers");
var debug = debug_1.default('tsdav:request');
var davRequest = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var url, init, _a, convertIncoming, _b, parseOutgoing, headers, body, namespace, method, attributes, xmlBody, davResponse, resText, result, responseBodies;
var _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
url = params.url, init = params.init, _a = params.convertIncoming, convertIncoming = _a === void 0 ? true : _a, _b = params.parseOutgoing, parseOutgoing = _b === void 0 ? true : _b;
headers = init.headers, body = init.body, namespace = init.namespace, method = init.method, attributes = init.attributes;
xmlBody = convertIncoming
? xml_js_1.default.js2xml(__assign(__assign({}, body), { _attributes: attributes }), {
compact: true,
spaces: 2,
elementNameFn: function (name) {
// add namespace to all keys without namespace
if (namespace && !/^.+:.+/.test(name)) {
return namespace + ":" + name;
}
return name;
},
})
: body;
return [4 /*yield*/, cross_fetch_1.fetch(url, {
headers: __assign({ 'Content-Type': 'text/xml;charset=UTF-8' }, requestHelpers_1.cleanupFalsy(headers)),
body: xmlBody,
method: method,
})];
case 1:
davResponse = _d.sent();
return [4 /*yield*/, davResponse.text()];
case 2:
resText = _d.sent();
// filter out invalid responses
// debug('response xml:');
// debug(resText);
// debug(davResponse);
if (!davResponse.ok ||
!((_c = davResponse.headers.get('content-type')) === null || _c === void 0 ? void 0 : _c.includes('xml')) ||
!parseOutgoing) {
return [2 /*return*/, [
{
href: davResponse.url,
ok: davResponse.ok,
status: davResponse.status,
statusText: davResponse.statusText,
raw: resText,
},
]];
const cross_fetch_1 = require("cross-fetch");
const debug_1 = __importDefault(require("debug"));
const xml_js_1 = __importDefault(require("xml-js"));
const consts_1 = require("./consts");
const camelCase_1 = require("./util/camelCase");
const nativeType_1 = require("./util/nativeType");
const requestHelpers_1 = require("./util/requestHelpers");
const debug = debug_1.default('tsdav:request');
const davRequest = (params) => __awaiter(void 0, void 0, void 0, function* () {
var _a;
const { url, init, convertIncoming = true, parseOutgoing = true } = params;
const { headers, body, namespace, method, attributes } = init;
const xmlBody = convertIncoming
? xml_js_1.default.js2xml(Object.assign(Object.assign({}, body), { _attributes: attributes }), {
compact: true,
spaces: 2,
elementNameFn: (name) => {
// add namespace to all keys without namespace
if (namespace && !/^.+:.+/.test(name)) {
return `${namespace}:${name}`;
}
result = xml_js_1.default.xml2js(resText, {
compact: true,
trim: true,
textFn: function (value, parentElement) {
try {
// This is needed for xml-js design reasons
// eslint-disable-next-line no-underscore-dangle
var parentOfParent = parentElement._parent;
var pOpKeys = Object.keys(parentOfParent);
var keyNo = pOpKeys.length;
var keyName = pOpKeys[keyNo - 1];
var arrOfKey = parentOfParent[keyName];
var arrOfKeyLen = arrOfKey.length;
if (arrOfKeyLen > 0) {
var arr = arrOfKey;
var arrIndex = arrOfKey.length - 1;
arr[arrIndex] = nativeType_1.nativeType(value);
}
else {
parentOfParent[keyName] = nativeType_1.nativeType(value);
}
}
catch (e) {
debug(e.stack);
}
},
// remove namespace & camelCase
elementNameFn: function (attributeName) { return camelCase_1.camelCase(attributeName.replace(/^.+:/, '')); },
attributesFn: function (value) {
var newVal = __assign({}, value);
delete newVal.xmlns;
return newVal;
},
ignoreDeclaration: true,
});
responseBodies = Array.isArray(result.multistatus.response)
? result.multistatus.response
: [result.multistatus.response];
return [2 /*return*/, responseBodies.map(function (responseBody) {
var _a, _b;
var statusRegex = /^\S+\s(?<status>\d+)\s(?<statusText>.+)$/;
if (!responseBody) {
return {
status: davResponse.status,
statusText: davResponse.statusText,
ok: davResponse.ok,
};
}
var matchArr = statusRegex.exec(responseBody.status);
return {
raw: result,
href: responseBody.href,
status: (matchArr === null || matchArr === void 0 ? void 0 : matchArr.groups) ? Number.parseInt(matchArr === null || matchArr === void 0 ? void 0 : matchArr.groups.status, 10) : davResponse.status,
statusText: (_b = (_a = matchArr === null || matchArr === void 0 ? void 0 : matchArr.groups) === null || _a === void 0 ? void 0 : _a.statusText) !== null && _b !== void 0 ? _b : davResponse.statusText,
ok: !responseBody.error,
error: responseBody.error,
responsedescription: responseBody.responsedescription,
props: (Array.isArray(responseBody.propstat)
? responseBody.propstat
: [responseBody.propstat]).reduce(function (prev, curr) {
return __assign(__assign({}, prev), curr === null || curr === void 0 ? void 0 : curr.prop);
}, {}),
};
})];
return name;
},
})
: body;
// debug('outgoing xml:');
// debug(xmlBody);
const davResponse = yield cross_fetch_1.fetch(url, {
headers: Object.assign({ 'Content-Type': 'text/xml;charset=UTF-8' }, requestHelpers_1.cleanupFalsy(headers)),
body: xmlBody,
method,
});
const resText = yield davResponse.text();
// filter out invalid responses
// debug('response xml:');
// debug(resText);
// debug(davResponse);
if (!davResponse.ok ||
!((_a = davResponse.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('xml')) ||
!parseOutgoing) {
return [
{
href: davResponse.url,
ok: davResponse.ok,
status: davResponse.status,
statusText: davResponse.statusText,
raw: resText,
},
];
}
const result = xml_js_1.default.xml2js(resText, {
compact: true,
trim: true,
textFn: (value, parentElement) => {
try {
// This is needed for xml-js design reasons
// eslint-disable-next-line no-underscore-dangle
const parentOfParent = parentElement._parent;
const pOpKeys = Object.keys(parentOfParent);
const keyNo = pOpKeys.length;
const keyName = pOpKeys[keyNo - 1];
const arrOfKey = parentOfParent[keyName];
const arrOfKeyLen = arrOfKey.length;
if (arrOfKeyLen > 0) {
const arr = arrOfKey;
const arrIndex = arrOfKey.length - 1;
arr[arrIndex] = nativeType_1.nativeType(value);
}
else {
parentOfParent[keyName] = nativeType_1.nativeType(value);
}
}
catch (e) {
debug(e.stack);
}
},
// remove namespace & camelCase
elementNameFn: (attributeName) => camelCase_1.camelCase(attributeName.replace(/^.+:/, '')),
attributesFn: (value) => {
const newVal = Object.assign({}, value);
delete newVal.xmlns;
return newVal;
},
ignoreDeclaration: true,
});
const responseBodies = Array.isArray(result.multistatus.response)
? result.multistatus.response
: [result.multistatus.response];
return responseBodies.map((responseBody) => {
var _a, _b;
const statusRegex = /^\S+\s(?<status>\d+)\s(?<statusText>.+)$/;
if (!responseBody) {
return {
status: davResponse.status,
statusText: davResponse.statusText,
ok: davResponse.ok,
};
}
const matchArr = statusRegex.exec(responseBody.status);
return {
raw: result,
href: responseBody.href,
status: (matchArr === null || matchArr === void 0 ? void 0 : matchArr.groups) ? Number.parseInt(matchArr === null || matchArr === void 0 ? void 0 : matchArr.groups.status, 10) : davResponse.status,
statusText: (_b = (_a = matchArr === null || matchArr === void 0 ? void 0 : matchArr.groups) === null || _a === void 0 ? void 0 : _a.statusText) !== null && _b !== void 0 ? _b : davResponse.statusText,
ok: !responseBody.error,
error: responseBody.error,
responsedescription: responseBody.responsedescription,
props: (Array.isArray(responseBody.propstat)
? responseBody.propstat
: [responseBody.propstat]).reduce((prev, curr) => {
return Object.assign(Object.assign({}, prev), curr === null || curr === void 0 ? void 0 : curr.prop);
}, {}),
};
});
}); };
});
exports.davRequest = davRequest;
var propfind = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var url, props, depth, headers;
return __generator(this, function (_a) {
url = params.url, props = params.props, depth = params.depth, headers = params.headers;
return [2 /*return*/, exports.davRequest({
url: url,
init: {
method: 'PROPFIND',
headers: requestHelpers_1.cleanupFalsy(__assign(__assign({}, headers), { depth: depth })),
namespace: consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV],
body: {
propfind: {
_attributes: requestHelpers_1.getDAVAttribute([
consts_1.DAVNamespace.CALDAV,
consts_1.DAVNamespace.CALDAV_APPLE,
consts_1.DAVNamespace.CALENDAR_SERVER,
consts_1.DAVNamespace.CARDDAV,
consts_1.DAVNamespace.DAV,
]),
prop: requestHelpers_1.formatProps(props),
},
},
const propfind = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { url, props, depth, headers } = params;
return exports.davRequest({
url,
init: {
method: 'PROPFIND',
headers: requestHelpers_1.cleanupFalsy(Object.assign(Object.assign({}, headers), { depth })),
namespace: consts_1.DAVNamespaceShorthandMap[consts_1.DAVNamespace.DAV],
body: {
propfind: {
_attributes: requestHelpers_1.getDAVAttribute([
consts_1.DAVNamespace.CALDAV,
consts_1.DAVNamespace.CALDAV_APPLE,
consts_1.DAVNamespace.CALENDAR_SERVER,
consts_1.DAVNamespace.CARDDAV,
consts_1.DAVNamespace.DAV,
]),
prop: requestHelpers_1.formatProps(props),
},
})];
},
},
});
}); };
});
exports.propfind = propfind;
var createObject = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var url, data, headers;
return __generator(this, function (_a) {
url = params.url, data = params.data, headers = params.headers;
return [2 /*return*/, cross_fetch_1.fetch(url, { method: 'PUT', body: data, headers: headers })];
});
}); };
const createObject = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { url, data, headers } = params;
return cross_fetch_1.fetch(url, { method: 'PUT', body: data, headers });
});
exports.createObject = createObject;
var updateObject = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var url, data, etag, headers;
return __generator(this, function (_a) {
url = params.url, data = params.data, etag = params.etag, headers = params.headers;
return [2 /*return*/, cross_fetch_1.fetch(url, {
method: 'PUT',
body: data,
headers: requestHelpers_1.cleanupFalsy(__assign(__assign({}, headers), { 'If-Match': etag })),
})];
const updateObject = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { url, data, etag, headers } = params;
return cross_fetch_1.fetch(url, {
method: 'PUT',
body: data,
headers: requestHelpers_1.cleanupFalsy(Object.assign(Object.assign({}, headers), { 'If-Match': etag })),
});
}); };
});
exports.updateObject = updateObject;
var deleteObject = function (params) { return __awaiter(void 0, void 0, void 0, function () {
var url, headers, etag;
return __generator(this, function (_a) {
url = params.url, headers = params.headers, etag = params.etag;
return [2 /*return*/, cross_fetch_1.fetch(url, {
method: 'DELETE',
headers: requestHelpers_1.cleanupFalsy(__assign(__assign({}, headers), { 'If-Match': etag })),
})];
const deleteObject = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { url, headers, etag } = params;
return cross_fetch_1.fetch(url, {
method: 'DELETE',
headers: requestHelpers_1.cleanupFalsy(Object.assign(Object.assign({}, headers), { 'If-Match': etag })),
});
}); };
});
exports.deleteObject = deleteObject;
//# sourceMappingURL=request.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.camelCase = void 0;
var camelCase = function (str) {
return str.replace(/([-_]\w)/g, function (g) { return g[1].toUpperCase(); });
};
const camelCase = (str) => str.replace(/([-_]\w)/g, (g) => g[1].toUpperCase());
exports.camelCase = camelCase;
//# sourceMappingURL=camelCase.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.nativeType = void 0;
var nativeType = function (value) {
var nValue = Number(value);
const nativeType = (value) => {
const nValue = Number(value);
if (!Number.isNaN(nValue)) {
return nValue;
}
var bValue = value.toLowerCase();
const bValue = value.toLowerCase();
if (bValue === 'true') {

@@ -11,0 +11,0 @@ return true;

import { DAVNamespace } from '../consts';
import { DAVFilter, DAVProp } from '../types/DAVTypes';
import type { NoUndefinedField, ValueOf } from './typeHelper';
import type { NoUndefinedField } from './typeHelpers';
export declare const urlEquals: (urlA?: string | undefined, urlB?: string | undefined) => boolean;
export declare const urlContains: (urlA?: string | undefined, urlB?: string | undefined) => boolean;
export declare const mergeObjectDupKeyArray: <T, U>(objA: T, ObjB: U) => { [key in keyof T & keyof U]: ValueOf<T> | ValueOf<U>; };
declare type ShallowMergeDupKeyArray<A, B> = {
[key in keyof A | keyof B]: key extends keyof A & keyof B ? Array<A[key] | B[key]> : key extends keyof A ? A[key] : key extends keyof B ? B[key] : never;
};
export declare const mergeObjectDupKeyArray: <A, B>(objA: A, objB: B) => ShallowMergeDupKeyArray<A, B>;
export declare const getDAVAttribute: (nsArr: DAVNamespace[]) => {

@@ -17,1 +20,2 @@ [key: string]: DAVNamespace;

export declare const cleanupFalsy: <T = unknown>(obj: T) => NoUndefinedField<T>;
export {};
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.cleanupFalsy = exports.formatFilters = exports.formatProps = exports.getDAVAttribute = exports.mergeObjectDupKeyArray = exports.urlContains = exports.urlEquals = void 0;
var consts_1 = require("../consts");
var urlEquals = function (urlA, urlB) {
const consts_1 = require("../consts");
const urlEquals = (urlA, urlB) => {
if (!urlA && !urlB) {

@@ -28,13 +12,13 @@ return true;

}
var trimmedUrlA = urlA.trim();
var trimmedUrlB = urlB.trim();
const trimmedUrlA = urlA.trim();
const trimmedUrlB = urlB.trim();
if (Math.abs(trimmedUrlA.length - trimmedUrlB.length) > 1) {
return false;
}
var strippedUrlA = trimmedUrlA.slice(-1) === '/' ? trimmedUrlA.slice(0, -1) : trimmedUrlA;
var strippedUrlB = trimmedUrlB.slice(-1) === '/' ? trimmedUrlB.slice(0, -1) : trimmedUrlB;
const strippedUrlA = trimmedUrlA.slice(-1) === '/' ? trimmedUrlA.slice(0, -1) : trimmedUrlA;
const strippedUrlB = trimmedUrlB.slice(-1) === '/' ? trimmedUrlB.slice(0, -1) : trimmedUrlB;
return urlA.includes(strippedUrlB) || urlB.includes(strippedUrlA);
};
exports.urlEquals = urlEquals;
var urlContains = function (urlA, urlB) {
const urlContains = (urlA, urlB) => {
if (!urlA && !urlB) {

@@ -46,65 +30,47 @@ return true;

}
var trimmedUrlA = urlA.trim();
var trimmedUrlB = urlB.trim();
var strippedUrlA = trimmedUrlA.slice(-1) === '/' ? trimmedUrlA.slice(0, -1) : trimmedUrlA;
var strippedUrlB = trimmedUrlB.slice(-1) === '/' ? trimmedUrlB.slice(0, -1) : trimmedUrlB;
const trimmedUrlA = urlA.trim();
const trimmedUrlB = urlB.trim();
const strippedUrlA = trimmedUrlA.slice(-1) === '/' ? trimmedUrlA.slice(0, -1) : trimmedUrlA;
const strippedUrlB = trimmedUrlB.slice(-1) === '/' ? trimmedUrlB.slice(0, -1) : trimmedUrlB;
return urlA.includes(strippedUrlB) || urlB.includes(strippedUrlA);
};
exports.urlContains = urlContains;
// merge two objects, same key property become array
var mergeObjectDupKeyArray = function (objA, ObjB) {
return Object.entries(objA).reduce(function (merged, _a) {
var _b, _c, _d;
var currKey = _a[0], currValue = _a[1];
const mergeObjectDupKeyArray = (objA, objB) => {
return Object.entries(objA).reduce((merged, [currKey, currValue]) => {
if (merged[currKey] && Array.isArray(merged[currKey])) {
// is array
return __assign(__assign({}, merged), (_b = {}, _b[currKey] = __spreadArray(__spreadArray([], merged[currKey]), [currValue]), _b));
return Object.assign(Object.assign({}, merged), { [currKey]: [...merged[currKey], currValue] });
}
if (merged[currKey] && !Array.isArray(merged[currKey])) {
// not array
return __assign(__assign({}, merged), (_c = {}, _c[currKey] = [merged[currKey], currValue], _c));
return Object.assign(Object.assign({}, merged), { [currKey]: [merged[currKey], currValue] });
}
// not exist
return __assign(__assign({}, merged), (_d = {}, _d[currKey] = currValue, _d));
}, ObjB);
return Object.assign(Object.assign({}, merged), { [currKey]: currValue });
}, objB);
};
exports.mergeObjectDupKeyArray = mergeObjectDupKeyArray;
var getDAVAttribute = function (nsArr) {
return nsArr.reduce(function (prev, curr) {
var _a;
return (__assign(__assign({}, prev), (_a = {}, _a[consts_1.DAVAttributeMap[curr]] = curr, _a)));
}, {});
};
const getDAVAttribute = (nsArr) => nsArr.reduce((prev, curr) => (Object.assign(Object.assign({}, prev), { [consts_1.DAVAttributeMap[curr]]: curr })), {});
exports.getDAVAttribute = getDAVAttribute;
var formatProps = function (props) {
return props === null || props === void 0 ? void 0 : props.reduce(function (prev, curr) {
var _a, _b;
var _c, _d;
if (curr.namespace) {
return __assign(__assign({}, prev), (_a = {}, _a[consts_1.DAVNamespaceShorthandMap[curr.namespace] + ":" + curr.name] = (_c = curr.value) !== null && _c !== void 0 ? _c : {}, _a));
}
return __assign(__assign({}, prev), (_b = {}, _b["" + curr.name] = (_d = curr.value) !== null && _d !== void 0 ? _d : {}, _b));
}, {});
};
const formatProps = (props) => props === null || props === void 0 ? void 0 : props.reduce((prev, curr) => {
var _a, _b;
if (curr.namespace) {
return Object.assign(Object.assign({}, prev), { [`${consts_1.DAVNamespaceShorthandMap[curr.namespace]}:${curr.name}`]: (_a = curr.value) !== null && _a !== void 0 ? _a : {} });
}
return Object.assign(Object.assign({}, prev), { [`${curr.name}`]: (_b = curr.value) !== null && _b !== void 0 ? _b : {} });
}, {});
exports.formatProps = formatProps;
var formatFilters = function (filters) {
return filters === null || filters === void 0 ? void 0 : filters.map(function (f) {
var _a;
var _b, _c;
return (_a = {},
_a[f.type] = __assign(__assign({ _attributes: f.attributes }, (_b = (f.children ? exports.formatFilters(f.children) : [])) === null || _b === void 0 ? void 0 : _b.reduce(function (prev, curr) { return exports.mergeObjectDupKeyArray(prev, curr); }, {})), { _text: (_c = f.value) !== null && _c !== void 0 ? _c : '' }),
_a);
const formatFilters = (filters) => filters === null || filters === void 0 ? void 0 : filters.map((f) => {
var _a, _b;
return ({
[f.type]: Object.assign(Object.assign({ _attributes: f.attributes }, (_a = (f.children ? exports.formatFilters(f.children) : [])) === null || _a === void 0 ? void 0 : _a.reduce((prev, curr) => exports.mergeObjectDupKeyArray(prev, curr), {})), { _text: (_b = f.value) !== null && _b !== void 0 ? _b : '' }),
});
};
});
exports.formatFilters = formatFilters;
var cleanupFalsy = function (obj) {
return Object.entries(obj).reduce(function (prev, _a) {
var _b;
var key = _a[0], value = _a[1];
if (value)
return __assign(__assign({}, prev), (_b = {}, _b[key] = value, _b));
return prev;
}, {});
};
const cleanupFalsy = (obj) => Object.entries(obj).reduce((prev, [key, value]) => {
if (value)
return Object.assign(Object.assign({}, prev), { [key]: value });
return prev;
}, {});
exports.cleanupFalsy = cleanupFalsy;
//# sourceMappingURL=requestHelpers.js.map
{
"name": "tsdav",
"version": "1.0.6",
"version": "1.1.0",
"description": "WebDAV, CALDAV, and CARDDAV client for Nodejs and the Browser",

@@ -26,15 +26,18 @@ "keywords": [

"author": "linlilulll@gmail.com",
"main": "dist/index.js",
"module": "dist/index.js",
"main": "dist",
"module": "dist-esm",
"types": "dist/index.d.ts",
"files": [
"dist",
"dist-esm",
"package.json"
],
"scripts": {
"clean": "rimraf dist*",
"typecheck": "tsc --noEmit",
"lint": "eslint src",
"lint": "eslint src --ext .ts",
"lintFix": "eslint src --ext .ts --fix",
"test": "jest",
"prepublishOnly": "yarn build",
"build": "rimraf dist && tsc -p ./tsconfig.build.json && copyfiles package.json LICENSE README.md ./dist",
"build": "yarn -s clean && tsc -p tsconfig.cjs.json && tsc -p tsconfig.esm.json && copyfiles package.json LICENSE README.md ./dist && copyfiles package.json LICENSE README.md ./dist-esm",
"watch": "tsc --watch --outDir ./dist"

@@ -51,7 +54,7 @@ },

"@types/debug": "^4.1.7",
"@types/jest": "^26.0.24",
"@types/node": "^16.4.13",
"@typescript-eslint/eslint-plugin": "^4.29.0",
"@typescript-eslint/parser": "^4.29.0",
"concurrently": "^6.2.0",
"@types/jest": "^27.0.1",
"@types/node": "^16.7.1",
"@typescript-eslint/eslint-plugin": "^4.29.2",
"@typescript-eslint/parser": "4.29.2",
"concurrently": "^6.2.1",
"copyfiles": "^2.4.1",

@@ -61,6 +64,7 @@ "cross-env": "^7.0.3",

"eslint": "^7.32.0",
"eslint-config-airbnb-typescript": "^12.3.1",
"eslint-config-airbnb": "18.2.1",
"eslint-config-airbnb-typescript": "^13.0.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-import": "^2.23.4",
"eslint-plugin-prettier": "^3.4.0",
"eslint-plugin-import": "^2.24.1",
"eslint-plugin-prettier": "^3.4.1",
"jest": "^27.0.6",

@@ -70,3 +74,3 @@ "prettier": "^2.3.2",

"sort-package-json": "1.50.0",
"ts-jest": "27.0.4",
"ts-jest": "27.0.5",
"typescript": "^4.3.5"

@@ -73,0 +77,0 @@ },

@@ -27,2 +27,3 @@ <p align="center">

- Works in both `Browsers` and `Node.js`
- Supports Both `commonjs` and `esm`
- OAuth2 & Basic Auth helpers built-in

@@ -53,3 +54,3 @@ - Native typescript, fully linted and well tested

(async () => {
const googleClient = await createDAVClient({
const client = await createDAVClient({
serverUrl: 'https://apidata.googleusercontent.com/caldav/v2/',

@@ -95,2 +96,55 @@ credentials: {

After `v1.1.0`, you have a new way of creating clients.
##### Google CALDAV
```ts
import { DAVClient } from 'tsdav';
const client = new DAVClient({
serverUrl: 'https://apidata.googleusercontent.com/caldav/v2/',
credentials: {
refreshToken: 'YOUR_REFRESH_TOKEN_WITH_CALDAV_PERMISSION',
},
authMethod: 'Oauth',
defaultAccountType: 'caldav',
});
(async () => {
await googleClient.login();
const calendars = await client.fetchCalendars();
const calendarObjects = await client.fetchCalendarObjects({
calendar: calendars[0],
});
})();
```
##### Apple CARDDAV
```ts
import { DAVClient } from 'tsdav';
const client = new DAVClient({
serverUrl: 'https://contacts.icloud.com',
credentials: {
username: 'YOUR_APPLE_ID',
password: 'YOUR_APP_SPECIFIC_PASSWORD',
},
authMethod: 'Basic',
defaultAccountType: 'carddav',
});
(async () => {
await client.login();
const addressBooks = await client.fetchAddressBooks();
const vcards = await client.fetchVCards({
addressBook: addressBooks[0],
});
})();
```
### Documentation

@@ -106,10 +160,9 @@

### RELEASE NOTES
### Changelog
##### v1.0.6
refers to [Changelog](./CHANGELOG.md)
Fixed a bug where timeRange filter sometimes might be in the wrong format.
### Debugging
##### v1.0.3
Fixed a bug where calendar objects with `http` in its id would cause operations on it to fail.
this package uses `debug` package,
add `tsdav:*` to `DEBUG` env variable to enable debug logs

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc