@poe-platform/safe-fs 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +290 -0
  3. package/dist/safe-fs/bridge/confinement.d.ts +3 -0
  4. package/dist/safe-fs/bridge/confinement.js +171 -0
  5. package/dist/safe-fs/bridge/filesystem.d.ts +88 -0
  6. package/dist/safe-fs/bridge/filesystem.js +411 -0
  7. package/dist/safe-fs/bridge/index.d.ts +6 -0
  8. package/dist/safe-fs/bridge/index.js +18 -0
  9. package/dist/safe-fs/bridge/stats.d.ts +4 -0
  10. package/dist/safe-fs/bridge/stats.js +37 -0
  11. package/dist/safe-fs/bridge/types.d.ts +75 -0
  12. package/dist/safe-fs/bridge/types.js +1 -0
  13. package/dist/safe-fs/bridge/values.d.ts +6 -0
  14. package/dist/safe-fs/bridge/values.js +65 -0
  15. package/dist/safe-fs/config/memory.d.ts +3 -0
  16. package/dist/safe-fs/config/memory.js +9 -0
  17. package/dist/safe-fs/config/real.d.ts +5 -0
  18. package/dist/safe-fs/config/real.js +16 -0
  19. package/dist/safe-fs/config.d.ts +15 -0
  20. package/dist/safe-fs/config.js +46 -0
  21. package/dist/safe-fs/config.node.d.ts +2 -0
  22. package/dist/safe-fs/config.node.js +22 -0
  23. package/dist/safe-fs/contracts/abort.d.ts +5 -0
  24. package/dist/safe-fs/contracts/abort.js +34 -0
  25. package/dist/safe-fs/contracts/cleanup.d.ts +1 -0
  26. package/dist/safe-fs/contracts/cleanup.js +9 -0
  27. package/dist/safe-fs/contracts/errors.d.ts +50 -0
  28. package/dist/safe-fs/contracts/errors.js +77 -0
  29. package/dist/safe-fs/contracts/filesystem.d.ts +96 -0
  30. package/dist/safe-fs/contracts/filesystem.js +1 -0
  31. package/dist/safe-fs/contracts/index.d.ts +4 -0
  32. package/dist/safe-fs/contracts/index.js +4 -0
  33. package/dist/safe-fs/contracts/io.d.ts +8 -0
  34. package/dist/safe-fs/contracts/io.js +92 -0
  35. package/dist/safe-fs/contracts/path.d.ts +8 -0
  36. package/dist/safe-fs/contracts/path.js +8 -0
  37. package/dist/safe-fs/contracts/portable-path.d.ts +13 -0
  38. package/dist/safe-fs/contracts/portable-path.js +57 -0
  39. package/dist/safe-fs/contracts/virtual-path.d.ts +7 -0
  40. package/dist/safe-fs/contracts/virtual-path.js +66 -0
  41. package/dist/safe-fs/core.d.ts +12 -0
  42. package/dist/safe-fs/core.js +12 -0
  43. package/dist/safe-fs/fs/memory/index.d.ts +58 -0
  44. package/dist/safe-fs/fs/memory/index.js +532 -0
  45. package/dist/safe-fs/fs/mount/comparison.d.ts +19 -0
  46. package/dist/safe-fs/fs/mount/comparison.js +118 -0
  47. package/dist/safe-fs/fs/mount/identity.d.ts +2 -0
  48. package/dist/safe-fs/fs/mount/identity.js +12 -0
  49. package/dist/safe-fs/fs/mount/index.d.ts +44 -0
  50. package/dist/safe-fs/fs/mount/index.js +546 -0
  51. package/dist/safe-fs/fs/overlay/index.d.ts +73 -0
  52. package/dist/safe-fs/fs/overlay/index.js +927 -0
  53. package/dist/safe-fs/fs/readonly/index.d.ts +31 -0
  54. package/dist/safe-fs/fs/readonly/index.js +128 -0
  55. package/dist/safe-fs/fs/real/allocation.d.ts +1 -0
  56. package/dist/safe-fs/fs/real/allocation.js +8 -0
  57. package/dist/safe-fs/fs/real/index.d.ts +76 -0
  58. package/dist/safe-fs/fs/real/index.js +543 -0
  59. package/dist/safe-fs/fs/s3/authority.d.ts +7 -0
  60. package/dist/safe-fs/fs/s3/authority.js +31 -0
  61. package/dist/safe-fs/fs/s3/filesystem.d.ts +93 -0
  62. package/dist/safe-fs/fs/s3/filesystem.js +1024 -0
  63. package/dist/safe-fs/fs/s3/http/index.d.ts +2 -0
  64. package/dist/safe-fs/fs/s3/http/index.js +1 -0
  65. package/dist/safe-fs/fs/s3/http/request.d.ts +16 -0
  66. package/dist/safe-fs/fs/s3/http/request.js +196 -0
  67. package/dist/safe-fs/fs/s3/http/signature.d.ts +20 -0
  68. package/dist/safe-fs/fs/s3/http/signature.js +74 -0
  69. package/dist/safe-fs/fs/s3/http/transport.d.ts +3 -0
  70. package/dist/safe-fs/fs/s3/http/transport.js +455 -0
  71. package/dist/safe-fs/fs/s3/http/types.d.ts +30 -0
  72. package/dist/safe-fs/fs/s3/http/types.js +1 -0
  73. package/dist/safe-fs/fs/s3/http/xml.d.ts +11 -0
  74. package/dist/safe-fs/fs/s3/http/xml.js +188 -0
  75. package/dist/safe-fs/fs/s3/index.d.ts +6 -0
  76. package/dist/safe-fs/fs/s3/index.js +3 -0
  77. package/dist/safe-fs/fs/s3/mock.d.ts +48 -0
  78. package/dist/safe-fs/fs/s3/mock.js +233 -0
  79. package/dist/safe-fs/fs/s3/registry.d.ts +10 -0
  80. package/dist/safe-fs/fs/s3/registry.js +71 -0
  81. package/dist/safe-fs/fs/s3/transport.d.ts +103 -0
  82. package/dist/safe-fs/fs/s3/transport.js +28 -0
  83. package/dist/safe-fs/fs/webdav/index.d.ts +2 -0
  84. package/dist/safe-fs/fs/webdav/index.js +1 -0
  85. package/dist/safe-fs/fs/webdav/resource-id.d.ts +18 -0
  86. package/dist/safe-fs/fs/webdav/resource-id.js +109 -0
  87. package/dist/safe-fs/fs/webdav/webdav.d.ts +101 -0
  88. package/dist/safe-fs/fs/webdav/webdav.js +1226 -0
  89. package/dist/safe-fs/fs/webdav/xml.d.ts +15 -0
  90. package/dist/safe-fs/fs/webdav/xml.js +250 -0
  91. package/dist/safe-fs/index.d.ts +14 -0
  92. package/dist/safe-fs/index.js +12 -0
  93. package/dist/safe-fs/node/filesystem.d.ts +11 -0
  94. package/dist/safe-fs/node/filesystem.js +28 -0
  95. package/dist/safe-fs/node/index.d.ts +2 -0
  96. package/dist/safe-fs/node/index.js +1 -0
  97. package/dist/safe-fs/node/stats.d.ts +1 -0
  98. package/dist/safe-fs/node/stats.js +1 -0
  99. package/dist/safe-fs/node/values.d.ts +1 -0
  100. package/dist/safe-fs/node/values.js +1 -0
  101. package/dist/safe-fs/node-host.d.ts +1 -0
  102. package/dist/safe-fs/node-host.js +1 -0
  103. package/dist/safe-fs/node-unavailable.d.ts +1 -0
  104. package/dist/safe-fs/node-unavailable.js +1 -0
  105. package/dist/safe-fs/platform/browser.d.ts +12 -0
  106. package/dist/safe-fs/platform/browser.js +39 -0
  107. package/dist/safe-fs/platform/node.d.ts +13 -0
  108. package/dist/safe-fs/platform/node.js +26 -0
  109. package/package.json +108 -0
