@dimah-s3/server 1.7.1 → 2.0.0-beta.1

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 (187) hide show
  1. package/README.md +72 -16
  2. package/dist/adapters/express.d.ts +7 -7
  3. package/dist/adapters/express.d.ts.map +1 -1
  4. package/dist/adapters/express.js +94 -94
  5. package/dist/adapters/express.js.map +1 -1
  6. package/dist/adapters/fastify.d.ts +11 -5
  7. package/dist/adapters/fastify.d.ts.map +1 -1
  8. package/dist/adapters/fastify.js +94 -94
  9. package/dist/adapters/fastify.js.map +1 -1
  10. package/dist/adapters/node.d.ts +20 -3
  11. package/dist/adapters/node.d.ts.map +1 -1
  12. package/dist/adapters/node.js +92 -92
  13. package/dist/adapters/node.js.map +1 -1
  14. package/dist/api/context.d.ts +8 -4
  15. package/dist/api/context.d.ts.map +1 -1
  16. package/dist/api/{routes/index.d.ts → core-endpoints.d.ts} +43 -68
  17. package/dist/api/core-endpoints.d.ts.map +1 -0
  18. package/dist/api/create-s3-endpoint.d.ts +70 -48
  19. package/dist/api/create-s3-endpoint.d.ts.map +1 -1
  20. package/dist/api/create-s3-middleware.d.ts +19 -16
  21. package/dist/api/create-s3-middleware.d.ts.map +1 -1
  22. package/dist/api/router-context.d.ts +23 -0
  23. package/dist/api/router-context.d.ts.map +1 -0
  24. package/dist/api/router.d.ts +15 -5
  25. package/dist/api/router.d.ts.map +1 -1
  26. package/dist/config/feature-toggle.d.ts +16 -0
  27. package/dist/config/feature-toggle.d.ts.map +1 -0
  28. package/dist/config/resolve-config.d.ts +9 -0
  29. package/dist/config/resolve-config.d.ts.map +1 -0
  30. package/dist/config/resolve-routes.d.ts +37 -0
  31. package/dist/config/resolve-routes.d.ts.map +1 -0
  32. package/dist/dimah-s3.d.ts +22 -32
  33. package/dist/dimah-s3.d.ts.map +1 -1
  34. package/dist/helpers/authorize-download.d.ts +25 -0
  35. package/dist/helpers/authorize-download.d.ts.map +1 -0
  36. package/dist/helpers/aws-errors.d.ts +16 -0
  37. package/dist/helpers/aws-errors.d.ts.map +1 -0
  38. package/dist/helpers/best-effort.d.ts +22 -3
  39. package/dist/helpers/best-effort.d.ts.map +1 -1
  40. package/dist/helpers/checksum-config.d.ts +13 -0
  41. package/dist/helpers/checksum-config.d.ts.map +1 -0
  42. package/dist/helpers/constraints.d.ts +17 -12
  43. package/dist/helpers/constraints.d.ts.map +1 -1
  44. package/dist/helpers/error-boundary.d.ts +28 -0
  45. package/dist/helpers/error-boundary.d.ts.map +1 -0
  46. package/dist/helpers/finalize-confirmed.d.ts +42 -13
  47. package/dist/helpers/finalize-confirmed.d.ts.map +1 -1
  48. package/dist/helpers/head-object.d.ts +6 -9
  49. package/dist/helpers/head-object.d.ts.map +1 -1
  50. package/dist/helpers/hooks.d.ts +29 -15
  51. package/dist/helpers/hooks.d.ts.map +1 -1
  52. package/dist/helpers/inline-types.d.ts +24 -7
  53. package/dist/helpers/inline-types.d.ts.map +1 -1
  54. package/dist/helpers/list-parts.d.ts +4 -6
  55. package/dist/helpers/list-parts.d.ts.map +1 -1
  56. package/dist/helpers/metadata-encoding.d.ts +15 -0
  57. package/dist/helpers/metadata-encoding.d.ts.map +1 -0
  58. package/dist/helpers/object-meta.d.ts +39 -0
  59. package/dist/helpers/object-meta.d.ts.map +1 -0
  60. package/dist/helpers/object-s3.d.ts +5 -2
  61. package/dist/helpers/object-s3.d.ts.map +1 -1
  62. package/dist/helpers/open-target.d.ts +89 -0
  63. package/dist/helpers/open-target.d.ts.map +1 -0
  64. package/dist/helpers/part-layout.d.ts +19 -0
  65. package/dist/helpers/part-layout.d.ts.map +1 -0
  66. package/dist/helpers/presign.d.ts +54 -0
  67. package/dist/helpers/presign.d.ts.map +1 -0
  68. package/dist/helpers/request.d.ts +6 -11
  69. package/dist/helpers/request.d.ts.map +1 -1
  70. package/dist/helpers/resolve-target.d.ts +28 -20
  71. package/dist/helpers/resolve-target.d.ts.map +1 -1
  72. package/dist/helpers/sniff-object.d.ts +22 -0
  73. package/dist/helpers/sniff-object.d.ts.map +1 -0
  74. package/dist/helpers/ticket.d.ts +75 -0
  75. package/dist/helpers/ticket.d.ts.map +1 -0
  76. package/dist/index.d.ts +4 -12
  77. package/dist/index.d.ts.map +1 -1
  78. package/dist/index.js +2647 -1579
  79. package/dist/index.js.map +1 -1
  80. package/dist/operations/catalog.d.ts +16 -0
  81. package/dist/operations/catalog.d.ts.map +1 -0
  82. package/dist/operations/confirm.d.ts +19 -0
  83. package/dist/operations/confirm.d.ts.map +1 -0
  84. package/dist/operations/delete-many.d.ts +18 -0
  85. package/dist/operations/delete-many.d.ts.map +1 -0
  86. package/dist/operations/delete.d.ts +14 -0
  87. package/dist/operations/delete.d.ts.map +1 -0
  88. package/dist/operations/download.d.ts +20 -0
  89. package/dist/operations/download.d.ts.map +1 -0
  90. package/dist/operations/file.d.ts +38 -0
  91. package/dist/operations/file.d.ts.map +1 -0
  92. package/dist/operations/multipart/abort.d.ts +20 -0
  93. package/dist/operations/multipart/abort.d.ts.map +1 -0
  94. package/dist/operations/multipart/complete.d.ts +21 -0
  95. package/dist/operations/multipart/complete.d.ts.map +1 -0
  96. package/dist/operations/multipart/init.d.ts +19 -0
  97. package/dist/operations/multipart/init.d.ts.map +1 -0
  98. package/dist/operations/multipart/list-parts.d.ts +11 -0
  99. package/dist/operations/multipart/list-parts.d.ts.map +1 -0
  100. package/dist/operations/multipart/open-multipart.d.ts +25 -0
  101. package/dist/operations/multipart/open-multipart.d.ts.map +1 -0
  102. package/dist/operations/multipart/sign-part.d.ts +20 -0
  103. package/dist/operations/multipart/sign-part.d.ts.map +1 -0
  104. package/dist/operations/put.d.ts +18 -0
  105. package/dist/operations/put.d.ts.map +1 -0
  106. package/dist/operations/run-operation.d.ts +18 -0
  107. package/dist/operations/run-operation.d.ts.map +1 -0
  108. package/dist/operations/s3-api.d.ts +12 -0
  109. package/dist/operations/s3-api.d.ts.map +1 -0
  110. package/dist/operations/upload.d.ts +19 -0
  111. package/dist/operations/upload.d.ts.map +1 -0
  112. package/dist/plugin/apply-plugins.d.ts +9 -11
  113. package/dist/plugin/apply-plugins.d.ts.map +1 -1
  114. package/dist/plugin/chain-hooks.d.ts +12 -9
  115. package/dist/plugin/chain-hooks.d.ts.map +1 -1
  116. package/dist/plugin/define-plugin.d.ts +11 -4
  117. package/dist/plugin/define-plugin.d.ts.map +1 -1
  118. package/dist/plugin/index.d.ts +1 -2
  119. package/dist/plugin/index.d.ts.map +1 -1
  120. package/dist/plugin/types.d.ts +52 -56
  121. package/dist/plugin/types.d.ts.map +1 -1
  122. package/dist/plugins.d.ts +10 -8
  123. package/dist/plugins.d.ts.map +1 -1
  124. package/dist/plugins.js +325 -1627
  125. package/dist/plugins.js.map +1 -1
  126. package/dist/route.d.ts +0 -1
  127. package/dist/route.d.ts.map +1 -1
  128. package/dist/types/config.d.ts +171 -172
  129. package/dist/types/config.d.ts.map +1 -1
  130. package/dist/types/hook-contexts.d.ts +139 -147
  131. package/dist/types/hook-contexts.d.ts.map +1 -1
  132. package/dist/types/index.d.ts +3 -3
  133. package/dist/types/index.d.ts.map +1 -1
  134. package/dist/types/locals.d.ts +37 -0
  135. package/dist/types/locals.d.ts.map +1 -0
  136. package/dist/types/resolved.d.ts +118 -0
  137. package/dist/types/resolved.d.ts.map +1 -0
  138. package/package.json +8 -12
  139. package/dist/api/bind-endpoints.d.ts +0 -12
  140. package/dist/api/bind-endpoints.d.ts.map +0 -1
  141. package/dist/api/index.d.ts +0 -6
  142. package/dist/api/index.d.ts.map +0 -1
  143. package/dist/api/index.js +0 -1353
  144. package/dist/api/index.js.map +0 -1
  145. package/dist/api/routes/catalog.d.ts +0 -9
  146. package/dist/api/routes/catalog.d.ts.map +0 -1
  147. package/dist/api/routes/confirm.d.ts +0 -13
  148. package/dist/api/routes/confirm.d.ts.map +0 -1
  149. package/dist/api/routes/delete-batch.d.ts +0 -14
  150. package/dist/api/routes/delete-batch.d.ts.map +0 -1
  151. package/dist/api/routes/delete.d.ts +0 -26
  152. package/dist/api/routes/delete.d.ts.map +0 -1
  153. package/dist/api/routes/download.d.ts +0 -21
  154. package/dist/api/routes/download.d.ts.map +0 -1
  155. package/dist/api/routes/file.d.ts +0 -20
  156. package/dist/api/routes/file.d.ts.map +0 -1
  157. package/dist/api/routes/index.d.ts.map +0 -1
  158. package/dist/api/routes/multipart/abort.d.ts +0 -16
  159. package/dist/api/routes/multipart/abort.d.ts.map +0 -1
  160. package/dist/api/routes/multipart/complete.d.ts +0 -22
  161. package/dist/api/routes/multipart/complete.d.ts.map +0 -1
  162. package/dist/api/routes/multipart/init.d.ts +0 -22
  163. package/dist/api/routes/multipart/init.d.ts.map +0 -1
  164. package/dist/api/routes/multipart/list-parts.d.ts +0 -17
  165. package/dist/api/routes/multipart/list-parts.d.ts.map +0 -1
  166. package/dist/api/routes/multipart/part.d.ts +0 -20
  167. package/dist/api/routes/multipart/part.d.ts.map +0 -1
  168. package/dist/api/routes/upload.d.ts +0 -22
  169. package/dist/api/routes/upload.d.ts.map +0 -1
  170. package/dist/errors.d.ts +0 -23
  171. package/dist/errors.d.ts.map +0 -1
  172. package/dist/helpers/expires.d.ts +0 -21
  173. package/dist/helpers/expires.d.ts.map +0 -1
  174. package/dist/helpers/features.d.ts +0 -17
  175. package/dist/helpers/features.d.ts.map +0 -1
  176. package/dist/helpers/index.d.ts +0 -19
  177. package/dist/helpers/index.d.ts.map +0 -1
  178. package/dist/helpers/is-aws-not-found.d.ts +0 -5
  179. package/dist/helpers/is-aws-not-found.d.ts.map +0 -1
  180. package/dist/helpers/previous-key.d.ts +0 -5
  181. package/dist/helpers/previous-key.d.ts.map +0 -1
  182. package/dist/helpers/resolve-route.d.ts +0 -33
  183. package/dist/helpers/resolve-route.d.ts.map +0 -1
  184. package/dist/plugin/hook-registry.d.ts +0 -21
  185. package/dist/plugin/hook-registry.d.ts.map +0 -1
  186. package/dist/put.d.ts +0 -15
  187. package/dist/put.d.ts.map +0 -1
