@dimah-s3/core 1.7.1 → 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 (74) 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/checksum.d.ts +8 -2
  13. package/dist/helpers/checksum.d.ts.map +1 -1
  14. package/dist/helpers/content-type.d.ts +17 -0
  15. package/dist/helpers/content-type.d.ts.map +1 -0
  16. package/dist/helpers/fit-file-name.d.ts +15 -0
  17. package/dist/helpers/fit-file-name.d.ts.map +1 -0
  18. package/dist/helpers/index.d.ts +7 -9
  19. package/dist/helpers/index.d.ts.map +1 -1
  20. package/dist/helpers/magic-bytes.d.ts +9 -2
  21. package/dist/helpers/magic-bytes.d.ts.map +1 -1
  22. package/dist/helpers/normalize-object-key.d.ts +8 -3
  23. package/dist/helpers/normalize-object-key.d.ts.map +1 -1
  24. package/dist/helpers/parse-file-name.d.ts +5 -0
  25. package/dist/helpers/parse-file-name.d.ts.map +1 -1
  26. package/dist/helpers/resolve-inline-disposition.d.ts +16 -6
  27. package/dist/helpers/resolve-inline-disposition.d.ts.map +1 -1
  28. package/dist/helpers/validate-file.d.ts +13 -16
  29. package/dist/helpers/validate-file.d.ts.map +1 -1
  30. package/dist/index.d.ts +2 -2
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +711 -478
  33. package/dist/index.js.map +1 -1
  34. package/dist/limits.d.ts +30 -0
  35. package/dist/limits.d.ts.map +1 -0
  36. package/dist/plugin/create-s3-fetch.d.ts +5 -3
  37. package/dist/plugin/create-s3-fetch.d.ts.map +1 -1
  38. package/dist/plugin/types.d.ts +13 -4
  39. package/dist/plugin/types.d.ts.map +1 -1
  40. package/dist/routes.d.ts +10 -4
  41. package/dist/routes.d.ts.map +1 -1
  42. package/dist/schema/catalog.d.ts +30 -39
  43. package/dist/schema/catalog.d.ts.map +1 -1
  44. package/dist/schema/delete.d.ts +1 -2
  45. package/dist/schema/delete.d.ts.map +1 -1
  46. package/dist/schema/download.d.ts +16 -3
  47. package/dist/schema/download.d.ts.map +1 -1
  48. package/dist/schema/index.d.ts +5 -9
  49. package/dist/schema/index.d.ts.map +1 -1
  50. package/dist/schema/index.js +221 -0
  51. package/dist/schema/index.js.map +1 -0
  52. package/dist/schema/multipart.d.ts +6 -29
  53. package/dist/schema/multipart.d.ts.map +1 -1
  54. package/dist/schema/shared.d.ts +25 -17
  55. package/dist/schema/shared.d.ts.map +1 -1
  56. package/dist/schema/upload.d.ts +10 -7
  57. package/dist/schema/upload.d.ts.map +1 -1
  58. package/dist/types/index.d.ts +2 -2
  59. package/dist/types/index.d.ts.map +1 -1
  60. package/dist/types/requests.d.ts +25 -31
  61. package/dist/types/requests.d.ts.map +1 -1
  62. package/dist/types/responses.d.ts +96 -83
  63. package/dist/types/responses.d.ts.map +1 -1
  64. package/package.json +9 -4
  65. package/dist/helpers/format-file-size.d.ts +0 -18
  66. package/dist/helpers/format-file-size.d.ts.map +0 -1
  67. package/dist/helpers/sanitize-file-name.d.ts +0 -3
  68. package/dist/helpers/sanitize-file-name.d.ts.map +0 -1
  69. package/dist/helpers/truncate-file-name.d.ts +0 -5
  70. package/dist/helpers/truncate-file-name.d.ts.map +0 -1
  71. package/dist/schema/error.d.ts +0 -14
  72. package/dist/schema/error.d.ts.map +0 -1
  73. package/dist/schema/file.d.ts +0 -12
  74. package/dist/schema/file.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,135 +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
- };
36
- }
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
- };
44
- }
45
- return null;
46
- }
5
+ // src/error.ts
47
6
 
