@dimah-s3/core 1.7.0 → 2.0.0-beta.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 (78) hide show
  1. package/README.md +32 -13
  2. package/dist/create-s3-client.d.ts +3 -0
  3. package/dist/create-s3-client.d.ts.map +1 -1
  4. package/dist/error-codes.d.ts +297 -29
  5. package/dist/error-codes.d.ts.map +1 -1
  6. package/dist/error.d.ts +46 -14
  7. package/dist/error.d.ts.map +1 -1
  8. package/dist/helpers/base64url.d.ts +18 -0
  9. package/dist/helpers/base64url.d.ts.map +1 -0
  10. package/dist/helpers/build-content-disposition.d.ts +4 -4
  11. package/dist/helpers/build-content-disposition.d.ts.map +1 -1
  12. package/dist/helpers/build-object-key.d.ts.map +1 -1
  13. package/dist/helpers/checksum.d.ts +8 -2
  14. package/dist/helpers/checksum.d.ts.map +1 -1
  15. package/dist/helpers/content-type.d.ts +17 -0
  16. package/dist/helpers/content-type.d.ts.map +1 -0
  17. package/dist/helpers/fit-file-name.d.ts +15 -0
  18. package/dist/helpers/fit-file-name.d.ts.map +1 -0
  19. package/dist/helpers/index.d.ts +7 -9
  20. package/dist/helpers/index.d.ts.map +1 -1
  21. package/dist/helpers/magic-bytes.d.ts +9 -2
  22. package/dist/helpers/magic-bytes.d.ts.map +1 -1
  23. package/dist/helpers/normalize-object-key.d.ts +8 -3
  24. package/dist/helpers/normalize-object-key.d.ts.map +1 -1
  25. package/dist/helpers/parse-file-name.d.ts +5 -0
  26. package/dist/helpers/parse-file-name.d.ts.map +1 -1
  27. package/dist/helpers/public-object-url.d.ts.map +1 -1
  28. package/dist/helpers/resolve-inline-disposition.d.ts +16 -6
  29. package/dist/helpers/resolve-inline-disposition.d.ts.map +1 -1
  30. package/dist/helpers/strip-slashes.d.ts +5 -0
  31. package/dist/helpers/strip-slashes.d.ts.map +1 -0
  32. package/dist/helpers/validate-file.d.ts +13 -16
  33. package/dist/helpers/validate-file.d.ts.map +1 -1
  34. package/dist/index.d.ts +2 -2
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +713 -465
  37. package/dist/index.js.map +1 -1
  38. package/dist/limits.d.ts +30 -0
  39. package/dist/limits.d.ts.map +1 -0
  40. package/dist/plugin/create-s3-fetch.d.ts +5 -3
  41. package/dist/plugin/create-s3-fetch.d.ts.map +1 -1
  42. package/dist/plugin/types.d.ts +13 -4
  43. package/dist/plugin/types.d.ts.map +1 -1
  44. package/dist/routes.d.ts +10 -4
  45. package/dist/routes.d.ts.map +1 -1
  46. package/dist/schema/catalog.d.ts +30 -39
  47. package/dist/schema/catalog.d.ts.map +1 -1
  48. package/dist/schema/delete.d.ts +1 -2
  49. package/dist/schema/delete.d.ts.map +1 -1
  50. package/dist/schema/download.d.ts +16 -3
  51. package/dist/schema/download.d.ts.map +1 -1
  52. package/dist/schema/index.d.ts +5 -9
  53. package/dist/schema/index.d.ts.map +1 -1
  54. package/dist/schema/index.js +221 -0
  55. package/dist/schema/index.js.map +1 -0
  56. package/dist/schema/multipart.d.ts +6 -29
  57. package/dist/schema/multipart.d.ts.map +1 -1
  58. package/dist/schema/shared.d.ts +25 -17
  59. package/dist/schema/shared.d.ts.map +1 -1
  60. package/dist/schema/upload.d.ts +10 -7
  61. package/dist/schema/upload.d.ts.map +1 -1
  62. package/dist/types/index.d.ts +2 -2
  63. package/dist/types/index.d.ts.map +1 -1
  64. package/dist/types/requests.d.ts +25 -31
  65. package/dist/types/requests.d.ts.map +1 -1
  66. package/dist/types/responses.d.ts +96 -83
  67. package/dist/types/responses.d.ts.map +1 -1
  68. package/package.json +9 -4
  69. package/dist/helpers/format-file-size.d.ts +0 -18
  70. package/dist/helpers/format-file-size.d.ts.map +0 -1
  71. package/dist/helpers/sanitize-file-name.d.ts +0 -3
  72. package/dist/helpers/sanitize-file-name.d.ts.map +0 -1
  73. package/dist/helpers/truncate-file-name.d.ts +0 -5
  74. package/dist/helpers/truncate-file-name.d.ts.map +0 -1
  75. package/dist/schema/error.d.ts +0 -14
  76. package/dist/schema/error.d.ts.map +0 -1
  77. package/dist/schema/file.d.ts +0 -12
  78. package/dist/schema/file.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,120 +1,201 @@
1
- import * as z3 from 'zod';
2
- import { APIError as APIError$1 } from 'better-call/error';
1
+ import { statusCodes, APIError as APIError$1 } from 'better-call/error';
2
+ import { sha256 } from '@noble/hashes/sha2.js';
3
3
  import { createFetch } from '@better-fetch/fetch';
4
4
 
