@edgestore/server 1.0.0-next.4 → 1.0.0-next.5

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 (114) hide show
  1. package/README.md +2 -8
  2. package/agent-docs/README.md +1 -1
  3. package/agent-docs/astro.md +2 -8
  4. package/agent-docs/backend-client.md +16 -26
  5. package/agent-docs/configuration.md +41 -10
  6. package/agent-docs/express.md +2 -8
  7. package/agent-docs/fastify.md +2 -8
  8. package/agent-docs/hono.md +2 -8
  9. package/agent-docs/next.md +4 -16
  10. package/agent-docs/provider-azure-blob.md +7 -9
  11. package/agent-docs/provider-custom.md +25 -10
  12. package/agent-docs/provider-edgestore.md +9 -9
  13. package/agent-docs/provider-s3.md +223 -119
  14. package/agent-docs/remix.md +2 -8
  15. package/agent-docs/tanstack-start.md +2 -8
  16. package/dist/adapters/astro/index.d.ts +2 -2
  17. package/dist/adapters/astro/index.d.ts.map +1 -1
  18. package/dist/adapters/astro/index.js +1 -2
  19. package/dist/adapters/dispatcher.d.ts +2 -3
  20. package/dist/adapters/dispatcher.d.ts.map +1 -1
  21. package/dist/adapters/dispatcher.js +17 -22
  22. package/dist/adapters/express/index.d.ts +2 -2
  23. package/dist/adapters/express/index.d.ts.map +1 -1
  24. package/dist/adapters/express/index.js +1 -5
  25. package/dist/adapters/fastify/index.d.ts +2 -2
  26. package/dist/adapters/fastify/index.d.ts.map +1 -1
  27. package/dist/adapters/fastify/index.js +1 -5
  28. package/dist/adapters/hono/index.d.ts +2 -2
  29. package/dist/adapters/hono/index.d.ts.map +1 -1
  30. package/dist/adapters/hono/index.js +1 -2
  31. package/dist/adapters/next/app/index.d.ts +2 -2
  32. package/dist/adapters/next/app/index.d.ts.map +1 -1
  33. package/dist/adapters/next/app/index.js +1 -2
  34. package/dist/adapters/next/pages/index.d.ts +2 -2
  35. package/dist/adapters/next/pages/index.d.ts.map +1 -1
  36. package/dist/adapters/next/pages/index.js +1 -5
  37. package/dist/adapters/remix/index.d.ts +2 -2
  38. package/dist/adapters/remix/index.d.ts.map +1 -1
  39. package/dist/adapters/remix/index.js +1 -2
  40. package/dist/adapters/shared.d.ts +45 -67
  41. package/dist/adapters/shared.d.ts.map +1 -1
  42. package/dist/adapters/shared.js +59 -96
  43. package/dist/adapters/start/index.d.ts +2 -2
  44. package/dist/adapters/start/index.d.ts.map +1 -1
  45. package/dist/adapters/start/index.js +1 -2
  46. package/dist/core/client/bucketClient.d.ts +0 -1
  47. package/dist/core/client/bucketClient.d.ts.map +1 -1
  48. package/dist/core/client/bucketClient.js +6 -28
  49. package/dist/core/client/index.d.ts +29 -26
  50. package/dist/core/client/index.d.ts.map +1 -1
  51. package/dist/core/client/index.js +2 -3
  52. package/dist/core/index.d.ts +2 -20
  53. package/dist/core/index.d.ts.map +1 -1
  54. package/dist/core/index.js +2 -13
  55. package/dist/core/provider.d.ts +11 -1
  56. package/dist/core/provider.d.ts.map +1 -1
  57. package/dist/core/provider.js +21 -1
  58. package/dist/core/router.d.ts +25 -0
  59. package/dist/core/router.d.ts.map +1 -0
  60. package/dist/core/router.js +49 -0
  61. package/dist/core/routerRules.d.ts +1 -1
  62. package/dist/index.d.ts +2 -2
  63. package/dist/index.d.ts.map +1 -1
  64. package/dist/index.js +1 -2
  65. package/dist/providers/azure-blob/index.d.ts +7 -0
  66. package/dist/providers/azure-blob/index.d.ts.map +1 -1
  67. package/dist/providers/azure-blob/index.js +7 -0
  68. package/dist/providers/edgestore/index.d.ts +6 -10
  69. package/dist/providers/edgestore/index.d.ts.map +1 -1
  70. package/dist/providers/edgestore/index.js +15 -13
  71. package/dist/providers/s3/backendUpload.d.ts +13 -0
  72. package/dist/providers/s3/backendUpload.d.ts.map +1 -0
  73. package/dist/providers/s3/backendUpload.js +97 -0
  74. package/dist/providers/s3/index.d.ts +57 -93
  75. package/dist/providers/s3/index.d.ts.map +1 -1
  76. package/dist/providers/s3/index.js +241 -90
  77. package/dist/providers/s3/keys.d.ts +10 -0
  78. package/dist/providers/s3/keys.d.ts.map +1 -0
  79. package/dist/providers/s3/keys.js +40 -0
  80. package/dist/providers/s3/multipart.d.ts +25 -0
  81. package/dist/providers/s3/multipart.d.ts.map +1 -0
  82. package/dist/providers/s3/multipart.js +132 -0
  83. package/dist/providers/s3/objectHeaders.d.ts +4 -0
  84. package/dist/providers/s3/objectHeaders.d.ts.map +1 -0
  85. package/dist/providers/s3/objectHeaders.js +22 -0
  86. package/dist/providers/s3/options.d.ts +107 -0
  87. package/dist/providers/s3/options.d.ts.map +1 -0
  88. package/dist/version.d.ts +1 -1
  89. package/package.json +4 -4
  90. package/src/adapters/astro/index.ts +3 -4
  91. package/src/adapters/dispatcher.ts +21 -30
  92. package/src/adapters/express/index.ts +3 -9
  93. package/src/adapters/fastify/index.ts +3 -9
  94. package/src/adapters/hono/index.ts +3 -4
  95. package/src/adapters/next/app/index.ts +3 -4
  96. package/src/adapters/next/pages/index.ts +3 -9
  97. package/src/adapters/remix/index.ts +3 -4
  98. package/src/adapters/shared.ts +89 -162
  99. package/src/adapters/start/index.ts +3 -4
  100. package/src/core/client/bucketClient.ts +10 -41
  101. package/src/core/client/index.ts +32 -48
  102. package/src/core/index.ts +2 -36
  103. package/src/core/provider.ts +28 -5
  104. package/src/core/router.ts +97 -0
  105. package/src/index.ts +1 -3
  106. package/src/providers/azure-blob/index.ts +2 -0
  107. package/src/providers/edgestore/index.ts +19 -13
  108. package/src/providers/s3/backendUpload.ts +117 -0
  109. package/src/providers/s3/index.ts +302 -223
  110. package/src/providers/s3/keys.ts +59 -0
  111. package/src/providers/s3/multipart.ts +196 -0
  112. package/src/providers/s3/objectHeaders.ts +23 -0
  113. package/src/providers/s3/options.ts +125 -0
  114. package/src/version.ts +1 -1
