@softistx/s3 0.0.0-stage → 0.13.2

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 (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +609 -2
  3. package/dist/bucket/bind-bucket.d.ts +42 -0
  4. package/dist/bucket/bind-bucket.d.ts.map +1 -0
  5. package/dist/bucket/bound-bucket.d.ts +119 -0
  6. package/dist/bucket/bound-bucket.d.ts.map +1 -0
  7. package/dist/bucket/context.d.ts +55 -0
  8. package/dist/bucket/context.d.ts.map +1 -0
  9. package/dist/bucket/define-bucket.d.ts +16 -0
  10. package/dist/bucket/define-bucket.d.ts.map +1 -0
  11. package/dist/bucket/disposition.d.ts +9 -0
  12. package/dist/bucket/disposition.d.ts.map +1 -0
  13. package/dist/bucket/guards.d.ts +38 -0
  14. package/dist/bucket/guards.d.ts.map +1 -0
  15. package/dist/bucket/operations/counted-stream.d.ts +26 -0
  16. package/dist/bucket/operations/counted-stream.d.ts.map +1 -0
  17. package/dist/bucket/operations/deadline.d.ts +21 -0
  18. package/dist/bucket/operations/deadline.d.ts.map +1 -0
  19. package/dist/bucket/operations/fetch-object.d.ts +68 -0
  20. package/dist/bucket/operations/fetch-object.d.ts.map +1 -0
  21. package/dist/bucket/operations/list-xml.d.ts +18 -0
  22. package/dist/bucket/operations/list-xml.d.ts.map +1 -0
  23. package/dist/bucket/operations/list.d.ts +12 -0
  24. package/dist/bucket/operations/list.d.ts.map +1 -0
  25. package/dist/bucket/operations/open-answer.d.ts +5 -0
  26. package/dist/bucket/operations/open-answer.d.ts.map +1 -0
  27. package/dist/bucket/operations/open-range.d.ts +10 -0
  28. package/dist/bucket/operations/open-range.d.ts.map +1 -0
  29. package/dist/bucket/operations/open-relay.d.ts +8 -0
  30. package/dist/bucket/operations/open-relay.d.ts.map +1 -0
  31. package/dist/bucket/operations/open.d.ts +4 -0
  32. package/dist/bucket/operations/open.d.ts.map +1 -0
  33. package/dist/bucket/operations/post-policy.d.ts +77 -0
  34. package/dist/bucket/operations/post-policy.d.ts.map +1 -0
  35. package/dist/bucket/operations/post-signer.d.ts +21 -0
  36. package/dist/bucket/operations/post-signer.d.ts.map +1 -0
  37. package/dist/bucket/operations/presign-post.d.ts +44 -0
  38. package/dist/bucket/operations/presign-post.d.ts.map +1 -0
  39. package/dist/bucket/operations/presign.d.ts +34 -0
  40. package/dist/bucket/operations/presign.d.ts.map +1 -0
  41. package/dist/bucket/operations/put-body.d.ts +13 -0
  42. package/dist/bucket/operations/put-body.d.ts.map +1 -0
  43. package/dist/bucket/operations/query-sign.d.ts +15 -0
  44. package/dist/bucket/operations/query-sign.d.ts.map +1 -0
  45. package/dist/bucket/operations/reads.d.ts +8 -0
  46. package/dist/bucket/operations/reads.d.ts.map +1 -0
  47. package/dist/bucket/operations/sized-body.d.ts +24 -0
  48. package/dist/bucket/operations/sized-body.d.ts.map +1 -0
  49. package/dist/bucket/operations/slice.d.ts +4 -0
  50. package/dist/bucket/operations/slice.d.ts.map +1 -0
  51. package/dist/bucket/operations/writes.d.ts +10 -0
  52. package/dist/bucket/operations/writes.d.ts.map +1 -0
  53. package/dist/bucket/shape.d.ts +6 -0
  54. package/dist/bucket/shape.d.ts.map +1 -0
  55. package/dist/bucket/types.d.ts +164 -0
  56. package/dist/bucket/types.d.ts.map +1 -0
  57. package/dist/chunks/index-jgjey570.js +118 -0
  58. package/dist/chunks/index-jgjey570.js.map +13 -0
  59. package/dist/errors/is-bucket-unavailable.d.ts +18 -0
  60. package/dist/errors/is-bucket-unavailable.d.ts.map +1 -0
  61. package/dist/errors/s3-error.d.ts +80 -0
  62. package/dist/errors/s3-error.d.ts.map +1 -0
  63. package/dist/index.d.ts +8 -0
  64. package/dist/index.d.ts.map +1 -0
  65. package/dist/index.js +1288 -0
  66. package/dist/index.js.map +32 -0
  67. package/dist/testing/fetch-archive.d.ts +8 -0
  68. package/dist/testing/fetch-archive.d.ts.map +1 -0
  69. package/dist/testing/index.d.ts +6 -0
  70. package/dist/testing/index.d.ts.map +1 -0
  71. package/dist/testing/index.js +416 -0
  72. package/dist/testing/index.js.map +16 -0
  73. package/dist/testing/ports.d.ts +15 -0
  74. package/dist/testing/ports.d.ts.map +1 -0
  75. package/dist/testing/ready.d.ts +49 -0
  76. package/dist/testing/ready.d.ts.map +1 -0
  77. package/dist/testing/reaper.d.ts +4 -0
  78. package/dist/testing/reaper.d.ts.map +1 -0
  79. package/dist/testing/seaweedfs.d.ts +64 -0
  80. package/dist/testing/seaweedfs.d.ts.map +1 -0
  81. package/dist/testing/test-s3.d.ts +35 -0
  82. package/dist/testing/test-s3.d.ts.map +1 -0
  83. package/dist/testing/weed.d.ts +17 -0
  84. package/dist/testing/weed.d.ts.map +1 -0
  85. package/docs/README.md +17 -0
  86. package/docs/guide/buckets.md +220 -0
  87. package/docs/guide/presigned-urls.md +403 -0
  88. package/docs/guide/reads.md +417 -0
  89. package/docs/guide/testing.md +151 -0
  90. package/docs/guide/writes.md +374 -0
  91. package/docs/roadmap.md +116 -0
  92. package/docs/troubleshooting.md +982 -0
  93. package/package.json +61 -5
package/dist/index.js ADDED
@@ -0,0 +1,1288 @@
1
+ import {
2
+ secretOf,
3
+ bucketContext,
4
+ callOf,
5
+ keyOf,
6
+ parseKeyOf,
7
+ S3Error2,
8
+ shapeOf,
9
+ isWholeMs,
10
+ checkTimeout,
11
+ deadlineOf,
12
+ withDeadline
13
+ } from "./chunks/index-jgjey570.js";
14
+
15
+ // src/bucket/bind-bucket.ts
16
+ import { S3Client } from "bun";
17
+
18
+ // src/bucket/operations/fetch-object.ts
19
+ var BUN_CODES = {
20
+ ECONNREFUSED: "ConnectionRefused",
21
+ ConnectionRefused: "ConnectionRefused",
22
+ ECONNRESET: "ConnectionClosed",
23
+ ConnectionClosed: "ConnectionClosed",
24
+ ENOTFOUND: "DNSResolveFailed",
25
+ DNSResolveFailed: "DNSResolveFailed",
26
+ EPIPE: "ConnectionClosed",
27
+ UND_ERR_SOCKET: "ConnectionClosed"
28
+ };
29
+ function s3Error(code, key, message) {
30
+ const error = new Error(message);
31
+ error.name = "S3Error";
32
+ error.code = code;
33
+ error.path = key;
34
+ return error;
35
+ }
36
+ function readFailure(reason, key) {
37
+ const code = reason?.code;
38
+ return s3Error(typeof code === "string" && BUN_CODES[code] || "ConnectionClosed", key, "an unexpected error has occurred");
39
+ }
40
+ async function send(context, key, method, signal, request = {}) {
41
+ const url = request.url ?? context.client.presign(key, { method, expiresIn: 60, ...request.signed });
42
+ try {
43
+ const response = await fetch(url, {
44
+ method,
45
+ signal,
46
+ ...request.body === undefined ? {} : { body: request.body },
47
+ ...request.headers ? { headers: request.headers } : {}
48
+ });
49
+ const body = method === "HEAD" ? new Uint8Array : new Uint8Array(await response.arrayBuffer());
50
+ return {
51
+ status: response.status,
52
+ ok: response.ok,
53
+ headers: response.headers,
54
+ body
55
+ };
56
+ } catch (reason) {
57
+ if (signal.aborted)
58
+ throw reason;
59
+ throw readFailure(reason, key);
60
+ }
61
+ }
62
+ function failure(response, key) {
63
+ const body = new TextDecoder().decode(response.body);
64
+ const field = (tag) => new RegExp(`<${tag}>([^<]*)</${tag}>`).exec(body)?.[1];
65
+ const missing = response.status === 404;
66
+ return s3Error(field("Code") ?? (missing ? "NoSuchKey" : "UnknownError"), key, field("Message") ?? (missing ? "The specified key does not exist." : "an unexpected error has occurred"));
67
+ }
68
+ async function headObject(context, key, signal) {
69
+ const response = await send(context, key, "HEAD", signal);
70
+ if (response.status === 404)
71
+ return;
72
+ if (!response.ok)
73
+ throw failure(response, key);
74
+ const { headers } = response;
75
+ return {
76
+ size: Number(headers.get("content-length") ?? 0),
77
+ lastModified: new Date(headers.get("last-modified") ?? 0),
78
+ etag: headers.get("etag") ?? "",
79
+ type: headers.get("content-type") ?? ""
80
+ };
81
+ }
82
+ async function getObject(context, key, signal) {
83
+ const response = await send(context, key, "GET", signal);
84
+ if (response.ok)
85
+ return response.body;
86
+ const error = failure(response, key);
87
+ if (error.code === "NoSuchKey")
88
+ return;
89
+ throw error;
90
+ }
91
+ async function getRange(context, key, range, signal) {
92
+ const response = await send(context, key, "GET", signal, {
93
+ headers: { Range: `bytes=${range.start}-${range.end - 1}` }
94
+ });
95
+ if (response.status === 206)
96
+ return response.body;
97
+ if (response.status === 200)
98
+ return response.body.slice(range.start, range.end);
99
+ if (response.status === 416)
100
+ return new Uint8Array;
101
+ const error = failure(response, key);
102
+ if (error.code === "NoSuchKey")
103
+ return;
104
+ throw error;
105
+ }
106
+ async function removeObject(context, key, signal) {
107
+ const response = await send(context, key, "DELETE", signal);
108
+ if (!response.ok)
109
+ throw failure(response, key);
110
+ }
111
+ async function getListing(context, url, signal) {
112
+ const response = await send(context, "", "GET", signal, { url });
113
+ if (!response.ok)
114
+ throw failure(response, "");
115
+ return new TextDecoder().decode(response.body);
116
+ }
117
+ async function storeObject(context, key, request, signal) {
118
+ const response = await send(context, key, "PUT", signal, request);
119
+ if (!response.ok)
120
+ throw failure(response, key);
121
+ }
122
+
123
+ // src/bucket/operations/list-xml.ts
124
+ var ENTITIES = {
125
+ amp: "&",
126
+ lt: "<",
127
+ gt: ">",
128
+ quot: '"',
129
+ apos: "'"
130
+ };
131
+ var allowed = (code) => code === 9 || code === 10 || code === 13 || code >= 32 && code <= 55295 || code >= 57344 && code <= 65533 || code >= 65536 && code <= 1114111;
132
+ var malformed = () => s3Error("InvalidResponse", "", "ListObjectsV2 response is not a well-formed <ListBucketResult> document");
133
+ function unescapeXml(text) {
134
+ return text.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (whole, name) => {
135
+ if (!name.startsWith("#"))
136
+ return ENTITIES[name.toLowerCase()] ?? whole;
137
+ const code = name[1] === "x" || name[1] === "X" ? Number.parseInt(name.slice(2), 16) : Number.parseInt(name.slice(1), 10);
138
+ if (!allowed(code))
139
+ throw malformed();
140
+ return String.fromCodePoint(code);
141
+ });
142
+ }
143
+ function textOf(raw) {
144
+ return raw.split(/<!\[CDATA\[([\s\S]*?)\]\]>/).map((part, at) => at % 2 ? part : unescapeXml(part)).join("");
145
+ }
146
+ function field(xml, tag) {
147
+ const found = new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`).exec(xml)?.[1];
148
+ return found === undefined ? undefined : textOf(found);
149
+ }
150
+ var ROOT = /^\uFEFF?\s*(?:<\?xml[^>]*\?>\s*)?<ListBucketResult[\s>]/;
151
+ function parseListing(xml) {
152
+ if (!ROOT.test(xml))
153
+ throw malformed();
154
+ const contents = [];
155
+ const rest = xml.replace(/<Contents>([\s\S]*?)<\/Contents>/g, (_, entry) => {
156
+ const size = field(entry, "Size");
157
+ contents.push({
158
+ key: field(entry, "Key") ?? "",
159
+ size: size !== undefined && Number.isFinite(Number(size)) ? Number(size) : undefined,
160
+ lastModified: field(entry, "LastModified"),
161
+ eTag: field(entry, "ETag")
162
+ });
163
+ return "";
164
+ });
165
+ return {
166
+ contents,
167
+ isTruncated: field(rest, "IsTruncated") === "true",
168
+ nextContinuationToken: field(rest, "NextContinuationToken")
169
+ };
170
+ }
171
+
172
+ // src/bucket/operations/post-policy.ts
173
+ import { createHash, createHmac } from "node:crypto";
174
+ var ALGORITHM = "AWS4-HMAC-SHA256";
175
+ function amzDateOf(now) {
176
+ return now.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}/, "");
177
+ }
178
+ var hmac = (key, data) => createHmac("sha256", key).update(data).digest();
179
+ function signingKey(secretAccessKey, day, region, service = "s3") {
180
+ const date = hmac(`AWS4${secretAccessKey}`, day);
181
+ return hmac(hmac(hmac(date, region), service), "aws4_request");
182
+ }
183
+ function rawQueryOf(pairs) {
184
+ const query = new Map;
185
+ for (const pair of pairs) {
186
+ const at = pair.indexOf("=");
187
+ try {
188
+ query.set(pair.slice(0, at), decodeURIComponent(pair.slice(at + 1)));
189
+ } catch {
190
+ return;
191
+ }
192
+ }
193
+ return query;
194
+ }
195
+ function presignedSignature(url, method, secretAccessKey) {
196
+ const pairs = url.search.slice(1).split("&").filter((pair) => !pair.startsWith("X-Amz-Signature=")).sort();
197
+ const canonical = [
198
+ method,
199
+ url.pathname,
200
+ pairs.join("&"),
201
+ `host:${url.host}`,
202
+ "",
203
+ "host",
204
+ "UNSIGNED-PAYLOAD"
205
+ ].join(`
206
+ `);
207
+ const query = rawQueryOf(pairs) ?? new Map;
208
+ const scope = (query.get("X-Amz-Credential") ?? "").split("/").slice(-4);
209
+ const toSign = [
210
+ ALGORITHM,
211
+ query.get("X-Amz-Date") ?? "",
212
+ scope.join("/"),
213
+ createHash("sha256").update(canonical).digest("hex")
214
+ ].join(`
215
+ `);
216
+ const key = signingKey(secretAccessKey, scope[0] ?? "", scope[1] ?? "");
217
+ return createHmac("sha256", key).update(toSign).digest("hex");
218
+ }
219
+ function signPostPolicy(signer, policy) {
220
+ const amzDate = amzDateOf(policy.now);
221
+ const day = amzDate.slice(0, 8);
222
+ const signing = {
223
+ "x-amz-algorithm": ALGORITHM,
224
+ "x-amz-credential": `${signer.accessKeyId}/${day}/${signer.region}/s3/aws4_request`,
225
+ "x-amz-date": amzDate
226
+ };
227
+ if (signer.sessionToken) {
228
+ signing["x-amz-security-token"] = signer.sessionToken;
229
+ }
230
+ const fields = { ...policy.fields, ...signing };
231
+ const document = {
232
+ expiration: new Date(policy.now.getTime() + policy.expiresIn * 1000).toISOString(),
233
+ conditions: [
234
+ { bucket: signer.bucket },
235
+ ...Object.entries(fields).map(([name, value]) => [
236
+ "eq",
237
+ `$${name}`,
238
+ value
239
+ ]),
240
+ ...policy.conditions
241
+ ]
242
+ };
243
+ const encoded = Buffer.from(JSON.stringify(document)).toString("base64");
244
+ const signature = createHmac("sha256", signingKey(signer.secretAccessKey, day, signer.region)).update(encoded).digest("hex");
245
+ return {
246
+ url: signer.url,
247
+ fields: { ...fields, policy: encoded, "x-amz-signature": signature }
248
+ };
249
+ }
250
+
251
+ // src/bucket/operations/post-signer.ts
252
+ var PROBE = "nxgt-probe";
253
+ var SCOPE_PARTS = 5;
254
+ var queryOf = (url) => rawQueryOf(url.search.slice(1).split("&"));
255
+ function checkedSecret(context, probe, where, thing) {
256
+ const secret = secretOf(context);
257
+ if (!secret) {
258
+ throw new TypeError(`${where}: no secret access key to sign with, while Bun has one. ` + "Bun reads S3_SECRET_ACCESS_KEY and AWS_SECRET_ACCESS_KEY when the " + "process starts; one removed since is still Bun’s, and no longer " + "this package’s. Pass `secretAccessKey` to bindBucket");
259
+ }
260
+ const signed = queryOf(probe)?.get("X-Amz-Signature");
261
+ if (presignedSignature(probe, "PUT", secret) !== signed) {
262
+ throw new TypeError(`${where}: the secret access key this package would sign with is not ` + "the one Bun signs with, so the service would refuse the " + `${thing}. Bun ` + "reads S3_SECRET_ACCESS_KEY and AWS_SECRET_ACCESS_KEY when the " + "process starts; one changed since is not the one Bun uses. Pass " + "`secretAccessKey` to bindBucket");
263
+ }
264
+ return secret;
265
+ }
266
+ function signerOf(context, call = "presignPost") {
267
+ const where = callOf(context, call);
268
+ const thing = call === "presignPost" ? "form" : "request";
269
+ const probe = new URL((call === "presignPost" ? context.presignClient : context.client).presign(PROBE, { method: "PUT", expiresIn: 1 }));
270
+ const query = queryOf(probe);
271
+ const scope = (query?.get("X-Amz-Credential") ?? "").split("/");
272
+ if (!query || scope.length < SCOPE_PARTS || !probe.pathname.endsWith(PROBE)) {
273
+ throw new Error(`${where}: the URL Bun signed has no ` + "credential scope, or not the key at the end of its path, so there " + `is nowhere to ${thing === "form" ? "post the form" : "send the request"}. ` + "This Bun signs differently from the one this package was measured on");
274
+ }
275
+ return {
276
+ url: `${probe.origin}${probe.pathname.slice(0, -PROBE.length)}`,
277
+ bucket: context.definition.bucket,
278
+ accessKeyId: scope.slice(0, -4).join("/"),
279
+ region: scope.at(-3),
280
+ secretAccessKey: checkedSecret(context, probe, where, thing),
281
+ sessionToken: query.get("X-Amz-Security-Token")
282
+ };
283
+ }
284
+
285
+ // src/bucket/operations/query-sign.ts
286
+ var encode = (value) => encodeURIComponent(value).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
287
+ function signedBucketGet(signer, query, now = new Date, expiresIn = 60) {
288
+ const amzDate = amzDateOf(now);
289
+ const signing = {
290
+ "X-Amz-Algorithm": "AWS4-HMAC-SHA256",
291
+ "X-Amz-Credential": `${signer.accessKeyId}/${amzDate.slice(0, 8)}/${signer.region}/s3/aws4_request`,
292
+ "X-Amz-Date": amzDate,
293
+ "X-Amz-Expires": String(expiresIn),
294
+ "X-Amz-SignedHeaders": "host"
295
+ };
296
+ if (signer.sessionToken) {
297
+ signing["X-Amz-Security-Token"] = signer.sessionToken;
298
+ }
299
+ const pairs = Object.entries({ ...query, ...signing }).map(([name, value]) => [encode(name), encode(value)]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([name, value]) => `${name}=${value}`);
300
+ const unsigned = new URL(`${signer.url}?${pairs.join("&")}`);
301
+ const signature = presignedSignature(unsigned, "GET", signer.secretAccessKey);
302
+ return `${unsigned.href}&X-Amz-Signature=${signature}`;
303
+ }
304
+
305
+ // src/bucket/operations/list.ts
306
+ async function listObjects(context, options = {}) {
307
+ const timeoutMs = deadlineOf(context, "", "list", options);
308
+ if (timeoutMs === undefined)
309
+ return pageOf(await viaBun(context, options));
310
+ const query = { "list-type": "2" };
311
+ if (options.prefix !== undefined)
312
+ query["prefix"] = options.prefix;
313
+ if (options.limit !== undefined)
314
+ query["max-keys"] = String(options.limit);
315
+ if (options.cursor != null)
316
+ query["continuation-token"] = options.cursor;
317
+ if (options.startAfter !== undefined)
318
+ query["start-after"] = options.startAfter;
319
+ const url = signedBucketGet(signerOf(context, "list"), query);
320
+ return withDeadline(context, "", "list", timeoutMs, async (signal) => pageOf(parseListing(await getListing(context, url, signal))));
321
+ }
322
+ async function viaBun(context, options) {
323
+ const request = {};
324
+ if (options.prefix !== undefined)
325
+ request.prefix = options.prefix;
326
+ if (options.limit !== undefined)
327
+ request.maxKeys = options.limit;
328
+ if (options.cursor != null)
329
+ request.continuationToken = options.cursor;
330
+ if (options.startAfter !== undefined)
331
+ request.startAfter = options.startAfter;
332
+ const answer = await context.client.list(request);
333
+ const contents = answer.contents ?? [];
334
+ return {
335
+ contents: contents.map((found) => ({
336
+ key: found.key,
337
+ size: found.size,
338
+ lastModified: found.lastModified,
339
+ eTag: found.eTag
340
+ })),
341
+ isTruncated: answer.isTruncated === true,
342
+ nextContinuationToken: answer.nextContinuationToken
343
+ };
344
+ }
345
+ function pageOf(answer) {
346
+ const items = answer.contents.map((found) => ({
347
+ key: found.key,
348
+ size: found.size,
349
+ lastModified: found.lastModified ? new Date(found.lastModified) : undefined,
350
+ eTag: found.eTag
351
+ }));
352
+ const next = answer.isTruncated ? answer.nextContinuationToken ?? null : null;
353
+ return { items, nextCursor: next };
354
+ }
355
+
356
+ // src/bucket/operations/open-range.ts
357
+ var isOffset = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
358
+ function rangeHeader(context, key, range) {
359
+ const bad = (what) => new S3Error2("WRONG_OPTION", key, `range is { start, end? } with 0 <= start < end, or { suffix } with ` + `suffix >= 1, as whole numbers; ${what} (${callOf(context, "open")})`);
360
+ if (typeof range !== "object" || range === null || Array.isArray(range)) {
361
+ throw bad(`got ${shapeOf(range)}`);
362
+ }
363
+ const { start, end, suffix } = range;
364
+ if (suffix !== undefined) {
365
+ if (start !== undefined || end !== undefined) {
366
+ throw bad("got a suffix together with a start or an end");
367
+ }
368
+ if (!isOffset(suffix) || suffix < 1) {
369
+ throw bad(`got suffix ${shapeOf(suffix)}`);
370
+ }
371
+ return `bytes=-${suffix}`;
372
+ }
373
+ if (!isOffset(start) || end !== undefined && (!isOffset(end) || end <= start)) {
374
+ throw bad(`got start ${shapeOf(start)}, end ${shapeOf(end)}`);
375
+ }
376
+ return `bytes=${start}-${end === undefined ? "" : end - 1}`;
377
+ }
378
+ function parseContentRange(header) {
379
+ const match = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(header ?? "");
380
+ if (!match)
381
+ return;
382
+ return {
383
+ first: Number(match[1]),
384
+ last: Number(match[2]),
385
+ total: Number(match[3])
386
+ };
387
+ }
388
+
389
+ // src/bucket/operations/open-relay.ts
390
+ function relay(key, body, cancel, skip = 0, take = Number.POSITIVE_INFINITY) {
391
+ const reader = body?.getReader();
392
+ let toSkip = skip;
393
+ let toTake = take;
394
+ return new ReadableStream({
395
+ async pull(controller) {
396
+ if (!reader || toTake <= 0) {
397
+ controller.close();
398
+ cancel.abort();
399
+ return;
400
+ }
401
+ try {
402
+ for (;; ) {
403
+ const next = await reader.read();
404
+ if (next.done)
405
+ return controller.close();
406
+ let chunk = next.value;
407
+ if (toSkip > 0) {
408
+ const dropped = Math.min(toSkip, chunk.length);
409
+ toSkip -= dropped;
410
+ chunk = chunk.subarray(dropped);
411
+ }
412
+ if (chunk.length === 0)
413
+ continue;
414
+ if (chunk.length > toTake)
415
+ chunk = chunk.subarray(0, toTake);
416
+ toTake -= chunk.length;
417
+ controller.enqueue(chunk);
418
+ if (toTake <= 0)
419
+ cancel.abort();
420
+ return;
421
+ }
422
+ } catch (reason) {
423
+ if (cancel.signal.aborted && toTake <= 0)
424
+ return controller.close();
425
+ controller.error(readFailure(reason, key));
426
+ }
427
+ },
428
+ cancel: async (reason) => {
429
+ cancel.abort();
430
+ await reader?.cancel(reason).catch(() => {
431
+ return;
432
+ });
433
+ }
434
+ });
435
+ }
436
+
437
+ // src/bucket/operations/open-answer.ts
438
+ async function discard(response, signal) {
439
+ try {
440
+ await response.body?.cancel();
441
+ } catch (reason) {
442
+ if (signal.aborted)
443
+ throw reason;
444
+ }
445
+ }
446
+ function unsatisfiable(context, key, objectSize) {
447
+ return new S3Error2("RANGE_NOT_SATISFIABLE", key, `${callOf(context, "open")}: the range starts at or past the end of the object` + (objectSize === undefined ? "" : ` (${objectSize} bytes)`), { ...objectSize === undefined ? {} : { objectSize } });
448
+ }
449
+ async function refuse(context, key, response, signal) {
450
+ const { headers, status } = response;
451
+ if (status === 416) {
452
+ await discard(response, signal);
453
+ const size = /^bytes \*\/(\d+)$/.exec(headers.get("content-range") ?? "")?.[1];
454
+ throw unsatisfiable(context, key, size === undefined ? undefined : Number(size));
455
+ }
456
+ let body;
457
+ try {
458
+ body = new Uint8Array(await response.arrayBuffer());
459
+ } catch (reason) {
460
+ if (signal.aborted)
461
+ throw reason;
462
+ throw readFailure(reason, key);
463
+ }
464
+ const error = failure({ status, ok: false, headers, body }, key);
465
+ if (error.code === "NoSuchKey")
466
+ return;
467
+ throw error;
468
+ }
469
+ function numberHeader(headers, name) {
470
+ const value = headers.get(name);
471
+ return value !== null && /^\d+$/.test(value) ? Number(value) : undefined;
472
+ }
473
+ function described(headers) {
474
+ const modified = headers.get("last-modified");
475
+ const date = modified === null ? undefined : new Date(modified);
476
+ return {
477
+ contentType: headers.get("content-type") ?? undefined,
478
+ contentEncoding: headers.get("content-encoding") ?? undefined,
479
+ contentDisposition: headers.get("content-disposition") ?? undefined,
480
+ cacheControl: headers.get("cache-control") ?? undefined,
481
+ eTag: headers.get("etag") ?? undefined,
482
+ lastModified: date && !Number.isNaN(date.getTime()) ? date : undefined
483
+ };
484
+ }
485
+ async function cutLocally(context, key, range, response, cancel) {
486
+ const size = numberHeader(response.headers, "content-length");
487
+ const common = described(response.headers);
488
+ if (size === undefined) {
489
+ const [, from = "", to = ""] = /^bytes=(\d*)-(\d*)$/.exec(range) ?? [];
490
+ if (from === "") {
491
+ await discard(response, cancel.signal);
492
+ throw new S3Error2("RANGE_NOT_SATISFIABLE", key, `${callOf(context, "open")}: the service ignored the range and gave no ` + "Content-Length, so a suffix range cannot be cut: the end of the " + "object is not known");
493
+ }
494
+ const start = Number(from);
495
+ const length = to === "" ? undefined : Number(to) - start + 1;
496
+ return {
497
+ ...common,
498
+ stream: relay(key, response.body, cancel, start, length),
499
+ size: undefined,
500
+ contentLength: length,
501
+ contentRange: undefined
502
+ };
503
+ }
504
+ const [, from = "", to = ""] = /^bytes=(\d*)-(\d*)$/.exec(range) ?? [];
505
+ const first = from === "" ? Math.max(0, size - Number(to)) : Number(from);
506
+ const last = from === "" || to === "" ? size - 1 : Math.min(Number(to), size - 1);
507
+ if (first >= size) {
508
+ await discard(response, cancel.signal);
509
+ throw unsatisfiable(context, key, size);
510
+ }
511
+ return {
512
+ ...common,
513
+ stream: relay(key, response.body, cancel, first, last - first + 1),
514
+ size,
515
+ contentLength: last - first + 1,
516
+ contentRange: `bytes ${first}-${last}/${size}`
517
+ };
518
+ }
519
+ async function answer(context, key, range, response, signal, cancel) {
520
+ const { headers, status } = response;
521
+ if (!response.ok)
522
+ return refuse(context, key, response, signal);
523
+ const common = described(headers);
524
+ const length = numberHeader(headers, "content-length");
525
+ const stream = () => relay(key, response.body, cancel);
526
+ if (status === 206) {
527
+ const parsed = parseContentRange(headers.get("content-range"));
528
+ return {
529
+ ...common,
530
+ stream: stream(),
531
+ size: parsed?.total,
532
+ contentLength: parsed ? parsed.last - parsed.first + 1 : length,
533
+ contentRange: headers.get("content-range") ?? undefined
534
+ };
535
+ }
536
+ if (range === undefined) {
537
+ return {
538
+ ...common,
539
+ stream: stream(),
540
+ size: length,
541
+ contentLength: length,
542
+ contentRange: undefined
543
+ };
544
+ }
545
+ return cutLocally(context, key, range, response, cancel);
546
+ }
547
+
548
+ // src/bucket/operations/open.ts
549
+ async function send2(context, key, range, signal) {
550
+ const url = context.client.presign(key, { method: "GET", expiresIn: 60 });
551
+ try {
552
+ return await fetch(url, {
553
+ method: "GET",
554
+ signal,
555
+ decompress: false,
556
+ ...range ? { headers: { Range: range } } : {}
557
+ });
558
+ } catch (reason) {
559
+ if (signal.aborted)
560
+ throw reason;
561
+ throw readFailure(reason, key);
562
+ }
563
+ }
564
+ async function request(context, key, range, signal, cancel) {
565
+ const response = await send2(context, key, range, signal);
566
+ return answer(context, key, range, response, signal, cancel);
567
+ }
568
+ async function openObject(context, params, options) {
569
+ const key = keyOf(context, params);
570
+ const range = options?.range === undefined ? undefined : rangeHeader(context, key, options.range);
571
+ const timeoutMs = deadlineOf(context, key, "open", options);
572
+ const cancel = new AbortController;
573
+ const bare = context;
574
+ try {
575
+ if (timeoutMs === undefined) {
576
+ return await request(bare, key, range, cancel.signal, cancel);
577
+ }
578
+ return await withDeadline(context, key, "open", timeoutMs, (signal) => request(bare, key, range, AbortSignal.any([signal, cancel.signal]), cancel));
579
+ } catch (reason) {
580
+ cancel.abort();
581
+ throw reason;
582
+ }
583
+ }
584
+
585
+ // src/bucket/disposition.ts
586
+ var PRINTABLE_ASCII = /^[\x20-\x7E]+$/;
587
+ function checkDisposition(key, value, where) {
588
+ if (typeof value === "string" && PRINTABLE_ASCII.test(value))
589
+ return;
590
+ throw new S3Error2("WRONG_OPTION", key, "contentDisposition must be a non-empty string of printable ASCII, " + "with no line break or control character (spell a non-ASCII filename " + `as filename*=UTF-8''...); got ${typeof value === "string" && value !== "" ? "a string with other characters" : shapeOf(value)} (${where})`);
591
+ }
592
+
593
+ // src/bucket/guards.ts
594
+ function essenceOf(type) {
595
+ return (type.split(";")[0] ?? "").trim().toLowerCase();
596
+ }
597
+ function effectiveType(body, named) {
598
+ return named ?? (body instanceof Blob ? body.type || undefined : undefined);
599
+ }
600
+ function sizeOf(body) {
601
+ if (typeof body === "string")
602
+ return Buffer.byteLength(body, "utf8");
603
+ if (body instanceof Blob) {
604
+ return Number.isFinite(body.size) ? body.size : undefined;
605
+ }
606
+ if (body instanceof ArrayBuffer)
607
+ return body.byteLength;
608
+ if (ArrayBuffer.isView(body))
609
+ return body.byteLength;
610
+ return;
611
+ }
612
+ var named = (where) => ` (${where})`;
613
+ function checkType(context, key, type, where) {
614
+ const { accepted } = context;
615
+ if (!accepted)
616
+ return;
617
+ const list = accepted.join(", ");
618
+ const suffix = named(where);
619
+ if (!type) {
620
+ throw new S3Error2("WRONG_TYPE", key, `"${context.definition.bucket}" accepts ${list}, and no content type ` + `was named. Pass \`type\`${suffix}`);
621
+ }
622
+ if (!accepted.some((one) => essenceOf(one) === essenceOf(type))) {
623
+ throw new S3Error2("WRONG_TYPE", key, `"${context.definition.bucket}" accepts ${list}, not the type given${suffix}`);
624
+ }
625
+ }
626
+ function checkSize(context, key, body, where) {
627
+ const { maxSize, bucket } = context.definition;
628
+ if (maxSize === undefined)
629
+ return;
630
+ const size = sizeOf(body);
631
+ if (size === undefined) {
632
+ throw new S3Error2("UNMEASURABLE", key, `"${bucket}" has a maxSize, and this body's size cannot be known ` + "before sending it. Read it into memory first, or drop `maxSize` " + `and let the service refuse it${named(where)}`);
633
+ }
634
+ if (size > maxSize) {
635
+ throw new S3Error2("TOO_LARGE", key, `"${bucket}" accepts ${maxSize} bytes at most, and this body is ` + `${size}${named(where)}`);
636
+ }
637
+ }
638
+ var ACLS = [
639
+ "private",
640
+ "public-read",
641
+ "public-read-write",
642
+ "aws-exec-read",
643
+ "authenticated-read",
644
+ "bucket-owner-read",
645
+ "bucket-owner-full-control",
646
+ "log-delivery-write"
647
+ ];
648
+ var STORAGE_CLASSES = [
649
+ "STANDARD",
650
+ "DEEP_ARCHIVE",
651
+ "EXPRESS_ONEZONE",
652
+ "GLACIER",
653
+ "GLACIER_IR",
654
+ "INTELLIGENT_TIERING",
655
+ "ONEZONE_IA",
656
+ "OUTPOSTS",
657
+ "REDUCED_REDUNDANCY",
658
+ "SNOW",
659
+ "STANDARD_IA"
660
+ ];
661
+ var ALLOWED = {
662
+ acl: ACLS,
663
+ storageClass: STORAGE_CLASSES
664
+ };
665
+ var MAX_EXPIRES_IN = 604800;
666
+ function checkOption(key, name, value, where) {
667
+ if (value === undefined)
668
+ return;
669
+ if (name === "expiresIn") {
670
+ checkExpiresIn(key, value, where);
671
+ return;
672
+ }
673
+ if (name === "contentDisposition") {
674
+ checkDisposition(key, value, where);
675
+ return;
676
+ }
677
+ const allowed = ALLOWED[name];
678
+ if (!allowed)
679
+ return;
680
+ if (!allowed.includes(value)) {
681
+ throw new S3Error2("WRONG_OPTION", key, `${name} must be one of ${allowed.join(", ")}; got ` + `${typeof value === "string" ? "another string" : shapeOf(value)}` + named(where));
682
+ }
683
+ }
684
+ function checkExpiresIn(key, value, where) {
685
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0 || value > MAX_EXPIRES_IN) {
686
+ throw new S3Error2("WRONG_OPTION", key, `expiresIn is seconds, and must be above 0 and at most ` + `${MAX_EXPIRES_IN} (seven days, which is S3's own limit); ` + `got ${tooLong(value) ? "a number above that" : shapeOf(value)}` + named(where));
687
+ }
688
+ }
689
+ var tooLong = (value) => typeof value === "number" && Number.isFinite(value) && value > MAX_EXPIRES_IN;
690
+
691
+ // src/bucket/operations/presign.ts
692
+ var SIGNED_PUT = [
693
+ "expiresIn",
694
+ "acl"
695
+ ];
696
+ var SIGNED_GET = [
697
+ "expiresIn",
698
+ "acl",
699
+ "contentDisposition"
700
+ ];
701
+ function signed(key, options, names, where) {
702
+ const forwarded = {};
703
+ for (const name of names) {
704
+ const value = options?.[name];
705
+ if (value === undefined)
706
+ continue;
707
+ checkOption(key, name, value, where);
708
+ forwarded[name] = value;
709
+ }
710
+ return forwarded;
711
+ }
712
+ function presignGetUrl(context, params, options) {
713
+ const key = keyOf(context, params);
714
+ return context.presignClient.presign(key, {
715
+ ...signed(key, options, SIGNED_GET, callOf(context, "presignGet")),
716
+ method: "GET"
717
+ });
718
+ }
719
+ function presignPutUrl(context, params, options) {
720
+ const key = keyOf(context, params);
721
+ return context.presignClient.presign(key, {
722
+ ...signed(key, options, SIGNED_PUT, callOf(context, "presignPut")),
723
+ method: "PUT"
724
+ });
725
+ }
726
+
727
+ // src/bucket/operations/presign-post.ts
728
+ var DEFAULT_EXPIRES_IN = 86400;
729
+ var callOn = (context) => callOf(context, "presignPost");
730
+ function checkBytes(context, key, name, value, least) {
731
+ if (typeof value === "number" && Number.isSafeInteger(value)) {
732
+ if (value >= least)
733
+ return;
734
+ }
735
+ throw new S3Error2("WRONG_OPTION", key, `${callOn(context)}: ${name} is a whole number of bytes, at least ` + `${least}; got ${shapeOf(value)}`);
736
+ }
737
+ function sizeRange(context, key, options) {
738
+ const bound = context.definition.maxSize;
739
+ const max = options?.maxSize ?? bound;
740
+ if (max === undefined) {
741
+ throw new S3Error2("WRONG_OPTION", key, `${callOn(context)}: this bucket has no maxSize, and a presigned POST ` + "is a bound on what a browser uploads. Pass `maxSize`, in bytes");
742
+ }
743
+ checkBytes(context, key, "maxSize", max, 1);
744
+ if (bound !== undefined && max > bound) {
745
+ throw new S3Error2("WRONG_OPTION", key, `${callOn(context)}: maxSize cannot be above the bucket's own ` + `${bound} bytes; got a larger number`);
746
+ }
747
+ const min = options?.minSize ?? 0;
748
+ checkBytes(context, key, "minSize", min, 0);
749
+ if (min > max) {
750
+ throw new S3Error2("WRONG_OPTION", key, `${callOn(context)}: minSize is above maxSize, so no body could be posted`);
751
+ }
752
+ return ["content-length-range", min, max];
753
+ }
754
+ function isPrefix(type) {
755
+ return typeof type === "object" && type !== null && typeof type.startsWith === "string";
756
+ }
757
+ function typeRule(context, key, type) {
758
+ const { accepted } = context;
759
+ if (type === undefined) {
760
+ if (!accepted)
761
+ return { condition: ["starts-with", "$Content-Type", ""] };
762
+ if (accepted.length === 1)
763
+ return { field: accepted[0] };
764
+ checkType(context, key, undefined, callOn(context));
765
+ }
766
+ if (typeof type === "string" && type.length > 0) {
767
+ checkType(context, key, type, callOn(context));
768
+ return { field: type };
769
+ }
770
+ if (isPrefix(type)) {
771
+ if (accepted) {
772
+ throw new S3Error2("WRONG_TYPE", key, `${callOn(context)}: this bucket accepts ${accepted.join(", ")}, ` + "and a prefix would let another type through. Pass one of them " + "as `type`");
773
+ }
774
+ return {
775
+ condition: ["starts-with", "$Content-Type", type.startsWith]
776
+ };
777
+ }
778
+ throw new S3Error2("WRONG_OPTION", key, `${callOn(context)}: type is a content type ` + `or { startsWith }; got ${shapeOf(type)}`);
779
+ }
780
+ function presignPostForm(context, params, options, now = new Date) {
781
+ const key = keyOf(context, params);
782
+ const expiresIn = options?.expiresIn ?? DEFAULT_EXPIRES_IN;
783
+ checkOption(key, "expiresIn", expiresIn, callOn(context));
784
+ const range = sizeRange(context, key, options);
785
+ const rule = typeRule(context, key, options?.type);
786
+ const fields = { key };
787
+ if ("field" in rule)
788
+ fields["Content-Type"] = rule.field;
789
+ if (options?.acl !== undefined) {
790
+ checkOption(key, "acl", options.acl, callOn(context));
791
+ fields["acl"] = options.acl;
792
+ }
793
+ if (options?.contentDisposition !== undefined) {
794
+ checkOption(key, "contentDisposition", options.contentDisposition, callOn(context));
795
+ fields["Content-Disposition"] = options.contentDisposition;
796
+ }
797
+ return signPostPolicy(signerOf(context), {
798
+ fields,
799
+ conditions: "condition" in rule ? [range, rule.condition] : [range],
800
+ expiresIn,
801
+ now
802
+ });
803
+ }
804
+
805
+ // src/bucket/operations/reads.ts
806
+ async function whenPresent(context, params, read) {
807
+ try {
808
+ return await read(context.client.file(keyOf(context, params)));
809
+ } catch (reason) {
810
+ if (reason.code === "NoSuchKey")
811
+ return;
812
+ throw reason;
813
+ }
814
+ }
815
+ async function readBytes(context, params, options) {
816
+ const key = keyOf(context, params);
817
+ const timeoutMs = deadlineOf(context, key, "bytes", options);
818
+ if (timeoutMs === undefined) {
819
+ return whenPresent(context, params, (file) => file.bytes());
820
+ }
821
+ return withDeadline(context, key, "bytes", timeoutMs, (signal) => getObject(context, key, signal));
822
+ }
823
+ async function readText(context, params, options) {
824
+ const key = keyOf(context, params);
825
+ const timeoutMs = deadlineOf(context, key, "text", options);
826
+ if (timeoutMs === undefined) {
827
+ return whenPresent(context, params, (file) => file.text());
828
+ }
829
+ return withDeadline(context, key, "text", timeoutMs, async (signal) => {
830
+ const found = await getObject(context, key, signal);
831
+ return found && new TextDecoder().decode(found);
832
+ });
833
+ }
834
+ async function statObject(context, params, options) {
835
+ const key = keyOf(context, params);
836
+ const timeoutMs = deadlineOf(context, key, "stat", options);
837
+ if (timeoutMs === undefined) {
838
+ return whenPresent(context, params, (file) => file.stat());
839
+ }
840
+ return withDeadline(context, key, "stat", timeoutMs, (signal) => headObject(context, key, signal));
841
+ }
842
+ async function objectExists(context, params, options) {
843
+ const key = keyOf(context, params);
844
+ const timeoutMs = deadlineOf(context, key, "exists", options);
845
+ if (timeoutMs === undefined)
846
+ return context.client.exists(key);
847
+ return withDeadline(context, key, "exists", timeoutMs, async (signal) => await headObject(context, key, signal) !== undefined);
848
+ }
849
+
850
+ // src/bucket/operations/slice.ts
851
+ var isOffset2 = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
852
+ function checkRange(context, key, range) {
853
+ const { start, end } = range ?? {};
854
+ if (!isOffset2(start) || !isOffset2(end) || end < start) {
855
+ throw new S3Error2("WRONG_OPTION", key, `range is { start, end } as whole numbers with 0 <= start <= end; ` + `got start ${shapeOf(start)}, end ${shapeOf(end)} (${callOf(context, "slice")})`);
856
+ }
857
+ }
858
+ var streamOf = (bytes) => new ReadableStream({
859
+ start(controller) {
860
+ if (bytes.length > 0)
861
+ controller.enqueue(bytes);
862
+ controller.close();
863
+ }
864
+ });
865
+ async function bunSlice(context, key, { start, end }) {
866
+ const file = context.client.file(key);
867
+ if (start === end)
868
+ return await file.exists() ? streamOf(new Uint8Array) : undefined;
869
+ const reader = file.slice(start, end).stream().getReader();
870
+ let first;
871
+ try {
872
+ first = await reader.read();
873
+ } catch (reason) {
874
+ const { code } = reason;
875
+ if (code === "NoSuchKey")
876
+ return;
877
+ if (code === "InvalidRange")
878
+ return streamOf(new Uint8Array);
879
+ throw reason;
880
+ }
881
+ return new ReadableStream({
882
+ start(controller) {
883
+ if (first.done)
884
+ controller.close();
885
+ else
886
+ controller.enqueue(first.value);
887
+ },
888
+ async pull(controller) {
889
+ if (first.done)
890
+ return;
891
+ const next = await reader.read();
892
+ if (next.done)
893
+ controller.close();
894
+ else
895
+ controller.enqueue(next.value);
896
+ },
897
+ cancel: (reason) => reader.cancel(reason)
898
+ });
899
+ }
900
+ async function sliceObject(context, params, range, options) {
901
+ const key = keyOf(context, params);
902
+ checkRange(context, key, range);
903
+ const timeoutMs = deadlineOf(context, key, "slice", options);
904
+ if (timeoutMs === undefined)
905
+ return bunSlice(context, key, range);
906
+ return withDeadline(context, key, "slice", timeoutMs, async (signal) => {
907
+ if (range.start === range.end) {
908
+ return await headObject(context, key, signal) && streamOf(new Uint8Array);
909
+ }
910
+ const bytes = await getRange(context, key, range, signal);
911
+ return bytes && streamOf(bytes);
912
+ });
913
+ }
914
+
915
+ // src/bucket/operations/counted-stream.ts
916
+ function countedStream(source, size, key, where, watch = () => {}) {
917
+ let reader;
918
+ let iterator;
919
+ try {
920
+ if (source instanceof ReadableStream)
921
+ reader = source.getReader();
922
+ else
923
+ iterator = source[Symbol.asyncIterator]();
924
+ } catch (reason) {
925
+ throw sourceFailed(key, where, 0, "could not be read", reason);
926
+ }
927
+ const state = {
928
+ reader,
929
+ iterator,
930
+ key,
931
+ where,
932
+ size,
933
+ sent: 0,
934
+ ahead: undefined,
935
+ failure: undefined,
936
+ watch
937
+ };
938
+ const body = new ReadableStream({
939
+ pull: (controller) => pullStep(state, controller),
940
+ cancel: (reason) => stopSource(state, reason)
941
+ }, { highWaterMark: 0 });
942
+ return { body, failure: () => state.failure };
943
+ }
944
+ function mismatch(key, where, size, what) {
945
+ return new S3Error2("SIZE_MISMATCH", key, `the stream ${what} the declared size of ${size} bytes; the upload ` + `was aborted and nothing is stored (${where})`);
946
+ }
947
+ function sourceFailed(key, where, sent, what, cause) {
948
+ return new S3Error2("SOURCE_FAILED", key, `the stream ${what} after ${sent} bytes; the upload was aborted and ` + `nothing is stored (${where})`, { cause });
949
+ }
950
+ function stopSource(state, reason) {
951
+ try {
952
+ const ended = state.reader ? state.reader.cancel(reason) : state.iterator?.return?.();
953
+ Promise.resolve(ended).catch(() => {});
954
+ } catch {}
955
+ }
956
+ async function readChunk(state) {
957
+ for (;; ) {
958
+ const step = state.reader ? await state.reader.read() : await state.iterator?.next();
959
+ if (!step || step.done)
960
+ return { done: true };
961
+ if (!(step.value instanceof Uint8Array)) {
962
+ throw sourceFailed(state.key, state.where, state.sent, `gave ${shapeOf(step.value)}, not bytes`);
963
+ }
964
+ if (step.value.byteLength > 0)
965
+ return { done: false, value: step.value };
966
+ }
967
+ }
968
+ async function pullStep(state, controller) {
969
+ const { key, where, size, watch } = state;
970
+ watch(true);
971
+ try {
972
+ const current = state.ahead ?? await readChunk(state);
973
+ state.ahead = undefined;
974
+ if (current.done) {
975
+ if (state.sent !== size) {
976
+ throw mismatch(key, where, size, `ended after ${state.sent} bytes, short of`);
977
+ }
978
+ controller.close();
979
+ watch(true);
980
+ return;
981
+ }
982
+ state.sent += current.value.byteLength;
983
+ if (state.sent > size)
984
+ throw mismatch(key, where, size, "has more bytes than");
985
+ if (state.sent === size) {
986
+ state.ahead = await readChunk(state);
987
+ if (!state.ahead.done) {
988
+ throw mismatch(key, where, size, "has more bytes than");
989
+ }
990
+ }
991
+ controller.enqueue(current.value);
992
+ watch(true);
993
+ } catch (reason) {
994
+ const error = reason instanceof S3Error2 ? reason : sourceFailed(key, where, state.sent, "failed", reason);
995
+ state.failure = error;
996
+ stopSource(state);
997
+ controller.error(error);
998
+ }
999
+ }
1000
+
1001
+ // src/bucket/operations/put-body.ts
1002
+ function sendable(body) {
1003
+ if (typeof body === "string")
1004
+ return true;
1005
+ if (body instanceof ArrayBuffer || ArrayBuffer.isView(body))
1006
+ return true;
1007
+ return body instanceof Blob && Number.isFinite(body.size);
1008
+ }
1009
+ async function checkFileThere(body) {
1010
+ if (!(body instanceof Blob) || !Number.isFinite(body.size))
1011
+ return;
1012
+ const file = body;
1013
+ if (typeof file.exists !== "function" || await file.exists())
1014
+ return;
1015
+ const path = file.name ?? "";
1016
+ const error = new Error(`ENOENT: no such file or directory, open '${path}'`);
1017
+ error.code = "ENOENT";
1018
+ error.path = path;
1019
+ error.errno = -2;
1020
+ error.syscall = "open";
1021
+ throw error;
1022
+ }
1023
+ function streamOf2(body) {
1024
+ if (body instanceof ReadableStream)
1025
+ return body;
1026
+ if (body instanceof Response || body instanceof Request) {
1027
+ return body.body ?? undefined;
1028
+ }
1029
+ if (body instanceof Blob)
1030
+ return body.stream();
1031
+ return new Response(body).body ?? undefined;
1032
+ }
1033
+ async function gather(stream, signal) {
1034
+ const reader = stream.getReader();
1035
+ const onAbort = () => void reader.cancel(signal.reason).catch(() => {});
1036
+ if (signal.aborted)
1037
+ onAbort();
1038
+ else
1039
+ signal.addEventListener("abort", onAbort, { once: true });
1040
+ const chunks = [];
1041
+ let length = 0;
1042
+ try {
1043
+ for (;; ) {
1044
+ const { done, value } = await reader.read();
1045
+ if (signal.aborted)
1046
+ throw signal.reason;
1047
+ if (done)
1048
+ break;
1049
+ chunks.push(value);
1050
+ length += value.byteLength;
1051
+ }
1052
+ } finally {
1053
+ signal.removeEventListener("abort", onAbort);
1054
+ }
1055
+ const whole = new Uint8Array(length);
1056
+ let at = 0;
1057
+ for (const chunk of chunks) {
1058
+ whole.set(chunk, at);
1059
+ at += chunk.byteLength;
1060
+ }
1061
+ return whole;
1062
+ }
1063
+ async function fetchBody(body, signal) {
1064
+ await checkFileThere(body);
1065
+ if (sendable(body))
1066
+ return body;
1067
+ const stream = streamOf2(body);
1068
+ return stream ? gather(stream, signal) : new Uint8Array(0);
1069
+ }
1070
+
1071
+ // src/bucket/operations/sized-body.ts
1072
+ function isStreamBody(body) {
1073
+ return body instanceof ReadableStream || typeof body === "object" && body !== null && typeof body[Symbol.asyncIterator] === "function";
1074
+ }
1075
+ function classify(key, body, size, where) {
1076
+ const streams = isStreamBody(body);
1077
+ if (size === undefined) {
1078
+ if (streams && !(body instanceof ReadableStream)) {
1079
+ throw new S3Error2("WRONG_OPTION", key, `an AsyncIterable body needs \`size\`, the number of bytes it will give (${where})`);
1080
+ }
1081
+ return { body };
1082
+ }
1083
+ if (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) {
1084
+ throw new S3Error2("WRONG_OPTION", key, `size is a whole number of bytes, 0 or more; got ${shapeOf(size)} (${where})`);
1085
+ }
1086
+ if (!streams) {
1087
+ throw new S3Error2("WRONG_OPTION", key, `size goes with a ReadableStream or an AsyncIterable body; this body ` + `knows its own length (${where})`);
1088
+ }
1089
+ return { body, size };
1090
+ }
1091
+ function checkDeclaredSize(context, key, size, where) {
1092
+ const { maxSize, bucket } = context.definition;
1093
+ if (maxSize !== undefined && size > maxSize) {
1094
+ throw new S3Error2("TOO_LARGE", key, `"${bucket}" accepts ${maxSize} bytes at most, and this body is ` + `${size} (${where})`);
1095
+ }
1096
+ }
1097
+
1098
+ // src/bucket/operations/writes.ts
1099
+ async function putObject(context, params, body, options = {}) {
1100
+ const key = keyOf(context, params);
1101
+ const where = callOf(context, "put");
1102
+ const write = classify(key, body, options.size, where);
1103
+ const type = effectiveType(write.body, options.type);
1104
+ checkType(context, key, type, where);
1105
+ if (write.size === undefined)
1106
+ checkSize(context, key, write.body, where);
1107
+ else
1108
+ checkDeclaredSize(context, key, write.size, where);
1109
+ const forwarded = passed(key, options, where);
1110
+ if (write.size !== undefined) {
1111
+ await putStream(context, key, write.body, write.size, type, forwarded, checkTimeout(key, options.timeoutMs, where), where);
1112
+ return;
1113
+ }
1114
+ const timeoutMs = deadlineOf(context, key, "put", options);
1115
+ if (timeoutMs !== undefined) {
1116
+ await withDeadline(context, key, "put", timeoutMs, async (signal) => storeObject(context, key, {
1117
+ ...headOf(type, forwarded),
1118
+ body: await fetchBody(write.body, signal)
1119
+ }, signal));
1120
+ return;
1121
+ }
1122
+ await context.client.write(key, write.body, {
1123
+ ...forwarded,
1124
+ ...type ? { type } : {}
1125
+ });
1126
+ }
1127
+ async function putStream(context, key, source, size, type, forwarded, timeoutMs, where) {
1128
+ const controller = new AbortController;
1129
+ let timer;
1130
+ const watch = (waiting) => {
1131
+ clearTimeout(timer);
1132
+ timer = waiting && timeoutMs !== undefined ? setTimeout(() => controller.abort(), timeoutMs) : undefined;
1133
+ };
1134
+ const counted = countedStream(source, size, key, where, watch);
1135
+ const head = headOf(type, forwarded);
1136
+ const request = {
1137
+ ...head,
1138
+ body: counted.body,
1139
+ headers: { ...head.headers, "Content-Length": String(size) }
1140
+ };
1141
+ try {
1142
+ watch(true);
1143
+ await storeObject(context, key, request, controller.signal);
1144
+ } catch (reason) {
1145
+ if (!controller.signal.aborted)
1146
+ throw counted.failure() ?? reason;
1147
+ throw new S3Error2("TIMEOUT", key, `${where}: nothing moved in ${timeoutMs}ms`);
1148
+ } finally {
1149
+ watch(false);
1150
+ }
1151
+ }
1152
+ function headOf(type, options) {
1153
+ const headers = {
1154
+ "Content-Type": new Blob([], { type: type ?? "application/octet-stream" }).type
1155
+ };
1156
+ if (options.contentDisposition) {
1157
+ headers["Content-Disposition"] = options.contentDisposition;
1158
+ }
1159
+ if (options.contentEncoding) {
1160
+ headers["Content-Encoding"] = options.contentEncoding;
1161
+ }
1162
+ const signed = {};
1163
+ if (options.acl)
1164
+ signed.acl = options.acl;
1165
+ if (options.storageClass)
1166
+ signed.storageClass = options.storageClass;
1167
+ return { headers, signed };
1168
+ }
1169
+ var PASSED = [
1170
+ "acl",
1171
+ "storageClass",
1172
+ "contentDisposition",
1173
+ "contentEncoding"
1174
+ ];
1175
+ function passed(key, options, where) {
1176
+ const forwarded = {};
1177
+ for (const name of PASSED) {
1178
+ const value = options[name];
1179
+ if (value === undefined)
1180
+ continue;
1181
+ checkOption(key, name, value, where);
1182
+ forwarded[name] = value;
1183
+ }
1184
+ return forwarded;
1185
+ }
1186
+ async function deleteObject(context, params, options) {
1187
+ const key = keyOf(context, params);
1188
+ const timeoutMs = deadlineOf(context, key, "delete", options);
1189
+ if (timeoutMs === undefined) {
1190
+ await context.client.delete(key);
1191
+ return;
1192
+ }
1193
+ await withDeadline(context, key, "delete", timeoutMs, (signal) => removeObject(context, key, signal));
1194
+ }
1195
+
1196
+ // src/bucket/bind-bucket.ts
1197
+ var trimmed = (endpoint) => endpoint?.replace(/\/+$/, "");
1198
+ function bindBucket(definition, options = {}) {
1199
+ const { timeoutMs, publicEndpoint, ...clientOptions } = options;
1200
+ if (timeoutMs !== undefined && !isWholeMs(timeoutMs)) {
1201
+ throw new TypeError(`bindBucket on "${definition.bucket}": timeoutMs is a whole number of ` + `milliseconds, 1 or more; got ${shapeOf(timeoutMs)}`);
1202
+ }
1203
+ if (publicEndpoint !== undefined && !URL.canParse(publicEndpoint)) {
1204
+ throw new TypeError(`bindBucket on "${definition.bucket}": publicEndpoint is an absolute ` + `URL such as https://media.example.com; got ${shapeOf(publicEndpoint)}`);
1205
+ }
1206
+ const deadline = timeoutMs;
1207
+ const client = new S3Client({ ...clientOptions, bucket: definition.bucket });
1208
+ const presignClient = publicEndpoint === undefined || trimmed(publicEndpoint) === trimmed(options.endpoint) ? client : new S3Client({
1209
+ ...clientOptions,
1210
+ endpoint: publicEndpoint,
1211
+ bucket: definition.bucket
1212
+ });
1213
+ const context = bucketContext(client, definition, options.secretAccessKey, deadline, presignClient);
1214
+ return {
1215
+ client,
1216
+ keyFor: (params) => keyOf(context, params),
1217
+ parseKey: (key) => parseKeyOf(context, key),
1218
+ file: (params) => client.file(keyOf(context, params)),
1219
+ put: putObject.bind(null, context),
1220
+ bytes: (params, callOptions) => readBytes(context, params, callOptions),
1221
+ slice: (params, range, callOptions) => sliceObject(context, params, range, callOptions),
1222
+ open: (params, openOptions) => openObject(context, params, openOptions),
1223
+ text: (params, callOptions) => readText(context, params, callOptions),
1224
+ exists: (params, callOptions) => objectExists(context, params, callOptions),
1225
+ stat: (params, callOptions) => statObject(context, params, callOptions),
1226
+ delete: (params, callOptions) => deleteObject(context, params, callOptions),
1227
+ list: (listOptions) => listObjects(context, listOptions),
1228
+ presignGet: (params, presignOptions) => presignGetUrl(context, params, presignOptions),
1229
+ presignPut: (params, presignOptions) => presignPutUrl(context, params, presignOptions),
1230
+ presignPost: (params, postOptions) => presignPostForm(context, params, postOptions)
1231
+ };
1232
+ }
1233
+ // src/bucket/define-bucket.ts
1234
+ function defineBucket(definition) {
1235
+ if (definition.bucket.length === 0) {
1236
+ throw new TypeError("defineBucket: a bucket definition needs a bucket");
1237
+ }
1238
+ if (definition.maxSize !== undefined) {
1239
+ const { maxSize } = definition;
1240
+ if (!Number.isFinite(maxSize) || maxSize <= 0) {
1241
+ throw new TypeError(`defineBucket: "${definition.bucket}" has a maxSize of ${maxSize}; ` + "it is a number of bytes, and must be above zero");
1242
+ }
1243
+ }
1244
+ const types = definition.contentType;
1245
+ if (Array.isArray(types) && types.length === 0) {
1246
+ throw new TypeError(`defineBucket: "${definition.bucket}" accepts an empty list of ` + "content types, so nothing could ever be written. Leave " + "`contentType` out to accept anything");
1247
+ }
1248
+ return Object.freeze({ ...definition });
1249
+ }
1250
+ // src/errors/is-bucket-unavailable.ts
1251
+ var UNAVAILABLE_CODES = new Set([
1252
+ "TIMEOUT",
1253
+ "ConnectionRefused",
1254
+ "ConnectionClosed",
1255
+ "DNSResolveFailed",
1256
+ "ECONNREFUSED",
1257
+ "ECONNRESET",
1258
+ "ECONNABORTED",
1259
+ "ETIMEDOUT",
1260
+ "EHOSTUNREACH",
1261
+ "ENETUNREACH",
1262
+ "ENOTFOUND",
1263
+ "EAI_AGAIN",
1264
+ "EPIPE",
1265
+ "AccessDenied",
1266
+ "InvalidAccessKeyId",
1267
+ "SignatureDoesNotMatch",
1268
+ "NoSuchBucket",
1269
+ "ExpiredToken",
1270
+ "InternalError",
1271
+ "ServiceUnavailable",
1272
+ "SlowDown"
1273
+ ]);
1274
+ function isBucketUnavailable(error) {
1275
+ if (!(error instanceof Error))
1276
+ return false;
1277
+ const { code } = error;
1278
+ return typeof code === "string" && UNAVAILABLE_CODES.has(code);
1279
+ }
1280
+ export {
1281
+ S3Error2 as S3Error,
1282
+ bindBucket,
1283
+ defineBucket,
1284
+ isBucketUnavailable
1285
+ };
1286
+
1287
+ //# debugId=F9795A19D400B5C464756E2164756E21
1288
+ //# sourceMappingURL=index.js.map