48
- // src/helpers/strip-slashes.ts
49
- var SLASH = "/";
50
- function stripTrailingSlashes(value) {
51
- let end = value.length;
52
- while (end > 0 && value.charAt(end - 1) === SLASH) end -= 1;
53
- return end === value.length ? value : value.slice(0, end);
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] };
12
+ }
13
+ return entries;
54
14
  }
55
- function stripSurroundingSlashes(value) {
56
- let start = 0;
57
- let end = value.length;
58
- while (start < end && value.charAt(start) === SLASH) start += 1;
59
- while (end > start && value.charAt(end - 1) === SLASH) end -= 1;
60
- return start === 0 && end === value.length ? value : value.slice(start, end);
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"
123
+ }
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
+ );
61
131
  }
62
132
 
63
- // src/helpers/build-object-key.ts
64
- function buildObjectKey(...parts) {
65
- return parts.map((part) => stripSurroundingSlashes(part)).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;
66
143
  }
67
-
68
- // src/helpers/parse-file-name.ts
69
- function parseFileName(contentDisposition) {
70
- if (!contentDisposition) return void 0;
71
- const utf8Match = contentDisposition.match(/filename\*=UTF-8''([^;,\s]+)/i);
72
- if (utf8Match) {
73
- try {
74
- return decodeURIComponent(utf8Match[1]);
75
- } 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;
76
151
  }
77
152
  }
78
- const asciiMatch = contentDisposition.match(/filename="([^"]*)"/i);
79
- return asciiMatch?.[1];
80
- }
81
- function fileNameFromKey(key) {
82
- return key.split("/").findLast((part) => part.length > 0);
83
- }
84
- function resolveStoredFileName(contentDisposition, key) {
85
- return parseFileName(contentDisposition) ?? fileNameFromKey(key);
86
- }
87
-
88
- // src/helpers/format-file-size.ts
89
- var UNITS = [
90
- "B",
91
- "KB",
92
- "MB",
93
- "GB",
94
- "TB",
95
- "PB",
96
- "EB"
97
- ];
98
- var numberFormats = /* @__PURE__ */ new Map();
99
- function numberFormat(locale, fractionDigits) {
100
- const id = `${String(locale)}|${fractionDigits}`;
101
- let format = numberFormats.get(id);
102
- if (!format) {
103
- format = new Intl.NumberFormat(
104
- typeof locale === "string" ? locale : [...locale],
105
- {
106
- minimumFractionDigits: fractionDigits,
107
- maximumFractionDigits: fractionDigits,
108
- useGrouping: false
109
- }
110
- );
111
- numberFormats.set(id, format);
153
+ /** Stable machine-readable code; always set. */
154
+ get code() {
155
+ return this.body.code;
112
156
  }
113
- return format;
114
- }
115
- function formatFileSize(bytes, options = {}) {
116
- const size = Number.isFinite(bytes) && bytes > 0 ? bytes : 0;
117
- const i = size === 0 ? 0 : Math.min(Math.floor(Math.log(size) / Math.log(1024)), UNITS.length - 1);
118
- const unit = UNITS[i] ?? "B";
119
- const value = numberFormat(options.locale ?? "en-US", i === 0 ? 0 : 1).format(
120
- size / 1024 ** i
121
- );
122
- 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
+ });
123
188
  }