@@ -1,287 +1,366 @@
1
1
  import {
2
- DeleteObjectCommand,
2
+ DeleteObjectsCommand,
3
+ GetObjectCommand,
3
4
  HeadObjectCommand,
4
5
  PutObjectCommand,
5
6
  S3Client,
6
- type S3ClientConfig,
7
+ type PutObjectCommandInput,
7
8
  } from '@aws-sdk/client-s3';
8
9
  import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
9
- import { type MaybePromise, type RequestUploadParams } from '@edgestore/shared';
10
+ import { planMultipartUpload } from '@edgestore/sdk';
11
+ import {
12
+ type RequestUploadParams,
13
+ type RequestUploadRes,
14
+ } from '@edgestore/shared';
10
15
  import { z } from 'zod';
11
16
  import { defineProvider } from '../../core/provider';
12
17
  import { getEnv } from '../../libs/env';
18
+ import { uploadObject } from './backendUpload';
19
+ import { createObjectKeys } from './keys';
20
+ import { createMultipartUploads } from './multipart';
21
+ import { objectUploadHeaders } from './objectHeaders';
22
+ import type { S3ProviderOptions } from './options';
13
23
 
14
- // FileInfo type as received by the provider's requestUpload, part of RequestUploadParams
15
- type ProviderUploadedFileInfo = RequestUploadParams['fileInfo'];
16
-
17
- export type S3PathFnArgs = {
18
- /** Logical EdgeStore router bucket name. */
19
- edgestoreBucketName: string;
20
- /** File info after EdgeStore path and metadata generation. */
21
- fileInfo: ProviderUploadedFileInfo;
22
- /** Default object path relative to the logical bucket prefix. */
23
- defaultPath: string;
24
- };
24
+ export type {
25
+ S3ObjectOptions,
26
+ S3PathFn,
27
+ S3PathFnArgs,
28
+ S3ProviderOptions,
29
+ } from './options';
25
30
 
