File size: 7,357 Bytes
3246b69 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 | /**
* WebDAV API helper
*
* Uses only Fetch/Web APIs so it works in Cloudflare Pages Functions,
* Cloudflare Workers, and the local Node-based test/runtime paths.
*/
export class WebDAVAPI {
constructor(config = {}) {
const baseUrl = config.baseUrl;
if (!baseUrl) {
throw new Error('WebDAV baseUrl is required');
}
this.baseUrl = normalizeBaseUrl(baseUrl);
this.username = config.username || '';
this.password = config.password || '';
this.headers = normalizeHeaders(config.headers || {});
this.createDirectory = config.createDirectory !== false;
}
buildObjectUrl(path) {
return buildWebDAVUrl(this.baseUrl, path);
}
buildPublicUrl(path, publicUrl = '') {
if (!publicUrl) return '';
return buildWebDAVUrl(normalizeBaseUrl(publicUrl), path);
}
getRequestHeaders(extraHeaders = {}) {
const headers = new Headers(this.headers);
if ((this.username || this.password) && !headers.has('Authorization')) {
headers.set('Authorization', `Basic ${base64EncodeUtf8(`${this.username}:${this.password}`)}`);
}
for (const [key, value] of Object.entries(extraHeaders || {})) {
if (value !== undefined && value !== null && value !== '') {
headers.set(key, value);
}
}
return headers;
}
async ensureDirectory(path) {
if (!this.createDirectory) return;
const dirParts = getDirectoryParts(path);
if (dirParts.length === 0) return;
let currentPath = '';
for (const part of dirParts) {
currentPath = currentPath ? `${currentPath}/${part}` : part;
const response = await fetch(this.buildObjectUrl(currentPath), {
method: 'MKCOL',
headers: this.getRequestHeaders(),
redirect: 'manual',
});
// 405 commonly means the collection already exists. Some servers return 200/204.
if (![200, 201, 204, 405].includes(response.status)) {
throw new Error(`WebDAV MKCOL failed for ${currentPath}: ${response.status} ${response.statusText}`);
}
}
}
async putFile(path, body, contentType = '') {
await this.ensureDirectory(path);
const headers = this.getRequestHeaders(contentType ? { 'Content-Type': contentType } : {});
const response = await fetch(this.buildObjectUrl(path), {
method: 'PUT',
headers,
body,
redirect: 'manual',
});
if (!isSuccessStatus(response.status)) {
const detail = await safeReadResponseText(response);
throw new Error(`WebDAV PUT failed: ${response.status} ${response.statusText}${detail ? ` - ${detail}` : ''}`);
}
return response;
}
async getFile(path, options = {}) {
const response = await fetch(this.buildObjectUrl(path), {
method: options.method || 'GET',
headers: this.getRequestHeaders(options.headers || {}),
redirect: 'manual',
});
if (!isSuccessStatus(response.status) && response.status !== 304) {
const detail = await safeReadResponseText(response);
throw new Error(`WebDAV ${options.method || 'GET'} failed: ${response.status} ${response.statusText}${detail ? ` - ${detail}` : ''}`);
}
return response;
}
async moveFile(oldPath, newPath, overwrite = true) {
await this.ensureDirectory(newPath);
const response = await fetch(this.buildObjectUrl(oldPath), {
method: 'MOVE',
headers: this.getRequestHeaders({
Destination: this.buildObjectUrl(newPath),
Overwrite: overwrite ? 'T' : 'F',
}),
redirect: 'manual',
});
if (!isSuccessStatus(response.status)) {
const detail = await safeReadResponseText(response);
throw new Error(`WebDAV MOVE failed: ${response.status} ${response.statusText}${detail ? ` - ${detail}` : ''}`);
}
return true;
}
async deleteFile(path) {
const response = await fetch(this.buildObjectUrl(path), {
method: 'DELETE',
headers: this.getRequestHeaders(),
redirect: 'manual',
});
// DELETE is idempotent for app semantics; a missing remote object should not block DB cleanup.
if (response.status === 404) return true;
if (!isSuccessStatus(response.status)) {
const detail = await safeReadResponseText(response);
throw new Error(`WebDAV DELETE failed: ${response.status} ${response.statusText}${detail ? ` - ${detail}` : ''}`);
}
return true;
}
}
export function normalizeBaseUrl(baseUrl) {
const normalized = String(baseUrl || '').trim();
if (!normalized) {
throw new Error('WebDAV baseUrl is required');
}
const url = new URL(normalized);
if (!['http:', 'https:'].includes(url.protocol)) {
throw new Error('WebDAV baseUrl must use http or https');
}
if (!url.pathname.endsWith('/')) {
url.pathname = `${url.pathname}/`;
}
return url.toString();
}
export function buildWebDAVUrl(baseUrl, path) {
const cleanPath = String(path || '')
.replace(/^\/+/, '')
.split('/')
.filter(Boolean)
.map(encodeURIComponent)
.join('/');
return new URL(cleanPath, normalizeBaseUrl(baseUrl)).toString();
}
export function normalizeWebDAVHeaders(headers) {
return normalizeHeaders(headers);
}
function getDirectoryParts(path) {
const parts = String(path || '').replace(/^\/+/, '').split('/').filter(Boolean);
parts.pop();
return parts;
}
function normalizeHeaders(headers) {
if (!headers) return {};
if (typeof headers === 'string') {
try {
const parsed = JSON.parse(headers);
return normalizeHeaders(parsed);
} catch {
return {};
}
}
if (headers instanceof Headers) {
const result = {};
headers.forEach((value, key) => {
result[key] = value;
});
return result;
}
if (typeof headers === 'object' && !Array.isArray(headers)) {
const result = {};
for (const [key, value] of Object.entries(headers)) {
if (value !== undefined && value !== null && value !== '') {
result[key] = String(value);
}
}
return result;
}
return {};
}
function isSuccessStatus(status) {
return status >= 200 && status < 300;
}
async function safeReadResponseText(response) {
try {
const text = await response.text();
return text.slice(0, 500);
} catch {
return '';
}
}
function base64EncodeUtf8(value) {
const bytes = new TextEncoder().encode(value);
let binary = '';
const chunkSize = 0x8000;
for (let i = 0; i < bytes.length; i += chunkSize) {
binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
}
if (typeof btoa === 'function') {
return btoa(binary);
}
// Node-based local tests/runtimes.
return Buffer.from(value, 'utf8').toString('base64');
}
|