124
-
125
- // src/helpers/build-content-disposition.ts
126
- function buildContentDisposition(fileName, type = "attachment") {
127
- const ascii = fileName.replaceAll(/[^\x20-\x7E]/g, "_").replaceAll(/["\\]/g, "_");
128
- const encoded = encodeURIComponent(fileName);
129
- 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;
130
196
  }
131
197
 
132
- // src/helpers/resolve-inline-disposition.ts
198
+ // src/helpers/content-type.ts
133
199
  var TYPE_BY_EXTENSION = {
134
200
  avif: "image/avif",
135
201
  bmp: "image/bmp",
@@ -174,8 +240,117 @@ function typeFromFileName(fileName) {
174
240
  if (!fileName || dot < 0) return void 0;
175
241
  return TYPE_BY_EXTENSION[fileName.slice(dot + 1).toLowerCase()];
176
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
+ ];
177
352
  function isActiveContentType(type) {
178
- 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");
179
354
  }
180
355
  function isAllowed(type, allow) {
181
356
  const active = isActiveContentType(type);
@@ -187,43 +362,92 @@ function isAllowed(type, allow) {
187
362
  });
188
363
  }
189
364
  function resolveInlineDisposition(input) {
190
- if (input.requested !== "inline") return { disposition: "attachment" };
191
- const stored = baseType(input.contentType);
192
- const untyped = UNTYPED.has(stored);
193
- const type = untyped ? typeFromFileName(input.fileName) : stored;
194
- if (!type || !isAllowed(type, input.allow)) {
365
+ const allow = input.allow ?? DEFAULT_INLINE_TYPES;
366
+ if (input.requested !== "inline" || allow === false) {
367
+ return { disposition: "attachment" };
368
+ }
369
+ const type = effectiveContentType(input.contentType, input.fileName);
370
+ if (!type || !isAllowed(type, allow)) {
195
371
  return { disposition: "attachment" };
196
372
  }
197
- return untyped ? { disposition: "inline", contentType: type } : { disposition: "inline" };
373
+ return type === baseType(input.contentType) ? { disposition: "inline" } : { disposition: "inline", contentType: type };
198
374
  }
199
375
 
200
- // src/helpers/sanitize-file-name.ts
201
- function sanitizeFileName(fileName) {
202
- return fileName.replaceAll(/["\\\r\n\0]/g, "_");
203
- }
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;
204
390
 
205
- // src/helpers/truncate-file-name.ts
206
- function truncateFileName(name, maxChars = 48) {
207
- if (name.length <= maxChars) return name;
208
- const dotIndex = name.lastIndexOf(".");
209
- if (dotIndex <= 0) {
210
- 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;
211
405
  }
212
- const ext = name.slice(dotIndex);
213
- const available = maxChars - ext.length - 1;
214
- if (available <= 0) {
215
- 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;
216
416
  }
217
- 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}`;
218
435
  }
219
436
 
220
437
  // src/helpers/normalize-object-key.ts
221
- 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;
222
444
  function normalizeObjectKey(key) {
223
445
  const trimmed = stripSurroundingSlashes(key);
224
- if (!trimmed) return null;
225
- if (trimmed.length > S3_MAX_OBJECT_KEY_LENGTH) return null;
226
- if (trimmed.includes("\\") || trimmed.includes("\0")) return null;
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;
227
451
  const parts = trimmed.split("/");
228
452
  if (parts.some((part) => part === "" || part === "." || part === "..")) {
229
453
  return null;
@@ -231,48 +455,246 @@ function normalizeObjectKey(key) {
231
455
  return parts.join("/");
232
456
  }
233
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
+
234
488
  // src/helpers/checksum.ts
489
+ var CHUNK_SIZE2 = 1024 * 1024;
490
+ function toUnpaddedBase64(bytes) {
491
+ return bytesToBase64(bytes).replace(/=+$/, "");
492
+ }
235
493
  async function sha256Base64(data) {
236
494
  const digest = await crypto.subtle.digest("SHA-256", data);
237
- const bytes = new Uint8Array(digest);
238
- return btoa(String.fromCharCode(...bytes)).replaceAll(/=+$/g, "");
239
- }
240
- async function sha256File(file) {
241
- 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());
242
507
  }
243
508
 
244
509
  // src/helpers/magic-bytes.ts
245
- var MAGIC = [
246
- { mime: "image/png", bytes: [137, 80, 78, 71] },
247
- { mime: "image/jpeg", bytes: [255, 216, 255] },
248
- { mime: "image/gif", bytes: [71, 73, 70, 56] },
249
- { mime: "image/webp", bytes: [82, 73, 70, 70], offset: 0 },
250
- { mime: "application/pdf", bytes: [37, 80, 68, 70] },
251
- { mime: "application/zip", bytes: [80, 75, 3, 4] },
252
- { 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
+ }
253
537
  ];
254
- function prefixEquals(bytes, expected, offset = 0) {
538
+ function startsWith(bytes, expected, offset = 0) {
255
539
  if (bytes.length < offset + expected.length) return false;
256
540
  return expected.every((value, i) => bytes[offset + i] === value);
257
541
  }
258
- function sniffContentType(bytes) {
259
- if (prefixEquals(bytes, [82, 73, 70, 70]) && bytes.length >= 12) {
260
- const tag = String.fromCharCode(...bytes.subarray(8, 12));
261
- 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));
262
563
  }
263
- for (const entry of MAGIC) {
264
- if (entry.mime === "image/webp") continue;
265
- 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")
266
673
  }
267
- 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));
268
687
  }
269
688
  function matchesMagicBytes(bytes, expected) {
270
- const sniffed = sniffContentType(bytes);
271
- if (!sniffed) return false;
272
- if (expected.endsWith("/*")) {
273
- 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));
274
696
  }
275
- return sniffed === expected;
697
+ return types.includes(base);
276
698
  }
277
699
 
278
700
  // src/helpers/public-object-url.ts
@@ -281,297 +703,87 @@ function buildPublicObjectUrl(options) {
281
703
  const path = options.key.split("/").filter((part) => part.length > 0).map((part) => encodeURIComponent(part)).join("/");
282
704
  return `${base}/${path}`;
283
705
  }
284
- var S3_DEFAULT_EXPIRES_IN = 600;
285
- var S3_MAX_EXPIRES_IN = 604800;
286
- var S3_MAX_POST_OBJECT_BYTES = 5 * 1024 * 1024 * 1024;
287
- var S3_MAX_PART_NUMBER = 1e4;
288
- var S3_MAX_METADATA_ENTRIES = 32;
289
- var ROUTE_NAME_PATTERN = /^[a-z][\w-]{0,63}$/i;
290
- var trimmedString = z3.string().trim().min(1);
291
- var optionalTrimmedString = z3.preprocess((value) => {
292
- if (typeof value !== "string") return value;
293
- const trimmed = value.trim();
294
- return trimmed === "" ? void 0 : trimmed;
295
- }, z3.string().optional());
296
- var routeNameSchema = trimmedString.regex(
297
- ROUTE_NAME_PATTERN,
298
- "Invalid route name"
299
- );
300
- var objectKeySchema = trimmedString.max(S3_MAX_OBJECT_KEY_LENGTH).transform((value, ctx) => {
301
- const normalized = normalizeObjectKey(value);
302
- if (normalized == null) {
303
- ctx.issues.push({
304
- code: "custom",
305
- message: "Invalid object key",
306
- input: value
307
- });
308
- return z3.NEVER;
309
- }
310
- return normalized;
311
- });
312
- var partNumberSchema = z3.int().min(1).max(S3_MAX_PART_NUMBER);
313
- var s3ObjectAclSchema = z3.enum(["private", "public-read"]);
314
- var sha256ChecksumSchema = z3.stringFormat(
315
- "sha256-base64",
316
- /^[A-Z0-9+/]{43}=?$/i
317
- );
318
- var optionalChecksumSchema = optionalTrimmedString.pipe(
319
- sha256ChecksumSchema.optional()
320
- );
321
- var metadataKeySchema = z3.string().regex(/^[a-z0-9][a-z0-9-]*$/i, "Invalid metadata key").max(128);
322
- var metadataSchema = z3.record(metadataKeySchema, z3.string().max(2048)).refine((value) => Object.keys(value).length <= S3_MAX_METADATA_ENTRIES, {
323
- message: "Too many metadata entries"
324
- });
325
- var uploadBodySchema = z3.strictObject({
326
- route: routeNameSchema,
327
- fileName: trimmedString,
328
- fileSize: z3.int().positive(),
329
- contentType: optionalTrimmedString,
330
- metadata: metadataSchema.optional(),
331
- /** Unpadded base64 SHA-256. Required when the route sets `upload.checksum`. */
332
- checksum: optionalChecksumSchema
333
- });
334
- var confirmBodySchema = z3.strictObject({
335
- route: routeNameSchema,
336
- key: objectKeySchema
337
- });
338
- var downloadDispositionSchema = z3.enum(["inline", "attachment"]);
339
- var downloadModeSchema = z3.enum(["presign", "proxy"]);
340
- var routeCatalogUploadSchema = z3.discriminatedUnion("enabled", [
341
- z3.strictObject({
342
- enabled: z3.literal(true),
343
- fileTypes: z3.array(z3.string()).optional(),
344
- maxFileSize: z3.int().positive().optional(),
345
- multipart: z3.boolean(),
346
- checksum: z3.boolean().optional(),
347
- replace: z3.literal("overwrite").optional()
348
- }),
349
- z3.strictObject({ enabled: z3.literal(false) })
350
- ]);
351
- var routeCatalogDownloadSchema = z3.discriminatedUnion("enabled", [
352
- z3.strictObject({
353
- enabled: z3.literal(true),
354
- /**
355
- * Maximum presign TTL in seconds. Clients may request a shorter
356
- * `expiresIn`. Omitted means the protocol default (600).
357
- */
358
- expiresIn: z3.int().positive().max(S3_MAX_EXPIRES_IN).optional(),
359
- disposition: downloadDispositionSchema.optional(),
360
- /** Types that may open inline. Pass to `resolveInlineDisposition`. */
361
- inlineTypes: z3.array(z3.string()).optional(),
362
- mode: downloadModeSchema.optional()
363
- }),
364
- z3.strictObject({ enabled: z3.literal(false) })
365
- ]);
366
- var routeCatalogDeleteSchema = z3.discriminatedUnion("enabled", [
367
- z3.strictObject({ enabled: z3.literal(true) }),
368
- z3.strictObject({ enabled: z3.literal(false) })
369
- ]);
370
- var routeCatalogEntrySchema = z3.strictObject({
371
- upload: routeCatalogUploadSchema,
372
- download: routeCatalogDownloadSchema,
373
- delete: routeCatalogDeleteSchema
374
- });
375
- var routeCatalogResponseSchema = z3.strictObject({
376
- routes: z3.record(routeNameSchema, routeCatalogEntrySchema)
377
- });
378
-
379
- // src/schema/download.ts
380
- var optionalExpiresInSchema = z3.preprocess((value) => {
381
- if (value == null || value === "") return void 0;
382
- if (typeof value === "number") return value;
383
- if (typeof value === "string") {
384
- const trimmed = value.trim();
385
- if (trimmed === "") return void 0;
386
- if (/^\d+$/.test(trimmed)) return Number(trimmed);
387
- }
388
- return value;
389
- }, z3.int().positive().max(S3_MAX_EXPIRES_IN).optional());
390
- var downloadQuerySchema = z3.strictObject({
391
- route: routeNameSchema,
392
- key: objectKeySchema,
393
- fileName: optionalTrimmedString,
394
- disposition: downloadDispositionSchema.optional(),
395
- /**
396
- * Requested TTL in seconds. Signed only when it is shorter than the
397
- * route `download.expiresIn`. `download.resolve` can still replace it.
398
- */
399
- expiresIn: optionalExpiresInSchema
400
- });
401
- var DELETE_BATCH_MAX_KEYS = 100;
402
- var deleteQuerySchema = z3.strictObject({
403
- route: routeNameSchema,
404
- key: objectKeySchema
405
- });
406
- var deleteBatchBodySchema = z3.strictObject({
407
- route: routeNameSchema,
408
- keys: z3.array(objectKeySchema).min(1).max(DELETE_BATCH_MAX_KEYS)
409
- });
410
- var fileQuerySchema = z3.strictObject({
411
- route: routeNameSchema,
412
- key: objectKeySchema,
413
- fileName: optionalTrimmedString,
414
- disposition: downloadDispositionSchema.optional()
415
- });
416
- var multipartInitBodySchema = uploadBodySchema;
417
- var multipartSessionFields = {
418
- route: routeNameSchema,
419
- key: objectKeySchema,
420
- uploadId: trimmedString
421
- };
422
- var multipartSignPartBodySchema = z3.strictObject({
423
- ...multipartSessionFields,
424
- partNumber: partNumberSchema,
425
- partSize: z3.int().positive()
426
- });
427
- var multipartListPartsQuerySchema = z3.strictObject({
428
- ...multipartSessionFields
429
- });
430
- var multipartCompletedPartSchema = z3.strictObject({
431
- partNumber: partNumberSchema
432
- });
433
- var multipartCompleteBodySchema = z3.strictObject({
434
- ...multipartSessionFields,
435
- parts: z3.array(multipartCompletedPartSchema).min(1)
436
- });
437
- var multipartAbortBodySchema = z3.strictObject({
438
- ...multipartSessionFields
439
- });
440
- var s3ErrorParamsSchema = z3.record(
441
- z3.string(),
442
- z3.union([z3.string(), z3.number()])
443
- );
444
- var s3FetchErrorSchema = z3.object({
445
- message: z3.string(),
446
- code: z3.string().optional(),
447
- params: s3ErrorParamsSchema.optional()
448
- });
449
-
450
- // src/error-codes.ts
451
- function defineErrorCodes(messages) {
452
- const codes = {};
453
- for (const code of Object.keys(messages)) {
454
- codes[code] = { code, message: messages[code] };
455
- }
456
- return codes;
457
- }
458
- var S3_ERROR_CODES = defineErrorCodes({
459
- NOT_FOUND: "Not Found",
460
- UNAUTHORIZED: "Unauthorized",
461
- FORBIDDEN: "Forbidden",
462
- CONFLICT: "Conflict",
463
- INTERNAL_ERROR: "Internal server error",
464
- OBJECT_NOT_FOUND: "Object not found",
465
- FEATURE_DISABLED: "{feature} is disabled",
466
- INVALID_KEY: "Object key is invalid",
467
- UNKNOWN_ROUTE: "Unknown file route",
468
- FILE_TYPE_NOT_ALLOWED: "File type is not allowed",
469
- S3_NETWORK_ERROR: "S3 endpoint unreachable ({code}): check your endpoint URL and network connectivity",
470
- MULTIPART_PART_MISSING: "Uploaded part {partNumber} was not found",
471
- PAYLOAD_TOO_LARGE: "Payload too large",
472
- QUOTA_EXCEEDED: "Storage quota exceeded",
473
- VALIDATION_ERROR: "Validation Error"
474
- });
475
-
476
- // src/error.ts
477
- var APIError = class _APIError extends APIError$1 {
478
- constructor(status = "BAD_REQUEST", body, headers) {
479
- const { cause, ...rest } = body ?? {};
480
- super(
481
- status,
482
- Object.keys(rest).length > 0 ? rest : void 0,
483
- headers
484
- );
485
- this.name = "APIError";
486
- if (cause !== void 0) {
487
- this.cause = cause;
488
- }
489
- }
490
- get code() {
491
- return this.body?.code;
492
- }
493
- get params() {
494
- return this.body?.params;
495
- }
496
- /** Throw a catalog (or custom) `{ code, message }` with an HTTP status. */
497
- static from(status, error) {
498
- return new _APIError(status, {
499
- message: error.message,
500
- code: error.code,
501
- ...error.params !== void 0 ? { params: error.params } : {}
502
- });
503
- }
504
- static fromStatus(status, body) {
505
- return new _APIError(status, body);
506
- }
507
- };
508
- function isAPIError(error) {
509
- return error instanceof APIError$1 || error instanceof APIError || error?.name === "APIError";
510
- }
511
- function isS3ErrorCode(error, code) {
512
- return isAPIError(error) && error.code === code;
513
- }
514
706
 
515
707
  // src/routes.ts
516
708
  var S3_API_BASE_PATH = "/api/s3";
517
709
  function normalizeS3ApiBasePath(basePath) {
518
- return stripTrailingSlashes(basePath);
710
+ const path = stripSurroundingSlashes(basePath.trim());
711
+ return path ? `/${path}` : "";
519
712
  }
520
713
  var S3_API_ROUTES = {
521
714
  upload: "/presign/upload",
522
- uploadConfirm: "/presign/upload/confirm",
715
+ confirm: "/presign/upload/confirm",
523
716
  download: "/presign/download",
524
717
  file: "/file",
525
718
  catalog: "/routes",
526
719
  delete: "/delete",
527
- deleteBatch: "/delete/batch",
720
+ deleteMany: "/delete/batch",
528
721
  multipartInit: "/presign/multipart/init",
529
- multipartPart: "/presign/multipart/part",
722
+ multipartSignPart: "/presign/multipart/part",
723
+ /** `POST`, because the body carries the upload ticket. */
724
+ multipartListParts: "/presign/multipart/parts",
530
725
  multipartComplete: "/presign/multipart/complete",
531
- multipartAbort: "/presign/multipart/abort",
532
- multipartListParts: "/presign/multipart/parts"
726
+ multipartAbort: "/presign/multipart/abort"
533
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
+ }
534
737
  async function resolveHeaders(headers) {
535
738
  if (headers == null) return void 0;
536
739
  if (typeof headers === "function") return headers();
537
740
  return headers;
538
741
  }
539
- function fallbackMessage(error) {
540
- if (typeof error.error === "string" && error.error.trim()) {
541
- return error.error;
542
- }
543
- return error.statusText || "Request failed";
544
- }
545
- function apiErrorFromFetch(error) {
546
- const { status } = error;
547
- if (s3FetchErrorSchema.validate(error)) {
548
- const { message, code, params } = error;
549
- return new APIError(status, {
550
- message,
551
- ...code !== void 0 ? { code } : {},
552
- ...params !== void 0 ? { params } : {}
553
- });
554
- }
555
- 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
+ };
556
763
  }
557
764
  function createS3Fetch(base, options) {
558
765
  return createFetch({
559
766
  baseURL: base,
560
767
  throw: true,
561
- errorSchema: s3FetchErrorSchema,
562
- customFetchImpl: options?.fetch,
768
+ customFetchImpl: withNetworkErrors(options?.fetch),
563
769
  credentials: options?.credentials,
564
770
  onRequest: async (ctx) => {
565
- const extra = await resolveHeaders(options?.headers);
566
- if (!extra) return ctx;
567
- const headers = new Headers(ctx.headers);
568
- 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) {
569
775
  headers.set(key, value);
570
776
  }
571
777
  return { ...ctx, headers };
572
778
  },
779
+ onSuccess: (ctx) => {
780
+ if (isJsonBody(ctx.data)) return;
781
+ throw s3Error("UNKNOWN_ERROR", void 0, {
782
+ status: ctx.response.status
783
+ });
784
+ },
573
785
  onError: (ctx) => {
574
- throw apiErrorFromFetch(ctx.error);
786
+ throw apiErrorFromResponse(ctx.response.status, ctx.error);
575
787
  }
576
788
  });
577
789
  }
@@ -606,88 +818,106 @@ var RESERVED_CLIENT_KEYS = [
606
818
  ];
607
819
 
608
820
  // src/create-s3-client.ts
609
- function withoutHeaders(value) {
610
- const { headers: _headers, ...rest } = value;
611
- 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
+ };
612
827
  }
613
- function createCoreApi($fetch) {
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;
832
+ }
833
+ function createCoreApi($fetch, base) {
614
834
  return {
615
- upload(payload) {
835
+ upload(payload, options) {
616
836
  return $fetch(S3_API_ROUTES.upload, {
617
837
  method: "POST",
618
- body: withoutHeaders(payload)
838
+ body: payload,
839
+ ...callOptions(options)
619
840
  });
620
841
  },
621
- confirm(payload) {
622
- return $fetch(S3_API_ROUTES.uploadConfirm, {
842
+ confirm(payload, options) {
843
+ return $fetch(S3_API_ROUTES.confirm, {
623
844
  method: "POST",
624
- body: withoutHeaders(payload)
845
+ body: payload,
846
+ ...callOptions(options)
625
847
  });
626
848
  },
627
- download(payload) {
628
- const { route, key, fileName, disposition, expiresIn } = withoutHeaders(payload);
629
- return $fetch(S3_API_ROUTES.download, {
630
- method: "GET",
631
- query: {
632
- route,
633
- key,
634
- fileName: fileName ? sanitizeFileName(fileName) : void 0,
635
- disposition,
636
- 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)
637
864
  }
638
- });
865
+ );
866
+ return { ...response, url: resolveProxyUrl(response.url, base) };
639
867
  },
640
- catalog() {
868
+ catalog(options) {
641
869
  return $fetch(S3_API_ROUTES.catalog, {
642
- method: "GET"
870
+ method: "GET",
871
+ ...callOptions(options)
643
872
  });
644
873
  },
645
- delete(payload) {
646
- const { route, key } = withoutHeaders(payload);
874
+ delete(payload, options) {
875
+ const { route, key } = payload;
647
876
  return $fetch(S3_API_ROUTES.delete, {
648
877
  method: "DELETE",
649
- query: { route, key }
878
+ query: { route, key },
879
+ ...callOptions(options)
650
880
  });
651
881
  },
652
- deleteMany(payload) {
653
- return $fetch(S3_API_ROUTES.deleteBatch, {
882
+ deleteMany(payload, options) {
883
+ return $fetch(S3_API_ROUTES.deleteMany, {
654
884
  method: "POST",
655
- body: withoutHeaders(payload)
885
+ body: payload,
886
+ ...callOptions(options)
656
887
  });
657
888
  },
658
889
  multipart: {
659
- init(payload) {
890
+ init(payload, options) {
660
891
  return $fetch(S3_API_ROUTES.multipartInit, {
661
892
  method: "POST",
662
- body: withoutHeaders(payload)
893
+ body: payload,
894
+ ...callOptions(options)
663
895
  });
664
896
  },
665
- signPart(payload) {
666
- return $fetch(S3_API_ROUTES.multipartPart, {
897
+ signPart(payload, options) {
898
+ return $fetch(S3_API_ROUTES.multipartSignPart, {
667
899
  method: "POST",
668
- body: withoutHeaders(payload)
900
+ body: payload,
901
+ ...callOptions(options)
669
902
  });
670
903
  },
671
- listParts(payload) {
672
- const { route, key, uploadId } = withoutHeaders(payload);
904
+ listParts(payload, options) {
673
905
  return $fetch(
674
906
  S3_API_ROUTES.multipartListParts,
675
- { method: "GET", query: { route, key, uploadId } }
907
+ { method: "POST", body: payload, ...callOptions(options) }
676
908
  );
677
909
  },
678
- complete(payload) {
910
+ complete(payload, options) {
679
911
  return $fetch(
680
912
  S3_API_ROUTES.multipartComplete,
681
- {
682
- method: "POST",
683
- body: withoutHeaders(payload)
684
- }
913
+ { method: "POST", body: payload, ...callOptions(options) }
685
914
  );
686
915
  },
687
- abort(payload) {
916
+ abort(payload, options) {
688
917
  return $fetch(S3_API_ROUTES.multipartAbort, {
689
918
  method: "POST",
690
- body: withoutHeaders(payload)
919
+ body: payload,
920
+ ...callOptions(options)
691
921
  });
692
922
  }
693
923
  }
@@ -695,11 +925,14 @@ function createCoreApi($fetch) {
695
925
  }
696
926
  function createS3Client(options) {
697
927
  const { basePath, baseURL, plugins, ...fetchOptions } = options ?? {};
698
- const base = normalizeS3ApiBasePath(baseURL ?? basePath ?? S3_API_BASE_PATH);
928
+ const base = baseURL !== void 0 ? stripTrailingSlashes(baseURL) : normalizeS3ApiBasePath(basePath ?? S3_API_BASE_PATH);
699
929
  const $fetch = createS3Fetch(base, fetchOptions);
700
- const api = createCoreApi($fetch);
930
+ const api = createCoreApi($fetch, base);
701
931
  const pluginMethods = {};
702
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
+ }
703
936
  if (RESERVED_CLIENT_KEYS.includes(plugin.id)) {
704
937
  throw new Error(
705
938
  `Client plugin id "${plugin.id}" is reserved on the S3 client.`
@@ -719,6 +952,6 @@ function createS3Client(options) {
719
952
  };
720
953
  }
721
954
 
722
- 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 };
723
956
  //# sourceMappingURL=index.js.map
724
957
  //# sourceMappingURL=index.js.map