26
- export type S3PathFn = (args: S3PathFnArgs) => MaybePromise<string>;
31
+ function expiration(value: number) {
32
+ if (!Number.isInteger(value) || value < 1 || value > 604800) {
33
+ throw new RangeError(
34
+ 'S3 signed URL expiration must be an integer between 1 and 604800 seconds.',
35
+ );
36
+ }
37
+ return value;
38
+ }
27
39
 
28
- export type S3ProviderOptions = {
29
- /**
30
- * AWS SDK credentials (or credentials provider) to use for S3 requests.
31
- *
32
- * If unset, the AWS SDK will use its default credential provider chain
33
- * (environment variables, shared config files, instance/task roles, etc).
34
- */
35
- credentials?: S3ClientConfig['credentials'];
36
- /**
37
- * Access key for AWS credentials.
38
- * Can also be set via the `ES_AWS_ACCESS_KEY_ID` environment variable.
39
- *
40
- * If unset, the SDK will attempt to use the default credentials provider chain.
41
- *
42
- * @deprecated Pass `credentials` instead.
43
- */
44
- accessKeyId?: string;
45
- /**
46
- * Secret access key for AWS credentials.
47
- * Can also be set via the `ES_AWS_SECRET_ACCESS_KEY` environment variable.
48
- *
49
- * If unset, the SDK will attempt to use the default credentials provider chain.
50
- *
51
- * @deprecated Pass `credentials` instead.
52
- */
53
- secretAccessKey?: string;
54
- /**
55
- * AWS region to use.
56
- * Can also be set via the `ES_AWS_REGION` environment variable.
57
- */
58
- region?: string;
59
- /**
60
- * Name of the S3 bucket to use.
61
- * Can also be set via the `ES_AWS_BUCKET_NAME` environment variable.
62
- */
63
- bucketName?: string;
64
- /**
65
- * Custom endpoint for S3-compatible storage providers (e.g., MinIO).
66
- * Can also be set via the `ES_AWS_ENDPOINT` environment variable.
67
- */
68
- endpoint?: string;
69
- /**
70
- * Force path style for S3-compatible storage providers.
71
- * Can also be set via the `ES_AWS_FORCE_PATH_STYLE` environment variable.
72
- * Defaults to false for AWS S3, but should be true for most S3-compatible providers.
73
- */
74
- forcePathStyle?: boolean;
75
- /**
76
- * Base URL to use for accessing files.
77
- * Only needed if you are using a custom domain or cloudfront.
78
- *
79
- * It can also be set via the `EDGE_STORE_BASE_URL` environment variable.
80
- */
81
- baseUrl?: string;
82
- /**
83
- * Secret to use for encrypting JWT tokens.
84
- * Can be generated with `openssl rand -base64 32`.
85
- *
86
- * It can also be set via the `EDGE_STORE_JWT_SECRET` environment variable.
87
- */
88
- jwtSecret?: string;
89
- /**
90
- * Customizes the object path beneath the logical EdgeStore bucket prefix.
91
- *
92
- * The logical bucket prefix is always preserved so router authorization for
93
- * one bucket cannot access objects from another.
94
- */
95
- path?: S3PathFn;
96
- };
40
+ /** Multipart sessions are EdgeStore JWTs, not S3 URLs, so S3's cap does not apply. */
41
+ function sessionLifetime(value: number) {
42
+ if (!Number.isSafeInteger(value) || value < 1) {
43
+ throw new RangeError(
44
+ 'S3 multipart session lifetime must be a positive integer number of seconds.',
45
+ );
46
+ }
47
+ return value;
48
+ }
97
49
 