5
- // src/helpers/validate-file.ts
6
- function matchesFileTypes(fileName, contentType, fileTypes) {
7
- if (!fileTypes.length) return true;
8
- const type = contentType ?? "";
9
- return fileTypes.some((token) => {
10
- if (token.startsWith(".")) {
11
- return fileName.toLowerCase().endsWith(token.toLowerCase());
12
- }
13
- if (token.endsWith("/*")) {
14
- return type.startsWith(token.slice(0, -1));
15
- }
16
- return type === token;
17
- });
18
- }
19
- function validateFile(file, options) {
20
- if (options.accept?.length) {
21
- if (!matchesFileTypes(file.name, file.type, options.accept)) {
22
- const ext = file.name.includes(".") ? file.name.split(".").pop() : null;
23
- const type = ext ? `.${ext}` : file.type || "unknown";
24
- return {
25
- code: "FILE_TYPE_NOT_ALLOWED",
26
- message: `File type "${type}" is not allowed`,
27
- params: { type }
28
- };
29
- }
30
- }
31
- if (file.size === 0) {
32
- return {
33
- code: "FILE_EMPTY",
34
- message: "File is empty"
35
- };
5
+ // src/error.ts
6
+
7
+ // src/error-codes.ts
8
+ function defineErrorCodes(codes) {
9
+ const entries = {};
10
+ for (const code of Object.keys(codes)) {
11
+ entries[code] = { code, ...codes[code] };
36
12
  }
37
- if (typeof options.maxFileSize === "number" && file.size > options.maxFileSize) {
38
- const maxMB = (options.maxFileSize / (1024 * 1024)).toFixed(1);
39
- return {
40
- code: "FILE_TOO_LARGE",
41
- message: `File size exceeds ${maxMB} MB limit`,
42
- params: { size: `${maxMB} MB` }
43
- };
13
+ return entries;
14
+ }
15
+ var S3_ERROR_CODES = defineErrorCodes({
16
+ // protocol
17
+ VALIDATION_ERROR: { status: 400, message: "Invalid request: {issue}" },
18
+ REQUEST_TOO_LARGE: {
19
+ status: 413,
20
+ message: "Request body exceeds {maxSize} bytes"
21
+ },
22
+ UNSUPPORTED_MEDIA_TYPE: {
23
+ status: 415,
24
+ message: "Request body must be application/json"
25
+ },
26
+ NOT_FOUND: { status: 404, message: "Not found" },
27
+ UNAUTHORIZED: { status: 401, message: "Unauthorized" },
28
+ FORBIDDEN: { status: 403, message: "Forbidden" },
29
+ /** A concurrent change won; retrying may succeed. */
30
+ CONFLICT: { status: 409, message: "Conflict" },
31
+ INTERNAL_ERROR: { status: 500, message: "Internal server error" },
32
+ S3_NETWORK_ERROR: {
33
+ status: 502,
34
+ message: "S3 endpoint unreachable ({code})"
35
+ },
36
+ UNKNOWN_ROUTE: { status: 404, message: 'Unknown file route "{route}"' },
37
+ FEATURE_DISABLED: { status: 404, message: "{feature} is disabled" },
38
+ KEY_INVALID: { status: 400, message: "Object key is invalid" },
39
+ OBJECT_NOT_FOUND: { status: 404, message: "Object not found" },
40
+ RANGE_NOT_SATISFIABLE: {
41
+ status: 416,
42
+ message: "Requested range not satisfiable"
43
+ },
44
+ PRECONDITION_FAILED: { status: 412, message: "Precondition failed" },
45
+ // files
46
+ FILE_EMPTY: { status: 400, message: "File is empty" },
47
+ FILE_TOO_LARGE: {
48
+ status: 413,
49
+ message: "File is {size} bytes; the limit is {maxFileSize} bytes"
50
+ },
51
+ FILE_TYPE_NOT_ALLOWED: {
52
+ status: 400,
53
+ message: 'File type "{type}" is not allowed'
54
+ },
55
+ FILE_CONTENT_MISMATCH: {
56
+ status: 400,
57
+ message: 'File content does not match type "{type}"'
58
+ },
59
+ CHECKSUM_REQUIRED: {
60
+ status: 400,
61
+ message: "A SHA-256 checksum is required"
62
+ },
63
+ QUOTA_EXCEEDED: { status: 403, message: "Storage quota exceeded" },
64
+ // upload sessions
65
+ UPLOAD_TICKET_INVALID: { status: 403, message: "Upload ticket is invalid" },
66
+ UPLOAD_TICKET_EXPIRED: { status: 410, message: "Upload ticket has expired" },
67
+ UPLOAD_SIZE_MISMATCH: {
68
+ status: 400,
69
+ message: "Uploaded {actual} bytes; expected {expected}"
70
+ },
71
+ MULTIPART_PART_MISSING: {
72
+ status: 400,
73
+ message: "Uploaded part {partNumber} was not found"
74
+ },
75
+ MULTIPART_PART_INVALID: {
76
+ status: 400,
77
+ message: "Part {partNumber} is outside 1..{partCount}"
78
+ },
79
+ // db plugin
80
+ OBJECT_EXISTS: {
81
+ status: 409,
82
+ message: "An object already exists at this key"
83
+ },
84
+ FOLDER_INVALID: { status: 400, message: "Folder path is invalid" },
85
+ FOLDER_EXISTS: { status: 409, message: "Folder already exists" },
86
+ FOLDER_NOT_EMPTY: { status: 409, message: "Folder is not empty" },
87
+ // client-only (never sent by the server)
88
+ TOO_MANY_FILES: {
89
+ status: 400,
90
+ client: true,
91
+ message: "At most {maxFiles} files can be added"
92
+ },
93
+ HOOK_FAILED: {
94
+ status: 500,
95
+ client: true,
96
+ message: "The {hook} callback failed"
97
+ },
98
+ NETWORK_ERROR: { status: 502, client: true, message: "Network error" },
99
+ UPLOAD_FAILED: {
100
+ status: 502,
101
+ client: true,
102
+ message: "Upload failed with HTTP {status}"
103
+ },
104
+ DOWNLOAD_FAILED: {
105
+ status: 502,
106
+ client: true,
107
+ message: "Download failed with HTTP {status}"
108
+ },
109
+ CHECKSUM_MISMATCH: {
110
+ status: 400,
111
+ client: true,
112
+ message: "Uploaded bytes do not match the checksum"
113
+ },
114
+ PARTIAL_FAILURE: {
115
+ status: 207,
116
+ client: true,
117
+ message: "{failed} of {total} operations failed"
118
+ },
119
+ UNKNOWN_ERROR: {
120
+ status: 500,
121
+ client: true,
122
+ message: "Something went wrong"
44
123
  }
45
- return null;
124
+ });
125
+ function formatErrorMessage(template, params) {
126
+ if (!params) return template;
127
+ return template.replaceAll(
128
+ /\{(\w+)\}/g,
129
+ (placeholder, name) => Object.hasOwn(params, name) ? String(params[name]) : placeholder
130
+ );
46
131
  }
47
132
 
48
- // src/helpers/build-object-key.ts
49
- function buildObjectKey(...parts) {
50
- return parts.map((p) => p.replaceAll(/^\/+|\/+$/g, "")).filter(Boolean).join("/");
133
+ // src/error.ts
134
+ var statusNames = new Map(
135
+ Object.keys(statusCodes).map((name) => [
136
+ statusCodes[name],
137
+ name
138
+ ])
139
+ );
140
+ function toNamedStatus(status) {
141
+ if (typeof status !== "number") return status;
142
+ return statusNames.get(status) ?? status;
51
143
  }
52
-
53
- // src/helpers/parse-file-name.ts
54
- function parseFileName(contentDisposition) {
55
- if (!contentDisposition) return void 0;
56
- const utf8Match = contentDisposition.match(/filename\*=UTF-8''([^;,\s]+)/i);
57
- if (utf8Match) {
58
- try {
59
- return decodeURIComponent(utf8Match[1]);
60
- } catch {
144
+ var APIError = class _APIError extends APIError$1 {
145
+ constructor(status, body, headers) {
146
+ const { cause, ...rest } = body;
147
+ super(toNamedStatus(status), rest, headers);
148
+ this.name = "APIError";
149
+ if (cause !== void 0) {
150
+ this.cause = cause;
61
151
  }
62
152
  }
63
- const asciiMatch = contentDisposition.match(/filename="([^"]*)"/i);
64
- return asciiMatch?.[1];
65
- }
66
- function fileNameFromKey(key) {
67
- return key.split("/").findLast((part) => part.length > 0);
68
- }
69
- function resolveStoredFileName(contentDisposition, key) {
70
- return parseFileName(contentDisposition) ?? fileNameFromKey(key);
71
- }
72
-
73
- // src/helpers/format-file-size.ts
74
- var UNITS = [
75
- "B",
76
- "KB",
77
- "MB",
78
- "GB",
79
- "TB",
80
- "PB",
81
- "EB"
82
- ];
83
- var numberFormats = /* @__PURE__ */ new Map();
84
- function numberFormat(locale, fractionDigits) {
85
- const id = `${String(locale)}|${fractionDigits}`;
86
- let format = numberFormats.get(id);
87
- if (!format) {
88
- format = new Intl.NumberFormat(
89
- typeof locale === "string" ? locale : [...locale],
90
- {
91
- minimumFractionDigits: fractionDigits,
92
- maximumFractionDigits: fractionDigits,
93
- useGrouping: false
94
- }
95
- );
96
- numberFormats.set(id, format);
153
+ /** Stable machine-readable code; always set. */
154
+ get code() {
155
+ return this.body.code;
97
156
  }
98
- return format;
99
- }
100
- function formatFileSize(bytes, options = {}) {
101
- const size = Number.isFinite(bytes) && bytes > 0 ? bytes : 0;
102
- const i = size === 0 ? 0 : Math.min(Math.floor(Math.log(size) / Math.log(1024)), UNITS.length - 1);
103
- const unit = UNITS[i] ?? "B";
104
- const value = numberFormat(options.locale ?? "en-US", i === 0 ? 0 : 1).format(
105
- size / 1024 ** i
106
- );
107
- return `${value} ${options.units?.[unit] ?? unit}`;
157
+ get params() {
158
+ return this.body.params;
159
+ }
160
+ /** Plugin-defined or catalog codes with an explicit status. */
161
+ static from(status, body) {
162
+ return new _APIError(status, {
163
+ code: body.code,
164
+ message: body.message,
165
+ ...body.params !== void 0 ? { params: body.params } : {}
166
+ });
167
+ }
168
+ /**
169
+ * Rebuild from a wire body (e.g. `deleteMany` `failed[].error`).
170
+ * Status: explicit, else the catalog status, else 500.
171
+ */
172
+ static fromShape(shape, status) {
173
+ return _APIError.from(status ?? catalogStatus(shape.code) ?? 500, shape);
174
+ }
175
+ };
176
+ function catalogStatus(code) {
177
+ return Object.hasOwn(S3_ERROR_CODES, code) ? S3_ERROR_CODES[code].status : void 0;
178
+ }
179
+ function s3Error(code, ...args) {
180
+ const [params, options] = args;
181
+ const entry = S3_ERROR_CODES[code];
182
+ return new APIError(options?.status ?? entry.status, {
183
+ code,
184
+ message: formatErrorMessage(entry.message, params),
185
+ ...params !== void 0 ? { params } : {},
186
+ ...options?.cause !== void 0 ? { cause: options.cause } : {}
187
+ });
108
188
  }
109
-
110
- // src/helpers/build-content-disposition.ts
111
- function buildContentDisposition(fileName, type = "attachment") {
112
- const ascii = fileName.replaceAll(/[^\x20-\x7E]/g, "_").replaceAll(/["\\]/g, "_");
113
- const encoded = encodeURIComponent(fileName);
114
- return `${type}; filename="${ascii}"; filename*=UTF-8''${encoded}`;
189
+ function isAPIError(error) {
190
+ if (error instanceof APIError) return true;
191
+ const candidate = error;
192
+ return candidate?.name === "APIError" && typeof candidate.code === "string" && typeof candidate.statusCode === "number";
193
+ }
194
+ function isS3ErrorCode(error, code) {
195
+ return isAPIError(error) && error.code === code;
115
196
  }
116
197
 
117
- // src/helpers/resolve-inline-disposition.ts
198
+ // src/helpers/content-type.ts
118
199
  var TYPE_BY_EXTENSION = {
119
200
  avif: "image/avif",
120
201
  bmp: "image/bmp",
@@ -159,8 +240,117 @@ function typeFromFileName(fileName) {
159
240
  if (!fileName || dot < 0) return void 0;
160
241
  return TYPE_BY_EXTENSION[fileName.slice(dot + 1).toLowerCase()];
161
242
  }
243
+ function effectiveContentType(contentType, fileName) {
244
+ const stored = baseType(contentType);
245
+ return UNTYPED.has(stored) ? typeFromFileName(fileName) : stored;
246
+ }
247
+ function describeFileType(fileName, contentType) {
248
+ const dot = fileName.lastIndexOf(".");
249
+ if (dot >= 0 && dot < fileName.length - 1) return fileName.slice(dot);
250
+ return contentType || "unknown";
251
+ }
252
+
253
+ // src/helpers/validate-file.ts
254
+ function matchesFileTypes(fileName, contentType, fileTypes) {
255
+ if (!fileTypes.length) return true;
256
+ const type = baseType(contentType);
257
+ const name = fileName.toLowerCase();
258
+ return fileTypes.some((entry) => {
259
+ const token = entry.trim().toLowerCase();
260
+ if (token === "*" || token === "*/*") return true;
261
+ if (token.startsWith(".")) return name.endsWith(token);
262
+ if (token.endsWith("/*")) return type.startsWith(token.slice(0, -1));
263
+ return type === token;
264
+ });
265
+ }
266
+ function validateFile(file, options) {
267
+ const { accept, maxFileSize } = options;
268
+ if (accept?.length && !matchesFileTypes(file.name, file.type, accept)) {
269
+ return s3Error("FILE_TYPE_NOT_ALLOWED", {
270
+ type: describeFileType(file.name, file.type),
271
+ allowed: accept.join(", ")
272
+ });
273
+ }
274
+ if (file.size === 0) {
275
+ return s3Error("FILE_EMPTY");
276
+ }
277
+ if (typeof maxFileSize === "number" && file.size > maxFileSize) {
278
+ return s3Error("FILE_TOO_LARGE", { size: file.size, maxFileSize });
279
+ }
280
+ return null;
281
+ }
282
+
283
+ // src/helpers/strip-slashes.ts
284
+ var SLASH = "/";
285
+ function stripTrailingSlashes(value) {
286
+ let end = value.length;
287
+ while (end > 0 && value.charAt(end - 1) === SLASH) end -= 1;
288
+ return end === value.length ? value : value.slice(0, end);
289
+ }
290
+ function stripSurroundingSlashes(value) {
291
+ let start = 0;
292
+ let end = value.length;
293
+ while (start < end && value.charAt(start) === SLASH) start += 1;
294
+ while (end > start && value.charAt(end - 1) === SLASH) end -= 1;
295
+ return start === 0 && end === value.length ? value : value.slice(start, end);
296
+ }
297
+
298
+ // src/helpers/build-object-key.ts
299
+ function buildObjectKey(...parts) {
300
+ return parts.map((part) => stripSurroundingSlashes(part)).filter(Boolean).join("/");
301
+ }
302
+
303
+ // src/helpers/parse-file-name.ts
304
+ var EXT_VALUE = /filename\*\s*=\s*([\w!#$&+.^`|~-]+)'[^']*'([^;\s]+)/i;
305
+ var QUOTED = /filename\s*=\s*"((?:[^"\\]|\\.)*)"/i;
306
+ var TOKEN = /filename\s*=\s*([^";\s]+)/i;
307
+ function parseFileName(contentDisposition) {
308
+ if (!contentDisposition) return void 0;
309
+ const ext = EXT_VALUE.exec(contentDisposition);
310
+ if (ext && /^utf-8$/i.test(ext[1])) {
311
+ try {
312
+ return decodeURIComponent(ext[2]);
313
+ } catch {
314
+ }
315
+ }
316
+ const quoted = QUOTED.exec(contentDisposition);
317
+ if (quoted) return quoted[1].replaceAll(/\\(.)/g, "$1");
318
+ return TOKEN.exec(contentDisposition)?.[1];
319
+ }
320
+ function fileNameFromKey(key) {
321
+ return key.split("/").findLast((part) => part.length > 0);
322
+ }
323
+ function resolveStoredFileName(contentDisposition, key) {
324
+ return parseFileName(contentDisposition) ?? fileNameFromKey(key);
325
+ }
326
+
327
+ // src/helpers/build-content-disposition.ts
328
+ function encodeExtValue(value) {
329
+ return encodeURIComponent(value).replaceAll(
330
+ /['()*]/g,
331
+ (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`
332
+ );
333
+ }
334
+ function buildContentDisposition(fileName, type = "attachment") {
335
+ const ascii2 = fileName.replaceAll(/[^\x20-\x7E]|["\\%]/g, "_");
336
+ return `${type}; filename="${ascii2}"; filename*=UTF-8''${encodeExtValue(fileName)}`;
337
+ }
338
+
339
+ // src/helpers/resolve-inline-disposition.ts
340
+ var DEFAULT_INLINE_TYPES = [
341
+ "image/png",
342
+ "image/jpeg",
343
+ "image/gif",
344
+ "image/webp",
345
+ "image/avif",
346
+ "image/bmp",
347
+ "application/pdf",
348
+ "audio/*",
349
+ "video/*",
350
+ "text/plain"
351
+ ];
162
352
  function isActiveContentType(type) {
163
- return type === "text/html" || type.endsWith("/xml") || type.endsWith("+xml") || type.includes("javascript") || type.includes("ecmascript");
353
+ return type === "text/html" || type === "text/xsl" || type.endsWith("/xml") || type.endsWith("+xml") || type.includes("javascript") || type.includes("ecmascript");
164
354
  }
165
355
  function isAllowed(type, allow) {
166
356
  const active = isActiveContentType(type);
@@ -172,43 +362,92 @@ function isAllowed(type, allow) {
172
362
  });
173
363
  }
174
364
  function resolveInlineDisposition(input) {
175
- if (input.requested !== "inline") return { disposition: "attachment" };
176
- const stored = baseType(input.contentType);
177
- const untyped = UNTYPED.has(stored);
178
- const type = untyped ? typeFromFileName(input.fileName) : stored;
179
- if (!type || !isAllowed(type, input.allow)) {
365
+ const allow = input.allow ?? DEFAULT_INLINE_TYPES;
366
+ if (input.requested !== "inline" || allow === false) {
180
367
  return { disposition: "attachment" };
181
368
  }
182
- return untyped ? { disposition: "inline", contentType: type } : { disposition: "inline" };
369
+ const type = effectiveContentType(input.contentType, input.fileName);
370
+ if (!type || !isAllowed(type, allow)) {
371
+ return { disposition: "attachment" };
372
+ }
373
+ return type === baseType(input.contentType) ? { disposition: "inline" } : { disposition: "inline", contentType: type };
183
374
  }
184
375
 
185
- // src/helpers/sanitize-file-name.ts
186
- function sanitizeFileName(fileName) {
187
- return fileName.replaceAll(/["\\\r\n\0]/g, "_");
188
- }
376
+ // src/limits.ts
377
+ var S3_DEFAULT_EXPIRES_IN = 600;
378
+ var S3_MAX_EXPIRES_IN = 604800;
379
+ var S3_MAX_POST_OBJECT_BYTES = 5 * 1024 * 1024 * 1024;
380
+ var S3_MAX_PART_NUMBER = 1e4;
381
+ var S3_MIN_PART_SIZE = 5 * 1024 * 1024;
382
+ var S3_MAX_PART_SIZE = 5 * 1024 * 1024 * 1024;
383
+ var S3_DEFAULT_PART_SIZE = 8 * 1024 * 1024;
384
+ var S3_MAX_OBJECT_SIZE = 5 * 1024 ** 4;
385
+ var S3_MAX_FILE_FIELD_BYTES = 255;
386
+ var UPLOAD_TICKET_MAX_LENGTH = 8192;
387
+ var S3_MAX_METADATA_ENTRIES = 32;
388
+ var DELETE_MANY_MAX_KEYS = 100;
389
+ var ROUTE_NAME_PATTERN = /^[a-z][\w-]{0,63}$/i;
189
390
 
190
- // src/helpers/truncate-file-name.ts
191
- function truncateFileName(name, maxChars = 48) {
192
- if (name.length <= maxChars) return name;
193
- const dotIndex = name.lastIndexOf(".");
194
- if (dotIndex <= 0) {
195
- return name.slice(0, maxChars - 1) + "\u2026";
391
+ // src/helpers/fit-file-name.ts
392
+ var MAX_EXTENSION_BYTES = 32;
393
+ var FALLBACK_FILE_NAME = "file";
394
+ var CONTROL_CHARACTERS = /\p{Cc}/gu;
395
+ var BIDI_CONTROL = /[\u202A-\u202E\u2066-\u2069]/u;
396
+ var BIDI_CONTROLS = new RegExp(BIDI_CONTROL.source, "gu");
397
+ var utf8 = new TextEncoder();
398
+ function byteLength(text) {
399
+ return utf8.encode(text).byteLength;
400
+ }
401
+ var graphemeSegmenter;
402
+ function graphemes(text) {
403
+ if (graphemeSegmenter === void 0) {
404
+ graphemeSegmenter = typeof Intl.Segmenter === "function" ? new Intl.Segmenter(void 0, { granularity: "grapheme" }) : null;
196
405
  }
197
- const ext = name.slice(dotIndex);
198
- const available = maxChars - ext.length - 1;
199
- if (available <= 0) {
200
- return name.slice(0, maxChars - 1) + "\u2026";
406
+ if (!graphemeSegmenter) return text;
407
+ return Array.from(graphemeSegmenter.segment(text), (part) => part.segment);
408
+ }
409
+ function takeWithin(parts, maxBytes) {
410
+ let taken = "";
411
+ let used = 0;
412
+ for (const part of parts) {
413
+ used += byteLength(part);
414
+ if (used > maxBytes) break;
415
+ taken += part;
201
416
  }
202
- return name.slice(0, available) + "\u2026 " + ext;
417
+ return taken;
418
+ }
419
+ function cutToBytes(text, maxBytes) {
420
+ return takeWithin(graphemes(text), maxBytes) || takeWithin(text, maxBytes);
421
+ }
422
+ function fitFileName(name) {
423
+ const cleaned = name.toWellFormed().replaceAll(CONTROL_CHARACTERS, "").replaceAll(BIDI_CONTROLS, "").trim();
424
+ if (byteLength(cleaned) <= S3_MAX_FILE_FIELD_BYTES) {
425
+ return cleaned || FALLBACK_FILE_NAME;
426
+ }
427
+ const dot = cleaned.lastIndexOf(".");
428
+ const extension = dot > 0 ? cleaned.slice(dot) : "";
429
+ const keepExtension = extension.length > 1 && byteLength(extension) <= MAX_EXTENSION_BYTES;
430
+ const suffix = keepExtension ? extension : "";
431
+ const stem = keepExtension ? cleaned.slice(0, dot) : cleaned;
432
+ const budget = S3_MAX_FILE_FIELD_BYTES - byteLength(suffix);
433
+ const base = cutToBytes(stem, budget).trimEnd() || FALLBACK_FILE_NAME;
434
+ return `${base}${suffix}`;
203
435
  }
204
436
 
205
437
  // src/helpers/normalize-object-key.ts
206
- var S3_MAX_OBJECT_KEY_LENGTH = 1024;
438
+ var S3_MAX_OBJECT_KEY_BYTES = 1024;
439
+ var utf82 = new TextEncoder();
440
+ function objectKeyByteLength(key) {
441
+ return utf82.encode(key).byteLength;
442
+ }
443
+ var CONTROL_CHARACTER = /\p{Cc}/u;
207
444
  function normalizeObjectKey(key) {
208
- const trimmed = key.replaceAll(/^\/+|\/+$/gu, "");
209
- if (!trimmed) return null;
210
- if (trimmed.length > S3_MAX_OBJECT_KEY_LENGTH) return null;
211
- if (trimmed.includes("\\") || trimmed.includes("\0")) return null;
445
+ const trimmed = stripSurroundingSlashes(key);
446
+ if (!trimmed || trimmed !== trimmed.trim()) return null;
447
+ if (trimmed.length > S3_MAX_OBJECT_KEY_BYTES) return null;
448
+ if (!trimmed.isWellFormed()) return null;
449
+ if (objectKeyByteLength(trimmed) > S3_MAX_OBJECT_KEY_BYTES) return null;
450
+ if (trimmed.includes("\\") || CONTROL_CHARACTER.test(trimmed)) return null;
212
451
  const parts = trimmed.split("/");
213
452
  if (parts.some((part) => part === "" || part === "." || part === "..")) {
214
453
  return null;
@@ -216,347 +455,335 @@ function normalizeObjectKey(key) {
216
455
  return parts.join("/");
217
456
  }
218
457
 
458
+ // src/helpers/base64url.ts
459
+ var CHUNK_SIZE = 32768;
460
+ var BASE64URL_PATTERN = /^[\w-]*$/;
461
+ var encoder = new TextEncoder();
462
+ function bytesToBase64(bytes) {
463
+ let binary = "";
464
+ for (let offset = 0; offset < bytes.length; offset += CHUNK_SIZE) {
465
+ binary += String.fromCharCode(
466
+ ...bytes.subarray(offset, offset + CHUNK_SIZE)
467
+ );
468
+ }
469
+ return btoa(binary);
470
+ }
471
+ function base64UrlEncode(bytes) {
472
+ const data = typeof bytes === "string" ? encoder.encode(bytes) : bytes;
473
+ return bytesToBase64(data).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
474
+ }
475
+ function base64UrlDecode(value) {
476
+ if (!BASE64URL_PATTERN.test(value) || value.length % 4 === 1) {
477
+ throw new TypeError("Invalid base64url string");
478
+ }
479
+ const base64 = value.replaceAll("-", "+").replaceAll("_", "/");
480
+ const binary = atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, "="));
481
+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
482
+ if (base64UrlEncode(bytes) !== value) {
483
+ throw new TypeError("Invalid base64url string");
484
+ }
485
+ return bytes;
486
+ }
487
+
219
488
  // src/helpers/checksum.ts
489
+ var CHUNK_SIZE2 = 1024 * 1024;
490
+ function toUnpaddedBase64(bytes) {
491
+ return bytesToBase64(bytes).replace(/=+$/, "");
492
+ }
220
493
  async function sha256Base64(data) {
221
494
  const digest = await crypto.subtle.digest("SHA-256", data);
222
- const bytes = new Uint8Array(digest);
223
- return btoa(String.fromCharCode(...bytes)).replaceAll(/=+$/g, "");
224
- }
225
- async function sha256File(file) {
226
- return sha256Base64(await file.arrayBuffer());
495
+ return toUnpaddedBase64(new Uint8Array(digest));
496
+ }
497
+ async function sha256Blob(blob, options = {}) {
498
+ const { signal } = options;
499
+ signal?.throwIfAborted();
500
+ const hash = sha256.create();
501
+ for (let offset = 0; offset < blob.size; offset += CHUNK_SIZE2) {
502
+ const chunk = await blob.slice(offset, offset + CHUNK_SIZE2).arrayBuffer();
503
+ signal?.throwIfAborted();
504
+ hash.update(new Uint8Array(chunk));
505
+ }
506
+ return toUnpaddedBase64(hash.digest());
227
507
  }
228
508
 
229
509
  // src/helpers/magic-bytes.ts
230
- var MAGIC = [
231
- { mime: "image/png", bytes: [137, 80, 78, 71] },
232
- { mime: "image/jpeg", bytes: [255, 216, 255] },
233
- { mime: "image/gif", bytes: [71, 73, 70, 56] },
234
- { mime: "image/webp", bytes: [82, 73, 70, 70], offset: 0 },
235
- { mime: "application/pdf", bytes: [37, 80, 68, 70] },
236
- { mime: "application/zip", bytes: [80, 75, 3, 4] },
237
- { mime: "video/webm", bytes: [26, 69, 223, 163] }
510
+ var SNIFF_BYTE_LENGTH = 4096;
511
+ var FTYP_BRANDS = [
512
+ { brands: ["avif", "avis"], type: "image/avif" },
513
+ {
514
+ brands: ["heic", "heix", "heim", "heis", "hevc", "hevx"],
515
+ type: "image/heic"
516
+ },
517
+ { brands: ["qt "], type: "video/quicktime" },
518
+ { brands: ["M4A ", "M4B ", "M4P "], type: "audio/mp4" },
519
+ {
520
+ brands: [
521
+ "isom",
522
+ "iso2",
523
+ "iso4",
524
+ "iso5",
525
+ "iso6",
526
+ "mp41",
527
+ "mp42",
528
+ "mp71",
529
+ "avc1",
530
+ "dash",
531
+ "M4V ",
532
+ "MSNV",
533
+ "f4v "
534
+ ],
535
+ type: "video/mp4"
536
+ }
238
537
  ];
239
- function prefixEquals(bytes, expected, offset = 0) {
538
+ function startsWith(bytes, expected, offset = 0) {
240
539
  if (bytes.length < offset + expected.length) return false;
241
540
  return expected.every((value, i) => bytes[offset + i] === value);
242
541
  }
243
- function sniffContentType(bytes) {
244
- if (prefixEquals(bytes, [82, 73, 70, 70]) && bytes.length >= 12) {
245
- const tag = String.fromCharCode(...bytes.subarray(8, 12));
246
- if (tag === "WEBP") return "image/webp";
542
+ function ascii(bytes, start, end) {
543
+ return String.fromCharCode(...bytes.subarray(start, end));
544
+ }
545
+ function hasAscii(bytes, text, offset = 0) {
546
+ return ascii(bytes, offset, offset + text.length) === text;
547
+ }
548
+ function isRiff(bytes, form) {
549
+ return hasAscii(bytes, "RIFF") && hasAscii(bytes, form, 8);
550
+ }
551
+ function ftypTypeOf(brand) {
552
+ return FTYP_BRANDS.find((entry) => entry.brands.includes(brand))?.type;
553
+ }
554
+ function ftypType(bytes) {
555
+ if (!hasAscii(bytes, "ftyp", 4) || bytes.length < 12) return void 0;
556
+ const major = ftypTypeOf(ascii(bytes, 8, 12));
557
+ if (major) return major;
558
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
559
+ const boxEnd = Math.min(view.getUint32(0), bytes.length);
560
+ const brands = [];
561
+ for (let offset = 16; offset + 4 <= boxEnd; offset += 4) {
562
+ brands.push(ascii(bytes, offset, offset + 4));
247
563
  }
248
- for (const entry of MAGIC) {
249
- if (entry.mime === "image/webp") continue;
250
- if (prefixEquals(bytes, entry.bytes, entry.offset)) return entry.mime;
564
+ return FTYP_BRANDS.find(
565
+ (entry) => entry.brands.some((brand) => brands.includes(brand))
566
+ )?.type;
567
+ }
568
+ function isMp3Frame(bytes) {
569
+ if (bytes.length < 3 || bytes[0] !== 255) return false;
570
+ const version = bytes[1] >> 3 & 3;
571
+ const layer = bytes[1] >> 1 & 3;
572
+ const bitrate = bytes[2] >> 4;
573
+ const sampleRate = bytes[2] >> 2 & 3;
574
+ return (bytes[1] & 224) === 224 && version !== 1 && layer === 1 && bitrate !== 15 && sampleRate !== 3;
575
+ }
576
+ function id3v2End(bytes) {
577
+ if (bytes.length < 10 || !hasAscii(bytes, "ID3")) return void 0;
578
+ if (bytes[3] < 2 || bytes[3] > 4) return void 0;
579
+ const size = bytes.subarray(6, 10);
580
+ if (size.some((byte) => byte & 128)) return void 0;
581
+ const footer = bytes[5] & 16 ? 10 : 0;
582
+ return 10 + (size[0] << 21 | size[1] << 14 | size[2] << 7 | size[3]) + footer;
583
+ }
584
+ function afterId3v2(bytes) {
585
+ const end = id3v2End(bytes);
586
+ return end === void 0 ? new Uint8Array() : bytes.subarray(end);
587
+ }
588
+ function hasTruncatedId3v2(bytes) {
589
+ const end = id3v2End(bytes);
590
+ return end !== void 0 && end >= bytes.length;
591
+ }
592
+ function isBmp(bytes) {
593
+ if (!hasAscii(bytes, "BM") || bytes.length < 18) return false;
594
+ const dibSize = bytes[14] | bytes[15] << 8 | bytes[16] << 16 | bytes[17] << 24;
595
+ return [12, 40, 52, 56, 64, 108, 124].includes(dibSize);
596
+ }
597
+ function ftypSignature(type, aliases) {
598
+ return { type, aliases, test: (bytes) => ftypType(bytes) === type };
599
+ }
600
+ var SIGNATURES = [
601
+ {
602
+ type: "image/png",
603
+ test: (bytes) => startsWith(bytes, [137, 80, 78, 71])
604
+ },
605
+ {
606
+ type: "image/jpeg",
607
+ test: (bytes) => startsWith(bytes, [255, 216, 255])
608
+ },
609
+ { type: "image/gif", test: (bytes) => hasAscii(bytes, "GIF8") },
610
+ { type: "image/bmp", test: isBmp },
611
+ {
612
+ type: "image/tiff",
613
+ test: (bytes) => startsWith(bytes, [73, 73, 42, 0]) || startsWith(bytes, [77, 77, 0, 42])
614
+ },
615
+ {
616
+ type: "image/x-icon",
617
+ aliases: ["image/vnd.microsoft.icon"],
618
+ test: (bytes) => startsWith(bytes, [0, 0, 1, 0])
619
+ },
620
+ { type: "image/webp", test: (bytes) => isRiff(bytes, "WEBP") },
621
+ ftypSignature("image/avif"),
622
+ ftypSignature("image/heic", ["image/heif"]),
623
+ ftypSignature("video/quicktime"),
624
+ ftypSignature("audio/mp4", ["audio/x-m4a", "video/mp4"]),
625
+ ftypSignature("video/mp4", ["audio/mp4", "audio/x-m4a", "video/x-m4v"]),
626
+ { type: "application/pdf", test: (bytes) => hasAscii(bytes, "%PDF") },
627
+ {
628
+ type: "application/zip",
629
+ aliases: ["application/x-zip-compressed"],
630
+ test: (bytes) => startsWith(bytes, [80, 75, 3, 4])
631
+ },
632
+ {
633
+ type: "application/gzip",
634
+ aliases: ["application/x-gzip"],
635
+ test: (bytes) => startsWith(bytes, [31, 139])
636
+ },
637
+ {
638
+ // EBML: WebM and Matroska share it.
639
+ type: "video/webm",
640
+ aliases: ["audio/webm", "video/x-matroska", "audio/x-matroska"],
641
+ test: (bytes) => startsWith(bytes, [26, 69, 223, 163])
642
+ },
643
+ {
644
+ type: "audio/flac",
645
+ aliases: ["audio/x-flac"],
646
+ test: (bytes) => hasAscii(afterId3v2(bytes), "fLaC")
647
+ },
648
+ {
649
+ // The tag hides what follows: MP3 is likelier, but FLAC is not ruled out.
650
+ type: "audio/mpeg",
651
+ aliases: ["audio/mp3", "audio/flac", "audio/x-flac"],
652
+ test: hasTruncatedId3v2
653
+ },
654
+ {
655
+ type: "audio/mpeg",
656
+ aliases: ["audio/mp3"],
657
+ test: (bytes) => hasAscii(bytes, "ID3") || isMp3Frame(bytes)
658
+ },
659
+ {
660
+ type: "audio/ogg",
661
+ aliases: ["video/ogg", "application/ogg"],
662
+ test: (bytes) => hasAscii(bytes, "OggS")
663
+ },
664
+ {
665
+ type: "audio/wav",
666
+ aliases: ["audio/wave", "audio/x-wav", "audio/vnd.wave"],
667
+ test: (bytes) => isRiff(bytes, "WAVE")
668
+ },
669
+ {
670
+ type: "audio/flac",
671
+ aliases: ["audio/x-flac"],
672
+ test: (bytes) => hasAscii(bytes, "fLaC")
251
673
  }
252
- return void 0;
674
+ ];
675
+ function typesOf(signature) {
676
+ return [signature.type, ...signature.aliases ?? []];
677
+ }
678
+ function sniffSignature(bytes) {
679
+ return SIGNATURES.find((signature) => signature.test(bytes));
680
+ }
681
+ function sniffContentType(bytes) {
682
+ return sniffSignature(bytes)?.type;
683
+ }
684
+ function isSniffableType(type) {
685
+ const base = baseType(type);
686
+ return SIGNATURES.some((signature) => typesOf(signature).includes(base));
253
687
  }
254
688
  function matchesMagicBytes(bytes, expected) {
255
- const sniffed = sniffContentType(bytes);
256
- if (!sniffed) return false;
257
- if (expected.endsWith("/*")) {
258
- return sniffed.startsWith(expected.slice(0, -1));
689
+ const signature = sniffSignature(bytes);
690
+ if (!signature) return false;
691
+ const base = baseType(expected);
692
+ const types = typesOf(signature);
693
+ if (base.endsWith("/*")) {
694
+ const prefix = base.slice(0, -1);
695
+ return types.some((type) => type.startsWith(prefix));
259
696
  }
260
- return sniffed === expected;
697
+ return types.includes(base);
261
698
  }
262
699
 
263
700
  // src/helpers/public-object-url.ts
264
701
  function buildPublicObjectUrl(options) {
265
- const base = options.baseUrl.replaceAll(/\/+$/g, "");
702
+ const base = stripTrailingSlashes(options.baseUrl);
266
703
  const path = options.key.split("/").filter((part) => part.length > 0).map((part) => encodeURIComponent(part)).join("/");
267
704
  return `${base}/${path}`;
268
705
  }
269
- var S3_DEFAULT_EXPIRES_IN = 600;
270
- var S3_MAX_EXPIRES_IN = 604800;
271
- var S3_MAX_POST_OBJECT_BYTES = 5 * 1024 * 1024 * 1024;
272
- var S3_MAX_PART_NUMBER = 1e4;
273
- var S3_MAX_METADATA_ENTRIES = 32;
274
- var ROUTE_NAME_PATTERN = /^[a-z][\w-]{0,63}$/i;
275
- var trimmedString = z3.string().trim().min(1);
276
- var optionalTrimmedString = z3.preprocess((value) => {
277
- if (typeof value !== "string") return value;
278
- const trimmed = value.trim();
279
- return trimmed === "" ? void 0 : trimmed;
280
- }, z3.string().optional());
281
- var routeNameSchema = trimmedString.regex(
282
- ROUTE_NAME_PATTERN,
283
- "Invalid route name"
284
- );
285
- var objectKeySchema = trimmedString.max(S3_MAX_OBJECT_KEY_LENGTH).transform((value, ctx) => {
286
- const normalized = normalizeObjectKey(value);
287
- if (normalized == null) {
288
- ctx.issues.push({
289
- code: "custom",
290
- message: "Invalid object key",
291
- input: value
292
- });
293
- return z3.NEVER;
294
- }
295
- return normalized;
296
- });
297
- var partNumberSchema = z3.int().min(1).max(S3_MAX_PART_NUMBER);
298
- var s3ObjectAclSchema = z3.enum(["private", "public-read"]);
299
- var sha256ChecksumSchema = z3.stringFormat(
300
- "sha256-base64",
301
- /^[A-Z0-9+/]{43}=?$/i
302
- );
303
- var optionalChecksumSchema = optionalTrimmedString.pipe(
304
- sha256ChecksumSchema.optional()
305
- );
306
- var metadataKeySchema = z3.string().regex(/^[a-z0-9][a-z0-9-]*$/i, "Invalid metadata key").max(128);
307
- var metadataSchema = z3.record(metadataKeySchema, z3.string().max(2048)).refine((value) => Object.keys(value).length <= S3_MAX_METADATA_ENTRIES, {
308
- message: "Too many metadata entries"
309
- });
310
- var uploadBodySchema = z3.strictObject({
311
- route: routeNameSchema,
312
- fileName: trimmedString,
313
- fileSize: z3.int().positive(),
314
- contentType: optionalTrimmedString,
315
- metadata: metadataSchema.optional(),
316
- /** Unpadded base64 SHA-256. Required when the route sets `upload.checksum`. */
317
- checksum: optionalChecksumSchema
318
- });
319
- var confirmBodySchema = z3.strictObject({
320
- route: routeNameSchema,
321
- key: objectKeySchema
322
- });
323
- var downloadDispositionSchema = z3.enum(["inline", "attachment"]);
324
- var downloadModeSchema = z3.enum(["presign", "proxy"]);
325
- var routeCatalogUploadSchema = z3.discriminatedUnion("enabled", [
326
- z3.strictObject({
327
- enabled: z3.literal(true),
328
- fileTypes: z3.array(z3.string()).optional(),
329
- maxFileSize: z3.int().positive().optional(),
330
- multipart: z3.boolean(),
331
- checksum: z3.boolean().optional(),
332
- replace: z3.literal("overwrite").optional()
333
- }),
334
- z3.strictObject({ enabled: z3.literal(false) })
335
- ]);
336
- var routeCatalogDownloadSchema = z3.discriminatedUnion("enabled", [
337
- z3.strictObject({
338
- enabled: z3.literal(true),
339
- /**
340
- * Maximum presign TTL in seconds. Clients may request a shorter
341
- * `expiresIn`. Omitted means the protocol default (600).
342
- */
343
- expiresIn: z3.int().positive().max(S3_MAX_EXPIRES_IN).optional(),
344
- disposition: downloadDispositionSchema.optional(),
345
- /** Types that may open inline. Pass to `resolveInlineDisposition`. */
346
- inlineTypes: z3.array(z3.string()).optional(),
347
- mode: downloadModeSchema.optional()
348
- }),
349
- z3.strictObject({ enabled: z3.literal(false) })
350
- ]);
351
- var routeCatalogDeleteSchema = z3.discriminatedUnion("enabled", [
352
- z3.strictObject({ enabled: z3.literal(true) }),
353
- z3.strictObject({ enabled: z3.literal(false) })
354
- ]);
355
- var routeCatalogEntrySchema = z3.strictObject({
356
- upload: routeCatalogUploadSchema,
357
- download: routeCatalogDownloadSchema,
358
- delete: routeCatalogDeleteSchema
359
- });
360
- var routeCatalogResponseSchema = z3.strictObject({
361
- routes: z3.record(routeNameSchema, routeCatalogEntrySchema)
362
- });
363
-
364
- // src/schema/download.ts
365
- var optionalExpiresInSchema = z3.preprocess((value) => {
366
- if (value == null || value === "") return void 0;
367
- if (typeof value === "number") return value;
368
- if (typeof value === "string") {
369
- const trimmed = value.trim();
370
- if (trimmed === "") return void 0;
371
- if (/^\d+$/.test(trimmed)) return Number(trimmed);
372
- }
373
- return value;
374
- }, z3.int().positive().max(S3_MAX_EXPIRES_IN).optional());
375
- var downloadQuerySchema = z3.strictObject({
376
- route: routeNameSchema,
377
- key: objectKeySchema,
378
- fileName: optionalTrimmedString,
379
- disposition: downloadDispositionSchema.optional(),
380
- /**
381
- * Requested TTL in seconds. Signed only when it is shorter than the
382
- * route `download.expiresIn`. `download.resolve` can still replace it.
383
- */
384
- expiresIn: optionalExpiresInSchema
385
- });
386
- var DELETE_BATCH_MAX_KEYS = 100;
387
- var deleteQuerySchema = z3.strictObject({
388
- route: routeNameSchema,
389
- key: objectKeySchema
390
- });
391
- var deleteBatchBodySchema = z3.strictObject({
392
- route: routeNameSchema,
393
- keys: z3.array(objectKeySchema).min(1).max(DELETE_BATCH_MAX_KEYS)
394
- });
395
- var fileQuerySchema = z3.strictObject({
396
- route: routeNameSchema,
397
- key: objectKeySchema,
398
- fileName: optionalTrimmedString,
399
- disposition: downloadDispositionSchema.optional()
400
- });
401
- var multipartInitBodySchema = uploadBodySchema;
402
- var multipartSessionFields = {
403
- route: routeNameSchema,
404
- key: objectKeySchema,
405
- uploadId: trimmedString
406
- };
407
- var multipartSignPartBodySchema = z3.strictObject({
408
- ...multipartSessionFields,
409
- partNumber: partNumberSchema,
410
- partSize: z3.int().positive()
411
- });
412
- var multipartListPartsQuerySchema = z3.strictObject({
413
- ...multipartSessionFields
414
- });
415
- var multipartCompletedPartSchema = z3.strictObject({
416
- partNumber: partNumberSchema
417
- });
418
- var multipartCompleteBodySchema = z3.strictObject({
419
- ...multipartSessionFields,
420
- parts: z3.array(multipartCompletedPartSchema).min(1)
421
- });
422
- var multipartAbortBodySchema = z3.strictObject({
423
- ...multipartSessionFields
424
- });
425
- var s3ErrorParamsSchema = z3.record(
426
- z3.string(),
427
- z3.union([z3.string(), z3.number()])
428
- );
429
- var s3FetchErrorSchema = z3.object({
430
- message: z3.string(),
431
- code: z3.string().optional(),
432
- params: s3ErrorParamsSchema.optional()
433
- });
434
-
435
- // src/error-codes.ts
436
- function defineErrorCodes(messages) {
437
- const codes = {};
438
- for (const code of Object.keys(messages)) {
439
- codes[code] = { code, message: messages[code] };
440
- }
441
- return codes;
442
- }
443
- var S3_ERROR_CODES = defineErrorCodes({
444
- NOT_FOUND: "Not Found",
445
- UNAUTHORIZED: "Unauthorized",
446
- FORBIDDEN: "Forbidden",
447
- CONFLICT: "Conflict",
448
- INTERNAL_ERROR: "Internal server error",
449
- OBJECT_NOT_FOUND: "Object not found",
450
- FEATURE_DISABLED: "{feature} is disabled",
451
- INVALID_KEY: "Object key is invalid",
452
- UNKNOWN_ROUTE: "Unknown file route",
453
- FILE_TYPE_NOT_ALLOWED: "File type is not allowed",
454
- S3_NETWORK_ERROR: "S3 endpoint unreachable ({code}): check your endpoint URL and network connectivity",
455
- MULTIPART_PART_MISSING: "Uploaded part {partNumber} was not found",
456
- PAYLOAD_TOO_LARGE: "Payload too large",
457
- QUOTA_EXCEEDED: "Storage quota exceeded",
458
- VALIDATION_ERROR: "Validation Error"
459
- });
460
-
461
- // src/error.ts
462
- var APIError = class _APIError extends APIError$1 {
463
- constructor(status = "BAD_REQUEST", body, headers) {
464
- const { cause, ...rest } = body ?? {};
465
- super(
466
- status,
467
- Object.keys(rest).length > 0 ? rest : void 0,
468
- headers
469
- );
470
- this.name = "APIError";
471
- if (cause !== void 0) {
472
- this.cause = cause;
473
- }
474
- }
475
- get code() {
476
- return this.body?.code;
477
- }
478
- get params() {
479
- return this.body?.params;
480
- }
481
- /** Throw a catalog (or custom) `{ code, message }` with an HTTP status. */
482
- static from(status, error) {
483
- return new _APIError(status, {
484
- message: error.message,
485
- code: error.code,
486
- ...error.params !== void 0 ? { params: error.params } : {}
487
- });
488
- }
489
- static fromStatus(status, body) {
490
- return new _APIError(status, body);
491
- }
492
- };
493
- function isAPIError(error) {
494
- return error instanceof APIError$1 || error instanceof APIError || error?.name === "APIError";
495
- }
496
- function isS3ErrorCode(error, code) {
497
- return isAPIError(error) && error.code === code;
498
- }
499
706
 
500
707
  // src/routes.ts
501
708
  var S3_API_BASE_PATH = "/api/s3";
502
709
  function normalizeS3ApiBasePath(basePath) {
503
- return basePath.replaceAll(/\/+$/g, "");
710
+ const path = stripSurroundingSlashes(basePath.trim());
711
+ return path ? `/${path}` : "";
504
712
  }
505
713
  var S3_API_ROUTES = {
506
714
  upload: "/presign/upload",
507
- uploadConfirm: "/presign/upload/confirm",
715
+ confirm: "/presign/upload/confirm",
508
716
  download: "/presign/download",
509
717
  file: "/file",
510
718
  catalog: "/routes",
511
719
  delete: "/delete",
512
- deleteBatch: "/delete/batch",
720
+ deleteMany: "/delete/batch",
513
721
  multipartInit: "/presign/multipart/init",
514
- multipartPart: "/presign/multipart/part",
722
+ multipartSignPart: "/presign/multipart/part",
723
+ /** `POST`, because the body carries the upload ticket. */
724
+ multipartListParts: "/presign/multipart/parts",
515
725
  multipartComplete: "/presign/multipart/complete",
516
- multipartAbort: "/presign/multipart/abort",
517
- multipartListParts: "/presign/multipart/parts"
726
+ multipartAbort: "/presign/multipart/abort"
518
727
  };
728
+ function readErrorBody(value) {
729
+ if (typeof value !== "object" || value === null) return void 0;
730
+ const { code, message, params } = value;
731
+ if (typeof code !== "string" || typeof message !== "string") return void 0;
732
+ const kept = typeof params === "object" && params !== null && !Array.isArray(params) ? Object.entries(params).filter(
733
+ (entry) => typeof entry[1] === "string" || typeof entry[1] === "number"
734
+ ) : [];
735
+ return kept.length > 0 ? { code, message, params: Object.fromEntries(kept) } : { code, message };
736
+ }
519
737
  async function resolveHeaders(headers) {
520
738
  if (headers == null) return void 0;
521
739
  if (typeof headers === "function") return headers();
522
740
  return headers;
523
741
  }
524
- function fallbackMessage(error) {
525
- if (typeof error.error === "string" && error.error.trim()) {
526
- return error.error;
527
- }
528
- return error.statusText || "Request failed";
529
- }
530
- function apiErrorFromFetch(error) {
531
- const { status } = error;
532
- if (s3FetchErrorSchema.validate(error)) {
533
- const { message, code, params } = error;
534
- return new APIError(status, {
535
- message,
536
- ...code !== void 0 ? { code } : {},
537
- ...params !== void 0 ? { params } : {}
538
- });
539
- }
540
- return new APIError(status, { message: fallbackMessage(error) });
742
+ function apiErrorFromResponse(status, body) {
743
+ const shape = readErrorBody(body);
744
+ if (shape) return APIError.fromShape(shape, status);
745
+ const code = status >= 500 ? "INTERNAL_ERROR" : "UNKNOWN_ERROR";
746
+ return s3Error(code, void 0, { status });
747
+ }
748
+ function isJsonBody(data) {
749
+ if (Array.isArray(data)) return true;
750
+ if (data === null || typeof data !== "object") return false;
751
+ const prototype = Object.getPrototypeOf(data);
752
+ return prototype === Object.prototype || prototype === null;
753
+ }
754
+ function withNetworkErrors(fetchImpl) {
755
+ return async (input, init) => {
756
+ try {
757
+ return await (fetchImpl ?? fetch)(input, init);
758
+ } catch (error) {
759
+ if (init?.signal?.aborted) throw init.signal.reason;
760
+ throw s3Error("NETWORK_ERROR", void 0, { cause: error });
761
+ }
762
+ };
541
763
  }
542
764
  function createS3Fetch(base, options) {
543
765
  return createFetch({
544
766
  baseURL: base,
545
767
  throw: true,
546
- errorSchema: s3FetchErrorSchema,
547
- customFetchImpl: options?.fetch,
768
+ customFetchImpl: withNetworkErrors(options?.fetch),
548
769
  credentials: options?.credentials,
549
770
  onRequest: async (ctx) => {
550
- const extra = await resolveHeaders(options?.headers);
551
- if (!extra) return ctx;
552
- const headers = new Headers(ctx.headers);
553
- for (const [key, value] of new Headers(extra)) {
771
+ const clientHeaders = await resolveHeaders(options?.headers);
772
+ if (!clientHeaders) return ctx;
773
+ const headers = new Headers(clientHeaders);
774
+ for (const [key, value] of ctx.headers) {
554
775
  headers.set(key, value);
555
776
  }
556
777
  return { ...ctx, headers };
557
778
  },
779
+ onSuccess: (ctx) => {
780
+ if (isJsonBody(ctx.data)) return;
781
+ throw s3Error("UNKNOWN_ERROR", void 0, {
782
+ status: ctx.response.status
783
+ });
784
+ },
558
785
  onError: (ctx) => {
559
- throw apiErrorFromFetch(ctx.error);
786
+ throw apiErrorFromResponse(ctx.response.status, ctx.error);
560
787
  }
561
788
  });
562
789
  }
@@ -591,88 +818,106 @@ var RESERVED_CLIENT_KEYS = [
591
818
  ];
592
819
 
593
820
  // src/create-s3-client.ts
594
- function withoutHeaders(value) {
595
- const { headers: _headers, ...rest } = value;
596
- return rest;
821
+ var ABSOLUTE_URL = /^[a-z][a-z\d+.-]*:\/\//i;
822
+ function callOptions(options) {
823
+ return {
824
+ signal: options?.signal,
825
+ headers: options?.headers ? new Headers(options.headers) : void 0
826
+ };
827
+ }
828
+ function resolveProxyUrl(url, base) {
829
+ if (!url.startsWith("/") || url.startsWith("//")) return url;
830
+ if (!ABSOLUTE_URL.test(base)) return url;
831
+ return new URL(url, base).href;
597
832
  }
598
- function createCoreApi($fetch) {
833
+ function createCoreApi($fetch, base) {
599
834
  return {
600
- upload(payload) {
835
+ upload(payload, options) {
601
836
  return $fetch(S3_API_ROUTES.upload, {
602
837
  method: "POST",
603
- body: withoutHeaders(payload)
838
+ body: payload,
839
+ ...callOptions(options)
604
840
  });
605
841
  },
606
- confirm(payload) {
607
- return $fetch(S3_API_ROUTES.uploadConfirm, {
842
+ confirm(payload, options) {
843
+ return $fetch(S3_API_ROUTES.confirm, {
608
844
  method: "POST",
609
- body: withoutHeaders(payload)
845
+ body: payload,
846
+ ...callOptions(options)
610
847
  });
611
848
  },
612
- download(payload) {
613
- const { route, key, fileName, disposition, expiresIn } = withoutHeaders(payload);
614
- return $fetch(S3_API_ROUTES.download, {
615
- method: "GET",
616
- query: {
617
- route,
618
- key,
619
- fileName: fileName ? sanitizeFileName(fileName) : void 0,
620
- disposition,
621
- expiresIn
849
+ async download(payload, options) {
850
+ const { route, key, name, disposition, expiresIn } = payload;
851
+ const response = await $fetch(
852
+ S3_API_ROUTES.download,
853
+ {
854
+ method: "GET",
855
+ query: {
856
+ route,
857
+ key,
858
+ // The same rule as an upload name, so any name downloads.
859
+ name: name ? fitFileName(name) : void 0,
860
+ disposition,
861
+ expiresIn
862
+ },
863
+ ...callOptions(options)
622
864
  }
623
- });
865
+ );
866
+ return { ...response, url: resolveProxyUrl(response.url, base) };
624
867
  },
625
- catalog() {
868
+ catalog(options) {
626
869
  return $fetch(S3_API_ROUTES.catalog, {
627
- method: "GET"
870
+ method: "GET",
871
+ ...callOptions(options)
628
872
  });
629
873
  },
630
- delete(payload) {
631
- const { route, key } = withoutHeaders(payload);
874
+ delete(payload, options) {
875
+ const { route, key } = payload;
632
876
  return $fetch(S3_API_ROUTES.delete, {
633
877
  method: "DELETE",
634
- query: { route, key }
878
+ query: { route, key },
879
+ ...callOptions(options)
635
880
  });
636
881
  },
637
- deleteMany(payload) {
638
- return $fetch(S3_API_ROUTES.deleteBatch, {
882
+ deleteMany(payload, options) {
883
+ return $fetch(S3_API_ROUTES.deleteMany, {
639
884
  method: "POST",
640
- body: withoutHeaders(payload)
885
+ body: payload,
886
+ ...callOptions(options)
641
887
  });
642
888
  },
643
889
  multipart: {
644
- init(payload) {
890
+ init(payload, options) {
645
891
  return $fetch(S3_API_ROUTES.multipartInit, {
646
892
  method: "POST",
647
- body: withoutHeaders(payload)
893
+ body: payload,
894
+ ...callOptions(options)
648
895
  });
649
896
  },
650
- signPart(payload) {
651
- return $fetch(S3_API_ROUTES.multipartPart, {
897
+ signPart(payload, options) {
898
+ return $fetch(S3_API_ROUTES.multipartSignPart, {
652
899
  method: "POST",
653
- body: withoutHeaders(payload)
900
+ body: payload,
901
+ ...callOptions(options)
654
902
  });
655
903
  },
656
- listParts(payload) {
657
- const { route, key, uploadId } = withoutHeaders(payload);
904
+ listParts(payload, options) {
658
905
  return $fetch(
659
906
  S3_API_ROUTES.multipartListParts,
660
- { method: "GET", query: { route, key, uploadId } }
907
+ { method: "POST", body: payload, ...callOptions(options) }
661
908
  );
662
909
  },
663
- complete(payload) {
910
+ complete(payload, options) {
664
911
  return $fetch(
665
912
  S3_API_ROUTES.multipartComplete,
666
- {
667
- method: "POST",
668
- body: withoutHeaders(payload)
669
- }
913
+ { method: "POST", body: payload, ...callOptions(options) }
670
914
  );
671
915
  },
672
- abort(payload) {
916
+ abort(payload, options) {
673
917
  return $fetch(S3_API_ROUTES.multipartAbort, {
674
918
  method: "POST",
675
- body: withoutHeaders(payload)
919
+ body: payload,
920
+ ...callOptions(options)
676
921
  });
677
922
  }
678
923
  }
@@ -680,11 +925,14 @@ function createCoreApi($fetch) {
680
925
  }
681
926
  function createS3Client(options) {
682
927
  const { basePath, baseURL, plugins, ...fetchOptions } = options ?? {};
683
- const base = normalizeS3ApiBasePath(baseURL ?? basePath ?? S3_API_BASE_PATH);
928
+ const base = baseURL !== void 0 ? stripTrailingSlashes(baseURL) : normalizeS3ApiBasePath(basePath ?? S3_API_BASE_PATH);
684
929
  const $fetch = createS3Fetch(base, fetchOptions);
685
- const api = createCoreApi($fetch);
930
+ const api = createCoreApi($fetch, base);
686
931
  const pluginMethods = {};
687
932
  for (const plugin of plugins ?? []) {
933
+ if (!ROUTE_NAME_PATTERN.test(plugin.id)) {
934
+ throw new Error(`Client plugin id "${plugin.id}" is invalid.`);
935
+ }
688
936
  if (RESERVED_CLIENT_KEYS.includes(plugin.id)) {
689
937
  throw new Error(
690
938
  `Client plugin id "${plugin.id}" is reserved on the S3 client.`
@@ -704,6 +952,6 @@ function createS3Client(options) {
704
952
  };
705
953
  }
706
954
 
707
- export { APIError, DELETE_BATCH_MAX_KEYS, RESERVED_CLIENT_KEYS, ROUTE_NAME_PATTERN, S3_API_BASE_PATH, S3_API_ROUTES, S3_DEFAULT_EXPIRES_IN, S3_ERROR_CODES, S3_MAX_EXPIRES_IN, S3_MAX_METADATA_ENTRIES, S3_MAX_OBJECT_KEY_LENGTH, S3_MAX_PART_NUMBER, S3_MAX_POST_OBJECT_BYTES, buildContentDisposition, buildObjectKey, buildPublicObjectUrl, confirmBodySchema, createS3Client, createS3Fetch, defineClientPlugin, defineErrorCodes, deleteBatchBodySchema, deleteQuerySchema, downloadDispositionSchema, downloadModeSchema, downloadQuerySchema, fileNameFromKey, fileQuerySchema, formatFileSize, isAPIError, isS3ErrorCode, matchesFileTypes, matchesMagicBytes, metadataSchema, multipartAbortBodySchema, multipartCompleteBodySchema, multipartCompletedPartSchema, multipartInitBodySchema, multipartListPartsQuerySchema, multipartSignPartBodySchema, normalizeObjectKey, normalizeS3ApiBasePath, objectKeySchema, optionalChecksumSchema, optionalTrimmedString, parseFileName, partNumberSchema, pluginPath, resolveInlineDisposition, resolveStoredFileName, routeCatalogEntrySchema, routeCatalogResponseSchema, routeNameSchema, s3ErrorParamsSchema, s3FetchErrorSchema, s3ObjectAclSchema, sanitizeFileName, sha256Base64, sha256ChecksumSchema, sha256File, sniffContentType, trimmedString, truncateFileName, uploadBodySchema, validateFile };
955
+ export { APIError, DEFAULT_INLINE_TYPES, DELETE_MANY_MAX_KEYS, RESERVED_CLIENT_KEYS, ROUTE_NAME_PATTERN, S3_API_BASE_PATH, S3_API_ROUTES, S3_DEFAULT_EXPIRES_IN, S3_DEFAULT_PART_SIZE, S3_ERROR_CODES, S3_MAX_EXPIRES_IN, S3_MAX_FILE_FIELD_BYTES, S3_MAX_METADATA_ENTRIES, S3_MAX_OBJECT_KEY_BYTES, S3_MAX_OBJECT_SIZE, S3_MAX_PART_NUMBER, S3_MAX_PART_SIZE, S3_MAX_POST_OBJECT_BYTES, S3_MIN_PART_SIZE, SNIFF_BYTE_LENGTH, UPLOAD_TICKET_MAX_LENGTH, base64UrlDecode, base64UrlEncode, buildContentDisposition, buildObjectKey, buildPublicObjectUrl, createS3Client, createS3Fetch, defineClientPlugin, defineErrorCodes, describeFileType, effectiveContentType, fileNameFromKey, fitFileName, formatErrorMessage, isAPIError, isS3ErrorCode, isSniffableType, matchesFileTypes, matchesMagicBytes, normalizeObjectKey, normalizeS3ApiBasePath, objectKeyByteLength, parseFileName, pluginPath, resolveInlineDisposition, resolveStoredFileName, s3Error, sha256Base64, sha256Blob, sniffContentType, validateFile };
708
956
  //# sourceMappingURL=index.js.map
709
957
  //# sourceMappingURL=index.js.map