@@ -0,0 +1,1226 @@
1
+ import { FsError, isErrnoCode, isFsError } from "../../contracts/errors.js";
2
+ import { composeAbortSignals } from "../../contracts/abort.js";
3
+ import { readBytes } from "../../contracts/io.js";
4
+ import { davChild, davChildren, parseXml, scalar } from "./xml.js";
5
+ import { assertCallbackAuthorityAllowed, compareEntries, registerEntryAuthority } from "../mount/comparison.js";
6
+ import { compareWebDavResources, ownedResponseIdentifier, recordOwnedResourceStat, registerResourceQuery, resourceIdentifier } from "./resource-id.js";
7
+ const timestampNamespace = "urn:virtual-bash:metadata";
8
+ const propfindBody = '<?xml version="1.0" encoding="utf-8"?>'
9
+ + '<d:propfind xmlns:d="DAV:"><d:prop><d:resourcetype/><d:getcontentlength/>'
10
+ + `<d:getlastmodified/><d:creationdate/><d:getetag/><v:timestamps xmlns:v="${timestampNamespace}"/></d:prop></d:propfind>`;
11
+ const lockBody = '<d:lockinfo xmlns:d="DAV:"><d:lockscope><d:exclusive/></d:lockscope>'
12
+ + '<d:locktype><d:write/></d:locktype></d:lockinfo>';
13
+ const resourceIdBody = '<?xml version="1.0" encoding="utf-8"?>'
14
+ + '<d:propfind xmlns:d="DAV:"><d:prop><d:resource-id/></d:prop></d:propfind>';
15
+ function fail(code, syscall, path, message) {
16
+ throw new FsError(code, { syscall, path, ...(message === undefined ? {} : { message }) });
17
+ }
18
+ function positive(value, name, zero = false) {
19
+ if (!Number.isSafeInteger(value) || value < (zero ? 0 : 1)) {
20
+ throw new FsError("EINVAL", { message: `${name} must be a ${zero ? "nonnegative" : "positive"} safe integer` });
21
+ }
22
+ return value;
23
+ }
24
+ function createRequestTimeout(timeoutMs) {
25
+ const controller = new AbortController();
26
+ const timer = setTimeout(() => {
27
+ controller.abort(new DOMException("The operation was aborted due to timeout", "TimeoutError"));
28
+ }, timeoutMs);
29
+ if (typeof timer === "object" && timer !== null) {
30
+ const handle = timer;
31
+ handle.unref?.();
32
+ }
33
+ return {
34
+ signal: controller.signal,
35
+ dispose() {
36
+ clearTimeout(timer);
37
+ }
38
+ };
39
+ }
40
+ function nativeRequestStreamsSupported(url) {
41
+ let body;
42
+ try {
43
+ body = new ReadableStream({ start(destination) { destination.close(); } });
44
+ let duplexAccessed = false;
45
+ const init = {
46
+ method: "PUT", body,
47
+ get duplex() { duplexAccessed = true; return "half"; },
48
+ };
49
+ const request = new Request(url, init);
50
+ return duplexAccessed && !request.headers.has("Content-Type");
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ finally {
56
+ if (body && !body.locked)
57
+ void body.cancel().catch(() => { });
58
+ }
59
+ }
60
+ function strongEtag(value, path) {
61
+ if (!value || !/^"[\x21\x23-\x7e\x80-\xff]*"$/.test(value)) {
62
+ fail("ENOTSUP", "webdav", path, "operation requires a strong entity tag");
63
+ }
64
+ return value;
65
+ }
66
+ function normalize(path) {
67
+ if (typeof path !== "string" || path.includes("\0") || path.includes("\\")) {
68
+ fail("EINVAL", "resolve", String(path), "invalid WebDAV path");
69
+ }
70
+ try {
71
+ encodeURIComponent(path);
72
+ }
73
+ catch {
74
+ fail("EINVAL", "resolve", path, "path contains an unpaired surrogate");
75
+ }
76
+ const segments = [];
77
+ for (const segment of path.split("/")) {
78
+ if (!segment || segment === ".")
79
+ continue;
80
+ if (segment === "..") {
81
+ if (!segments.length)
82
+ fail("EACCES", "resolve", path, "path escapes WebDAV root");
83
+ segments.pop();
84
+ }
85
+ else
86
+ segments.push(segment);
87
+ }
88
+ return `/${segments.join("/")}`;
89
+ }
90
+ function validateDirectoryAccessPath(path) {
91
+ if (typeof path !== "string")
92
+ fail("EINVAL", "resolve", String(path), "invalid WebDAV path");
93
+ let bytes = 0;
94
+ let components = 0;
95
+ let inComponent = false;
96
+ for (let offset = 0; offset < path.length; offset++) {
97
+ const point = path.codePointAt(offset);
98
+ if (point === 47)
99
+ inComponent = false;
100
+ else if (!inComponent) {
101
+ components++;
102
+ inComponent = true;
103
+ }
104
+ bytes += point <= 0x7f ? 1 : point <= 0x7ff ? 2 : point <= 0xffff ? 3 : 4;
105
+ if (point > 0xffff)
106
+ offset++;
107
+ if (bytes > 65_536 || components > 256) {
108
+ fail("ENAMETOOLONG", "access", path, "directory access exceeds the 64KiB path or 256 component limit");
109
+ }
110
+ }
111
+ }
112
+ function requiresCollection(path) {
113
+ const last = path.split("/").at(-1);
114
+ return last === "" || last === "." || last === "..";
115
+ }
116
+ function validateUrlText(text) {
117
+ if (/[\u0000-\u0020\u007f\\?#]/.test(text))
118
+ throw new Error("invalid URL characters");
119
+ for (const segment of text.split("/")) {
120
+ const decoded = decodeURIComponent(segment);
121
+ if (decoded === "." || decoded === ".." || /[/\\\u0000]/.test(decoded)) {
122
+ throw new Error("ambiguous URL segment");
123
+ }
124
+ }
125
+ }
126
+ function urlSegments(url) {
127
+ const pathname = url.pathname.endsWith("/") ? url.pathname.slice(0, -1) : url.pathname;
128
+ const segments = pathname.slice(1).split("/");
129
+ if (segments.length === 1 && segments[0] === "")
130
+ return [];
131
+ if (segments.some((segment) => segment === ""))
132
+ throw new Error("empty URL segment");
133
+ return segments.map((segment) => decodeURIComponent(segment));
134
+ }
135
+ function statusCode(element) {
136
+ const text = scalar(element);
137
+ if (!/^HTTP\/\d+\.\d+ [2-5]\d\d(?:[ \t].*)?$/.test(text))
138
+ throw new Error("invalid DAV status line");
139
+ return Number(text.split(" ")[1]);
140
+ }
141
+ export class WebDavFileSystem {
142
+ capabilities = Object.freeze({
143
+ symlinks: false, hardlinks: false, permissions: false, timestamps: true,
144
+ atomicRename: false, streamingRead: true, streamingWrite: true,
145
+ });
146
+ base;
147
+ baseSegments;
148
+ transport;
149
+ requestStreamSupport;
150
+ headers;
151
+ maxResponseBytes;
152
+ maxXmlBytes;
153
+ maxEntries;
154
+ timeoutMs;
155
+ overwritePolicy;
156
+ configuredComparison;
157
+ atomicEmptyDirectory;
158
+ etags = new WeakMap();
159
+ constructor(options) {
160
+ if (typeof options.fetch !== "function")
161
+ throw new FsError("EINVAL", { message: "an explicit fetch transport is required" });
162
+ if (options.requestStreamSupport !== undefined && options.requestStreamSupport !== "native"
163
+ && typeof options.requestStreamSupport !== "boolean") {
164
+ throw new FsError("EINVAL", { message: "requestStreamSupport must be native or a boolean" });
165
+ }
166
+ if (options.compareEntry !== undefined && typeof options.compareEntry !== "function") {
167
+ throw new FsError("EINVAL", { message: "compareEntry must be a function" });
168
+ }
169
+ if (options.compareEntry !== undefined)
170
+ assertCallbackAuthorityAllowed();
171
+ try {
172
+ validateUrlText(options.baseUrl);
173
+ this.base = new URL(options.baseUrl);
174
+ if (!["http:", "https:"].includes(this.base.protocol) || this.base.username || this.base.password
175
+ || this.base.search || this.base.hash)
176
+ throw new Error("invalid base URL");
177
+ this.baseSegments = urlSegments(this.base);
178
+ this.base.pathname = `/${this.baseSegments.map(encodeURIComponent).join("/")}${this.baseSegments.length ? "/" : ""}`;
179
+ this.headers = new Headers(options.headers);
180
+ for (const name of this.headers.keys()) {
181
+ if (["host", "destination", "depth", "overwrite", "if", "if-match", "if-none-match", "range",
182
+ "content-length", "content-type", "transfer-encoding", "connection", "proxy-authorization", "lock-token", "timeout"].includes(name)) {
183
+ throw new Error(`reserved header ${name}`);
184
+ }
185
+ }
186
+ if (this.base.protocol !== "https:" && [...this.headers.keys()].some((name) => name === "authorization" || name === "cookie")) {
187
+ throw new Error("explicit credentials require HTTPS");
188
+ }
189
+ }
190
+ catch (cause) {
191
+ throw new FsError("EINVAL", { message: "invalid WebDAV base URL or headers", cause });
192
+ }
193
+ const binding = options.atomicEmptyDirectory;
194
+ if (binding !== undefined) {
195
+ if (!binding || typeof binding !== "object" || binding.namespaceUrl !== this.base.href
196
+ || typeof binding.removeEmptyDirectory !== "function") {
197
+ throw new FsError("EINVAL", { message: "atomicEmptyDirectory must bind the canonical WebDAV namespace and a callback" });
198
+ }
199
+ this.atomicEmptyDirectory = Object.freeze({ namespaceUrl: this.base.href, removeEmptyDirectory: binding.removeEmptyDirectory });
200
+ }
201
+ this.transport = options.fetch === globalThis.fetch ? options.fetch.bind(globalThis) : options.fetch;
202
+ this.requestStreamSupport = options.requestStreamSupport ?? (options.fetch === globalThis.fetch ? "native" : false);
203
+ this.maxResponseBytes = positive(options.maxResponseBytes ?? 64 * 1024 * 1024, "maxResponseBytes");
204
+ this.maxXmlBytes = positive(options.maxXmlBytes ?? 2 * 1024 * 1024, "maxXmlBytes");
205
+ this.maxEntries = positive(options.maxEntries ?? 10_000, "maxEntries");
206
+ this.timeoutMs = positive(options.timeoutMs ?? 30_000, "timeoutMs");
207
+ this.overwritePolicy = options.overwritePolicy ?? "lock";
208
+ this.configuredComparison = options.compareEntry !== undefined;
209
+ if (!["lock", "etag"].includes(this.overwritePolicy))
210
+ throw new FsError("EINVAL", { message: "invalid overwritePolicy" });
211
+ if (this.timeoutMs > 2_147_483_647)
212
+ throw new FsError("EINVAL", { message: "timeoutMs exceeds timer range" });
213
+ registerResourceQuery(this, (path, settings) => this.resourceId(path, settings), originalWebDavComparison, options.compareEntry);
214
+ registerEntryAuthority(this, compareWebDavResources);
215
+ }
216
+ compareEntry(path, peer, peerPath, options = {}) {
217
+ return compareEntries(this, path, peer, peerPath, options);
218
+ }
219
+ async resourceId(input, options) {
220
+ const path = normalize(input);
221
+ return this.request("PROPFIND", path, options, {
222
+ headers: { Depth: "0", "Content-Type": "application/xml; charset=utf-8" }, body: resourceIdBody,
223
+ }, async (response, signal) => {
224
+ if (response.status !== 207)
225
+ this.httpError(response.status, "PROPFIND", path);
226
+ const responses = await this.multistatus(response, signal, "PROPFIND", path);
227
+ if (responses.length !== 1)
228
+ throw new Error("resource identity requires exactly one DAV:response");
229
+ const entry = responses[0];
230
+ const href = davChild(entry, "href");
231
+ if (!href)
232
+ throw new Error("missing resource identity response href");
233
+ if (this.hrefPath(scalar(href)) !== path)
234
+ fail("EACCES", "PROPFIND", path, "resource identity response addresses another resource");
235
+ const wholeStatus = davChild(entry, "status");
236
+ const propstats = davChildren(entry, "propstat");
237
+ if (wholeStatus) {
238
+ if (propstats.length)
239
+ throw new Error("conflicting response status and propstat");
240
+ this.httpError(statusCode(wholeStatus), "PROPFIND", path);
241
+ }
242
+ if (propstats.length === 0)
243
+ throw new Error("missing resource identity propstat");
244
+ let seen = false;
245
+ let identifier;
246
+ for (const propstat of propstats) {
247
+ const status = davChild(propstat, "status");
248
+ const prop = davChild(propstat, "prop");
249
+ if (!status || !prop)
250
+ throw new Error("incomplete resource identity propstat");
251
+ const code = statusCode(status);
252
+ if (code !== 200 && code !== 404)
253
+ this.httpError(code, "PROPFIND", path);
254
+ for (const property of davChildren(prop, "resource-id")) {
255
+ if (seen)
256
+ throw new Error("duplicate or conflicting resource identity property");
257
+ seen = true;
258
+ if (code === 404)
259
+ continue;
260
+ const value = davChild(property, "href");
261
+ if (!value || property.children.length !== 1 || property.text.trim())
262
+ throw new Error("invalid resource identity property");
263
+ identifier = resourceIdentifier(scalar(value));
264
+ }
265
+ }
266
+ const owned = ownedResponseIdentifier(response, path);
267
+ if (owned !== undefined && identifier !== undefined && resourceIdentifier(owned) !== identifier) {
268
+ throw new Error("resource identity contradicts provider provenance");
269
+ }
270
+ return identifier;
271
+ });
272
+ }
273
+ url(path, collection = false) {
274
+ const relative = path.slice(1).split("/").map(encodeURIComponent).join("/");
275
+ return `${this.base.href}${relative}${collection && relative ? "/" : ""}`;
276
+ }
277
+ hrefPath(href) {
278
+ try {
279
+ validateUrlText(href);
280
+ if (!(href.startsWith("/") && !href.startsWith("//")) && !/^https?:\/\//i.test(href))
281
+ throw new Error("href must be absolute");
282
+ const url = new URL(href, this.base);
283
+ if (url.origin !== this.base.origin || url.username || url.password || url.search || url.hash)
284
+ throw new Error("href is not confined");
285
+ const segments = urlSegments(url);
286
+ if (segments.length < this.baseSegments.length || this.baseSegments.some((segment, index) => segments[index] !== segment)) {
287
+ throw new Error("href escapes root");
288
+ }
289
+ return normalize(`/${segments.slice(this.baseSegments.length).join("/")}`);
290
+ }
291
+ catch (cause) {
292
+ throw new FsError("EACCES", { syscall: "webdav", message: "response URL escapes or ambiguously addresses WebDAV root", cause });
293
+ }
294
+ }
295
+ httpError(status, method, path, exclusive = false) {
296
+ const codes = {
297
+ 400: "EINVAL", 401: "EACCES", 403: "EACCES", 404: "ENOENT", 405: method === "MKCOL" ? "EEXIST" : "ENOTSUP",
298
+ 408: "ETIMEDOUT", 409: method === "PUT" || method === "MKCOL" ? "ENOENT" : "EINVAL", 410: "ENOENT",
299
+ 412: exclusive ? "EEXIST" : "EAGAIN", 413: "EFBIG", 414: "ENAMETOOLONG", 415: "ENOTSUP",
300
+ 423: "EBUSY", 429: "EAGAIN", 501: "ENOTSUP", 503: "EAGAIN", 504: "ETIMEDOUT", 507: "ENOSPC",
301
+ };
302
+ fail(status >= 300 && status < 400 ? "ENOTSUP" : codes[status] ?? "EIO", method, path, status >= 300 && status < 400 ? "WebDAV redirects are not followed" : `WebDAV HTTP status ${status}`);
303
+ }
304
+ async request(method, path, options, init, consume, collection = false, received) {
305
+ for await (const result of this.requestStream(method, path, options, init, async function* (response, signal) {
306
+ yield await consume(response, signal);
307
+ }, collection, received))
308
+ return result;
309
+ throw new Error("missing WebDAV response");
310
+ }
311
+ async *requestStream(method, path, options, init, consume, collection = false, received) {
312
+ if (options.signal?.aborted)
313
+ fail("ECANCELED", method, path);
314
+ const deadline = createRequestTimeout(this.timeoutMs);
315
+ const timeout = deadline.signal;
316
+ try {
317
+ const headers = new Headers(this.headers);
318
+ for (const [name, value] of new Headers(init.headers))
319
+ headers.set(name, value);
320
+ headers.set("Cache-Control", "no-cache");
321
+ const signalScope = options.signal ? composeAbortSignals([timeout, options.signal]) : undefined;
322
+ const signal = signalScope?.signal ?? timeout;
323
+ let response;
324
+ const receive = (value, late) => {
325
+ if (value.redirected || value.type === "opaqueredirect")
326
+ fail("ENOTSUP", method, path, "transport followed or hid a redirect");
327
+ if (value.url && this.hrefPath(value.url) !== path)
328
+ fail("EACCES", method, path, "transport changed the requested resource");
329
+ received?.(value, late);
330
+ };
331
+ try {
332
+ let url = this.url(path, collection);
333
+ for (let attempt = 0;; attempt++) {
334
+ signal.throwIfAborted();
335
+ response = await new Promise((resolve, reject) => {
336
+ let abandoned = false;
337
+ const abort = () => {
338
+ abandoned = true;
339
+ signal.removeEventListener("abort", abort);
340
+ reject(signal.reason);
341
+ };
342
+ signal.addEventListener("abort", abort, { once: true });
343
+ try {
344
+ Promise.resolve(this.transport(url, {
345
+ ...init, method, headers, redirect: "manual", credentials: "omit", signal,
346
+ })).then((value) => {
347
+ signal.removeEventListener("abort", abort);
348
+ if (!abandoned)
349
+ resolve(value);
350
+ else {
351
+ try {
352
+ receive(value, true);
353
+ }
354
+ catch (ignoredError) {
355
+ void ignoredError;
356
+ }
357
+ finally {
358
+ if (value.body && !value.body.locked)
359
+ void value.body.cancel(signal.reason).catch(() => { });
360
+ }
361
+ }
362
+ }, (error) => {
363
+ signal.removeEventListener("abort", abort);
364
+ reject(error);
365
+ }).catch(reject);
366
+ }
367
+ catch (error) {
368
+ signal.removeEventListener("abort", abort);
369
+ reject(error);
370
+ }
371
+ });
372
+ receive(response, false);
373
+ signal.throwIfAborted();
374
+ const location = response.headers.get("Location");
375
+ if (attempt === 0 && method === "PROPFIND" && !url.endsWith("/")
376
+ && [301, 302, 307, 308].includes(response.status) && location !== null
377
+ && this.hrefPath(location) === path && new URL(location, this.base).href === `${url}/`) {
378
+ await response.body?.cancel();
379
+ signal.throwIfAborted();
380
+ url += "/";
381
+ continue;
382
+ }
383
+ yield* consume(response, signal);
384
+ return;
385
+ }
386
+ }
387
+ catch (cause) {
388
+ if (options.signal?.aborted)
389
+ throw new FsError("ECANCELED", { syscall: method, path, cause });
390
+ if (timeout.aborted)
391
+ throw new FsError("ETIMEDOUT", { syscall: method, path, cause });
392
+ if (isFsError(cause))
393
+ throw cause;
394
+ throw new FsError("EIO", { syscall: method, path, message: "WebDAV transport or response failure", cause });
395
+ }
396
+ finally {
397
+ signalScope?.dispose();
398
+ if (response?.body && !response.body.locked)
399
+ void response.body.cancel().catch(() => { });
400
+ }
401
+ }
402
+ finally {
403
+ deadline.dispose();
404
+ }
405
+ }
406
+ async bytes(response, limit, signal) {
407
+ const chunks = [];
408
+ let size = 0;
409
+ for await (const chunk of this.bodyChunks(response, limit, signal)) {
410
+ chunks.push(chunk);
411
+ size += chunk.byteLength;
412
+ }
413
+ const data = new Uint8Array(size);
414
+ let offset = 0;
415
+ for (const chunk of chunks) {
416
+ data.set(chunk, offset);
417
+ offset += chunk.byteLength;
418
+ }
419
+ return data;
420
+ }
421
+ async *bodyChunks(response, limit, signal) {
422
+ const length = response.headers.get("content-length");
423
+ if (length !== null && (!/^\d+$/.test(length) || !Number.isSafeInteger(Number(length)))) {
424
+ fail("EIO", "webdav", "", "invalid response Content-Length");
425
+ }
426
+ const encoding = response.headers.get("content-encoding");
427
+ const expected = length !== null && (!encoding || encoding.toLowerCase() === "identity") ? Number(length) : undefined;
428
+ if (expected !== undefined && expected > limit)
429
+ fail("EFBIG", "webdav", "", "response exceeds byte limit");
430
+ if (!response.body) {
431
+ if (expected !== undefined && expected !== 0)
432
+ fail("EIO", "webdav", "", "response body length differs from Content-Length");
433
+ return;
434
+ }
435
+ const reader = response.body.getReader();
436
+ let size = 0;
437
+ const abort = () => { void reader.cancel(signal.reason).catch(() => { }); };
438
+ signal.addEventListener("abort", abort, { once: true });
439
+ try {
440
+ while (true) {
441
+ signal.throwIfAborted();
442
+ const result = await reader.read();
443
+ signal.throwIfAborted();
444
+ if (result.done)
445
+ break;
446
+ size += result.value.byteLength;
447
+ if (size > limit)
448
+ fail("EFBIG", "webdav", "", "response exceeds byte limit");
449
+ if (expected !== undefined && size > expected)
450
+ fail("EIO", "webdav", "", "response body length differs from Content-Length");
451
+ yield new Uint8Array(result.value);
452
+ }
453
+ if (expected !== undefined && size !== expected)
454
+ fail("EIO", "webdav", "", "response body length differs from Content-Length");
455
+ }
456
+ finally {
457
+ signal.removeEventListener("abort", abort);
458
+ void reader.cancel().catch(() => { });
459
+ reader.releaseLock();
460
+ }
461
+ }
462
+ async xml(response, signal) {
463
+ const data = await this.bytes(response, this.maxXmlBytes, signal);
464
+ const encoding = (data[0] === 0xff && data[1] === 0xfe) || (data[0] === 0x3c && data[1] === 0)
465
+ ? "utf-16le" : (data[0] === 0xfe && data[1] === 0xff) || (data[0] === 0 && data[1] === 0x3c) ? "utf-16be" : "utf-8";
466
+ return parseXml(new TextDecoder(encoding, { fatal: true }).decode(data), {
467
+ maxNodes: this.maxXmlBytes, maxAttributes: this.maxXmlBytes,
468
+ });
469
+ }
470
+ async multistatus(response, signal, method = "PROPFIND", path = "") {
471
+ const link = response.headers.get("link");
472
+ if (link && /\brel\s*=\s*(?:"[^"]*\bnext\b[^"]*"|'[^']*\bnext\b[^']*'|next\b)/i.test(link)) {
473
+ fail("ENOTSUP", method, path, "paginated WebDAV responses are unsupported");
474
+ }
475
+ const root = await this.xml(response, signal);
476
+ if (root.namespace !== "DAV:" || root.localName !== "multistatus")
477
+ throw new Error("expected DAV:multistatus");
478
+ const responses = davChildren(root, "response");
479
+ if (responses.length > this.maxEntries)
480
+ fail("EFBIG", method, path, "response exceeds entry limit");
481
+ return responses;
482
+ }
483
+ async lockFailure(response, signal, path) {
484
+ try {
485
+ const members = new Set();
486
+ let failure;
487
+ for (const element of await this.multistatus(response, signal, "LOCK", path)) {
488
+ const href = davChild(element, "href");
489
+ const status = davChild(element, "status");
490
+ if (!href || !status)
491
+ throw new Error("invalid LOCK multistatus");
492
+ const member = this.hrefPath(scalar(href));
493
+ if (member !== path && !member.startsWith(`${path}/`)) {
494
+ fail("EACCES", "LOCK", path, "LOCK response member is outside requested subtree");
495
+ }
496
+ if (members.has(member))
497
+ throw new Error("duplicate LOCK response href");
498
+ members.add(member);
499
+ const code = statusCode(status);
500
+ if (code >= 300 && (!failure || (failure.status === 424 && code !== 424))) {
501
+ failure = { member, status: code };
502
+ }
503
+ }
504
+ if (!failure)
505
+ throw new Error("LOCK multistatus without a reported failure");
506
+ this.httpError(failure.status, "LOCK", failure.member);
507
+ }
508
+ catch (cause) {
509
+ throw new FsError(isFsError(cause) ? cause.code : "EIO", {
510
+ syscall: "LOCK", path, message: "WebDAV LOCK multistatus failure", cause,
511
+ });
512
+ }
513
+ }
514
+ entryStat(element, path) {
515
+ const wholeStatus = davChild(element, "status");
516
+ if (wholeStatus) {
517
+ const code = statusCode(wholeStatus);
518
+ if (code < 200 || code >= 300)
519
+ this.httpError(code, "PROPFIND", path);
520
+ }
521
+ const properties = new Map();
522
+ const failures = new Map();
523
+ let timestampProperty;
524
+ let timestampSeen = false;
525
+ for (const propstat of davChildren(element, "propstat")) {
526
+ const status = davChild(propstat, "status");
527
+ const prop = davChild(propstat, "prop");
528
+ if (!status || !prop)
529
+ throw new Error("incomplete DAV:propstat");
530
+ const code = statusCode(status);
531
+ for (const property of prop.children) {
532
+ if (property.namespace === timestampNamespace && property.localName === "timestamps") {
533
+ if (timestampSeen)
534
+ throw new Error("duplicate timestamp property");
535
+ timestampSeen = true;
536
+ if (code === 200)
537
+ timestampProperty = property;
538
+ }
539
+ if (property.namespace !== "DAV:")
540
+ continue;
541
+ if (properties.has(property.localName) || failures.has(property.localName))
542
+ throw new Error("duplicate DAV property");
543
+ if (code >= 200 && code < 300)
544
+ properties.set(property.localName, property);
545
+ else
546
+ failures.set(property.localName, code);
547
+ }
548
+ }
549
+ const required = (name) => {
550
+ const property = properties.get(name);
551
+ if (property)
552
+ return property;
553
+ const failure = failures.get(name);
554
+ if (failure !== undefined && failure !== 404)
555
+ this.httpError(failure, "PROPFIND", path);
556
+ return fail("ENOTSUP", "stat", path, `server does not expose DAV:${name}`);
557
+ };
558
+ const resourceType = required("resourcetype");
559
+ const directory = !!davChild(resourceType, "collection");
560
+ if (resourceType.text.trim() || resourceType.children.some((child) => child.namespace !== "DAV:" || child.localName !== "collection")) {
561
+ fail("ENOTSUP", "stat", path, "unsupported DAV resource type");
562
+ }
563
+ const sizeText = directory ? "0" : scalar(required("getcontentlength"));
564
+ if (!/^\d+$/.test(sizeText) || !Number.isSafeInteger(Number(sizeText)))
565
+ throw new Error("invalid content length property");
566
+ const date = (name) => {
567
+ const property = properties.get(name);
568
+ if (!property)
569
+ return undefined;
570
+ const value = Date.parse(scalar(property));
571
+ if (!Number.isFinite(value))
572
+ throw new Error("invalid date property");
573
+ return value;
574
+ };
575
+ const birthtimeMs = date("creationdate");
576
+ const etag = properties.get("getetag");
577
+ const validator = etag && scalar(etag);
578
+ let mtimeMs = date("getlastmodified") ?? 0;
579
+ let atimeMs = 0;
580
+ if (timestampProperty) {
581
+ const timestamps = JSON.parse(scalar(timestampProperty));
582
+ if (typeof timestamps !== "object" || timestamps === null
583
+ || !("version" in timestamps) || timestamps.version !== 1
584
+ || !("etag" in timestamps) || typeof timestamps.etag !== "string" || !/^"[\x21\x23-\x7e\x80-\xff]*"$/.test(timestamps.etag)
585
+ || !("type" in timestamps) || (timestamps.type !== "file" && timestamps.type !== "directory")
586
+ || !("atimeMs" in timestamps) || typeof timestamps.atimeMs !== "number" || !Number.isFinite(timestamps.atimeMs)
587
+ || Math.abs(timestamps.atimeMs) > 8.64e15
588
+ || !("mtimeMs" in timestamps) || typeof timestamps.mtimeMs !== "number" || !Number.isFinite(timestamps.mtimeMs)
589
+ || Math.abs(timestamps.mtimeMs) > 8.64e15)
590
+ throw new Error("invalid timestamp property");
591
+ if (timestamps.etag === validator && timestamps.type === (directory ? "directory" : "file")) {
592
+ mtimeMs = timestamps.mtimeMs;
593
+ atimeMs = timestamps.atimeMs;
594
+ }
595
+ }
596
+ const stat = {
597
+ type: directory ? "directory" : "file", size: Number(sizeText), mode: directory ? 0o40777 : 0o100666,
598
+ mtimeMs, atimeMs, ctimeMs: 0,
599
+ ...(birthtimeMs === undefined ? {} : { birthtimeMs }),
600
+ };
601
+ if (validator)
602
+ this.etags.set(stat, validator);
603
+ return stat;
604
+ }
605
+ async entries(path, depth, options, collection = depth === "1") {
606
+ return this.request("PROPFIND", path, options, {
607
+ headers: { Depth: depth, "Content-Type": "application/xml; charset=utf-8" }, body: propfindBody,
608
+ }, async (response, signal) => {
609
+ if (response.status !== 207)
610
+ this.httpError(response.status, "PROPFIND", path);
611
+ const result = new Map();
612
+ for (const element of await this.multistatus(response, signal)) {
613
+ const href = davChild(element, "href");
614
+ if (!href)
615
+ throw new Error("missing DAV:href");
616
+ const member = this.hrefPath(scalar(href));
617
+ const prefix = path === "/" ? "/" : `${path}/`;
618
+ if (member !== path && (depth === "0" || !member.startsWith(prefix) || member.slice(prefix.length).includes("/"))) {
619
+ fail("EACCES", "PROPFIND", path, "response member is outside requested depth");
620
+ }
621
+ if (result.has(member))
622
+ throw new Error("duplicate response href");
623
+ const stat = this.entryStat(element, member);
624
+ recordOwnedResourceStat(response, this, member, stat);
625
+ result.set(member, stat);
626
+ }
627
+ if (!result.has(path))
628
+ throw new Error("response omitted requested resource");
629
+ return result;
630
+ }, collection);
631
+ }
632
+ async mutation(method, path, options, init = {}, collection = false) {
633
+ await this.request(method, path, options, init, async (response, signal) => {
634
+ if (response.status === 207) {
635
+ for (const element of await this.multistatus(response, signal)) {
636
+ const href = davChild(element, "href");
637
+ const status = davChild(element, "status");
638
+ if (!href || !status)
639
+ throw new Error("invalid mutation multistatus");
640
+ const member = this.hrefPath(scalar(href));
641
+ const code = statusCode(status);
642
+ if (code < 200 || code >= 300) {
643
+ try {
644
+ this.httpError(code, method, member);
645
+ }
646
+ catch (cause) {
647
+ throw new FsError("EIO", { syscall: method, path, message: "WebDAV mutation partially failed", cause });
648
+ }
649
+ }
650
+ }
651
+ fail("EIO", method, path, "unexpected mutation multistatus without a reported failure");
652
+ }
653
+ const accepted = method === "PUT" ? [200, 201, 204] : method === "MKCOL" ? [201] : method === "DELETE" ? [204] : [201, 204];
654
+ if (!accepted.includes(response.status)) {
655
+ const headers = new Headers(init.headers);
656
+ this.httpError(response.status, method, path, headers.get("If-None-Match") === "*" || headers.get("Overwrite") === "F");
657
+ }
658
+ }, collection);
659
+ }
660
+ unsupported(operation, path) {
661
+ return fail("ENOTSUP", operation, path, `${operation} has no safe portable WebDAV equivalent`);
662
+ }
663
+ async maybeStat(path, options) {
664
+ try {
665
+ return await this.stat(path, options);
666
+ }
667
+ catch (error) {
668
+ if (isFsError(error, "ENOENT"))
669
+ return undefined;
670
+ throw error;
671
+ }
672
+ }
673
+ async stat(path, options = {}) {
674
+ const normalized = normalize(path);
675
+ const collection = requiresCollection(path);
676
+ try {
677
+ const stat = (await this.entries(normalized, "0", options, collection)).get(normalized);
678
+ if (collection && stat.type !== "directory")
679
+ fail("ENOTDIR", "stat", path);
680
+ return stat;
681
+ }
682
+ catch (error) {
683
+ if (!isFsError(error, "ENOENT"))
684
+ throw error;
685
+ let parent = "";
686
+ for (const segment of normalized.slice(1).split("/").slice(0, -1)) {
687
+ parent += `/${segment}`;
688
+ const ancestor = (await this.entries(parent, "0", options)).get(parent);
689
+ if (ancestor.type !== "directory")
690
+ fail("ENOTDIR", "stat", path);
691
+ }
692
+ throw error;
693
+ }
694
+ }
695
+ async lstat(path, options = {}) {
696
+ return this.stat(path, options);
697
+ }
698
+ async readdir(path, options = {}) {
699
+ const normalized = normalize(path);
700
+ const entries = await this.entries(normalized, "1", options);
701
+ if (entries.get(normalized).type !== "directory")
702
+ fail("ENOTDIR", "readdir", path);
703
+ return [...entries].filter(([member]) => member !== normalized)
704
+ .map(([member, stat]) => ({ name: member.slice(member.lastIndexOf("/") + 1), type: stat.type }))
705
+ .sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
706
+ }
707
+ async readFile(path, options = {}) {
708
+ const normalized = normalize(path);
709
+ const limit = Math.min(this.maxResponseBytes, positive(options.maxBytes ?? this.maxResponseBytes, "maxBytes", true));
710
+ if ((await this.stat(path, options)).type === "directory")
711
+ fail("EISDIR", "readFile", path);
712
+ return this.request("GET", normalized, options, { headers: { "Accept-Encoding": "identity" } }, async (response, signal) => {
713
+ if (response.status !== 200)
714
+ this.httpError(response.status, "GET", path);
715
+ return this.bytes(response, limit, signal);
716
+ });
717
+ }
718
+ async *readStream(path, options = {}) {
719
+ const normalized = normalize(path);
720
+ const start = positive(options.start ?? 0, "start", true);
721
+ const end = options.endExclusive === undefined ? Infinity : positive(options.endExclusive, "endExclusive", true);
722
+ const chunkSize = positive(options.chunkSize ?? 64 * 1024, "chunkSize");
723
+ if (end < start)
724
+ fail("EINVAL", "readStream", path, "endExclusive precedes start");
725
+ if ((await this.stat(path, options)).type === "directory")
726
+ fail("EISDIR", "readStream", path);
727
+ yield* this.requestStream("GET", normalized, options, { headers: { "Accept-Encoding": "identity" } }, async function* (response, signal) {
728
+ if (response.status !== 200)
729
+ this.httpError(response.status, "GET", path);
730
+ let position = 0;
731
+ for await (const chunk of this.bodyChunks(response, this.maxResponseBytes, signal)) {
732
+ const first = Math.max(0, start - position);
733
+ const last = Math.min(chunk.byteLength, end - position);
734
+ for (let offset = first; offset < last; offset += chunkSize) {
735
+ signal.throwIfAborted();
736
+ yield chunk.slice(offset, Math.min(last, offset + chunkSize));
737
+ }
738
+ position += chunk.byteLength;
739
+ if (position >= end)
740
+ return;
741
+ }
742
+ }.bind(this));
743
+ }
744
+ async prepareWrite(path, options) {
745
+ const normalized = normalize(path);
746
+ if (options.mode !== undefined)
747
+ this.unsupported("writeFile mode", path);
748
+ if (options.flag !== undefined && !["w", "wx", "a", "ax"].includes(options.flag))
749
+ fail("EINVAL", "writeFile", path);
750
+ if (options.signal?.aborted)
751
+ fail("ECANCELED", "writeFile", path);
752
+ if (normalized === "/")
753
+ fail("EISDIR", "writeFile", path);
754
+ if (requiresCollection(path)) {
755
+ await this.stat(path, options);
756
+ fail("EISDIR", "writeFile", path);
757
+ }
758
+ let parent = "";
759
+ for (const segment of normalized.slice(1).split("/").slice(0, -1)) {
760
+ parent += `/${segment}`;
761
+ await this.stat(`${parent}/`, options);
762
+ }
763
+ const exclusive = options.flag === "wx" || options.flag === "ax";
764
+ const existing = exclusive ? undefined : await this.maybeStat(normalized, options);
765
+ if (existing?.type === "directory")
766
+ fail("EISDIR", "writeFile", path);
767
+ let prefix = new Uint8Array();
768
+ const headers = { "Content-Type": "application/octet-stream" };
769
+ if (exclusive || (options.flag === "a" && !existing))
770
+ headers["If-None-Match"] = "*";
771
+ if (options.flag === "a" && existing) {
772
+ const snapshot = await this.request("GET", normalized, options, { headers: { "Accept-Encoding": "identity" } }, async (response, signal) => {
773
+ if (response.status !== 200)
774
+ this.httpError(response.status, "GET", path);
775
+ const etag = strongEtag(response.headers.get("ETag"), path);
776
+ if (response.headers.get("Content-Encoding") && response.headers.get("Content-Encoding").toLowerCase() !== "identity") {
777
+ fail("ENOTSUP", "appendFile", path, "conditional append requires an identity representation");
778
+ }
779
+ return { etag, data: await this.bytes(response, this.maxResponseBytes, signal) };
780
+ });
781
+ prefix = snapshot.data;
782
+ headers["If-Match"] = snapshot.etag;
783
+ }
784
+ return { normalized, headers, prefix };
785
+ }
786
+ async writeFile(path, data, options = {}) {
787
+ if (!(data instanceof Uint8Array))
788
+ fail("EINVAL", "writeFile", path, "data must be Uint8Array");
789
+ const { normalized, headers, prefix } = await this.prepareWrite(path, options);
790
+ if (options.flag === "a" && prefix.byteLength + data.byteLength > this.maxResponseBytes)
791
+ fail("EFBIG", "appendFile", path);
792
+ const body = new Uint8Array(prefix.byteLength + data.byteLength);
793
+ body.set(prefix);
794
+ body.set(data, prefix.byteLength);
795
+ await this.mutation("PUT", normalized, options, {
796
+ headers, body,
797
+ });
798
+ }
799
+ async writeStream(path, source, options = {}) {
800
+ if (options.signal?.aborted)
801
+ fail("ECANCELED", "writeStream", path);
802
+ if (this.requestStreamSupport === false
803
+ || (this.requestStreamSupport === "native" && !nativeRequestStreamsSupported(this.base.href))) {
804
+ fail("ENOTSUP", "writeStream", path, "transport does not declare supported request streams");
805
+ }
806
+ const { normalized, headers, prefix } = await this.prepareWrite(path, options);
807
+ const deadline = createRequestTimeout(this.timeoutMs);
808
+ const timeout = deadline.signal;
809
+ try {
810
+ const controller = new AbortController();
811
+ const signalScope = composeAbortSignals([timeout, controller.signal, ...(options.signal ? [options.signal] : [])]);
812
+ const signal = signalScope.signal;
813
+ const limit = this.maxResponseBytes;
814
+ const chunks = (async function* () {
815
+ let size = prefix.byteLength;
816
+ if (prefix.byteLength)
817
+ yield prefix;
818
+ for await (const chunk of readBytes(source, signal)) {
819
+ size += chunk.byteLength;
820
+ if (size > limit)
821
+ fail("EFBIG", "writeStream", path, "upload exceeds byte limit");
822
+ yield new Uint8Array(chunk);
823
+ }
824
+ })();
825
+ let finished = false;
826
+ let uploadError;
827
+ let body;
828
+ try {
829
+ body = new ReadableStream({
830
+ async pull(destination) {
831
+ try {
832
+ const result = await chunks.next();
833
+ if (result.done) {
834
+ finished = true;
835
+ destination.close();
836
+ }
837
+ else
838
+ destination.enqueue(result.value);
839
+ }
840
+ catch (cause) {
841
+ uploadError = cause;
842
+ destination.error(cause);
843
+ }
844
+ },
845
+ cancel(reason) { controller.abort(reason); void chunks.return(undefined).catch(() => { }); },
846
+ }, { highWaterMark: 0 });
847
+ try {
848
+ const request = { headers, body, duplex: "half" };
849
+ await this.mutation("PUT", normalized, options, request);
850
+ if (uploadError !== undefined)
851
+ throw uploadError;
852
+ if (!finished)
853
+ fail("EIO", "writeStream", path, "server responded before consuming the upload");
854
+ }
855
+ catch (cause) {
856
+ if (options.signal?.aborted)
857
+ throw new FsError("ECANCELED", { syscall: "writeStream", path, cause });
858
+ if (timeout.aborted)
859
+ throw new FsError("ETIMEDOUT", { syscall: "writeStream", path, cause });
860
+ if (isFsError(uploadError))
861
+ throw uploadError;
862
+ if (isFsError(cause))
863
+ throw cause;
864
+ throw new FsError("EIO", { syscall: "writeStream", path, cause });
865
+ }
866
+ }
867
+ finally {
868
+ controller.abort();
869
+ signalScope.dispose();
870
+ if (body && !body.locked)
871
+ void body.cancel().catch(() => { });
872
+ void chunks.return(undefined).catch(() => { });
873
+ }
874
+ }
875
+ finally {
876
+ deadline.dispose();
877
+ }
878
+ }
879
+ async appendFile(path, data, options = {}) {
880
+ await this.writeFile(path, data, { ...options, flag: "a" });
881
+ }
882
+ async mkdir(path, options = {}) {
883
+ const normalized = normalize(path);
884
+ if (options.mode !== undefined)
885
+ this.unsupported("mkdir mode", path);
886
+ if (!options.recursive) {
887
+ if (normalized === "/")
888
+ fail("EEXIST", "mkdir", path);
889
+ return this.mutation("MKCOL", normalized, options, {}, true);
890
+ }
891
+ let current = "";
892
+ for (const segment of normalized.slice(1).split("/").filter(Boolean)) {
893
+ current += `/${segment}`;
894
+ const existing = await this.maybeStat(`${current}/`, options);
895
+ if (existing) {
896
+ if (existing.type !== "directory")
897
+ fail("ENOTDIR", "mkdir", current);
898
+ continue;
899
+ }
900
+ try {
901
+ await this.mutation("MKCOL", current, options, {}, true);
902
+ }
903
+ catch (error) {
904
+ if (!isFsError(error, "EEXIST"))
905
+ throw error;
906
+ if ((await this.stat(`${current}/`, options)).type !== "directory")
907
+ fail("ENOTDIR", "mkdir", current);
908
+ }
909
+ }
910
+ if (normalized === "/")
911
+ await this.stat(normalized, options);
912
+ }
913
+ async rmdir(path, options = {}) {
914
+ try {
915
+ const normalized = normalize(path);
916
+ if (options.signal?.aborted)
917
+ fail("ECANCELED", "rmdir", path);
918
+ if (normalized === "/")
919
+ fail("EBUSY", "rmdir", path, "cannot remove WebDAV root");
920
+ const stat = await this.stat(path, options);
921
+ if (options.signal?.aborted)
922
+ fail("ECANCELED", "rmdir", path);
923
+ if (stat.type !== "directory")
924
+ fail("ENOTDIR", "rmdir", path);
925
+ if (this.atomicEmptyDirectory) {
926
+ await this.atomicRmdir(normalized, path, options);
927
+ return;
928
+ }
929
+ const entries = await this.readdir(path, options);
930
+ if (options.signal?.aborted)
931
+ fail("ECANCELED", "rmdir", path);
932
+ if (entries.length)
933
+ fail("ENOTEMPTY", "rmdir", path);
934
+ this.unsupported("rmdir", path);
935
+ }
936
+ catch (error) {
937
+ if (isFsError(error) && (error.syscall !== "rmdir" || error.path !== path)) {
938
+ throw new FsError(error.code, { syscall: "rmdir", path, cause: error });
939
+ }
940
+ throw error;
941
+ }
942
+ }
943
+ async atomicRmdir(normalized, path, options) {
944
+ const deadline = createRequestTimeout(this.timeoutMs);
945
+ const timeout = deadline.signal;
946
+ try {
947
+ const signalScope = options.signal ? composeAbortSignals([timeout, options.signal]) : undefined;
948
+ const signal = signalScope?.signal ?? timeout;
949
+ try {
950
+ signal.throwIfAborted();
951
+ const receipt = await new Promise((resolve, reject) => {
952
+ const abort = () => {
953
+ signal.removeEventListener("abort", abort);
954
+ reject(signal.reason);
955
+ };
956
+ signal.addEventListener("abort", abort, { once: true });
957
+ try {
958
+ Promise.resolve(this.atomicEmptyDirectory.removeEmptyDirectory(Object.freeze({
959
+ operation: "atomic-empty-rmdir/v1", namespaceUrl: this.base.href, path: normalized, signal,
960
+ }))).then((result) => {
961
+ signal.removeEventListener("abort", abort);
962
+ resolve(result);
963
+ }, (error) => {
964
+ signal.removeEventListener("abort", abort);
965
+ reject(error);
966
+ });
967
+ }
968
+ catch (error) {
969
+ signal.removeEventListener("abort", abort);
970
+ reject(error);
971
+ }
972
+ });
973
+ signal.throwIfAborted();
974
+ if (!receipt || receipt.operation !== "atomic-empty-rmdir/v1" || receipt.namespaceUrl !== this.base.href
975
+ || receipt.path !== normalized || receipt.outcome !== "removed") {
976
+ fail("EIO", "rmdir", path, "atomic empty-directory receipt mismatch; removal outcome is uncertain");
977
+ }
978
+ }
979
+ catch (cause) {
980
+ if (options.signal?.aborted)
981
+ throw new FsError("ECANCELED", { syscall: "rmdir", path, cause });
982
+ if (timeout.aborted)
983
+ throw new FsError("ETIMEDOUT", { syscall: "rmdir", path, cause });
984
+ if (isFsError(cause))
985
+ throw cause;
986
+ const code = cause && typeof cause === "object" && "code" in cause && isErrnoCode(cause.code) ? cause.code : "EIO";
987
+ throw new FsError(code, { syscall: "rmdir", path, cause });
988
+ }
989
+ finally {
990
+ signalScope?.dispose();
991
+ }
992
+ }
993
+ finally {
994
+ deadline.dispose();
995
+ }
996
+ }
997
+ async rm(path, options = {}) {
998
+ const normalized = normalize(path);
999
+ if (normalized === "/")
1000
+ fail("EBUSY", "rm", path, "cannot remove WebDAV root");
1001
+ try {
1002
+ const stat = await this.stat(path, options);
1003
+ if (stat.type === "directory" && !options.recursive)
1004
+ this.unsupported("nonrecursive directory removal", path);
1005
+ await this.mutation("DELETE", normalized, options, {}, stat.type === "directory");
1006
+ }
1007
+ catch (error) {
1008
+ if (!(options.force && isFsError(error, "ENOENT")))
1009
+ throw error;
1010
+ }
1011
+ }
1012
+ async guardTransferIdentity(source, destination, options) {
1013
+ if (!this.configuredComparison && this.compareEntry === originalWebDavComparison)
1014
+ return;
1015
+ const comparison = await compareEntries(this, source, this, destination, options);
1016
+ if (source === destination) {
1017
+ if (comparison === "distinct")
1018
+ fail("EIO", "compareEntry", source, "comparison contradicts identical WebDAV paths");
1019
+ return;
1020
+ }
1021
+ if (comparison === "same")
1022
+ fail("EINVAL", "compareEntry", destination, "source and destination refer to the same entry");
1023
+ if (comparison === "unknown")
1024
+ fail("ENOTSUP", "compareEntry", destination, "configured authority cannot establish distinct entries");
1025
+ }
1026
+ async transfer(method, source, destination, options) {
1027
+ const from = normalize(source);
1028
+ const to = normalize(destination);
1029
+ if (from === "/" || to === "/")
1030
+ fail("EBUSY", method, source, "cannot replace or transfer WebDAV root");
1031
+ const stat = await this.stat(source, options);
1032
+ if (method === "COPY" && stat.type === "directory")
1033
+ fail("EISDIR", "copyFile", source);
1034
+ if (requiresCollection(destination) && stat.type !== "directory")
1035
+ fail("ENOTDIR", method, destination);
1036
+ if (from === to) {
1037
+ await this.guardTransferIdentity(from, to, options);
1038
+ if (method === "MOVE")
1039
+ return;
1040
+ fail(options.exclusive ? "EEXIST" : "EINVAL", "copyFile", source, "source and destination are identical");
1041
+ }
1042
+ if (stat.type === "directory" && to.startsWith(`${from}/`))
1043
+ fail("EINVAL", method, destination, "cannot move directory into itself");
1044
+ const existing = await this.maybeStat(destination, options);
1045
+ if (existing)
1046
+ await this.guardTransferIdentity(from, to, options);
1047
+ if (existing && options.exclusive)
1048
+ fail("EEXIST", method, destination);
1049
+ const checkType = (target) => {
1050
+ if (target.type === "directory" && stat.type === "file")
1051
+ fail("EISDIR", method, destination);
1052
+ if (target.type !== "directory" && stat.type === "directory")
1053
+ fail("ENOTDIR", method, destination);
1054
+ };
1055
+ if (existing)
1056
+ checkType(existing);
1057
+ if (stat.type === "directory" && from.startsWith(`${to}/`))
1058
+ fail("EINVAL", method, destination, "cannot replace an ancestor of the source");
1059
+ const destinationUrl = this.url(to, stat.type === "directory");
1060
+ const headers = {
1061
+ Destination: destinationUrl, Overwrite: existing ? "T" : "F",
1062
+ Depth: method === "COPY" ? "0" : "infinity",
1063
+ };
1064
+ const sourceEtag = this.etags.get(stat);
1065
+ if (existing && sourceEtag && /^"[\x21\x23-\x7e\x80-\xff]*"$/.test(sourceEtag))
1066
+ headers["If-Match"] = sourceEtag;
1067
+ const mutate = () => this.mutation(method, from, options, { headers }, stat.type === "directory");
1068
+ if (!existing)
1069
+ return mutate();
1070
+ if (this.overwritePolicy === "etag" && existing.type === "file") {
1071
+ headers.If = `<${destinationUrl}> ([${strongEtag(this.etags.get(existing), destination)}])`;
1072
+ return mutate();
1073
+ }
1074
+ await this.withDestinationLock(to, existing, options, async (token) => {
1075
+ const locked = await this.stat(destination, options);
1076
+ checkType(locked);
1077
+ if (locked.type === "directory" && (await this.readdir(destination, options)).length)
1078
+ fail("ENOTEMPTY", method, destination);
1079
+ headers.If = `<${destinationUrl}> (${token})`;
1080
+ await mutate();
1081
+ });
1082
+ }
1083
+ async withDestinationLock(path, stat, options, operation) {
1084
+ let token;
1085
+ const collection = stat.type === "directory";
1086
+ const validator = this.etags.get(stat);
1087
+ const unlock = async (value) => {
1088
+ await this.request("UNLOCK", path, {}, { headers: { "Lock-Token": value } }, async (response) => {
1089
+ if (response.status !== 204)
1090
+ this.httpError(response.status, "UNLOCK", path);
1091
+ }, collection).catch(() => { });
1092
+ };
1093
+ try {
1094
+ await this.request("LOCK", path, options, {
1095
+ headers: { "Content-Type": "application/xml; charset=utf-8", Depth: "infinity", Timeout: "Second-60",
1096
+ "If-Match": validator && /^"[\x21\x23-\x7e\x80-\xff]*"$/.test(validator) ? validator : "*" },
1097
+ body: lockBody,
1098
+ }, async (response, signal) => {
1099
+ if (response.status === 207)
1100
+ return this.lockFailure(response, signal, path);
1101
+ if (response.status !== 200)
1102
+ this.httpError(response.status, "LOCK", path);
1103
+ const root = await this.xml(response, signal);
1104
+ const discovery = davChild(root, "lockdiscovery");
1105
+ const active = discovery && davChild(discovery, "activelock");
1106
+ const scope = active && davChild(active, "lockscope");
1107
+ const type = active && davChild(active, "locktype");
1108
+ const depth = active && davChild(active, "depth");
1109
+ const lockToken = active && davChild(active, "locktoken");
1110
+ const href = lockToken && davChild(lockToken, "href");
1111
+ const lockRoot = active && davChild(active, "lockroot");
1112
+ const rootHref = lockRoot && davChild(lockRoot, "href");
1113
+ const timeout = active && davChild(active, "timeout");
1114
+ if (root.namespace !== "DAV:" || root.localName !== "prop" || !scope || !davChild(scope, "exclusive")
1115
+ || davChild(scope, "shared")
1116
+ || !type || !davChild(type, "write") || !depth || scalar(depth) !== "infinity"
1117
+ || !href || `<${scalar(href)}>` !== token
1118
+ || (lockRoot !== undefined && (!rootHref || this.hrefPath(scalar(rootHref)) !== path))
1119
+ || !timeout || !/^Second-[1-9]\d*$/i.test(scalar(timeout)) || Number(scalar(timeout).slice(7)) > 4_294_967_295) {
1120
+ fail("ENOTSUP", "LOCK", path, "server did not grant a finite exclusive depth-infinity write lock");
1121
+ }
1122
+ }, collection, (response, late) => {
1123
+ if (response.status !== 200)
1124
+ return;
1125
+ const header = response.headers.get("Lock-Token");
1126
+ if (!header || !/^<[a-z][a-z0-9+.-]*:[^<>\s\x00-\x20\x7f]+>$/i.test(header))
1127
+ throw new Error("invalid LOCK token");
1128
+ if (late)
1129
+ void unlock(header);
1130
+ else
1131
+ token = header;
1132
+ });
1133
+ await operation(token);
1134
+ }
1135
+ finally {
1136
+ if (token)
1137
+ await unlock(token);
1138
+ }
1139
+ }
1140
+ async rename(source, destination, options = {}) {
1141
+ await this.transfer("MOVE", source, destination, options);
1142
+ }
1143
+ async copyFile(source, destination, options = {}) {
1144
+ await this.transfer("COPY", source, destination, options);
1145
+ }
1146
+ async realpath(path, options = {}) {
1147
+ const normalized = normalize(path);
1148
+ await this.stat(path, options);
1149
+ return normalized;
1150
+ }
1151
+ async access(path, mode = 0, options = {}) {
1152
+ if (!Number.isInteger(mode) || mode < 0 || mode > 7)
1153
+ fail("EINVAL", "access", path);
1154
+ if (options.signal?.aborted)
1155
+ fail("ECANCELED", "access", path);
1156
+ if (mode & 2)
1157
+ this.unsupported("access write/execute permission checks", path);
1158
+ if (mode & 1)
1159
+ validateDirectoryAccessPath(path);
1160
+ const stat = await this.stat(path, options);
1161
+ if (options.signal?.aborted)
1162
+ fail("ECANCELED", "access", path);
1163
+ if ((mode & 1) && stat.type !== "directory")
1164
+ this.unsupported("access execute permission checks", path);
1165
+ if (mode & 4) {
1166
+ if (stat.type === "directory")
1167
+ await this.readdir(path, options);
1168
+ else
1169
+ await this.request("GET", normalize(path), options, { headers: { "Accept-Encoding": "identity" } }, async (response) => {
1170
+ if (response.status !== 200)
1171
+ this.httpError(response.status, "GET", path);
1172
+ });
1173
+ }
1174
+ if (options.signal?.aborted)
1175
+ fail("ECANCELED", "access", path);
1176
+ }
1177
+ async readlink(path, _options = {}) { return this.unsupported("readlink", path); }
1178
+ async symlink(_target, path, _options = {}) { this.unsupported("symlink", path); }
1179
+ async link(_source, path, _options = {}) { this.unsupported("link", path); }
1180
+ async chmod(path, _mode, _options = {}) { this.unsupported("chmod", path); }
1181
+ async utimes(path, atimeMs, mtimeMs, options = {}) {
1182
+ const normalized = normalize(path);
1183
+ if (![atimeMs, mtimeMs].every(value => Number.isFinite(value) && Math.abs(value) <= 8.64e15))
1184
+ fail("EINVAL", "utimes", path);
1185
+ const stat = await this.stat(path, options);
1186
+ const etag = strongEtag(this.etags.get(stat), path);
1187
+ const metadata = JSON.stringify({ version: 1, etag, type: stat.type, atimeMs, mtimeMs })
1188
+ .replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
1189
+ await this.request("PROPPATCH", normalized, options, {
1190
+ headers: { "Content-Type": "application/xml; charset=utf-8", "If-Match": etag },
1191
+ body: `<d:propertyupdate xmlns:d="DAV:" xmlns:v="${timestampNamespace}"><d:set><d:prop>`
1192
+ + `<v:timestamps>${metadata}</v:timestamps></d:prop></d:set></d:propertyupdate>`,
1193
+ }, async (response, signal) => {
1194
+ if (response.status !== 207)
1195
+ this.httpError(response.status, "PROPPATCH", path);
1196
+ const entries = await this.multistatus(response, signal);
1197
+ if (entries.length !== 1)
1198
+ throw new Error("PROPPATCH must report the requested resource");
1199
+ const entry = entries[0];
1200
+ const href = davChild(entry, "href");
1201
+ if (!href || this.hrefPath(scalar(href)) !== normalized)
1202
+ fail("EACCES", "PROPPATCH", path, "unexpected response resource");
1203
+ const status = davChild(entry, "status");
1204
+ if (status)
1205
+ this.httpError(statusCode(status), "PROPPATCH", path);
1206
+ const propstats = davChildren(entry, "propstat");
1207
+ if (propstats.length !== 1)
1208
+ throw new Error("PROPPATCH must report the requested property");
1209
+ const prop = davChild(propstats[0], "prop");
1210
+ const result = davChild(propstats[0], "status");
1211
+ const property = prop?.children[0];
1212
+ if (!result || prop?.children.length !== 1 || property?.namespace !== timestampNamespace
1213
+ || property.localName !== "timestamps")
1214
+ throw new Error("invalid PROPPATCH property result");
1215
+ const code = statusCode(result);
1216
+ if (code !== 200)
1217
+ this.httpError(code, "PROPPATCH", path);
1218
+ }, stat.type === "directory");
1219
+ const updated = await this.stat(path, options);
1220
+ if (updated.atimeMs !== atimeMs || updated.mtimeMs !== mtimeMs) {
1221
+ fail("EAGAIN", "utimes", path, "server did not retain requested timestamps for the current representation");
1222
+ }
1223
+ }
1224
+ async truncate(path, _length, _options = {}) { this.unsupported("truncate", path); }
1225
+ }
1226
+ const originalWebDavComparison = WebDavFileSystem.prototype.compareEntry;