98
- export function s3(options?: S3ProviderOptions) {
50
+ export function s3(options: S3ProviderOptions = {}) {
99
51
  const {
100
- credentials: credentialsFromOptions,
52
+ credentials: configuredCredentials,
101
53
  accessKeyId = getEnv('ES_AWS_ACCESS_KEY_ID'),
102
54
  secretAccessKey = getEnv('ES_AWS_SECRET_ACCESS_KEY'),
103
55
  region = getEnv('ES_AWS_REGION'),
104
56
  bucketName = getEnv('ES_AWS_BUCKET_NAME'),
105
57
  endpoint = getEnv('ES_AWS_ENDPOINT'),
106
58
  forcePathStyle = getEnv('ES_AWS_FORCE_PATH_STYLE') === 'true',
107
- path: resolvePath,
108
- } = options ?? {};
109
-
59
+ } = options;
60
+ const client =
61
+ options.client ??
62
+ new S3Client({
63
+ region,
64
+ endpoint,
65
+ forcePathStyle,
66
+ credentials:
67
+ configuredCredentials ??
68
+ (accessKeyId && secretAccessKey
69
+ ? { accessKeyId, secretAccessKey }
70
+ : undefined),
71
+ // Presigning without a body must not sign an empty-body optional checksum.
72
+ requestChecksumCalculation: 'WHEN_REQUIRED',
73
+ });
110
74
  const baseUrl =
111
- options?.baseUrl ??
75
+ options.baseUrl ??
112
76
  getEnv('EDGE_STORE_BASE_URL') ??
113
77
  (endpoint
114
- ? `${endpoint}/${bucketName}`
115
- : `https://${bucketName}.s3.${region}.amazonaws.com`);
78
+ ? `${endpoint.replace(/\/+$/, '')}/${bucketName}`
79
+ : region
80
+ ? `https://${bucketName}.s3.${region}.amazonaws.com`
81
+ : async () =>
82
+ `https://${bucketName}.s3.${await client.config.region()}.amazonaws.com`);
83
+ const keys = async () =>
84
+ createObjectKeys(typeof baseUrl === 'function' ? await baseUrl() : baseUrl);
85
+ const uploadExpiresIn = expiration(options.uploadUrlExpiresIn ?? 3600);
86
+ const readExpiresIn = expiration(options.signedUrlExpiresIn ?? 3600);
116
87
 