package/dist/api/index.js DELETED
@@ -1,1353 +0,0 @@
1
- import { createMiddleware, createEndpoint } from 'better-call';
2
- import * as z from 'zod';
3
- import { S3_API_ROUTES, isAPIError, APIError, S3_ERROR_CODES, confirmBodySchema, deleteQuerySchema, deleteBatchBodySchema, downloadQuerySchema, fileQuerySchema, multipartAbortBodySchema, multipartCompleteBodySchema, multipartInitBodySchema, multipartListPartsQuerySchema, multipartSignPartBodySchema, uploadBodySchema, buildContentDisposition, S3_MAX_EXPIRES_IN, S3_MAX_POST_OBJECT_BYTES, resolveStoredFileName, resolveInlineDisposition, fileNameFromKey, S3_DEFAULT_EXPIRES_IN, matchesFileTypes, normalizeObjectKey, sanitizeFileName } from '@dimah-s3/core';
4
- import { DeleteObjectCommand, GetObjectCommand, CreateMultipartUploadCommand, UploadPartCommand, PutObjectCommand, HeadObjectCommand, ListPartsCommand, AbortMultipartUploadCommand, CompleteMultipartUploadCommand } from '@aws-sdk/client-s3';
5
- import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
6
- import { createPresignedPost } from '@aws-sdk/s3-presigned-post';
7
-
8
- // src/api/create-s3-endpoint.ts
9
- var errors = {
10
- notFound: () => APIError.from("NOT_FOUND", S3_ERROR_CODES.NOT_FOUND),
11
- unauthorized: () => APIError.from("UNAUTHORIZED", S3_ERROR_CODES.UNAUTHORIZED),
12
- forbidden: () => APIError.from("FORBIDDEN", S3_ERROR_CODES.FORBIDDEN),
13
- conflict: () => APIError.from("CONFLICT", S3_ERROR_CODES.CONFLICT),
14
- internalError: () => APIError.from("INTERNAL_SERVER_ERROR", S3_ERROR_CODES.INTERNAL_ERROR),
15
- objectNotFound: () => APIError.from("NOT_FOUND", S3_ERROR_CODES.OBJECT_NOT_FOUND),
16
- featureDisabled: (feature) => APIError.from("NOT_FOUND", {
17
- code: S3_ERROR_CODES.FEATURE_DISABLED.code,
18
- message: S3_ERROR_CODES.FEATURE_DISABLED.message.replaceAll(
19
- "{feature}",
20
- feature
21
- ),
22
- params: { feature }
23
- }),
24
- invalidKey: () => APIError.from("BAD_REQUEST", S3_ERROR_CODES.INVALID_KEY),
25
- unknownRoute: (route) => APIError.from("NOT_FOUND", {
26
- code: S3_ERROR_CODES.UNKNOWN_ROUTE.code,
27
- message: S3_ERROR_CODES.UNKNOWN_ROUTE.message,
28
- params: { route }
29
- }),
30
- fileTypeNotAllowed: (fileName, contentType) => APIError.from("BAD_REQUEST", {
31
- code: S3_ERROR_CODES.FILE_TYPE_NOT_ALLOWED.code,
32
- message: S3_ERROR_CODES.FILE_TYPE_NOT_ALLOWED.message,
33
- params: {
34
- fileName,
35
- ...contentType ? { contentType } : {}
36
- }
37
- }),
38
- s3NetworkError: (code) => APIError.from("BAD_GATEWAY", {
39
- code: S3_ERROR_CODES.S3_NETWORK_ERROR.code,
40
- message: S3_ERROR_CODES.S3_NETWORK_ERROR.message.replaceAll(
41
- "{code}",
42
- code
43
- ),
44
- params: { code }
45
- }),
46
- multipartPartMissing: (partNumber) => APIError.from("BAD_REQUEST", {
47
- code: S3_ERROR_CODES.MULTIPART_PART_MISSING.code,
48
- message: S3_ERROR_CODES.MULTIPART_PART_MISSING.message.replaceAll(
49
- "{partNumber}",
50
- String(partNumber)
51
- ),
52
- params: { partNumber }
53
- }),
54
- payloadTooLarge: (message = S3_ERROR_CODES.PAYLOAD_TOO_LARGE.message) => APIError.from("PAYLOAD_TOO_LARGE", {
55
- ...S3_ERROR_CODES.PAYLOAD_TOO_LARGE,
56
- message
57
- }),
58
- quotaExceeded: (message = S3_ERROR_CODES.QUOTA_EXCEEDED.message) => APIError.from("PAYLOAD_TOO_LARGE", {
59
- ...S3_ERROR_CODES.QUOTA_EXCEEDED,
60
- message
61
- }),
62
- validationError: (message) => APIError.from("BAD_REQUEST", {
63
- code: S3_ERROR_CODES.VALIDATION_ERROR.code,
64
- message
65
- })
66
- };
67
- async function deleteObjectBestEffort(client, bucket, key) {
68
- try {
69
- await client.send(new DeleteObjectCommand({ Bucket: bucket, Key: key }));
70
- } catch {
71
- }
72
- }
73
- async function abortMultipartBestEffort(client, bucket, key, uploadId) {
74
- try {
75
- await client.send(
76
- new AbortMultipartUploadCommand({
77
- Bucket: bucket,
78
- Key: key,
79
- UploadId: uploadId
80
- })
81
- );
82
- } catch {
83
- }
84
- }
85
-
86
- // src/helpers/is-aws-not-found.ts
87
- function isAwsNotFound(err) {
88
- const e = err;
89
- return e?.name === "NoSuchKey" || e?.name === "NotFound" || e?.name === "NoSuchUpload" || e?.Code === "NoSuchKey" || e?.Code === "NotFound" || e?.Code === "NoSuchUpload" || e?.$metadata?.httpStatusCode === 404;
90
- }
91
- async function sendOrObjectNotFound(send) {
92
- try {
93
- return await send();
94
- } catch (err) {
95
- if (isAwsNotFound(err)) throw errors.objectNotFound();
96
- throw err;
97
- }
98
- }
99
- function normalizeExpiresIn(value, maxExpiresIn = S3_MAX_EXPIRES_IN) {
100
- const n = Number(value);
101
- const expires = Number.isFinite(n) && n > 0 ? Math.floor(n) : S3_DEFAULT_EXPIRES_IN;
102
- const max = Number.isFinite(maxExpiresIn) && maxExpiresIn > 0 ? Math.floor(maxExpiresIn) : S3_MAX_EXPIRES_IN;
103
- return Math.min(expires, max);
104
- }
105
- function clampDownloadExpiresIn(options) {
106
- const max = options.maxExpiresIn;
107
- if (options.resolvedExpiresIn != null) {
108
- return normalizeExpiresIn(options.resolvedExpiresIn, max);
109
- }
110
- const cap = normalizeExpiresIn(options.routeExpiresIn, max);
111
- if (options.requested == null) return cap;
112
- return Math.min(normalizeExpiresIn(options.requested, max), cap);
113
- }
114
-
115
- // src/helpers/logger.ts
116
- var defaultLogger = {
117
- error: (message, ...args) => {
118
- console.error("[dimah-s3]", message, ...args);
119
- },
120
- warn: (message, ...args) => {
121
- console.warn("[dimah-s3]", message, ...args);
122
- }
123
- };
124
- function resolveLogger(logger) {
125
- if (logger === false) return {};
126
- if (!logger) return defaultLogger;
127
- return logger;
128
- }
129
-
130
- // src/helpers/hooks.ts
131
- function mapGuardError(err) {
132
- if (isAPIError(err)) throw err;
133
- if (err instanceof Error && err.message.trim()) {
134
- throw new APIError("FORBIDDEN", {
135
- message: err.message,
136
- cause: err
137
- });
138
- }
139
- throw errors.forbidden();
140
- }
141
- async function runHook(hook, context) {
142
- if (!hook) return;
143
- try {
144
- await hook(context);
145
- } catch (err) {
146
- mapGuardError(err);
147
- }
148
- }
149
- async function runObjectHook(hook, context) {
150
- if (!hook) return;
151
- try {
152
- return await hook(context);
153
- } catch (err) {
154
- mapGuardError(err);
155
- }
156
- }
157
- async function runLifecycleHook(hook, context, config) {
158
- if (!hook) return;
159
- try {
160
- await hook(context);
161
- } catch (err) {
162
- if (isAPIError(err)) throw err;
163
- resolveLogger(config?.logger).error?.("lifecycle hook failed", err);
164
- config?.onError?.(err, { request: context.request });
165
- throw errors.internalError();
166
- }
167
- }
168
-
169
- // src/helpers/previous-key.ts
170
- var DIMAH_PREVIOUS_KEY_META = "dimah-previous-key";
171
- function stripPreviousKeyMeta(metadata) {
172
- if (!metadata) return {};
173
- const { [DIMAH_PREVIOUS_KEY_META]: _omit, ...rest } = metadata;
174
- return rest;
175
- }
176
- function previousKeyFromMetadata(metadata) {
177
- const value = metadata?.[DIMAH_PREVIOUS_KEY_META]?.trim();
178
- return value || void 0;
179
- }
180
-
181
- // src/helpers/object-s3.ts
182
- var MAX_S3_TAGS = 10;
183
- var MAX_TAG_KEY_CHARS = 128;
184
- var MAX_TAG_VALUE_CHARS = 256;
185
- function present(value) {
186
- const trimmed = value?.trim();
187
- return trimmed ? trimmed : void 0;
188
- }
189
- function assertTagEntry(key, value) {
190
- if (key.length === 0) {
191
- throw errors.validationError("S3 object tag keys cannot be empty");
192
- }
193
- if (key.length > MAX_TAG_KEY_CHARS) {
194
- throw errors.validationError(
195
- `S3 object tag keys cannot exceed ${MAX_TAG_KEY_CHARS} characters`
196
- );
197
- }
198
- if (value.length > MAX_TAG_VALUE_CHARS) {
199
- throw errors.validationError(
200
- `S3 object tag values cannot exceed ${MAX_TAG_VALUE_CHARS} characters`
201
- );
202
- }
203
- }
204
- function encodeObjectTagging(tagging) {
205
- const entries = Object.entries(tagging);
206
- if (entries.length > MAX_S3_TAGS) {
207
- throw errors.validationError(
208
- `S3 object tagging allows at most ${MAX_S3_TAGS} tags`
209
- );
210
- }
211
- return entries.map(([key, value]) => {
212
- assertTagEntry(key, value);
213
- return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
214
- }).join("&");
215
- }
216
- function taggingHeader(tagging) {
217
- if (!tagging || Object.keys(tagging).length === 0) return void 0;
218
- return encodeObjectTagging(tagging);
219
- }
220
- function normalizeObjectS3(info) {
221
- const storageClass = present(info?.storageClass);
222
- const cacheControl = present(info?.cacheControl);
223
- const tagging = info?.tagging && Object.keys(info.tagging).length > 0 ? info.tagging : void 0;
224
- if (tagging) encodeObjectTagging(tagging);
225
- return {
226
- ...storageClass ? { storageClass } : {},
227
- ...cacheControl ? { cacheControl } : {},
228
- ...tagging ? { tagging } : {}
229
- };
230
- }
231
- function objectCommandExtras(opts) {
232
- const tagging = taggingHeader(opts.tagging);
233
- return {
234
- ...opts.storageClass ? { StorageClass: opts.storageClass } : {},
235
- ...opts.cacheControl ? { CacheControl: opts.cacheControl } : {},
236
- ...tagging ? { Tagging: tagging } : {}
237
- };
238
- }
239
- function objectPutHeaders(opts) {
240
- const tagging = taggingHeader(opts.tagging);
241
- return {
242
- ...opts.cacheControl ? { "Cache-Control": opts.cacheControl } : {},
243
- ...opts.storageClass ? { "x-amz-storage-class": opts.storageClass } : {},
244
- ...tagging ? { "x-amz-tagging": tagging } : {}
245
- };
246
- }
247
-
248
- // src/helpers/resolve-target.ts
249
- function assertSafeObjectKey(key) {
250
- const normalized = normalizeObjectKey(key);
251
- if (!normalized) throw errors.invalidKey();
252
- return normalized;
253
- }
254
- function applyPrefix(prefix, key) {
255
- const p = assertSafeObjectKey(prefix);
256
- const k = assertSafeObjectKey(key);
257
- if (k.startsWith(`${p}/`)) return k;
258
- if (k === p) throw errors.invalidKey();
259
- return `${p}/${k}`;
260
- }
261
- function nestKeyUnderPrefix(keyPrefix, key) {
262
- const safe = assertSafeObjectKey(key);
263
- if (keyPrefix === false) return safe;
264
- return applyPrefix(keyPrefix, safe);
265
- }
266
- function assertStoredKey(key, keyPrefix) {
267
- const safe = assertSafeObjectKey(key);
268
- if (keyPrefix === false) return safe;
269
- const root = assertSafeObjectKey(keyPrefix);
270
- if (safe.startsWith(`${root}/`)) return safe;
271
- throw errors.invalidKey();
272
- }
273
- function objectKeyFileName(fileName) {
274
- const sanitized = sanitizeFileName(fileName);
275
- const leaf = sanitized.split("/").findLast((part) => part.length > 0);
276
- if (!leaf || leaf === "." || leaf === "..") return "file";
277
- return leaf;
278
- }
279
- function generateObjectKey(folder, fileName) {
280
- const leaf = `${crypto.randomUUID()}/${objectKeyFileName(fileName)}`;
281
- if (folder === false) return assertSafeObjectKey(leaf);
282
- return applyPrefix(folder, leaf);
283
- }
284
- function resolveAcl(info, route) {
285
- return info?.acl ?? route.upload.acl ?? "private";
286
- }
287
- async function resolveUploadTarget(route, context) {
288
- const bucket = route.bucket;
289
- const objectContext = {
290
- ...context,
291
- bucket,
292
- keyPrefix: route.keyPrefix
293
- };
294
- const info = await runObjectHook(route.upload.object, objectContext) ?? void 0;
295
- const key = info?.key ? nestKeyUnderPrefix(route.keyPrefix, info.key) : generateObjectKey(
296
- info?.folder != null && info.folder !== "" ? nestKeyUnderPrefix(route.keyPrefix, info.folder) : route.keyPrefix === false ? false : route.keyPrefix,
297
- context.file.name
298
- );
299
- const metadata = { ...info?.metadata };
300
- if (info?.previousKey) {
301
- metadata[DIMAH_PREVIOUS_KEY_META] = nestKeyUnderPrefix(
302
- route.keyPrefix,
303
- info.previousKey
304
- );
305
- }
306
- return {
307
- key,
308
- bucket,
309
- metadata: Object.keys(metadata).length > 0 ? metadata : info?.metadata,
310
- acl: resolveAcl(info, route),
311
- ...normalizeObjectS3(info)
312
- };
313
- }
314
- function resolveStoredTarget(route, key) {
315
- return {
316
- key: assertStoredKey(key, route.keyPrefix),
317
- bucket: route.bucket
318
- };
319
- }
320
-
321
- // src/helpers/features.ts
322
- function isEnabled(feature) {
323
- return feature.enabled;
324
- }
325
-
326
- // src/helpers/request.ts
327
- var SYNTHETIC_ORIGIN = "http://dimah-s3.local";
328
- function requestFromHeaders(headers) {
329
- return new Request(SYNTHETIC_ORIGIN, { headers });
330
- }
331
- function assertWithinMaxFileSize(maxFileSize, size) {
332
- if (typeof maxFileSize === "number" && size > maxFileSize) {
333
- throw errors.payloadTooLarge();
334
- }
335
- }
336
- function assertDeclaredConstraints(constraints, input) {
337
- if (constraints?.fileTypes?.length && !matchesFileTypes(input.fileName, input.contentType, constraints.fileTypes)) {
338
- throw errors.fileTypeNotAllowed(input.fileName, input.contentType);
339
- }
340
- assertWithinMaxFileSize(constraints?.maxFileSize, input.fileSize);
341
- }
342
- function assertVerifiedConstraints(constraints, input) {
343
- assertWithinMaxFileSize(constraints?.maxFileSize, input.contentLength);
344
- const name = input.fileName ?? "";
345
- if (constraints?.fileTypes?.length && !matchesFileTypes(name, input.contentType, constraints.fileTypes)) {
346
- throw errors.fileTypeNotAllowed(name || "unknown", input.contentType);
347
- }
348
- }
349
-
350
- // src/helpers/resolve-route.ts
351
- function getResolvedRoute(config, name) {
352
- const route = config.routes[name];
353
- if (!route) {
354
- throw errors.unknownRoute(name);
355
- }
356
- return route;
357
- }
358
- function featureIsEnabled(route, feature) {
359
- if (feature === "multipart") return route.upload.multipart.enabled;
360
- return route[feature].enabled;
361
- }
362
- function assertFeatureEnabled(route, feature) {
363
- if (!featureIsEnabled(route, feature)) {
364
- throw errors.featureDisabled(feature);
365
- }
366
- }
367
- async function openRoute(config, name, request, feature) {
368
- const route = getResolvedRoute(config, name);
369
- assertFeatureEnabled(route, feature);
370
- await runHook(route.guard, { request, route: route.name });
371
- return route;
372
- }
373
- function storedObjectContext(request, route, key) {
374
- return { request, route: route.name, key, bucket: route.bucket };
375
- }
376
- async function openUploadTarget(config, input, request, feature) {
377
- const route = await openRoute(config, input.route, request, feature);
378
- const fileSize = Math.floor(input.fileSize);
379
- const fileName = input.fileName;
380
- assertDeclaredConstraints(route.upload, {
381
- fileName,
382
- fileSize,
383
- contentType: input.contentType
384
- });
385
- const target = await resolveUploadTarget(route, {
386
- request,
387
- route: route.name,
388
- file: {
389
- name: fileName,
390
- size: fileSize,
391
- type: input.contentType
392
- },
393
- clientMetadata: input.metadata
394
- });
395
- return {
396
- route,
397
- ...target,
398
- stored: storedObjectContext(request, route, target.key)
399
- };
400
- }
401
- async function openStoredTarget(config, input, request, feature) {
402
- const route = await openRoute(config, input.route, request, feature);
403
- const target = resolveStoredTarget(route, input.key);
404
- return {
405
- route,
406
- ...target,
407
- stored: storedObjectContext(request, route, target.key)
408
- };
409
- }
410
- async function objectExists(client, bucket, key) {
411
- try {
412
- await client.send(new HeadObjectCommand({ Bucket: bucket, Key: key }));
413
- return true;
414
- } catch (err) {
415
- if (isAwsNotFound(err)) return false;
416
- throw err;
417
- }
418
- }
419
- async function headObjectOrNotFound(client, bucket, key) {
420
- return sendOrObjectNotFound(
421
- () => client.send(new HeadObjectCommand({ Bucket: bucket, Key: key }))
422
- );
423
- }
424
- async function headObjectAfterMultipartComplete(client, bucket, key) {
425
- const send = () => sendOrObjectNotFound(
426
- () => client.send(new HeadObjectCommand({ Bucket: bucket, Key: key }))
427
- );
428
- let head = await send();
429
- for (let attempt = 0; attempt < 4 && typeof head.ContentLength !== "number"; attempt++) {
430
- await new Promise((r) => setTimeout(r, 250 * 2 ** attempt));
431
- head = await send();
432
- }
433
- return head;
434
- }
435
- function requireContentLength(head) {
436
- if (typeof head.ContentLength !== "number") {
437
- throw errors.internalError();
438
- }
439
- return head.ContentLength;
440
- }
441
- async function listAllParts(client, input) {
442
- const parts = [];
443
- let partNumberMarker;
444
- let isTruncated = true;
445
- while (isTruncated) {
446
- const response = await sendOrObjectNotFound(
447
- () => client.send(
448
- new ListPartsCommand({
449
- Bucket: input.bucket,
450
- Key: input.key,
451
- UploadId: input.uploadId,
452
- ...partNumberMarker ? { PartNumberMarker: partNumberMarker } : {}
453
- })
454
- )
455
- );
456
- parts.push(...response.Parts ?? []);
457
- isTruncated = response.IsTruncated === true;
458
- partNumberMarker = isTruncated ? response.NextPartNumberMarker : void 0;
459
- }
460
- return parts;
461
- }
462
- function listedPartsByteSize(parts, excludePartNumber) {
463
- let total = 0;
464
- for (const part of parts) {
465
- if (excludePartNumber !== void 0 && part.PartNumber === excludePartNumber) {
466
- continue;
467
- }
468
- total += part.Size ?? 0;
469
- }
470
- return total;
471
- }
472
- function applyInlineTypes(inlineTypes, input) {
473
- if (!inlineTypes) return { disposition: input.disposition };
474
- return resolveInlineDisposition({
475
- contentType: input.contentType,
476
- fileName: input.fileName ?? fileNameFromKey(input.key),
477
- allow: inlineTypes,
478
- requested: input.disposition
479
- });
480
- }
481
- async function finalizeConfirmedObject(client, bucket, key, input) {
482
- const { config, route, stored, head, uploadId, acl } = input;
483
- const rawMetadata = head.Metadata ?? {};
484
- const fileName = resolveStoredFileName(head.ContentDisposition, key);
485
- let context;
486
- try {
487
- const contentLength = requireContentLength(head);
488
- assertVerifiedConstraints(route.upload, {
489
- fileName,
490
- contentType: head.ContentType,
491
- contentLength
492
- });
493
- const metadata = stripPreviousKeyMeta(rawMetadata);
494
- context = {
495
- ...stored,
496
- contentType: head.ContentType,
497
- contentLength,
498
- eTag: head.ETag?.replaceAll('"', ""),
499
- metadata,
500
- acl,
501
- fileName,
502
- versionId: head.VersionId,
503
- lastModified: head.LastModified?.toISOString(),
504
- uploadId
505
- };
506
- await runLifecycleHook(route.upload.onConfirmed, context, config);
507
- } catch (err) {
508
- await deleteObjectBestEffort(client, bucket, key);
509
- throw err;
510
- }
511
- const previousKey = previousKeyFromMetadata(rawMetadata);
512
- if (previousKey && previousKey !== key) {
513
- try {
514
- const safe = assertStoredKey(previousKey, route.keyPrefix);
515
- await deleteObjectBestEffort(client, bucket, safe);
516
- } catch {
517
- }
518
- }
519
- return {
520
- key,
521
- bucket,
522
- contentType: context.contentType,
523
- contentLength: context.contentLength,
524
- eTag: context.eTag,
525
- metadata: context.metadata ?? {},
526
- acl,
527
- fileName,
528
- versionId: context.versionId,
529
- lastModified: context.lastModified
530
- };
531
- }
532
-
533
- // src/api/create-s3-middleware.ts
534
- var s3ContextMiddleware = createMiddleware(async (ctx) => {
535
- const injected = ctx.context;
536
- if (!injected?.config) {
537
- throw new Error(
538
- "createS3Endpoint requires dimahS3 router context. Call endpoints through dimahS3().api or the HTTP handler."
539
- );
540
- }
541
- const request = ctx.request ?? injected.request ?? requestFromHeaders(ctx.headers);
542
- await runHook(injected.config.guard, { request });
543
- return {
544
- config: injected.config,
545
- request
546
- };
547
- });
548
- var createS3Middleware = createMiddleware.create({
549
- use: [s3ContextMiddleware]
550
- });
551
-
552
- // src/api/create-s3-endpoint.ts
553
- var createEndpointWithContext = createEndpoint.create({
554
- use: [s3ContextMiddleware]
555
- });
556
- function compileIfZod(schema) {
557
- if (schema !== null && typeof schema === "object" && "_zod" in schema) {
558
- return z.compile(schema);
559
- }
560
- return schema;
561
- }
562
- function withS3Validation(options) {
563
- return {
564
- ...options,
565
- ...options.body !== void 0 ? { body: compileIfZod(options.body) } : {},
566
- ...options.query !== void 0 ? { query: compileIfZod(options.query) } : {},
567
- // better-call reads the body before hooks. Clone first so
568
- // `request.clone().json()` in guard / resolveScope still works.
569
- ...options.body !== void 0 && options.cloneRequest === void 0 ? { cloneRequest: true } : {},
570
- onValidationError: options.onValidationError ?? (({ message }) => {
571
- throw errors.validationError(message);
572
- })
573
- };
574
- }
575
- var createS3Endpoint = ((pathOrOptions, optionsOrHandler, maybeHandler) => {
576
- if (typeof pathOrOptions === "string") {
577
- return createEndpointWithContext(
578
- pathOrOptions,
579
- withS3Validation(optionsOrHandler),
580
- maybeHandler
581
- );
582
- }
583
- return createEndpointWithContext(
584
- withS3Validation(pathOrOptions),
585
- optionsOrHandler
586
- );
587
- });
588
- async function handleConfirm(config, input, request) {
589
- const { route, key, bucket, stored } = await openStoredTarget(
590
- config,
591
- input,
592
- request,
593
- "upload"
594
- );
595
- await runHook(route.upload.confirmGuard, {
596
- ...stored,
597
- replace: route.upload.replace
598
- });
599
- const head = await headObjectOrNotFound(route.client, bucket, key);
600
- return finalizeConfirmedObject(route.client, bucket, key, {
601
- config,
602
- route,
603
- stored,
604
- head,
605
- acl: route.upload.acl
606
- });
607
- }
608
- var confirm = createS3Endpoint(
609
- S3_API_ROUTES.uploadConfirm,
610
- { method: "POST", body: confirmBodySchema },
611
- async (ctx) => {
612
- return handleConfirm(ctx.context.config, ctx.body, ctx.context.request);
613
- }
614
- );
615
- async function deleteStoredObject(config, input, request) {
616
- const { route, key, bucket, stored } = await openStoredTarget(
617
- config,
618
- input,
619
- request,
620
- "delete"
621
- );
622
- await runHook(route.delete.guard, stored);
623
- const existed = await objectExists(route.client, bucket, key);
624
- if (existed) {
625
- await route.client.send(
626
- new DeleteObjectCommand({ Bucket: bucket, Key: key })
627
- );
628
- }
629
- await runLifecycleHook(
630
- route.delete.onDeleted,
631
- { ...stored, existed },
632
- config
633
- );
634
- return { success: true, bucket, key, existed };
635
- }
636
- var deleteObject = createS3Endpoint(
637
- S3_API_ROUTES.delete,
638
- { method: "DELETE", query: deleteQuerySchema },
639
- async (ctx) => {
640
- return deleteStoredObject(
641
- ctx.context.config,
642
- ctx.query,
643
- ctx.context.request
644
- );
645
- }
646
- );
647
- var deleteBatch = createS3Endpoint(
648
- S3_API_ROUTES.deleteBatch,
649
- { method: "POST", body: deleteBatchBodySchema },
650
- async (ctx) => {
651
- const config = ctx.context.config;
652
- const request = ctx.context.request;
653
- const results = [];
654
- for (const key of ctx.body.keys) {
655
- try {
656
- const { existed } = await deleteStoredObject(
657
- config,
658
- { route: ctx.body.route, key },
659
- request
660
- );
661
- results.push({ key, success: true, existed });
662
- } catch (err) {
663
- results.push({
664
- key,
665
- success: false,
666
- error: isAPIError(err) ? { code: err.code ?? "INTERNAL_ERROR", message: err.message } : { code: "INTERNAL_ERROR", message: "Internal server error" }
667
- });
668
- }
669
- }
670
- return { results };
671
- }
672
- );
673
- function fileUrl(request, basePath, query) {
674
- const url = new URL(request.url);
675
- const prefix = basePath.endsWith("/") ? basePath.slice(0, -1) : basePath;
676
- url.pathname = `${prefix}${S3_API_ROUTES.file}`;
677
- url.search = "";
678
- url.searchParams.set("route", query.route);
679
- url.searchParams.set("key", query.key);
680
- if (query.fileName) url.searchParams.set("fileName", query.fileName);
681
- if (query.disposition) url.searchParams.set("disposition", query.disposition);
682
- return url.toString();
683
- }
684
- async function handleDownload(config, input, request) {
685
- const { route, key, bucket, stored } = await openStoredTarget(
686
- config,
687
- input,
688
- request,
689
- "download"
690
- );
691
- const resolved = await route.download.resolve?.({
692
- ...stored,
693
- fileName: input.fileName,
694
- disposition: input.disposition ?? route.download.disposition,
695
- expiresIn: input.expiresIn
696
- });
697
- const fileName = resolved?.fileName ?? input.fileName;
698
- const disposition = resolved?.disposition ?? input.disposition ?? route.download.disposition ?? "attachment";
699
- const mode = route.download.mode ?? "presign";
700
- const expiresIn = mode === "proxy" ? 0 : clampDownloadExpiresIn({
701
- requested: input.expiresIn,
702
- routeExpiresIn: route.download.expiresIn,
703
- resolvedExpiresIn: resolved?.expiresIn,
704
- maxExpiresIn: config.maxExpiresIn
705
- });
706
- await runHook(route.download.guard, {
707
- ...stored,
708
- fileName,
709
- disposition,
710
- expiresIn
711
- });
712
- const head = await headObjectOrNotFound(route.client, bucket, key);
713
- const signed = applyInlineTypes(route.download.inlineTypes, {
714
- key,
715
- fileName,
716
- disposition,
717
- contentType: head.ContentType
718
- });
719
- const contentDisposition = fileName ? buildContentDisposition(fileName, signed.disposition) : signed.disposition;
720
- const url = mode === "proxy" ? fileUrl(request, config.basePath ?? "/api/s3", {
721
- route: input.route,
722
- key,
723
- fileName,
724
- disposition: signed.disposition
725
- }) : await getSignedUrl(
726
- route.client,
727
- new GetObjectCommand({
728
- Bucket: bucket,
729
- Key: key,
730
- ResponseContentDisposition: contentDisposition,
731
- ResponseContentType: signed.contentType
732
- }),
733
- { expiresIn }
734
- );
735
- await runLifecycleHook(
736
- route.download.onPresigned,
737
- {
738
- ...stored,
739
- fileName,
740
- url,
741
- expiresIn
742
- },
743
- config
744
- );
745
- return {
746
- bucket,
747
- key,
748
- url,
749
- expiresIn,
750
- mode,
751
- disposition: signed.disposition
752
- };
753
- }
754
- var download = createS3Endpoint(
755
- S3_API_ROUTES.download,
756
- { method: "GET", query: downloadQuerySchema },
757
- async (ctx) => {
758
- return handleDownload(ctx.context.config, ctx.query, ctx.context.request);
759
- }
760
- );
761
- function catalogUpload(upload2) {
762
- if (!isEnabled(upload2)) return { enabled: false };
763
- return {
764
- enabled: true,
765
- fileTypes: upload2.fileTypes,
766
- maxFileSize: upload2.maxFileSize,
767
- multipart: isEnabled(upload2.multipart),
768
- ...upload2.checksum ? { checksum: true } : {},
769
- ...upload2.replace ? { replace: upload2.replace } : {}
770
- };
771
- }
772
- function catalogDownload(download2, maxExpiresIn) {
773
- if (!isEnabled(download2)) return { enabled: false };
774
- return {
775
- enabled: true,
776
- expiresIn: normalizeExpiresIn(download2.expiresIn, maxExpiresIn),
777
- ...download2.disposition ? { disposition: download2.disposition } : {},
778
- ...download2.inlineTypes ? { inlineTypes: [...download2.inlineTypes] } : {},
779
- ...download2.mode ? { mode: download2.mode } : {}
780
- };
781
- }
782
- function buildRouteCatalog(config) {
783
- const routes = {};
784
- for (const [name, route] of Object.entries(config.routes)) {
785
- routes[name] = {
786
- upload: catalogUpload(route.upload),
787
- download: catalogDownload(route.download, config.maxExpiresIn),
788
- delete: isEnabled(route.delete) ? { enabled: true } : { enabled: false }
789
- };
790
- }
791
- return { routes };
792
- }
793
- var catalog = createS3Endpoint(
794
- S3_API_ROUTES.catalog,
795
- { method: "GET" },
796
- async (ctx) => {
797
- return buildRouteCatalog(ctx.context.config);
798
- }
799
- );
800
- async function handleFile(config, input, request) {
801
- const { route, key, bucket, stored } = await openStoredTarget(
802
- config,
803
- input,
804
- request,
805
- "download"
806
- );
807
- const resolved = await route.download.resolve?.({
808
- ...stored,
809
- fileName: input.fileName,
810
- disposition: input.disposition ?? route.download.disposition
811
- });
812
- const fileName = resolved?.fileName ?? input.fileName;
813
- const disposition = resolved?.disposition ?? input.disposition ?? route.download.disposition ?? "attachment";
814
- await runHook(route.download.guard, {
815
- ...stored,
816
- fileName,
817
- disposition
818
- });
819
- const head = await headObjectOrNotFound(route.client, bucket, key);
820
- const signed = applyInlineTypes(route.download.inlineTypes, {
821
- key,
822
- fileName,
823
- disposition,
824
- contentType: head.ContentType
825
- });
826
- const contentDisposition = fileName ? buildContentDisposition(fileName, signed.disposition) : signed.disposition;
827
- const result = await sendOrObjectNotFound(
828
- () => route.client.send(
829
- new GetObjectCommand({
830
- Bucket: bucket,
831
- Key: key,
832
- ResponseContentDisposition: contentDisposition
833
- })
834
- )
835
- );
836
- const body = result.Body;
837
- if (!body) throw errors.objectNotFound();
838
- const stream = "transformToWebStream" in body && typeof body.transformToWebStream === "function" ? body.transformToWebStream() : body;
839
- const headers = new Headers();
840
- headers.set(
841
- "Content-Type",
842
- signed.contentType ?? result.ContentType ?? "application/octet-stream"
843
- );
844
- headers.set("Content-Disposition", contentDisposition);
845
- headers.set("X-Content-Type-Options", "nosniff");
846
- if (typeof result.ContentLength === "number") {
847
- headers.set("Content-Length", String(result.ContentLength));
848
- }
849
- return new Response(stream, { headers });
850
- }
851
- var file = createS3Endpoint(
852
- S3_API_ROUTES.file,
853
- { method: "GET", query: fileQuerySchema },
854
- async (ctx) => {
855
- return handleFile(ctx.context.config, ctx.query, ctx.context.request);
856
- }
857
- );
858
- async function handleAbort(config, input, request) {
859
- const { route, key, bucket, stored } = await openStoredTarget(
860
- config,
861
- input,
862
- request,
863
- "multipart"
864
- );
865
- const uploadId = input.uploadId;
866
- await runHook(route.upload.multipart.guard, {
867
- ...stored,
868
- uploadId,
869
- action: "abort"
870
- });
871
- await sendOrObjectNotFound(
872
- () => route.client.send(
873
- new AbortMultipartUploadCommand({
874
- Bucket: bucket,
875
- Key: key,
876
- UploadId: uploadId
877
- })
878
- )
879
- );
880
- await runLifecycleHook(
881
- route.upload.multipart.onAbort,
882
- {
883
- ...stored,
884
- uploadId
885
- },
886
- config
887
- );
888
- return { bucket, key, uploadId, aborted: true };
889
- }
890
- var multipartAbort = createS3Endpoint(
891
- S3_API_ROUTES.multipartAbort,
892
- { method: "POST", body: multipartAbortBodySchema },
893
- async (ctx) => {
894
- return handleAbort(ctx.context.config, ctx.body, ctx.context.request);
895
- }
896
- );
897
- async function handleComplete(config, input, request) {
898
- const { route, key, bucket, stored } = await openStoredTarget(
899
- config,
900
- input,
901
- request,
902
- "multipart"
903
- );
904
- const uploadId = input.uploadId;
905
- const parts = [
906
- ...new Set(input.parts.map(({ partNumber }) => partNumber))
907
- ].toSorted((a, b) => a - b);
908
- const partRefs = parts.map((partNumber) => ({ partNumber }));
909
- await runHook(route.upload.multipart.guard, {
910
- ...stored,
911
- uploadId,
912
- action: "complete"
913
- });
914
- await runHook(route.upload.confirmGuard, {
915
- ...stored,
916
- uploadId,
917
- parts: partRefs,
918
- replace: route.upload.replace
919
- });
920
- const listedParts = await listAllParts(route.client, {
921
- bucket,
922
- key,
923
- uploadId
924
- });
925
- let assembledBytes = 0;
926
- const completeParts = parts.map((partNumber) => {
927
- const found = listedParts.find((p) => p.PartNumber === partNumber);
928
- if (!found?.ETag) {
929
- throw errors.multipartPartMissing(partNumber);
930
- }
931
- assembledBytes += found.Size ?? 0;
932
- return { PartNumber: partNumber, ETag: found.ETag };
933
- });
934
- try {
935
- assertWithinMaxFileSize(route.upload.maxFileSize, assembledBytes);
936
- } catch (err) {
937
- await abortMultipartBestEffort(route.client, bucket, key, uploadId);
938
- throw err;
939
- }
940
- const completeResult = await sendOrObjectNotFound(
941
- () => route.client.send(
942
- new CompleteMultipartUploadCommand({
943
- Bucket: bucket,
944
- Key: key,
945
- UploadId: uploadId,
946
- MultipartUpload: { Parts: completeParts }
947
- })
948
- )
949
- );
950
- const head = await headObjectAfterMultipartComplete(
951
- route.client,
952
- bucket,
953
- key
954
- );
955
- const confirmed = await finalizeConfirmedObject(route.client, bucket, key, {
956
- config,
957
- route,
958
- stored,
959
- head: {
960
- ...head,
961
- ETag: head.ETag ?? completeResult.ETag
962
- },
963
- uploadId,
964
- acl: route.upload.acl
965
- });
966
- return { ...confirmed, uploadId };
967
- }
968
- var multipartComplete = createS3Endpoint(
969
- S3_API_ROUTES.multipartComplete,
970
- { method: "POST", body: multipartCompleteBodySchema },
971
- async (ctx) => {
972
- return handleComplete(ctx.context.config, ctx.body, ctx.context.request);
973
- }
974
- );
975
- async function handleMultipartInit(config, input, request) {
976
- const fileSize = Math.floor(input.fileSize);
977
- const fileName = input.fileName;
978
- const {
979
- route,
980
- key,
981
- bucket,
982
- metadata,
983
- acl,
984
- storageClass,
985
- cacheControl,
986
- tagging,
987
- stored
988
- } = await openUploadTarget(
989
- config,
990
- {
991
- route: input.route,
992
- fileName,
993
- fileSize,
994
- contentType: input.contentType,
995
- metadata: input.metadata
996
- },
997
- request,
998
- "multipart"
999
- );
1000
- const objectS3 = normalizeObjectS3({ storageClass, cacheControl, tagging });
1001
- await runHook(route.upload.guard, {
1002
- ...stored,
1003
- file: {
1004
- name: fileName,
1005
- size: fileSize,
1006
- type: input.contentType
1007
- },
1008
- metadata,
1009
- clientMetadata: input.metadata,
1010
- acl,
1011
- ...objectS3,
1012
- replace: route.upload.replace
1013
- });
1014
- const { UploadId } = await route.client.send(
1015
- new CreateMultipartUploadCommand({
1016
- Bucket: bucket,
1017
- Key: key,
1018
- ContentType: input.contentType,
1019
- ContentDisposition: buildContentDisposition(fileName),
1020
- Metadata: metadata,
1021
- ACL: acl,
1022
- ...objectCommandExtras(objectS3)
1023
- })
1024
- );
1025
- if (!UploadId) {
1026
- throw errors.internalError();
1027
- }
1028
- try {
1029
- await runLifecycleHook(
1030
- route.upload.multipart.onInit,
1031
- {
1032
- ...stored,
1033
- uploadId: UploadId,
1034
- file: {
1035
- name: fileName,
1036
- size: fileSize,
1037
- type: input.contentType
1038
- },
1039
- metadata,
1040
- clientMetadata: input.metadata,
1041
- acl,
1042
- ...objectS3,
1043
- replace: route.upload.replace
1044
- },
1045
- config
1046
- );
1047
- } catch (err) {
1048
- await abortMultipartBestEffort(route.client, bucket, key, UploadId);
1049
- try {
1050
- await runLifecycleHook(
1051
- route.upload.multipart.onAbort,
1052
- {
1053
- ...stored,
1054
- uploadId: UploadId
1055
- },
1056
- config
1057
- );
1058
- } catch {
1059
- }
1060
- throw err;
1061
- }
1062
- return { bucket, key, uploadId: UploadId };
1063
- }
1064
- var multipartInit = createS3Endpoint(
1065
- S3_API_ROUTES.multipartInit,
1066
- { method: "POST", body: multipartInitBodySchema },
1067
- async (ctx) => {
1068
- const result = await handleMultipartInit(
1069
- ctx.context.config,
1070
- ctx.body,
1071
- ctx.context.request
1072
- );
1073
- ctx.setStatus(201);
1074
- return result;
1075
- }
1076
- );
1077
- async function handleListParts(config, input, request) {
1078
- const { route, key, bucket, stored } = await openStoredTarget(
1079
- config,
1080
- input,
1081
- request,
1082
- "multipart"
1083
- );
1084
- const uploadId = input.uploadId;
1085
- await runHook(route.upload.multipart.guard, {
1086
- ...stored,
1087
- uploadId,
1088
- action: "list"
1089
- });
1090
- const listed = await listAllParts(route.client, { bucket, key, uploadId });
1091
- const parts = listed.flatMap((p) => {
1092
- if (p.PartNumber == null || p.PartNumber < 1) return [];
1093
- return [
1094
- {
1095
- partNumber: p.PartNumber,
1096
- size: p.Size ?? 0,
1097
- eTag: (p.ETag ?? "").replaceAll('"', "")
1098
- }
1099
- ];
1100
- });
1101
- await runLifecycleHook(
1102
- route.upload.multipart.onList,
1103
- {
1104
- ...stored,
1105
- uploadId,
1106
- parts
1107
- },
1108
- config
1109
- );
1110
- return { parts };
1111
- }
1112
- var multipartListParts = createS3Endpoint(
1113
- S3_API_ROUTES.multipartListParts,
1114
- { method: "GET", query: multipartListPartsQuerySchema },
1115
- async (ctx) => {
1116
- return handleListParts(ctx.context.config, ctx.query, ctx.context.request);
1117
- }
1118
- );
1119
- async function handleSignPart(config, input, request) {
1120
- const { route, key, bucket, stored } = await openStoredTarget(
1121
- config,
1122
- input,
1123
- request,
1124
- "multipart"
1125
- );
1126
- const uploadId = input.uploadId;
1127
- const partNumber = input.partNumber;
1128
- const expiresIn = normalizeExpiresIn(
1129
- route.upload.expiresIn,
1130
- config.maxExpiresIn
1131
- );
1132
- const partSize = Math.floor(input.partSize);
1133
- await runHook(route.upload.multipart.guard, {
1134
- ...stored,
1135
- uploadId,
1136
- action: "part",
1137
- partNumber,
1138
- partSize
1139
- });
1140
- const maxFileSize = route.upload.maxFileSize;
1141
- assertWithinMaxFileSize(maxFileSize, partSize);
1142
- if (typeof maxFileSize === "number") {
1143
- const listed = await listAllParts(route.client, { bucket, key, uploadId });
1144
- assertWithinMaxFileSize(
1145
- maxFileSize,
1146
- listedPartsByteSize(listed, partNumber) + partSize
1147
- );
1148
- }
1149
- const url = await getSignedUrl(
1150
- route.client,
1151
- new UploadPartCommand({
1152
- Bucket: bucket,
1153
- Key: key,
1154
- UploadId: uploadId,
1155
- PartNumber: partNumber,
1156
- ContentLength: partSize
1157
- }),
1158
- {
1159
- expiresIn,
1160
- signableHeaders: /* @__PURE__ */ new Set(["content-length"])
1161
- }
1162
- );
1163
- return {
1164
- url,
1165
- partNumber,
1166
- uploadId,
1167
- bucket,
1168
- expiresIn,
1169
- partSize
1170
- };
1171
- }
1172
- var multipartPart = createS3Endpoint(
1173
- S3_API_ROUTES.multipartPart,
1174
- { method: "POST", body: multipartSignPartBodySchema },
1175
- async (ctx) => {
1176
- return handleSignPart(ctx.context.config, ctx.body, ctx.context.request);
1177
- }
1178
- );
1179
- function objectUserMetadata(metadata) {
1180
- if (!metadata) return {};
1181
- const fields = {};
1182
- for (const [k, v] of Object.entries(metadata)) {
1183
- fields[`x-amz-meta-${k}`] = v;
1184
- }
1185
- return fields;
1186
- }
1187
- async function handleUpload(config, input, request) {
1188
- const fileSize = Math.floor(input.fileSize);
1189
- const fileName = input.fileName;
1190
- const {
1191
- route,
1192
- key,
1193
- bucket,
1194
- metadata,
1195
- acl,
1196
- storageClass,
1197
- cacheControl,
1198
- tagging,
1199
- stored
1200
- } = await openUploadTarget(
1201
- config,
1202
- {
1203
- route: input.route,
1204
- fileName,
1205
- fileSize,
1206
- contentType: input.contentType,
1207
- metadata: input.metadata
1208
- },
1209
- request,
1210
- "upload"
1211
- );
1212
- const objectS3 = normalizeObjectS3({ storageClass, cacheControl, tagging });
1213
- const method = route.upload.method ?? "POST";
1214
- if (route.upload.checksum && !input.checksum) {
1215
- throw errors.validationError("Checksum is required for this route");
1216
- }
1217
- if (method === "POST" && fileSize > S3_MAX_POST_OBJECT_BYTES) {
1218
- throw errors.payloadTooLarge(
1219
- `POST uploads cannot exceed ${S3_MAX_POST_OBJECT_BYTES} bytes. Enable upload.multipart or set upload.method to "PUT".`
1220
- );
1221
- }
1222
- const expiresIn = normalizeExpiresIn(
1223
- route.upload.expiresIn,
1224
- config.maxExpiresIn
1225
- );
1226
- const contentType = input.contentType ?? "application/octet-stream";
1227
- const hookCtx = {
1228
- ...stored,
1229
- file: {
1230
- name: fileName,
1231
- size: fileSize,
1232
- type: input.contentType
1233
- },
1234
- metadata,
1235
- clientMetadata: input.metadata,
1236
- acl,
1237
- ...objectS3,
1238
- replace: route.upload.replace
1239
- };
1240
- await runHook(route.upload.guard, hookCtx);
1241
- if (method === "PUT") {
1242
- const putHeaders = {
1243
- "Content-Type": contentType,
1244
- ...objectUserMetadata(metadata),
1245
- "Content-Disposition": buildContentDisposition(fileName),
1246
- ...objectPutHeaders(objectS3),
1247
- ...input.checksum ? { "x-amz-checksum-sha256": input.checksum } : {}
1248
- };
1249
- const url2 = await getSignedUrl(
1250
- route.client,
1251
- new PutObjectCommand({
1252
- Bucket: bucket,
1253
- Key: key,
1254
- ContentType: contentType,
1255
- ACL: acl,
1256
- Metadata: metadata,
1257
- ContentDisposition: buildContentDisposition(fileName),
1258
- ContentLength: fileSize,
1259
- ...objectCommandExtras(objectS3),
1260
- ...input.checksum ? { ChecksumSHA256: input.checksum, ChecksumAlgorithm: "SHA256" } : {}
1261
- }),
1262
- {
1263
- expiresIn,
1264
- signableHeaders: /* @__PURE__ */ new Set([
1265
- "content-length",
1266
- ...input.checksum ? ["x-amz-checksum-sha256"] : []
1267
- ])
1268
- }
1269
- );
1270
- await runLifecycleHook(
1271
- route.upload.onPresigned,
1272
- {
1273
- ...hookCtx,
1274
- url: url2,
1275
- expiresIn
1276
- },
1277
- config
1278
- );
1279
- return {
1280
- bucket,
1281
- key,
1282
- url: url2,
1283
- headers: putHeaders,
1284
- expiresIn,
1285
- method: "PUT"
1286
- };
1287
- }
1288
- const fields = {
1289
- acl,
1290
- "Content-Type": contentType,
1291
- "Content-Disposition": buildContentDisposition(fileName),
1292
- ...objectUserMetadata(metadata),
1293
- ...objectPutHeaders(objectS3),
1294
- ...input.checksum ? { "x-amz-checksum-sha256": input.checksum } : {}
1295
- };
1296
- const { url, fields: signedFields } = await createPresignedPost(
1297
- route.client,
1298
- {
1299
- Bucket: bucket,
1300
- Key: key,
1301
- Conditions: [["content-length-range", fileSize, fileSize]],
1302
- Fields: fields,
1303
- Expires: expiresIn
1304
- }
1305
- );
1306
- await runLifecycleHook(
1307
- route.upload.onPresigned,
1308
- {
1309
- ...hookCtx,
1310
- url,
1311
- expiresIn
1312
- },
1313
- config
1314
- );
1315
- return {
1316
- bucket,
1317
- key,
1318
- url,
1319
- fields: signedFields,
1320
- expiresIn,
1321
- method: "POST"
1322
- };
1323
- }
1324
- var upload = createS3Endpoint(
1325
- S3_API_ROUTES.upload,
1326
- { method: "POST", body: uploadBodySchema },
1327
- async (ctx) => {
1328
- return handleUpload(ctx.context.config, ctx.body, ctx.context.request);
1329
- }
1330
- );
1331
-
1332
- // src/api/routes/index.ts
1333
- var coreEndpoints = {
1334
- upload,
1335
- confirm,
1336
- download,
1337
- catalog,
1338
- file,
1339
- delete: deleteObject,
1340
- deleteBatch,
1341
- multipartInit,
1342
- multipartPart,
1343
- multipartListParts,
1344
- multipartComplete,
1345
- multipartAbort
1346
- };
1347
- var CORE_ENDPOINT_NAMES = Object.keys(
1348
- coreEndpoints
1349
- );
1350
-
1351
- export { CORE_ENDPOINT_NAMES, createS3Endpoint, createS3Middleware };
1352
- //# sourceMappingURL=index.js.map
1353
- //# sourceMappingURL=index.js.map