117
- const credentials =
118
- credentialsFromOptions ??
119
- (accessKeyId && secretAccessKey
120
- ? {
121
- accessKeyId,
122
- secretAccessKey,
123
- }
124
- : undefined);
125
- const s3Client = new S3Client({
126
- region,
127
- credentials,
128
- endpoint,
129
- forcePathStyle,
88
+ function bucket() {
89
+ if (!bucketName)
90
+ throw new Error('S3 bucketName is not configured in S3ProviderOptions.');
91
+ return bucketName;
92
+ }
93
+ function plan(sizeBytes: number) {
94
+ if (!Number.isSafeInteger(sizeBytes) || sizeBytes < 0)
95
+ throw new RangeError(
96
+ 'S3 upload size must be a nonnegative safe integer.',
97
+ );
98
+ const result = planMultipartUpload({
99
+ sizeBytes,
100
+ thresholdBytes: options.multipart?.thresholdBytes,
101
+ preferredPartSizeBytes: options.multipart?.partSizeBytes,
102
+ forceMultipart: sizeBytes > 5 * 1024 ** 3,
103
+ });
104
+ if (result && result.partSizeBytes > 5 * 1024 ** 3)
105
+ throw new RangeError('S3 multipart parts cannot exceed 5 GiB.');
106
+ return result;
107
+ }
108
+ // Validate multipart settings even before the first large upload.
109
+ plan(0);
110
+ const multipart = createMultipartUploads({
111
+ client,
112
+ bucket,
113
+ partUrlExpiresIn: uploadExpiresIn,
114
+ sessionExpiresIn: sessionLifetime(
115
+ options.multipart?.sessionExpiresIn ?? 86400,
116
+ ),
117
+ audience: `edgestore:s3:${endpoint ?? region ?? 'aws'}:${bucketName}`,
118
+ secret: () =>
119
+ options.jwtSecret ??
120
+ getEnv('EDGE_STORE_JWT_SECRET') ??
121
+ getEnv('EDGE_STORE_SECRET_KEY'),
130
122
  });
131
- const normalizedBaseUrl = baseUrl.replace(/\/+$/, '');
132
123
 
133
- function objectKeyToUrl(objectKey: string) {
134
- const encodedKey = objectKey
135
- .split('/')
136
- .map((segment) => encodeURIComponent(segment))
137
- .join('/');
138
- return `${normalizedBaseUrl}/${encodedKey}`;
124
+ async function prepare({
125
+ bucketName: logicalBucket,
126
+ fileInfo,
127
+ }: RequestUploadParams) {
128
+ const physicalBucket = bucket();
129
+ const objectKeys = await keys();
130
+ const extension = fileInfo.extension
131
+ ? `.${fileInfo.extension.replace(/^\./, '')}`
132
+ : '';
133
+ const defaultPath = [
134
+ ...(fileInfo.isPublic ? ['_public'] : []),
135
+ ...fileInfo.path.map((part) => part.value),
136
+ fileInfo.fileName ?? `${crypto.randomUUID()}${extension}`,
137
+ ].join('/');
138
+ const args = { edgestoreBucketName: logicalBucket, fileInfo, defaultPath };
139
+ const relativePath = objectKeys.normalizeRelativePath(
140
+ options.path ? await options.path(args) : defaultPath,
141
+ );
142
+ const key = `${logicalBucket}/${relativePath}`;
143
+ const objectOptions =
144
+ typeof options.objectOptions === 'function'
145
+ ? await options.objectOptions(args)
146
+ : options.objectOptions;
147
+ const input: PutObjectCommandInput = {
148
+ ...objectOptions,
149
+ Bucket: physicalBucket,
150
+ Key: key,
151
+ ContentLength: fileInfo.size,
152
+ ContentType: fileInfo.type || 'application/octet-stream',
153
+ };
154
+ return {
155
+ input,
156
+ key,
157
+ url: objectKeys.toUrl(key),
158
+ plan: plan(fileInfo.size),
159
+ };
139
160
  }
140
161
 
141
- function urlToObjectKey(edgestoreBucketName: string, url: string) {
142
- let objectKey: string;
143
- try {
144
- const fileUrl = new URL(url);
145
- const providerUrl = new URL(`${normalizedBaseUrl}/`);
146
- if (
147
- fileUrl.origin !== providerUrl.origin ||
148
- !fileUrl.pathname.startsWith(providerUrl.pathname)
149
- ) {
150
- throw new Error();
162
+ async function signedRead(key: string, expiresIn = readExpiresIn) {
163
+ const ttl = expiration(expiresIn);
164
+ const signedUrl = await getSignedUrl(
165
+ client,
166
+ new GetObjectCommand({ Bucket: bucket(), Key: key }),
167
+ { expiresIn: ttl },
168
+ );
169
+ return {
170
+ url: (await keys()).toUrl(key),
171
+ signedUrl,
172
+ expiresAt: new Date(Date.now() + ttl * 1000),
173
+ expiresIn: ttl,
174
+ };
175
+ }
176
+ // Presigned browser uploads must not sign a checksum of the empty body.
177
+ let presignable: Promise<void> | undefined;
178
+ function assertPresignableClient() {
179
+ return (presignable ??= (async () => {
180
+ const policy = options.client
181
+ ? await client.config.requestChecksumCalculation?.()
182
+ : undefined;
183
+ if (policy && policy !== 'WHEN_REQUIRED') {
184
+ throw new Error(
185
+ 'An injected S3 client must use requestChecksumCalculation: "WHEN_REQUIRED" for browser uploads.',
186
+ );
151
187
  }
152
- objectKey = decodeURIComponent(
153
- fileUrl.pathname.slice(providerUrl.pathname.length),
154
- );
155
- } catch {
156
- throw new Error('File URL does not belong to this S3 provider.');
157
- }
158
-
159
- if (!objectKey.startsWith(`${edgestoreBucketName}/`)) {
160
- throw new Error(
161
- `File does not belong to EdgeStore bucket "${edgestoreBucketName}".`,
162
- );
163
- }
164
- return objectKey;
188
+ })());
165
189
  }
166
190
 
167
- function normalizeRelativePath(value: string) {
168
- const path = value.replace(/^\/+|\/+$/g, '');
169
- if (
170
- path.length === 0 ||
171
- path.split('/').some((segment) => segment === '.' || segment === '..')
172
- ) {
173
- throw new Error('S3 paths must stay within the EdgeStore bucket prefix.');
174
- }
175
- return path;
191
+ async function readForUpload(key: string, params: RequestUploadParams) {
192
+ if (params.fileInfo.isPublic || !params.autoSignedUrls) return undefined;
193
+ return signedRead(key, params.autoSignedUrls.expiresIn);
176
194
  }
177
195
 
178
196
  return defineProvider({
179
197
  name: 's3',
180
198
  baseUrl,
181
199
  reference: {
182
- schema: z.object({ url: z.string() }),
200
+ schema: z.union([
201
+ z.object({ key: z.string().min(1) }),
202
+ z.object({ url: z.string().url() }),
203
+ ]),
183
204
  fromUrl: (url) => ({ url }),
184
205
  },
185
- async init() {
206
+ async init({ router }) {
207
+ bucket();
208
+ for (const logicalBucket of Object.values(router.buckets)) {
209
+ if (
210
+ logicalBucket._def.accessControl !== undefined &&
211
+ logicalBucket._def.accessControl !== 'private'
212
+ ) {
213
+ throw new Error(
214
+ 'S3 supports accessControl("private") with backend signed URLs, not cookie-based access-control rules.',
215
+ );
216
+ }
217
+ }
186
218
  return {};
187
219
  },
188
220
  uploads: {
189
- async request(params: RequestUploadParams) {
190
- const { bucketName: esBucketName, fileInfo } = params;
191
-
192
- if (!bucketName) {
193
- throw new Error(
194
- 'S3 bucketName is not configured in S3ProviderOptions.',
195
- );
221
+ supportedOptions: { temporary: false, replaceTargetUrl: false },
222
+ async request(params): Promise<RequestUploadRes> {
223
+ await assertPresignableClient();
224
+ const prepared = await prepare(params);
225
+ const read = await readForUpload(prepared.key, params);
226
+ const access = {
227
+ key: prepared.key,
228
+ accessUrl: prepared.url,
229
+ ...(read
230
+ ? {
231
+ accessSignedUrl: read.signedUrl,
232
+ accessSignedUrlExpiresAt: read.expiresAt,
233
+ accessSignedUrlExpiresIn: read.expiresIn,
234
+ }
235
+ : {}),
236
+ };
237
+ if (prepared.plan) {
238
+ return {
239
+ ...access,
240
+ multipart: await multipart.request(prepared.input, prepared.plan),
241
+ };
196
242
  }
197
-
198
- const extension = fileInfo.extension
199
- ? `.${fileInfo.extension.replace('.', '')}`
200
- : '';
201
- const defaultResolvedFileName =
202
- fileInfo.fileName ?? `${crypto.randomUUID()}${extension}`;
203
- const defaultPath = [
204
- ...(fileInfo.isPublic ? ['_public'] : []),
205
- ...fileInfo.path.map((item) => item.value),
206
- defaultResolvedFileName,
207
- ].join('/');
208
-
209
- const relativePath = normalizeRelativePath(
210
- resolvePath
211
- ? await resolvePath({
212
- edgestoreBucketName: esBucketName,
213
- fileInfo,
214
- defaultPath,
215
- })
216
- : defaultPath,
217
- );
218
- const accessPath = `${esBucketName}/${relativePath}`;
219
-
220
- const command = new PutObjectCommand({
221
- Bucket: bucketName,
222
- Key: accessPath,
243
+ const uploadHeaders = objectUploadHeaders(prepared.input);
244
+ return {
245
+ ...access,
246
+ uploadUrl: await getSignedUrl(
247
+ client,
248
+ new PutObjectCommand(prepared.input),
249
+ {
250
+ expiresIn: uploadExpiresIn,
251
+ signableHeaders: new Set(['content-type']),
252
+ unhoistableHeaders: new Set(
253
+ Object.keys(uploadHeaders).map((name) => name.toLowerCase()),
254
+ ),
255
+ },
256
+ ),
257
+ uploadHeaders,
258
+ };
259
+ },
260
+ multipart: multipart.operations,
261
+ async upload(params) {
262
+ const prepared = await prepare({
263
+ ...params,
264
+ fileInfo: {
265
+ ...params.fileInfo,
266
+ size: params.source.size,
267
+ type: params.source.type || params.fileInfo.type,
268
+ },
223
269
  });
224
- const signedUrl = await getSignedUrl(s3Client, command, {
225
- expiresIn: 60 * 60,
270
+ // Sign the read URL before sending bytes: nothing fallible may run
271
+ // after the object is committed.
272
+ const signedReadUrl = await readForUpload(prepared.key, params);
273
+ await uploadObject({
274
+ client,
275
+ input: prepared.input,
276
+ plan: prepared.plan,
277
+ source: params.source,
278
+ signal: params.signal,
279
+ onProgress: params.onProgress,
226
280
  });
281
+ // The object is committed. Describe it from what we sent, so a failed
282
+ // or canceled follow-up request cannot turn success into an error.
283
+ const uploadedAt = new Date();
227
284
  return {
228
- uploadUrl: signedUrl,
229
- accessUrl: objectKeyToUrl(accessPath),
285
+ file: {
286
+ key: prepared.key,
287
+ url: prepared.url,
288
+ sizeBytes: params.source.size,
289
+ uploadedAt,
290
+ updatedAt: uploadedAt,
291
+ },
292
+ signedReadUrl,
230
293
  };
231
294
  },
232
295
  },
233
296
  files: {
234
- async get({ bucketName: edgestoreBucketName, file }) {
235
- const path = urlToObjectKey(edgestoreBucketName, file.url);
236
- const { ContentLength, LastModified } = await s3Client.send(
237
- new HeadObjectCommand({
238
- Bucket: bucketName,
239
- Key: path,
240
- }),
297
+ async get({ bucketName: logicalBucket, file }) {
298
+ const objectKeys = await keys();
299
+ const key = objectKeys.fromReference(logicalBucket, file);
300
+ const { ContentLength, LastModified } = await client.send(
301
+ new HeadObjectCommand({ Bucket: bucket(), Key: key }),
241
302
  );
242
-
243
- if (ContentLength === undefined || !LastModified) {
303
+ if (ContentLength === undefined || !LastModified)
244
304
  throw new Error('File not found');
245
- }
246
-
247
305
  return {
248
- url: file.url,
306
+ key,
307
+ url: objectKeys.toUrl(key),
249
308
  sizeBytes: ContentLength,
250
309
  uploadedAt: LastModified,
251
310
  updatedAt: LastModified,
252
311
  };
253
312
  },
254
- async delete({ bucketName: edgestoreBucketName, files }) {
255
- if (!bucketName) {
256
- throw new Error(
257
- 'S3 bucketName is not configured in S3ProviderOptions for deleteFile.',
258
- );
259
- }
260
- const objectKeys = files.map((file) =>
261
- urlToObjectKey(edgestoreBucketName, file.url),
313
+ async getSignedUrls({ bucketName: logicalBucket, files, expiresIn }) {
314
+ const objectKeys = await keys();
315
+ const objectKeysToSign = files.map((file) =>
316
+ objectKeys.fromReference(logicalBucket, file),
262
317
  );
263
- const results = await Promise.all(
264
- objectKeys.map(async (objectKey) => {
265
- try {
266
- await s3Client.send(
267
- new DeleteObjectCommand({
268
- Bucket: bucketName,
269
- Key: objectKey,
270
- }),
271
- );
272
- return { success: true as const };
273
- } catch (error) {
274
- return {
275
- success: false as const,
276
- error: {
277
- code: 'DELETE_FAILED' as const,
278
- message:
279
- error instanceof Error ? error.message : 'Delete failed',
318
+ return Promise.all(
319
+ objectKeysToSign.map((key) => signedRead(key, expiresIn)),
320
+ );
321
+ },
322
+ async delete({ bucketName: logicalBucket, files }) {
323
+ const physicalBucket = bucket();
324
+ const objectKeys = await keys();
325
+ const paths = files.map((file) =>
326
+ objectKeys.fromReference(logicalBucket, file),
327
+ );
328
+ const results = [];
329
+ // DeleteObjects accepts up to 1,000 keys per request.
330
+ for (let start = 0; start < paths.length; start += 1000) {
331
+ const batch = paths.slice(start, start + 1000);
332
+ const errors = new Map<string, string>();
333
+ try {
334
+ const { Errors } = await client.send(
335
+ new DeleteObjectsCommand({
336
+ Bucket: physicalBucket,
337
+ Delete: {
338
+ Objects: [...new Set(batch)].map((Key) => ({ Key })),
339
+ Quiet: true,
280
340
  },
281
- };
341
+ }),
342
+ );
343
+ for (const error of Errors ?? []) {
344
+ if (error.Key)
345
+ errors.set(error.Key, error.Message ?? 'Delete failed');
282
346
  }
283
- }),
284
- );
347
+ } catch (error) {
348
+ const message =
349
+ error instanceof Error ? error.message : 'Delete failed';
350
+ for (const key of batch) errors.set(key, message);
351
+ }
352
+ for (const key of batch) {
353
+ const message = errors.get(key);
354
+ results.push(
355
+ message === undefined
356
+ ? { success: true as const }
357
+ : {
358
+ success: false as const,
359
+ error: { code: 'DELETE_FAILED' as const, message },
360
+ },
361
+ );
362
+ }
363
+ }
285
364
  return { results };
286
365
  },
287
366
  },
@@ -0,0 +1,59 @@
1
+ export function createObjectKeys(baseUrl: string) {
2
+ const normalizedBaseUrl = baseUrl.replace(/\/+$/, '');
3
+
4
+ function objectKeyToUrl(objectKey: string) {
5
+ const encodedKey = objectKey
6
+ .split('/')
7
+ .map((segment) => encodeURIComponent(segment))
8
+ .join('/');
9
+ return `${normalizedBaseUrl}/${encodedKey}`;
10
+ }
11
+
12
+ function urlToObjectKey(url: string) {
13
+ try {
14
+ const fileUrl = new URL(url);
15
+ const providerUrl = new URL(`${normalizedBaseUrl}/`);
16
+ if (
17
+ fileUrl.origin !== providerUrl.origin ||
18
+ !fileUrl.pathname.startsWith(providerUrl.pathname)
19
+ ) {
20
+ throw new Error();
21
+ }
22
+ return decodeURIComponent(
23
+ fileUrl.pathname.slice(providerUrl.pathname.length),
24
+ );
25
+ } catch {
26
+ throw new Error('File URL does not belong to this S3 provider.');
27
+ }
28
+ }
29
+
30
+ function normalizeRelativePath(value: string) {
31
+ const path = value.replace(/^\/+|\/+$/g, '');
32
+ if (
33
+ path.length === 0 ||
34
+ path.split('/').some((segment) => segment === '.' || segment === '..')
35
+ ) {
36
+ throw new Error('S3 paths must stay within the EdgeStore bucket prefix.');
37
+ }
38
+ return path;
39
+ }
40
+
41
+ /** Keys from both URLs and key references must stay inside the logical bucket. */
42
+ function fromReference(
43
+ bucketName: string,
44
+ file: { url: string } | { key: string },
45
+ ) {
46
+ const key = 'url' in file ? urlToObjectKey(file.url) : file.key;
47
+ if (
48
+ normalizeRelativePath(key) !== key ||
49
+ !key.startsWith(`${bucketName}/`)
50
+ ) {
51
+ throw new Error(
52
+ `File does not belong to EdgeStore bucket "${bucketName}".`,
53
+ );
54
+ }
55
+ return key;
56
+ }
57
+
58
+ return { toUrl: objectKeyToUrl, fromReference, normalizeRelativePath };
59
+ }