@payloadcms/storage-s3 4.0.0-internal.cea8867 → 4.0.0-internal.d21c039
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.
- package/README.md +1 -1
- package/dist/adapter.d.ts.map +1 -1
- package/dist/adapter.js +22 -15
- package/dist/adapter.js.map +1 -1
- package/dist/deleteFile.d.ts +2 -5
- package/dist/deleteFile.d.ts.map +1 -1
- package/dist/deleteFile.js +2 -9
- package/dist/deleteFile.js.map +1 -1
- package/dist/generateURL.js +4 -4
- package/dist/generateURL.js.map +1 -1
- package/dist/generateUploadInstructions.d.ts +13 -0
- package/dist/generateUploadInstructions.d.ts.map +1 -0
- package/dist/generateUploadInstructions.js +70 -0
- package/dist/generateUploadInstructions.js.map +1 -0
- package/dist/getFile.d.ts +4 -4
- package/dist/getFile.d.ts.map +1 -1
- package/dist/getFile.js +18 -16
- package/dist/getFile.js.map +1 -1
- package/dist/index.d.ts +9 -18
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +14 -36
- package/dist/index.js.map +1 -1
- package/dist/uploadFile.d.ts +2 -5
- package/dist/uploadFile.d.ts.map +1 -1
- package/dist/uploadFile.js +3 -10
- package/dist/uploadFile.js.map +1 -1
- package/package.json +4 -9
- package/dist/client/S3ClientUploadHandler.d.ts +0 -9
- package/dist/client/S3ClientUploadHandler.d.ts.map +0 -1
- package/dist/client/S3ClientUploadHandler.js +0 -47
- package/dist/client/S3ClientUploadHandler.js.map +0 -1
- package/dist/exports/client.d.ts +0 -2
- package/dist/exports/client.d.ts.map +0 -1
- package/dist/exports/client.js +0 -3
- package/dist/exports/client.js.map +0 -1
- package/dist/generateSignedURL.d.ts +0 -15
- package/dist/generateSignedURL.d.ts.map +0 -1
- package/dist/generateSignedURL.js +0 -64
- package/dist/generateSignedURL.js.map +0 -1
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@ pnpm add @payloadcms/storage-s3
|
|
|
15
15
|
- Configure the `collections` object to specify which collections should use the AWS S3 adapter. The slug _must_ match one of your existing collection slugs.
|
|
16
16
|
- The `config` object can be any [`S3ClientConfig`](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3) object (from [`@aws-sdk/client-s3`](https://github.com/aws/aws-sdk-js-v3)). _This is highly dependent on your AWS setup_. Check the AWS documentation for more information.
|
|
17
17
|
- When enabled, this package will automatically set `disableLocalStorage` to `true` for each collection.
|
|
18
|
-
- When deploying to Vercel, server uploads are limited
|
|
18
|
+
- When deploying to Vercel, server uploads are limited to 4.5MB. Set `clientUploads` to `true` to use upload instructions and send files directly to S3. You must allow CORS `PUT` requests from your website.
|
|
19
19
|
- Configure `signedDownloads` (either globally of per-collection in `collections`) to use [presigned URLs](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html) for files downloading. This can improve performance for large files (like videos) while still respecting your access control. Additionally, with `signedDownloads.shouldUseSignedURL` you can specify a condition whether Payload should use a presigned URL, if you want to use this feature only for specific files.
|
|
20
20
|
|
|
21
21
|
```ts
|
package/dist/adapter.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AAC5D,OAAO,KAAK,EACV,OAAO,EACP,mBAAmB,EAEpB,MAAM,wCAAwC,CAAA;AAE/C,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAA;
|
|
1
|
+
{"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AAC5D,OAAO,KAAK,EACV,OAAO,EACP,mBAAmB,EAEpB,MAAM,wCAAwC,CAAA;AAE/C,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAA;AAKzD,UAAU,mBAAmB;IAC3B,GAAG,CAAC,EAAE,SAAS,GAAG,aAAa,CAAA;IAC/B,MAAM,EAAE,MAAM,CAAA;IACd,aAAa,CAAC,EAAE,mBAAmB,CAAA;IACnC,MAAM,EAAE,cAAc,CAAA;IACtB,gBAAgB,EAAE,MAAM,EAAE,CAAA;IAC1B,eAAe,EAAE,qBAAqB,CAAA;IACtC,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B;AAED,wBAAgB,eAAe,CAAC,EAC9B,GAAG,EACH,MAAM,EACN,aAAa,EACb,MAAM,EACN,gBAAgB,EAChB,eAAe,EACf,oBAA4B,GAC7B,EAAE,mBAAmB,GAAG,OAAO,CAuE/B"}
|
package/dist/adapter.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
+
import { generateUploadInstructions } from './generateUploadInstructions.js';
|
|
1
2
|
import { generateURL } from './generateURL.js';
|
|
2
3
|
export function createS3Adapter({ acl, bucket, clientUploads, config, getStorageClient, signedDownloads, useCompositePrefixes = false }) {
|
|
3
4
|
return ({ collection, prefix = '' })=>({
|
|
4
5
|
name: 's3',
|
|
5
|
-
clientUploads,
|
|
6
6
|
generateURL: ({ filename, prefix: urlPrefix = '' })=>generateURL({
|
|
7
7
|
bucket,
|
|
8
8
|
collectionPrefix: prefix,
|
|
@@ -11,48 +11,55 @@ export function createS3Adapter({ acl, bucket, clientUploads, config, getStorage
|
|
|
11
11
|
prefix: urlPrefix,
|
|
12
12
|
useCompositePrefixes
|
|
13
13
|
}),
|
|
14
|
+
uploadInstructions: {
|
|
15
|
+
enabled: Boolean(clientUploads),
|
|
16
|
+
generate: generateUploadInstructions({
|
|
17
|
+
access: typeof clientUploads === 'object' ? clientUploads.access : undefined,
|
|
18
|
+
acl,
|
|
19
|
+
bucket,
|
|
20
|
+
collectionPrefix: prefix,
|
|
21
|
+
getStorageClient,
|
|
22
|
+
useCompositePrefixes
|
|
23
|
+
}),
|
|
24
|
+
requiresUploadReceipt: true,
|
|
25
|
+
useInAdmin: true
|
|
26
|
+
},
|
|
14
27
|
// Helpers below dynamic-import their @aws-sdk dependencies so the SDK only
|
|
15
28
|
// loads on the first request that actually needs it.
|
|
16
|
-
handleDelete: async ({
|
|
29
|
+
handleDelete: async ({ storageFilePath })=>{
|
|
17
30
|
const { deleteFile } = await import('./deleteFile.js');
|
|
18
31
|
return deleteFile({
|
|
19
32
|
bucket,
|
|
20
33
|
client: getStorageClient(),
|
|
21
|
-
|
|
22
|
-
docPrefix,
|
|
23
|
-
filename,
|
|
24
|
-
useCompositePrefixes
|
|
34
|
+
storageFilePath
|
|
25
35
|
});
|
|
26
36
|
},
|
|
27
|
-
handleUpload: async ({ data, file })=>{
|
|
37
|
+
handleUpload: async ({ data, file, storageFilePath })=>{
|
|
28
38
|
const { uploadFile } = await import('./uploadFile.js');
|
|
29
39
|
await uploadFile({
|
|
30
40
|
acl,
|
|
31
41
|
bucket,
|
|
32
42
|
buffer: file.buffer,
|
|
33
43
|
client: getStorageClient(),
|
|
34
|
-
collectionPrefix: prefix,
|
|
35
|
-
docPrefix: data.prefix,
|
|
36
|
-
filename: file.filename,
|
|
37
44
|
mimeType: file.mimeType,
|
|
38
|
-
|
|
39
|
-
|
|
45
|
+
storageFilePath,
|
|
46
|
+
tempFilePath: file.tempFilePath
|
|
40
47
|
});
|
|
41
48
|
return data;
|
|
42
49
|
},
|
|
43
|
-
staticHandler: async (req, { headers, params: {
|
|
50
|
+
staticHandler: async (req, { doc, headers, params: { filename, uploadReference } })=>{
|
|
44
51
|
const { getFile } = await import('./getFile.js');
|
|
45
52
|
return getFile({
|
|
46
53
|
bucket,
|
|
47
54
|
client: getStorageClient(),
|
|
48
|
-
clientUploadContext,
|
|
49
55
|
collection,
|
|
50
56
|
collectionPrefix: prefix,
|
|
57
|
+
doc,
|
|
51
58
|
filename,
|
|
52
59
|
incomingHeaders: headers,
|
|
53
|
-
prefixQueryParam,
|
|
54
60
|
req,
|
|
55
61
|
signedDownloads,
|
|
62
|
+
uploadReference,
|
|
56
63
|
useCompositePrefixes
|
|
57
64
|
});
|
|
58
65
|
}
|
package/dist/adapter.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapter.ts"],"sourcesContent":["import type { S3, S3ClientConfig } from '@aws-sdk/client-s3'\nimport type {\n Adapter,\n ClientUploadsConfig,\n GeneratedAdapter,\n} from '@payloadcms/plugin-cloud-storage/types'\n\nimport type { SignedDownloadsConfig } from './getFile.js'\n\nimport { generateURL } from './generateURL.js'\n\ninterface CreateS3AdapterArgs {\n acl?: 'private' | 'public-read'\n bucket: string\n clientUploads?: ClientUploadsConfig\n config: S3ClientConfig\n getStorageClient: () => S3\n signedDownloads: SignedDownloadsConfig\n useCompositePrefixes?: boolean\n}\n\nexport function createS3Adapter({\n acl,\n bucket,\n clientUploads,\n config,\n getStorageClient,\n signedDownloads,\n useCompositePrefixes = false,\n}: CreateS3AdapterArgs): Adapter {\n return ({ collection, prefix = '' }): GeneratedAdapter => ({\n name: 's3',\n
|
|
1
|
+
{"version":3,"sources":["../src/adapter.ts"],"sourcesContent":["import type { S3, S3ClientConfig } from '@aws-sdk/client-s3'\nimport type {\n Adapter,\n ClientUploadsConfig,\n GeneratedAdapter,\n} from '@payloadcms/plugin-cloud-storage/types'\n\nimport type { SignedDownloadsConfig } from './getFile.js'\n\nimport { generateUploadInstructions } from './generateUploadInstructions.js'\nimport { generateURL } from './generateURL.js'\n\ninterface CreateS3AdapterArgs {\n acl?: 'private' | 'public-read'\n bucket: string\n clientUploads?: ClientUploadsConfig\n config: S3ClientConfig\n getStorageClient: () => S3\n signedDownloads: SignedDownloadsConfig\n useCompositePrefixes?: boolean\n}\n\nexport function createS3Adapter({\n acl,\n bucket,\n clientUploads,\n config,\n getStorageClient,\n signedDownloads,\n useCompositePrefixes = false,\n}: CreateS3AdapterArgs): Adapter {\n return ({ collection, prefix = '' }): GeneratedAdapter => ({\n name: 's3',\n\n generateURL: ({ filename, prefix: urlPrefix = '' }) =>\n generateURL({\n bucket,\n collectionPrefix: prefix,\n endpoint: config.endpoint,\n filename,\n prefix: urlPrefix,\n useCompositePrefixes,\n }),\n\n uploadInstructions: {\n enabled: Boolean(clientUploads),\n generate: generateUploadInstructions({\n access: typeof clientUploads === 'object' ? clientUploads.access : undefined,\n acl,\n bucket,\n collectionPrefix: prefix,\n getStorageClient,\n useCompositePrefixes,\n }),\n requiresUploadReceipt: true,\n useInAdmin: true,\n },\n\n // Helpers below dynamic-import their @aws-sdk dependencies so the SDK only\n // loads on the first request that actually needs it.\n handleDelete: async ({ storageFilePath }) => {\n const { deleteFile } = await import('./deleteFile.js')\n return deleteFile({\n bucket,\n client: getStorageClient(),\n storageFilePath,\n })\n },\n\n handleUpload: async ({ data, file, storageFilePath }) => {\n const { uploadFile } = await import('./uploadFile.js')\n await uploadFile({\n acl,\n bucket,\n buffer: file.buffer,\n client: getStorageClient(),\n mimeType: file.mimeType,\n storageFilePath,\n tempFilePath: file.tempFilePath,\n })\n\n return data\n },\n\n staticHandler: async (req, { doc, headers, params: { filename, uploadReference } }) => {\n const { getFile } = await import('./getFile.js')\n return getFile({\n bucket,\n client: getStorageClient(),\n collection,\n collectionPrefix: prefix,\n doc,\n filename,\n incomingHeaders: headers,\n req,\n signedDownloads,\n uploadReference,\n useCompositePrefixes,\n })\n },\n })\n}\n"],"names":["generateUploadInstructions","generateURL","createS3Adapter","acl","bucket","clientUploads","config","getStorageClient","signedDownloads","useCompositePrefixes","collection","prefix","name","filename","urlPrefix","collectionPrefix","endpoint","uploadInstructions","enabled","Boolean","generate","access","undefined","requiresUploadReceipt","useInAdmin","handleDelete","storageFilePath","deleteFile","client","handleUpload","data","file","uploadFile","buffer","mimeType","tempFilePath","staticHandler","req","doc","headers","params","uploadReference","getFile","incomingHeaders"],"mappings":"AASA,SAASA,0BAA0B,QAAQ,kCAAiC;AAC5E,SAASC,WAAW,QAAQ,mBAAkB;AAY9C,OAAO,SAASC,gBAAgB,EAC9BC,G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A,QAAQ;oBACbtC;oBACAwB,QAAQrB;oBACRG;oBACAK,kBAAkBJ;oBAClB2B;oBACAzB;oBACA8B,iBAAiBJ;oBACjBF;oBACA7B;oBACAiC;oBACAhC;gBACF;YACF;QACF,CAAA;AACF"}
|
package/dist/deleteFile.d.ts
CHANGED
|
@@ -2,11 +2,8 @@ import type * as AWS from '@aws-sdk/client-s3';
|
|
|
2
2
|
interface DeleteArgs {
|
|
3
3
|
bucket: string;
|
|
4
4
|
client: AWS.S3;
|
|
5
|
-
|
|
6
|
-
docPrefix: string;
|
|
7
|
-
filename: string;
|
|
8
|
-
useCompositePrefixes?: boolean;
|
|
5
|
+
storageFilePath: string;
|
|
9
6
|
}
|
|
10
|
-
export declare function deleteFile({ bucket, client,
|
|
7
|
+
export declare function deleteFile({ bucket, client, storageFilePath }: DeleteArgs): Promise<void>;
|
|
11
8
|
export {};
|
|
12
9
|
//# sourceMappingURL=deleteFile.d.ts.map
|
package/dist/deleteFile.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"deleteFile.d.ts","sourceRoot":"","sources":["../src/deleteFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,GAAG,MAAM,oBAAoB,CAAA;
|
|
1
|
+
{"version":3,"file":"deleteFile.d.ts","sourceRoot":"","sources":["../src/deleteFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,GAAG,MAAM,oBAAoB,CAAA;AAE9C,UAAU,UAAU;IAClB,MAAM,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,GAAG,CAAC,EAAE,CAAA;IACd,eAAe,EAAE,MAAM,CAAA;CACxB;AAED,wBAAsB,UAAU,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,eAAe,EAAE,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAK/F"}
|
package/dist/deleteFile.js
CHANGED
|
@@ -1,14 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
export async function deleteFile({ bucket, client, collectionPrefix = '', docPrefix, filename, useCompositePrefixes = false }) {
|
|
3
|
-
const { fileKey } = getFileKey({
|
|
4
|
-
collectionPrefix,
|
|
5
|
-
docPrefix,
|
|
6
|
-
filename,
|
|
7
|
-
useCompositePrefixes
|
|
8
|
-
});
|
|
1
|
+
export async function deleteFile({ bucket, client, storageFilePath }) {
|
|
9
2
|
await client.deleteObject({
|
|
10
3
|
Bucket: bucket,
|
|
11
|
-
Key:
|
|
4
|
+
Key: storageFilePath
|
|
12
5
|
});
|
|
13
6
|
}
|
|
14
7
|
|
package/dist/deleteFile.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/deleteFile.ts"],"sourcesContent":["import type * as AWS from '@aws-sdk/client-s3'\n\
|
|
1
|
+
{"version":3,"sources":["../src/deleteFile.ts"],"sourcesContent":["import type * as AWS from '@aws-sdk/client-s3'\n\ninterface DeleteArgs {\n bucket: string\n client: AWS.S3\n storageFilePath: string\n}\n\nexport async function deleteFile({ bucket, client, storageFilePath }: DeleteArgs): Promise<void> {\n await client.deleteObject({\n Bucket: bucket,\n Key: storageFilePath,\n })\n}\n"],"names":["deleteFile","bucket","client","storageFilePath","deleteObject","Bucket","Key"],"mappings":"AAQA,OAAO,eAAeA,WAAW,EAAEC,MAAM,EAAEC,MAAM,EAAEC,eAAe,EAAc;IAC9E,MAAMD,OAAOE,YAAY,CAAC;QACxBC,QAAQJ;QACRK,KAAKH;IACP;AACF"}
|
package/dist/generateURL.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { buildStoragePathData } from '@payloadcms/plugin-cloud-storage/utilities';
|
|
2
2
|
import path from 'path';
|
|
3
3
|
export function generateURL({ bucket, collectionPrefix = '', endpoint, filename, prefix, useCompositePrefixes = false }) {
|
|
4
|
-
const {
|
|
4
|
+
const { storageFilePath } = buildStoragePathData({
|
|
5
5
|
collectionPrefix,
|
|
6
6
|
docPrefix: prefix,
|
|
7
7
|
filename,
|
|
8
8
|
useCompositePrefixes
|
|
9
9
|
});
|
|
10
|
-
const dir = path.posix.dirname(
|
|
11
|
-
const encodedFilename = encodeURIComponent(path.posix.basename(
|
|
10
|
+
const dir = path.posix.dirname(storageFilePath);
|
|
11
|
+
const encodedFilename = encodeURIComponent(path.posix.basename(storageFilePath));
|
|
12
12
|
const fileKey = dir === '.' ? encodedFilename : path.posix.join(dir, encodedFilename);
|
|
13
13
|
const stringifiedEndpoint = typeof endpoint === 'string' ? endpoint : endpoint?.toString();
|
|
14
14
|
return `${stringifiedEndpoint}/${bucket}/${fileKey}`;
|
package/dist/generateURL.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/generateURL.ts"],"sourcesContent":["import type * as AWS from '@aws-sdk/client-s3'\n\nimport {
|
|
1
|
+
{"version":3,"sources":["../src/generateURL.ts"],"sourcesContent":["import type * as AWS from '@aws-sdk/client-s3'\n\nimport { buildStoragePathData } from '@payloadcms/plugin-cloud-storage/utilities'\nimport path from 'path'\n\ninterface GenerateURLArgs {\n bucket: string\n collectionPrefix?: string\n endpoint?: AWS.S3ClientConfig['endpoint']\n filename: string\n prefix: string\n useCompositePrefixes?: boolean\n}\n\nexport function generateURL({\n bucket,\n collectionPrefix = '',\n endpoint,\n filename,\n prefix,\n useCompositePrefixes = false,\n}: GenerateURLArgs): string {\n const { storageFilePath } = buildStoragePathData({\n collectionPrefix,\n docPrefix: prefix,\n filename,\n useCompositePrefixes,\n })\n const dir = path.posix.dirname(storageFilePath)\n const encodedFilename = encodeURIComponent(path.posix.basename(storageFilePath))\n const fileKey = dir === '.' ? encodedFilename : path.posix.join(dir, encodedFilename)\n\n const stringifiedEndpoint = typeof endpoint === 'string' ? endpoint : endpoint?.toString()\n return `${stringifiedEndpoint}/${bucket}/${fileKey}`\n}\n"],"names":["buildStoragePathData","path","generateURL","bucket","collectionPrefix","endpoint","filename","prefix","useCompositePrefixes","storageFilePath","docPrefix","dir","posix","dirname","encodedFilename","encodeURIComponent","basename","fileKey","join","stringifiedEndpoint","toString"],"mappings":"AAEA,SAASA,oBAAoB,QAAQ,6CAA4C;AACjF,OAAOC,UAAU,OAAM;AAWvB,OAAO,SAASC,YAAY,EAC1BC,MAAM,EACNC,mBAAmB,EAAE,EACrBC,QAAQ,EACRC,QAAQ,EACRC,MAAM,EACNC,uBAAuB,KAAK,EACZ;IAChB,MAAM,EAAEC,eAAe,EAAE,GAAGT,qBAAqB;QAC/CI;QACAM,WAAWH;QACXD;QACAE;IACF;IACA,MAAMG,MAAMV,KAAKW,KAAK,CAACC,OAAO,CAACJ;IAC/B,MAAMK,kBAAkBC,mBAAmBd,KAAKW,KAAK,CAACI,QAAQ,CAACP;IAC/D,MAAMQ,UAAUN,QAAQ,MAAMG,kBAAkBb,KAAKW,KAAK,CAACM,IAAI,CAACP,KAAKG;IAErE,MAAMK,sBAAsB,OAAOd,aAAa,WAAWA,WAAWA,UAAUe;IAChF,OAAO,GAAGD,oBAAoB,CAAC,EAAEhB,OAAO,CAAC,EAAEc,SAAS;AACtD"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { S3 } from '@aws-sdk/client-s3';
|
|
2
|
+
import type { GenerateUploadInstructions, UploadInstructionsAccess } from 'payload';
|
|
3
|
+
interface Args {
|
|
4
|
+
access?: UploadInstructionsAccess;
|
|
5
|
+
acl?: 'private' | 'public-read';
|
|
6
|
+
bucket: string;
|
|
7
|
+
collectionPrefix: string;
|
|
8
|
+
getStorageClient: () => S3;
|
|
9
|
+
useCompositePrefixes?: boolean;
|
|
10
|
+
}
|
|
11
|
+
export declare const generateUploadInstructions: ({ access, acl, bucket, collectionPrefix, getStorageClient, useCompositePrefixes, }: Args) => GenerateUploadInstructions;
|
|
12
|
+
export {};
|
|
13
|
+
//# sourceMappingURL=generateUploadInstructions.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generateUploadInstructions.d.ts","sourceRoot":"","sources":["../src/generateUploadInstructions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,oBAAoB,CAAA;AAC5C,OAAO,KAAK,EAAE,0BAA0B,EAAE,wBAAwB,EAAE,MAAM,SAAS,CAAA;AAQnF,UAAU,IAAI;IACZ,MAAM,CAAC,EAAE,wBAAwB,CAAA;IACjC,GAAG,CAAC,EAAE,SAAS,GAAG,aAAa,CAAA;IAC/B,MAAM,EAAE,MAAM,CAAA;IACd,gBAAgB,EAAE,MAAM,CAAA;IACxB,gBAAgB,EAAE,MAAM,EAAE,CAAA;IAC1B,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B;AAED,eAAO,MAAM,0BAA0B,uFAOpC,IAAI,KAAG,0BA4ET,CAAA"}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { PutObjectCommand } from '@aws-sdk/client-s3';
|
|
2
|
+
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
|
|
3
|
+
import { resolveSignedURLKey } from '@payloadcms/plugin-cloud-storage/utilities';
|
|
4
|
+
import { Forbidden } from 'payload';
|
|
5
|
+
import { assertClientUploadAllowed } from 'payload/internal';
|
|
6
|
+
export const generateUploadInstructions = ({ access, acl, bucket, collectionPrefix, getStorageClient, useCompositePrefixes = false })=>{
|
|
7
|
+
return async ({ collectionSlug, docPrefix, filename, filesize, mimeType, overrideAccess, req })=>{
|
|
8
|
+
if (!overrideAccess && (access ? !await access({
|
|
9
|
+
collectionSlug,
|
|
10
|
+
req
|
|
11
|
+
}) : !req.user)) {
|
|
12
|
+
throw new Forbidden(req.t);
|
|
13
|
+
}
|
|
14
|
+
assertClientUploadAllowed({
|
|
15
|
+
collection: req.payload.collections[collectionSlug]?.config,
|
|
16
|
+
filename,
|
|
17
|
+
mimeType
|
|
18
|
+
});
|
|
19
|
+
let filesizeLimit = req.payload.config.upload.limits?.fileSize;
|
|
20
|
+
if (filesizeLimit === Infinity) {
|
|
21
|
+
filesizeLimit = undefined;
|
|
22
|
+
}
|
|
23
|
+
const { sanitizedFilename, storageFilePath, uploadReference } = await resolveSignedURLKey({
|
|
24
|
+
collectionPrefix,
|
|
25
|
+
collectionSlug,
|
|
26
|
+
docPrefix,
|
|
27
|
+
filename,
|
|
28
|
+
req,
|
|
29
|
+
useCompositePrefixes
|
|
30
|
+
});
|
|
31
|
+
const signableHeaders = new Set([
|
|
32
|
+
'content-type'
|
|
33
|
+
]);
|
|
34
|
+
if (filesizeLimit) {
|
|
35
|
+
// Still force S3 to validate
|
|
36
|
+
signableHeaders.add('content-length');
|
|
37
|
+
}
|
|
38
|
+
const url = await getSignedUrl(getStorageClient(), new PutObjectCommand({
|
|
39
|
+
ACL: acl,
|
|
40
|
+
Bucket: bucket,
|
|
41
|
+
ContentLength: filesizeLimit ? Math.min(filesize, filesizeLimit) : undefined,
|
|
42
|
+
ContentType: mimeType,
|
|
43
|
+
IfNoneMatch: '*',
|
|
44
|
+
Key: storageFilePath
|
|
45
|
+
}), {
|
|
46
|
+
expiresIn: 600,
|
|
47
|
+
signableHeaders
|
|
48
|
+
});
|
|
49
|
+
return {
|
|
50
|
+
type: 'http',
|
|
51
|
+
file: {
|
|
52
|
+
filename: sanitizedFilename,
|
|
53
|
+
mimeType,
|
|
54
|
+
size: filesize,
|
|
55
|
+
uploadReference
|
|
56
|
+
},
|
|
57
|
+
request: {
|
|
58
|
+
headers: {
|
|
59
|
+
'Content-Length': String(filesize),
|
|
60
|
+
'Content-Type': mimeType,
|
|
61
|
+
'If-None-Match': '*'
|
|
62
|
+
},
|
|
63
|
+
method: 'PUT',
|
|
64
|
+
url
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
//# sourceMappingURL=generateUploadInstructions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/generateUploadInstructions.ts"],"sourcesContent":["import type { S3 } from '@aws-sdk/client-s3'\nimport type { GenerateUploadInstructions, UploadInstructionsAccess } from 'payload'\n\nimport { PutObjectCommand } from '@aws-sdk/client-s3'\nimport { getSignedUrl } from '@aws-sdk/s3-request-presigner'\nimport { resolveSignedURLKey } from '@payloadcms/plugin-cloud-storage/utilities'\nimport { Forbidden } from 'payload'\nimport { assertClientUploadAllowed } from 'payload/internal'\n\ninterface Args {\n access?: UploadInstructionsAccess\n acl?: 'private' | 'public-read'\n bucket: string\n collectionPrefix: string\n getStorageClient: () => S3\n useCompositePrefixes?: boolean\n}\n\nexport const generateUploadInstructions = ({\n access,\n acl,\n bucket,\n collectionPrefix,\n getStorageClient,\n useCompositePrefixes = false,\n}: Args): GenerateUploadInstructions => {\n return async ({\n collectionSlug,\n docPrefix,\n filename,\n filesize,\n mimeType,\n overrideAccess,\n req,\n }) => {\n if (!overrideAccess && (access ? !(await access({ collectionSlug, req })) : !req.user)) {\n throw new Forbidden(req.t)\n }\n\n assertClientUploadAllowed({\n collection: req.payload.collections[collectionSlug]?.config,\n filename,\n mimeType,\n })\n let filesizeLimit = req.payload.config.upload.limits?.fileSize\n\n if (filesizeLimit === Infinity) {\n filesizeLimit = undefined\n }\n\n const { sanitizedFilename, storageFilePath, uploadReference } = await resolveSignedURLKey({\n collectionPrefix,\n collectionSlug,\n docPrefix,\n filename,\n req,\n useCompositePrefixes,\n })\n\n const signableHeaders = new Set<string>(['content-type'])\n\n if (filesizeLimit) {\n // Still force S3 to validate\n signableHeaders.add('content-length')\n }\n\n const url = await getSignedUrl(\n getStorageClient(),\n new PutObjectCommand({\n ACL: acl,\n Bucket: bucket,\n ContentLength: filesizeLimit ? Math.min(filesize, filesizeLimit) : undefined,\n ContentType: mimeType,\n IfNoneMatch: '*',\n Key: storageFilePath,\n }),\n {\n expiresIn: 600,\n signableHeaders,\n },\n )\n\n return {\n type: 'http',\n file: {\n filename: sanitizedFilename,\n mimeType,\n size: filesize,\n uploadReference,\n },\n request: {\n headers: {\n 'Content-Length': String(filesize),\n 'Content-Type': mimeType,\n 'If-None-Match': '*',\n },\n method: 'PUT',\n url,\n },\n }\n }\n}\n"],"names":["PutObjectCommand","getSignedUrl","resolveSignedURLKey","Forbidden","assertClientUploadAllowed","generateUploadInstructions","access","acl","bucket","collectionPrefix","getStorageClient","useCompositePrefixes","collectionSlug","docPrefix","filename","filesize","mimeType","overrideAccess","req","user","t","collection","payload","collections","config","filesizeLimit","upload","limits","fileSize","Infinity","undefined","sanitizedFilename","storageFilePath","uploadReference","signableHeaders","Set","add","url","ACL","Bucket","ContentLength","Math","min","ContentType","IfNoneMatch","Key","expiresIn","type","file","size","request","headers","String","method"],"mappings":"AAGA,SAASA,gBAAgB,QAAQ,qBAAoB;AACrD,SAASC,YAAY,QAAQ,gCAA+B;AAC5D,SAASC,mBAAmB,QAAQ,6CAA4C;AAChF,SAASC,SAAS,QAAQ,UAAS;AACnC,SAASC,yBAAyB,QAAQ,mBAAkB;AAW5D,OAAO,MAAMC,6BAA6B,CAAC,EACzCC,MAAM,EACNC,GAAG,EACHC,MAAM,EACNC,gBAAgB,EAChBC,gBAAgB,EAChBC,uBAAuB,KAAK,EACvB;IACL,OAAO,OAAO,EACZC,cAAc,EACdC,SAAS,EACTC,QAAQ,EACRC,QAAQ,EACRC,QAAQ,EACRC,cAAc,EACdC,GAAG,EACJ;QACC,IAAI,CAACD,kBAAmBX,CAAAA,SAAS,CAAE,MAAMA,OAAO;YAAEM;YAAgBM;QAAI,KAAM,CAACA,IAAIC,IAAI,AAAD,GAAI;YACtF,MAAM,IAAIhB,UAAUe,IAAIE,CAAC;QAC3B;QAEAhB,0BAA0B;YACxBiB,YAAYH,IAAII,OAAO,CAACC,WAAW,CAACX,eAAe,EAAEY;YACrDV;YACAE;QACF;QACA,IAAIS,gBAAgBP,IAAII,OAAO,CAACE,MAAM,CAACE,MAAM,CAACC,MAAM,EAAEC;QAEtD,IAAIH,kBAAkBI,UAAU;YAC9BJ,gBAAgBK;QAClB;QAEA,MAAM,EAAEC,iBAAiB,EAAEC,eAAe,EAAEC,eAAe,EAAE,GAAG,MAAM/B,oBAAoB;YACxFO;YACAG;YACAC;YACAC;YACAI;YACAP;QACF;QAEA,MAAMuB,kBAAkB,IAAIC,IAAY;YAAC;SAAe;QAExD,IAAIV,eAAe;YACjB,6BAA6B;YAC7BS,gBAAgBE,GAAG,CAAC;QACtB;QAEA,MAAMC,MAAM,MAAMpC,aAChBS,oBACA,IAAIV,iBAAiB;YACnBsC,KAAK/B;YACLgC,QAAQ/B;YACRgC,eAAef,gBAAgBgB,KAAKC,GAAG,CAAC3B,UAAUU,iBAAiBK;YACnEa,aAAa3B;YACb4B,aAAa;YACbC,KAAKb;QACP,IACA;YACEc,WAAW;YACXZ;QACF;QAGF,OAAO;YACLa,MAAM;YACNC,MAAM;gBACJlC,UAAUiB;gBACVf;gBACAiC,MAAMlC;gBACNkB;YACF;YACAiB,SAAS;gBACPC,SAAS;oBACP,kBAAkBC,OAAOrC;oBACzB,gBAAgBC;oBAChB,iBAAiB;gBACnB;gBACAqC,QAAQ;gBACRhB;YACF;QACF;IACF;AACF,EAAC"}
|
package/dist/getFile.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type * as AWS from '@aws-sdk/client-s3';
|
|
2
|
-
import type { CollectionConfig, PayloadRequest } from 'payload';
|
|
2
|
+
import type { CollectionConfig, PayloadRequest, TypeWithID } from 'payload';
|
|
3
3
|
export type SignedDownloadsConfig = {
|
|
4
4
|
/** @default 7200 */
|
|
5
5
|
expiresIn?: number;
|
|
@@ -12,16 +12,16 @@ export type SignedDownloadsConfig = {
|
|
|
12
12
|
interface GetFileArgs {
|
|
13
13
|
bucket: string;
|
|
14
14
|
client: AWS.S3;
|
|
15
|
-
clientUploadContext?: unknown;
|
|
16
15
|
collection: CollectionConfig;
|
|
17
16
|
collectionPrefix?: string;
|
|
17
|
+
doc?: TypeWithID;
|
|
18
18
|
filename: string;
|
|
19
19
|
incomingHeaders?: Headers;
|
|
20
|
-
prefixQueryParam?: string;
|
|
21
20
|
req: PayloadRequest;
|
|
22
21
|
signedDownloads: SignedDownloadsConfig;
|
|
22
|
+
uploadReference?: unknown;
|
|
23
23
|
useCompositePrefixes?: boolean;
|
|
24
24
|
}
|
|
25
|
-
export declare function getFile({ bucket, client,
|
|
25
|
+
export declare function getFile({ bucket, client, collection, collectionPrefix, doc, filename, incomingHeaders, req, signedDownloads, uploadReference, useCompositePrefixes, }: GetFileArgs): Promise<Response>;
|
|
26
26
|
export {};
|
|
27
27
|
//# sourceMappingURL=getFile.d.ts.map
|
package/dist/getFile.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getFile.d.ts","sourceRoot":"","sources":["../src/getFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,GAAG,MAAM,oBAAoB,CAAA;AAC9C,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"getFile.d.ts","sourceRoot":"","sources":["../src/getFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,GAAG,MAAM,oBAAoB,CAAA;AAC9C,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAW3E,MAAM,MAAM,qBAAqB,GAC7B;IACE,oBAAoB;IACpB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,kBAAkB,CAAC,CAAC,IAAI,EAAE;QACxB,UAAU,EAAE,gBAAgB,CAAA;QAC5B,QAAQ,EAAE,MAAM,CAAA;QAChB,GAAG,EAAE,cAAc,CAAA;KACpB,GAAG,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;CAC/B,GACD,OAAO,CAAA;AAEX,UAAU,WAAW;IACnB,MAAM,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,GAAG,CAAC,EAAE,CAAA;IACd,UAAU,EAAE,gBAAgB,CAAA;IAC5B,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,GAAG,CAAC,EAAE,UAAU,CAAA;IAChB,QAAQ,EAAE,MAAM,CAAA;IAChB,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,GAAG,EAAE,cAAc,CAAA;IACnB,eAAe,EAAE,qBAAqB,CAAA;IACtC,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B;AA8BD,wBAAsB,OAAO,CAAC,EAC5B,MAAM,EACN,MAAM,EACN,UAAU,EACV,gBAAqB,EACrB,GAAG,EACH,QAAQ,EACR,eAAe,EACf,GAAG,EACH,eAAe,EACf,eAAe,EACf,oBAA4B,GAC7B,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC,CAgKjC"}
|
package/dist/getFile.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { GetObjectCommand } from '@aws-sdk/client-s3';
|
|
2
2
|
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
|
|
3
|
-
import { getFilePrefix as getDocPrefix
|
|
4
|
-
import { getRangeRequestInfo } from 'payload/internal';
|
|
3
|
+
import { buildStoragePathData, getFilePrefix as getDocPrefix } from '@payloadcms/plugin-cloud-storage/utilities';
|
|
4
|
+
import { getRangeRequestInfo, isXmlMimeType, uploadContentSecurityPolicy } from 'payload/internal';
|
|
5
5
|
const isNodeReadableStream = (body)=>{
|
|
6
6
|
return typeof body === 'object' && body !== null && 'pipe' in body && typeof body.pipe === 'function' && 'destroy' in body && typeof body.destroy === 'function';
|
|
7
7
|
};
|
|
@@ -14,7 +14,7 @@ const abortRequestAndDestroyStream = ({ abortController, object })=>{
|
|
|
14
14
|
object.Body.destroy();
|
|
15
15
|
}
|
|
16
16
|
};
|
|
17
|
-
export async function getFile({ bucket, client,
|
|
17
|
+
export async function getFile({ bucket, client, collection, collectionPrefix = '', doc, filename, incomingHeaders, req, signedDownloads, uploadReference, useCompositePrefixes = false }) {
|
|
18
18
|
let object = undefined;
|
|
19
19
|
let streamed = false;
|
|
20
20
|
const abortController = new AbortController();
|
|
@@ -28,19 +28,21 @@ export async function getFile({ bucket, client, clientUploadContext, collection,
|
|
|
28
28
|
}
|
|
29
29
|
try {
|
|
30
30
|
const docPrefix = await getDocPrefix({
|
|
31
|
-
clientUploadContext,
|
|
32
31
|
collection,
|
|
32
|
+
collectionPrefix,
|
|
33
|
+
doc,
|
|
33
34
|
filename,
|
|
34
|
-
|
|
35
|
-
|
|
35
|
+
req,
|
|
36
|
+
uploadReference,
|
|
37
|
+
useCompositePrefixes
|
|
36
38
|
});
|
|
37
|
-
const {
|
|
39
|
+
const { storageFilePath } = buildStoragePathData({
|
|
38
40
|
collectionPrefix,
|
|
39
41
|
docPrefix,
|
|
40
42
|
filename,
|
|
41
43
|
useCompositePrefixes
|
|
42
44
|
});
|
|
43
|
-
if (signedDownloads && !
|
|
45
|
+
if (signedDownloads && !uploadReference) {
|
|
44
46
|
let useSignedURL = true;
|
|
45
47
|
if (typeof signedDownloads === 'object' && typeof signedDownloads.shouldUseSignedURL === 'function') {
|
|
46
48
|
useSignedURL = await signedDownloads.shouldUseSignedURL({
|
|
@@ -52,7 +54,7 @@ export async function getFile({ bucket, client, clientUploadContext, collection,
|
|
|
52
54
|
if (useSignedURL) {
|
|
53
55
|
const command = new GetObjectCommand({
|
|
54
56
|
Bucket: bucket,
|
|
55
|
-
Key:
|
|
57
|
+
Key: storageFilePath
|
|
56
58
|
});
|
|
57
59
|
const signedUrl = await getSignedUrl(client, command, typeof signedDownloads === 'object' ? signedDownloads : {
|
|
58
60
|
expiresIn: 7200
|
|
@@ -63,7 +65,7 @@ export async function getFile({ bucket, client, clientUploadContext, collection,
|
|
|
63
65
|
// Get file size first for range validation and to set Content-Length header before streaming
|
|
64
66
|
const headObject = await client.headObject({
|
|
65
67
|
Bucket: bucket,
|
|
66
|
-
Key:
|
|
68
|
+
Key: storageFilePath
|
|
67
69
|
});
|
|
68
70
|
const fileSize = headObject.ContentLength;
|
|
69
71
|
if (!fileSize) {
|
|
@@ -93,9 +95,9 @@ export async function getFile({ bucket, client, clientUploadContext, collection,
|
|
|
93
95
|
if (headObject.ETag) {
|
|
94
96
|
headers.append('ETag', headObject.ETag);
|
|
95
97
|
}
|
|
96
|
-
//
|
|
97
|
-
if (headObject.ContentType
|
|
98
|
-
headers.append('Content-Security-Policy',
|
|
98
|
+
// Apply a restrictive policy to XML-family responses served through Payload.
|
|
99
|
+
if (isXmlMimeType(headObject.ContentType)) {
|
|
100
|
+
headers.append('Content-Security-Policy', uploadContentSecurityPolicy);
|
|
99
101
|
}
|
|
100
102
|
const etagFromHeaders = req.headers.get('etag') || req.headers.get('if-none-match');
|
|
101
103
|
const objectEtag = headObject.ETag;
|
|
@@ -112,7 +114,7 @@ export async function getFile({ bucket, client, clientUploadContext, collection,
|
|
|
112
114
|
}
|
|
113
115
|
object = await client.getObject({
|
|
114
116
|
Bucket: bucket,
|
|
115
|
-
Key:
|
|
117
|
+
Key: storageFilePath,
|
|
116
118
|
Range: rangeForS3
|
|
117
119
|
}, {
|
|
118
120
|
abortSignal: abortController.signal
|
|
@@ -125,7 +127,7 @@ export async function getFile({ bucket, client, clientUploadContext, collection,
|
|
|
125
127
|
}
|
|
126
128
|
if (!isNodeReadableStream(object.Body)) {
|
|
127
129
|
req.payload.logger.error({
|
|
128
|
-
key,
|
|
130
|
+
key: storageFilePath,
|
|
129
131
|
msg: 'S3 object body is not a readable stream'
|
|
130
132
|
});
|
|
131
133
|
return new Response('Internal Server Error', {
|
|
@@ -136,7 +138,7 @@ export async function getFile({ bucket, client, clientUploadContext, collection,
|
|
|
136
138
|
stream.on('error', (err)=>{
|
|
137
139
|
req.payload.logger.error({
|
|
138
140
|
err,
|
|
139
|
-
key,
|
|
141
|
+
key: storageFilePath,
|
|
140
142
|
msg: 'Error while streaming S3 object (aborting)'
|
|
141
143
|
});
|
|
142
144
|
abortRequestAndDestroyStream({
|
package/dist/getFile.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/getFile.ts"],"sourcesContent":["import type * as AWS from '@aws-sdk/client-s3'\nimport type { CollectionConfig, PayloadRequest } from 'payload'\nimport type { Readable } from 'stream'\n\nimport { GetObjectCommand } from '@aws-sdk/client-s3'\nimport { getSignedUrl } from '@aws-sdk/s3-request-presigner'\nimport {\n getFilePrefix as getDocPrefix,\n getFileKey,\n} from '@payloadcms/plugin-cloud-storage/utilities'\nimport { getRangeRequestInfo } from 'payload/internal'\n\nexport type SignedDownloadsConfig =\n | {\n /** @default 7200 */\n expiresIn?: number\n shouldUseSignedURL?(args: {\n collection: CollectionConfig\n filename: string\n req: PayloadRequest\n }): boolean | Promise<boolean>\n }\n | boolean\n\ninterface GetFileArgs {\n bucket: string\n client: AWS.S3\n clientUploadContext?: unknown\n collection: CollectionConfig\n collectionPrefix?: string\n filename: string\n incomingHeaders?: Headers\n prefixQueryParam?: string\n req: PayloadRequest\n signedDownloads: SignedDownloadsConfig\n useCompositePrefixes?: boolean\n}\n\nconst isNodeReadableStream = (body: AWS.GetObjectOutput['Body']): body is Readable => {\n return (\n typeof body === 'object' &&\n body !== null &&\n 'pipe' in body &&\n typeof body.pipe === 'function' &&\n 'destroy' in body &&\n typeof body.destroy === 'function'\n )\n}\n\nconst abortRequestAndDestroyStream = ({\n abortController,\n object,\n}: {\n abortController: AbortController\n object?: AWS.GetObjectOutput\n}) => {\n try {\n abortController.abort()\n } catch {\n /* noop */\n }\n if (object?.Body && isNodeReadableStream(object.Body)) {\n object.Body.destroy()\n }\n}\n\nexport async function getFile({\n bucket,\n client,\n clientUploadContext,\n collection,\n collectionPrefix = '',\n filename,\n incomingHeaders,\n prefixQueryParam,\n req,\n signedDownloads,\n useCompositePrefixes = false,\n}: GetFileArgs): Promise<Response> {\n let object: AWS.GetObjectOutput | undefined = undefined\n let streamed = false\n\n const abortController = new AbortController()\n if (req.signal) {\n req.signal.addEventListener('abort', () => {\n abortRequestAndDestroyStream({ abortController, object })\n })\n }\n\n try {\n const docPrefix = await getDocPrefix({\n clientUploadContext,\n collection,\n filename,\n prefixQueryParam,\n req,\n })\n\n const { fileKey: key } = getFileKey({\n collectionPrefix,\n docPrefix,\n filename,\n useCompositePrefixes,\n })\n\n if (signedDownloads && !clientUploadContext) {\n let useSignedURL = true\n if (\n typeof signedDownloads === 'object' &&\n typeof signedDownloads.shouldUseSignedURL === 'function'\n ) {\n useSignedURL = await signedDownloads.shouldUseSignedURL({ collection, filename, req })\n }\n\n if (useSignedURL) {\n const command = new GetObjectCommand({ Bucket: bucket, Key: key })\n const signedUrl = await getSignedUrl(\n client,\n command,\n typeof signedDownloads === 'object' ? signedDownloads : { expiresIn: 7200 },\n )\n return Response.redirect(signedUrl, 302)\n }\n }\n\n // Get file size first for range validation and to set Content-Length header before streaming\n const headObject = await client.headObject({\n Bucket: bucket,\n Key: key,\n })\n const fileSize = headObject.ContentLength\n\n if (!fileSize) {\n return new Response('Internal Server Error', { status: 500 })\n }\n\n // Handle range request\n const rangeHeader = req.headers.get('range')\n const rangeResult = getRangeRequestInfo({ fileSize, rangeHeader })\n\n if (rangeResult.type === 'invalid') {\n return new Response(null, {\n headers: new Headers(rangeResult.headers),\n status: rangeResult.status,\n })\n }\n\n const rangeForS3 =\n rangeResult.type === 'partial'\n ? `bytes=${rangeResult.rangeStart}-${rangeResult.rangeEnd}`\n : undefined\n\n let headers = new Headers(incomingHeaders)\n\n // Add range-related headers from the result\n for (const [headerKey, value] of Object.entries(rangeResult.headers)) {\n headers.append(headerKey, value)\n }\n\n headers.append('Content-Type', String(headObject.ContentType))\n if (headObject.ETag) {\n headers.append('ETag', headObject.ETag)\n }\n\n // Add Content-Security-Policy header for SVG files to prevent executable code\n if (headObject.ContentType === 'image/svg+xml') {\n headers.append('Content-Security-Policy', \"script-src 'none'\")\n }\n\n const etagFromHeaders = req.headers.get('etag') || req.headers.get('if-none-match')\n const objectEtag = headObject.ETag\n\n if (\n collection.upload &&\n typeof collection.upload === 'object' &&\n typeof collection.upload.modifyResponseHeaders === 'function'\n ) {\n headers = collection.upload.modifyResponseHeaders({ headers }) || headers\n }\n\n if (etagFromHeaders && etagFromHeaders === objectEtag) {\n return new Response(null, {\n headers,\n status: 304,\n })\n }\n\n object = await client.getObject(\n {\n Bucket: bucket,\n Key: key,\n Range: rangeForS3,\n },\n { abortSignal: abortController.signal },\n )\n\n if (!object.Body) {\n return new Response(null, { status: 404, statusText: 'Not Found' })\n }\n\n if (!isNodeReadableStream(object.Body)) {\n req.payload.logger.error({\n key,\n msg: 'S3 object body is not a readable stream',\n })\n return new Response('Internal Server Error', { status: 500 })\n }\n\n const stream = object.Body\n stream.on('error', (err: Error) => {\n req.payload.logger.error({\n err,\n key,\n msg: 'Error while streaming S3 object (aborting)',\n })\n abortRequestAndDestroyStream({ abortController, object })\n })\n\n streamed = true\n return new Response(stream, { headers, status: rangeResult.status })\n } catch (err) {\n if (\n err &&\n typeof err === 'object' &&\n (('name' in err && (err.name === 'NoSuchKey' || err.name === 'NotFound')) ||\n ('httpStatusCode' in err && err.httpStatusCode === 404))\n ) {\n return new Response(null, { status: 404, statusText: 'Not Found' })\n }\n req.payload.logger.error(err)\n return new Response('Internal Server Error', { status: 500 })\n } finally {\n if (!streamed) {\n abortRequestAndDestroyStream({ abortController, object })\n }\n }\n}\n"],"names":["GetObjectCommand","getSignedUrl","getFilePrefix","getDocPrefix","getFileKey","getRangeRequestInfo","isNodeReadableStream","body","pipe","destroy","abortRequestAndDestroyStream","abortController","object","abort","Body","getFile","bucket","client","clientUploadContext","collection","collectionPrefix","filename","incomingHeaders","prefixQueryParam","req","signedDownloads","useCompositePrefixes","undefined","streamed","AbortController","signal","addEventListener","docPrefix","fileKey","key","useSignedURL","shouldUseSignedURL","command","Bucket","Key","signedUrl","expiresIn","Response","redirect","headObject","fileSize","ContentLength","status","rangeHeader","headers","get","rangeResult","type","Headers","rangeForS3","rangeStart","rangeEnd","headerKey","value","Object","entries","append","String","ContentType","ETag","etagFromHeaders","objectEtag","upload","modifyResponseHeaders","getObject","Range","abortSignal","statusText","payload","logger","error","msg","stream","on","err","name","httpStatusCode"],"mappings":"AAIA,SAASA,gBAAgB,QAAQ,qBAAoB;AACrD,SAASC,YAAY,QAAQ,gCAA+B;AAC5D,SACEC,iBAAiBC,YAAY,EAC7BC,UAAU,QACL,6CAA4C;AACnD,SAASC,mBAAmB,QAAQ,mBAAkB;AA4BtD,MAAMC,uBAAuB,CAACC;IAC5B,OACE,OAAOA,SAAS,YAChBA,SAAS,QACT,UAAUA,QACV,OAAOA,KAAKC,IAAI,KAAK,cACrB,aAAaD,QACb,OAAOA,KAAKE,OAAO,KAAK;AAE5B;AAEA,MAAMC,+BAA+B,CAAC,EACpCC,eAAe,EACfC,MAAM,EAIP;IACC,IAAI;QACFD,gBAAgBE,KAAK;IACvB,EAAE,OAAM;IACN,QAAQ,GACV;IACA,IAAID,QAAQE,QAAQR,qBAAqBM,OAAOE,IAAI,GAAG;QACrDF,OAAOE,IAAI,CAACL,OAAO;IACrB;AACF;AAEA,OAAO,eAAeM,QAAQ,EAC5BC,MAAM,EACNC,MAAM,EACNC,mBAAmB,EACnBC,UAAU,EACVC,mBAAmB,EAAE,EACrBC,QAAQ,EACRC,eAAe,EACfC,gBAAgB,EAChBC,GAAG,EACHC,eAAe,EACfC,uBAAuB,KAAK,EAChB;IACZ,IAAId,SAA0Ce;IAC9C,IAAIC,WAAW;IAEf,MAAMjB,kBAAkB,IAAIkB;IAC5B,IAAIL,IAAIM,MAAM,EAAE;QACdN,IAAIM,MAAM,CAACC,gBAAgB,CAAC,SAAS;YACnCrB,6BAA6B;gBAAEC;gBAAiBC;YAAO;QACzD;IACF;IAEA,IAAI;QACF,MAAMoB,YAAY,MAAM7B,aAAa;YACnCe;YACAC;YACAE;YACAE;YACAC;QACF;QAEA,MAAM,EAAES,SAASC,GAAG,EAAE,GAAG9B,WAAW;YAClCgB;YACAY;YACAX;YACAK;QACF;QAEA,IAAID,mBAAmB,CAACP,qBAAqB;YAC3C,IAAIiB,eAAe;YAC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AAC;gBACvBI;gBACA7C;gBACA0C,KAAK;YACP;YACAlE,6BAA6B;gBAAEC;gBAAiBC;YAAO;QACzD;QAEAgB,WAAW;QACX,OAAO,IAAIc,SAASmC,QAAQ;YAAE5B;YAASF,QAAQI,YAAYJ,MAAM;QAAC;IACpE,EAAE,OAAOgC,KAAK;QACZ,IACEA,OACA,OAAOA,QAAQ,YACd,CAAA,AAAC,UAAUA,OAAQA,CAAAA,IAAIC,IAAI,KAAK,eAAeD,IAAIC,IAAI,KAAK,UAAS,KACnE,oBAAoBD,OAAOA,IAAIE,cAAc,KAAK,GAAG,GACxD;YACA,OAAO,IAAIvC,SAAS,MAAM;gBAAEK,QAAQ;gBAAKyB,YAAY;YAAY;QACnE;QACAhD,IAAIiD,OAAO,CAACC,MAAM,CAACC,KAAK,CAACI;QACzB,OAAO,IAAIrC,SAAS,yBAAyB;YAAEK,QAAQ;QAAI;IAC7D,SAAU;QACR,IAAI,CAACnB,UAAU;YACblB,6BAA6B;gBAAEC;gBAAiBC;YAAO;QACzD;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../src/getFile.ts"],"sourcesContent":["import type * as AWS from '@aws-sdk/client-s3'\nimport type { CollectionConfig, PayloadRequest, TypeWithID } from 'payload'\nimport type { Readable } from 'stream'\n\nimport { GetObjectCommand } from '@aws-sdk/client-s3'\nimport { getSignedUrl } from '@aws-sdk/s3-request-presigner'\nimport {\n buildStoragePathData,\n getFilePrefix as getDocPrefix,\n} from '@payloadcms/plugin-cloud-storage/utilities'\nimport { getRangeRequestInfo, isXmlMimeType, uploadContentSecurityPolicy } from 'payload/internal'\n\nexport type SignedDownloadsConfig =\n | {\n /** @default 7200 */\n expiresIn?: number\n shouldUseSignedURL?(args: {\n collection: CollectionConfig\n filename: string\n req: PayloadRequest\n }): boolean | Promise<boolean>\n }\n | boolean\n\ninterface GetFileArgs {\n bucket: string\n client: AWS.S3\n collection: CollectionConfig\n collectionPrefix?: string\n doc?: TypeWithID\n filename: string\n incomingHeaders?: Headers\n req: PayloadRequest\n signedDownloads: SignedDownloadsConfig\n uploadReference?: unknown\n useCompositePrefixes?: boolean\n}\n\nconst isNodeReadableStream = (body: AWS.GetObjectOutput['Body']): body is Readable => {\n return (\n typeof body === 'object' &&\n body !== null &&\n 'pipe' in body &&\n typeof body.pipe === 'function' &&\n 'destroy' in body &&\n typeof body.destroy === 'function'\n )\n}\n\nconst abortRequestAndDestroyStream = ({\n abortController,\n object,\n}: {\n abortController: AbortController\n object?: AWS.GetObjectOutput\n}) => {\n try {\n abortController.abort()\n } catch {\n /* noop */\n }\n if (object?.Body && isNodeReadableStream(object.Body)) {\n object.Body.destroy()\n }\n}\n\nexport async function getFile({\n bucket,\n client,\n collection,\n collectionPrefix = '',\n doc,\n filename,\n incomingHeaders,\n req,\n signedDownloads,\n uploadReference,\n useCompositePrefixes = false,\n}: GetFileArgs): Promise<Response> {\n let object: AWS.GetObjectOutput | undefined = undefined\n let streamed = false\n\n const abortController = new AbortController()\n if (req.signal) {\n req.signal.addEventListener('abort', () => {\n abortRequestAndDestroyStream({ abortController, object })\n })\n }\n\n try {\n const docPrefix = await getDocPrefix({\n collection,\n collectionPrefix,\n doc,\n filename,\n req,\n uploadReference,\n useCompositePrefixes,\n })\n\n const { storageFilePath } = buildStoragePathData({\n collectionPrefix,\n docPrefix,\n filename,\n useCompositePrefixes,\n })\n\n if (signedDownloads && !uploadReference) {\n let useSignedURL = true\n if (\n typeof signedDownloads === 'object' &&\n typeof signedDownloads.shouldUseSignedURL === 'function'\n ) {\n useSignedURL = await signedDownloads.shouldUseSignedURL({ collection, filename, req })\n }\n\n if (useSignedURL) {\n const command = new GetObjectCommand({ Bucket: bucket, Key: storageFilePath })\n const signedUrl = await getSignedUrl(\n client,\n command,\n typeof signedDownloads === 'object' ? signedDownloads : { expiresIn: 7200 },\n )\n return Response.redirect(signedUrl, 302)\n }\n }\n\n // Get file size first for range validation and to set Content-Length header before streaming\n const headObject = await client.headObject({\n Bucket: bucket,\n Key: storageFilePath,\n })\n const fileSize = headObject.ContentLength\n\n if (!fileSize) {\n return new Response('Internal Server Error', { status: 500 })\n }\n\n // Handle range request\n const rangeHeader = req.headers.get('range')\n const rangeResult = getRangeRequestInfo({ fileSize, rangeHeader })\n\n if (rangeResult.type === 'invalid') {\n return new Response(null, {\n headers: new Headers(rangeResult.headers),\n status: rangeResult.status,\n })\n }\n\n const rangeForS3 =\n rangeResult.type === 'partial'\n ? `bytes=${rangeResult.rangeStart}-${rangeResult.rangeEnd}`\n : undefined\n\n let headers = new Headers(incomingHeaders)\n\n // Add range-related headers from the result\n for (const [headerKey, value] of Object.entries(rangeResult.headers)) {\n headers.append(headerKey, value)\n }\n\n headers.append('Content-Type', String(headObject.ContentType))\n if (headObject.ETag) {\n headers.append('ETag', headObject.ETag)\n }\n\n // Apply a restrictive policy to XML-family responses served through Payload.\n if (isXmlMimeType(headObject.ContentType)) {\n headers.append('Content-Security-Policy', uploadContentSecurityPolicy)\n }\n\n const etagFromHeaders = req.headers.get('etag') || req.headers.get('if-none-match')\n const objectEtag = headObject.ETag\n\n if (\n collection.upload &&\n typeof collection.upload === 'object' &&\n typeof collection.upload.modifyResponseHeaders === 'function'\n ) {\n headers = collection.upload.modifyResponseHeaders({ headers }) || headers\n }\n\n if (etagFromHeaders && etagFromHeaders === objectEtag) {\n return new Response(null, {\n headers,\n status: 304,\n })\n }\n\n object = await client.getObject(\n {\n Bucket: bucket,\n Key: storageFilePath,\n Range: rangeForS3,\n },\n { abortSignal: abortController.signal },\n )\n\n if (!object.Body) {\n return new Response(null, { status: 404, statusText: 'Not Found' })\n }\n\n if (!isNodeReadableStream(object.Body)) {\n req.payload.logger.error({\n key: storageFilePath,\n msg: 'S3 object body is not a readable stream',\n })\n return new Response('Internal Server Error', { status: 500 })\n }\n\n const stream = object.Body\n stream.on('error', (err: Error) => {\n req.payload.logger.error({\n err,\n key: storageFilePath,\n msg: 'Error while streaming S3 object (aborting)',\n })\n abortRequestAndDestroyStream({ abortController, object })\n })\n\n streamed = true\n return new Response(stream, { headers, status: rangeResult.status })\n } catch (err) {\n if (\n err &&\n typeof err === 'object' &&\n (('name' in err && (err.name === 'NoSuchKey' || err.name === 'NotFound')) ||\n ('httpStatusCode' in err && err.httpStatusCode === 404))\n ) {\n return new Response(null, { status: 404, statusText: 'Not Found' })\n }\n req.payload.logger.error(err)\n return new Response('Internal Server Error', { status: 500 })\n } finally {\n if (!streamed) {\n abortRequestAndDestroyStream({ abortController, object })\n }\n }\n}\n"],"names":["GetObjectCommand","getSignedUrl","buildStoragePathData","getFilePrefix","getDocPrefix","getRangeRequestInfo","isXmlMimeType","uploadContentSecurityPolicy","isNodeReadableStream","body","pipe","destroy","abortRequestAndDestroyStream","abortController","object","abort","Body","getFile","bucket","client","collection","collectionPrefix","doc","filename","incomingHeaders","req","signedDownloads","uploadReference","useCompositePrefixes","undefined","streamed","AbortController","signal","addEventListener","docPrefix","storageFilePath","useSignedURL","shouldUseSignedURL","command","Bucket","Key","signedUrl","expiresIn","Response","redirect","headObject","fileSize","ContentLength","status","rangeHeader","headers","get","rangeResult","type","Headers","rangeForS3","rangeStart","rangeEnd","headerKey","value","Object","entries","append","String","ContentType","ETag","etagFromHeaders","objectEtag","upload","modifyResponseHeaders","getObject","Range","abortSignal","statusText","payload","logger","error","key","msg","stream","on","err","name","httpStatusCode"],"mappings":"AAIA,SAASA,gBAAgB,QAAQ,qBAAoB;AACrD,SAASC,YAAY,QAAQ,gCAA+B;AAC5D,SACEC,oBAAoB,EACpBC,iBAAiBC,YAAY,QACxB,6CAA4C;AACnD,SAASC,mBAAmB,EAAEC,aAAa,EAAEC,2BAA2B,QAAQ,mBAAkB;AA4BlG,MAAMC,uBAAuB,CAACC;IAC5B,OACE,OAAOA,SAAS,YAChBA,SAAS,QACT,UAAUA,QACV,OAAOA,KAAKC,IAAI,KAAK,cACrB,aAAaD,QACb,OAAOA,KAAKE,OAAO,KAAK;AAE5B;AAEA,MAAMC,+BAA+B,CAAC,EACpCC,eAAe,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;gBAAEK,QAAQ;gBAAKyB,YAAY;YAAY;QACnE;QACAhD,IAAIiD,OAAO,CAACC,MAAM,CAACC,KAAK,CAACK;QACzB,OAAO,IAAItC,SAAS,yBAAyB;YAAEK,QAAQ;QAAI;IAC7D,SAAU;QACR,IAAI,CAAClB,UAAU;YACblB,6BAA6B;gBAAEC;gBAAiBC;YAAO;QACzD;IACF;AACF"}
|
package/dist/index.d.ts
CHANGED
|
@@ -7,16 +7,6 @@ export type S3StorageOptions = {
|
|
|
7
7
|
* Access control list for uploaded files.
|
|
8
8
|
*/
|
|
9
9
|
acl?: 'private' | 'public-read';
|
|
10
|
-
/**
|
|
11
|
-
* When enabled, fields (like the prefix field) will always be inserted into
|
|
12
|
-
* the collection schema regardless of whether the plugin is enabled. This
|
|
13
|
-
* ensures a consistent schema across all environments.
|
|
14
|
-
*
|
|
15
|
-
* This will be enabled by default in Payload v4.
|
|
16
|
-
*
|
|
17
|
-
* @default false
|
|
18
|
-
*/
|
|
19
|
-
alwaysInsertFields?: boolean;
|
|
20
10
|
/**
|
|
21
11
|
* Bucket name to upload files to.
|
|
22
12
|
*
|
|
@@ -31,7 +21,7 @@ export type S3StorageOptions = {
|
|
|
31
21
|
*/
|
|
32
22
|
clientCacheKey?: string;
|
|
33
23
|
/**
|
|
34
|
-
*
|
|
24
|
+
* Upload directly to S3 instead of through Payload. You must allow CORS PUT requests from your website.
|
|
35
25
|
*/
|
|
36
26
|
clientUploads?: ClientUploadsConfig;
|
|
37
27
|
/**
|
|
@@ -64,14 +54,15 @@ export type S3StorageOptions = {
|
|
|
64
54
|
signedDownloads?: SignedDownloadsConfig;
|
|
65
55
|
/**
|
|
66
56
|
* When true, the collection-level prefix and document-level prefix are combined
|
|
67
|
-
* (compositional). When false (default), document prefix
|
|
68
|
-
* prefix
|
|
57
|
+
* (compositional). When false (default), a document prefix already within the
|
|
58
|
+
* collection prefix is used as-is for new uploads; otherwise it is nested beneath it.
|
|
59
|
+
* Existing files retain their stored prefixes for reads, URLs, and cleanup.
|
|
69
60
|
*
|
|
70
|
-
* Example:
|
|
71
|
-
* - collection prefix: `
|
|
72
|
-
* - document prefix: `
|
|
73
|
-
* - resulting prefix with useCompositePrefixes=true: `
|
|
74
|
-
* - resulting prefix with useCompositePrefixes=false: `
|
|
61
|
+
* Example with a document prefix already contained by the collection prefix:
|
|
62
|
+
* - collection prefix: `uploads/`
|
|
63
|
+
* - document prefix: `uploads/documents/`
|
|
64
|
+
* - resulting prefix with useCompositePrefixes=true: `uploads/uploads/documents/`
|
|
65
|
+
* - resulting prefix with useCompositePrefixes=false: `uploads/documents/`
|
|
75
66
|
*
|
|
76
67
|
* @default false
|
|
77
68
|
*/
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AACxD,OAAO,KAAK,EACV,mBAAmB,EAEnB,iBAAiB,EAClB,MAAM,wCAAwC,CAAA;AAE/C,OAAO,KAAK,EAAU,cAAc,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AACxD,OAAO,KAAK,EACV,mBAAmB,EAEnB,iBAAiB,EAClB,MAAM,wCAAwC,CAAA;AAE/C,OAAO,KAAK,EAAU,cAAc,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAK3E,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAA;AAIzD,MAAM,MAAM,gBAAgB,GAAG;IAC7B;;OAEG;IACH,GAAG,CAAC,EAAE,SAAS,GAAG,aAAa,CAAA;IAE/B;;;;OAIG;IAEH,MAAM,EAAE,MAAM,CAAA;IAEd;;;;;OAKG;IACH,cAAc,CAAC,EAAE,MAAM,CAAA;IAEvB;;OAEG;IACH,aAAa,CAAC,EAAE,mBAAmB,CAAA;IACnC;;OAEG;IACH,WAAW,EAAE,OAAO,CAClB,MAAM,CACJ,oBAAoB,EAClB,CAAC;QACC,eAAe,CAAC,EAAE,qBAAqB,CAAA;KACxC,GAAG,IAAI,CAAC,iBAAiB,EAAE,SAAS,CAAC,CAAC,GACvC,IAAI,CACP,CACF,CAAA;IACD;;;;OAIG;IACH,MAAM,EAAE,cAAc,CAAA;IAEtB;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAA;IAE7B;;;;OAIG;IACH,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB;;OAEG;IACH,eAAe,CAAC,EAAE,qBAAqB,CAAA;IACvC;;;;;;;;;;;;;OAaG;IACH,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B,CAAA;AAED,KAAK,gBAAgB,GAAG,CAAC,aAAa,EAAE,gBAAgB,KAAK,cAAc,CAAA;AAe3E,eAAO,MAAM,SAAS,EAAE,gBA8GtB,CAAA"}
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import { S3 } from '@aws-sdk/client-s3';
|
|
2
2
|
import { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage';
|
|
3
|
-
import { initClientUploads } from '@payloadcms/plugin-cloud-storage/utilities';
|
|
4
3
|
import { createS3Adapter } from './adapter.js';
|
|
5
|
-
import { getGenerateSignedURLHandler } from './generateSignedURL.js';
|
|
6
4
|
const s3Clients = new Map();
|
|
7
5
|
const defaultRequestHandlerOpts = {
|
|
8
6
|
httpAgent: {
|
|
@@ -30,40 +28,21 @@ export const s3Storage = (s3StorageOptions)=>({
|
|
|
30
28
|
}));
|
|
31
29
|
return s3Clients.get(cacheKey);
|
|
32
30
|
};
|
|
33
|
-
initClientUploads({
|
|
34
|
-
clientHandler: '@payloadcms/storage-s3/client#S3ClientUploadHandler',
|
|
35
|
-
collections: s3StorageOptions.collections,
|
|
36
|
-
config: incomingConfig,
|
|
37
|
-
enabled: !isPluginDisabled && Boolean(s3StorageOptions.clientUploads),
|
|
38
|
-
serverHandler: getGenerateSignedURLHandler({
|
|
39
|
-
access: typeof s3StorageOptions.clientUploads === 'object' ? s3StorageOptions.clientUploads.access : undefined,
|
|
40
|
-
acl: s3StorageOptions.acl,
|
|
41
|
-
bucket: s3StorageOptions.bucket,
|
|
42
|
-
collections: s3StorageOptions.collections,
|
|
43
|
-
getStorageClient,
|
|
44
|
-
useCompositePrefixes: s3StorageOptions.useCompositePrefixes
|
|
45
|
-
}),
|
|
46
|
-
serverHandlerPath: '/storage-s3-generate-signed-url'
|
|
47
|
-
});
|
|
48
31
|
if (isPluginDisabled) {
|
|
49
|
-
//
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
useCompositePrefixes: s3StorageOptions.useCompositePrefixes
|
|
64
|
-
})(incomingConfig);
|
|
65
|
-
}
|
|
66
|
-
return incomingConfig;
|
|
32
|
+
// Still call cloudStoragePlugin with adapter: null so fields (like prefix) are
|
|
33
|
+
// inserted into the schema, keeping it consistent across environments.
|
|
34
|
+
const collectionsWithoutAdapter = Object.entries(s3StorageOptions.collections).reduce((acc, [slug, collOptions])=>({
|
|
35
|
+
...acc,
|
|
36
|
+
[slug]: {
|
|
37
|
+
...collOptions === true ? {} : collOptions,
|
|
38
|
+
adapter: null
|
|
39
|
+
}
|
|
40
|
+
}), {});
|
|
41
|
+
return cloudStoragePlugin({
|
|
42
|
+
collections: collectionsWithoutAdapter,
|
|
43
|
+
enabled: false,
|
|
44
|
+
useCompositePrefixes: s3StorageOptions.useCompositePrefixes
|
|
45
|
+
})(incomingConfig);
|
|
67
46
|
}
|
|
68
47
|
// Determine signedDownloads for this collection
|
|
69
48
|
const resolveSignedDownloads = (slug)=>{
|
|
@@ -107,7 +86,6 @@ export const s3Storage = (s3StorageOptions)=>({
|
|
|
107
86
|
})
|
|
108
87
|
};
|
|
109
88
|
return cloudStoragePlugin({
|
|
110
|
-
alwaysInsertFields: s3StorageOptions.alwaysInsertFields,
|
|
111
89
|
collections: collectionsWithAdapter,
|
|
112
90
|
useCompositePrefixes: s3StorageOptions.useCompositePrefixes
|
|
113
91
|
})(config);
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { S3ClientConfig } from '@aws-sdk/client-s3'\nimport type {\n ClientUploadsConfig,\n PluginOptions as CloudStoragePluginOptions,\n CollectionOptions,\n} from '@payloadcms/plugin-cloud-storage/types'\nimport type { NodeHttpHandlerOptions } from '@smithy/node-http-handler'\nimport type { Config, StorageAdapter, UploadCollectionSlug } from 'payload'\n\nimport { S3 } from '@aws-sdk/client-s3'\nimport { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage'\nimport { initClientUploads } from '@payloadcms/plugin-cloud-storage/utilities'\n\nimport type { SignedDownloadsConfig } from './getFile.js'\n\nimport { createS3Adapter } from './adapter.js'\nimport { getGenerateSignedURLHandler } from './generateSignedURL.js'\n\nexport type S3StorageOptions = {\n /**\n * Access control list for uploaded files.\n */\n acl?: 'private' | 'public-read'\n\n /**\n * When enabled, fields (like the prefix field) will always be inserted into\n * the collection schema regardless of whether the plugin is enabled. This\n * ensures a consistent schema across all environments.\n *\n * This will be enabled by default in Payload v4.\n *\n * @default false\n */\n alwaysInsertFields?: boolean\n\n /**\n * Bucket name to upload files to.\n *\n * Must follow [AWS S3 bucket naming conventions](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html).\n */\n\n bucket: string\n\n /**\n * Optional cache key to identify the S3 storage client instance.\n * If not provided, a default key will be used.\n *\n * @default `s3:containerName`\n */\n clientCacheKey?: string\n\n /**\n * Do uploads directly on the client to bypass limits on Vercel. You must allow CORS PUT method for the bucket to your website.\n */\n clientUploads?: ClientUploadsConfig\n /**\n * Collection options to apply the S3 adapter to.\n */\n collections: Partial<\n Record<\n UploadCollectionSlug,\n | ({\n signedDownloads?: SignedDownloadsConfig\n } & Omit<CollectionOptions, 'adapter'>)\n | true\n >\n >\n /**\n * AWS S3 client configuration. Highly dependent on your AWS setup.\n *\n * [AWS.S3ClientConfig Docs](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-s3/interfaces/s3clientconfig.html)\n */\n config: S3ClientConfig\n\n /**\n * Whether or not to disable local storage\n *\n * @default true\n */\n disableLocalStorage?: boolean\n\n /**\n * Whether or not to enable the plugin\n *\n * Default: true\n */\n enabled?: boolean\n /**\n * Use pre-signed URLs for files downloading. Can be overriden per-collection.\n */\n signedDownloads?: SignedDownloadsConfig\n /**\n * When true, the collection-level prefix and document-level prefix are combined\n * (compositional). When false (default), document prefix overrides collection\n * prefix entirely.\n *\n * Example:\n * - collection prefix: `collection-prefix/`\n * - document prefix: `document-prefix/`\n * - resulting prefix with useCompositePrefixes=true: `collection-prefix/document-prefix/`\n * - resulting prefix with useCompositePrefixes=false: `document-prefix/`\n *\n * @default false\n */\n useCompositePrefixes?: boolean\n}\n\ntype S3StorageFactory = (storageS3Args: S3StorageOptions) => StorageAdapter\n\nconst s3Clients = new Map<string, S3>()\n\nconst defaultRequestHandlerOpts: NodeHttpHandlerOptions = {\n httpAgent: {\n keepAlive: true,\n maxSockets: 100,\n },\n httpsAgent: {\n keepAlive: true,\n maxSockets: 100,\n },\n}\n\nexport const s3Storage: S3StorageFactory = (\n s3StorageOptions: S3StorageOptions,\n): StorageAdapter => ({\n name: 's3',\n collections: Object.keys(s3StorageOptions.collections),\n init: (incomingConfig: Config): Config => {\n const cacheKey = s3StorageOptions.clientCacheKey || `s3:${s3StorageOptions.bucket}`\n\n const isPluginDisabled = s3StorageOptions.enabled === false\n\n const getStorageClient: () => S3 = () => {\n if (s3Clients.has(cacheKey)) {\n return s3Clients.get(cacheKey)!\n }\n\n s3Clients.set(\n cacheKey,\n new S3({\n requestHandler: defaultRequestHandlerOpts,\n ...(s3StorageOptions.config ?? {}),\n }),\n )\n\n return s3Clients.get(cacheKey)!\n }\n\n initClientUploads({\n clientHandler: '@payloadcms/storage-s3/client#S3ClientUploadHandler',\n collections: s3StorageOptions.collections,\n config: incomingConfig,\n enabled: !isPluginDisabled && Boolean(s3StorageOptions.clientUploads),\n serverHandler: getGenerateSignedURLHandler({\n access:\n typeof s3StorageOptions.clientUploads === 'object'\n ? s3StorageOptions.clientUploads.access\n : undefined,\n acl: s3StorageOptions.acl,\n bucket: s3StorageOptions.bucket,\n collections: s3StorageOptions.collections,\n getStorageClient,\n useCompositePrefixes: s3StorageOptions.useCompositePrefixes,\n }),\n serverHandlerPath: '/storage-s3-generate-signed-url',\n })\n\n if (isPluginDisabled) {\n // If alwaysInsertFields is true, still call cloudStoragePlugin to insert fields\n if (s3StorageOptions.alwaysInsertFields) {\n // Build collections with adapter: null since plugin is disabled\n const collectionsWithoutAdapter: CloudStoragePluginOptions['collections'] = Object.entries(\n s3StorageOptions.collections,\n ).reduce(\n (acc, [slug, collOptions]) => ({\n ...acc,\n [slug]: {\n ...(collOptions === true ? {} : collOptions),\n adapter: null,\n },\n }),\n {} as Record<string, CollectionOptions>,\n )\n\n return cloudStoragePlugin({\n alwaysInsertFields: true,\n collections: collectionsWithoutAdapter,\n enabled: false,\n useCompositePrefixes: s3StorageOptions.useCompositePrefixes,\n })(incomingConfig)\n }\n\n return incomingConfig\n }\n\n // Determine signedDownloads for this collection\n const resolveSignedDownloads = (slug: string): SignedDownloadsConfig => {\n const collectionStorageConfig = s3StorageOptions.collections[slug]\n\n let signedDownloads: null | SignedDownloadsConfig =\n typeof collectionStorageConfig === 'object'\n ? (collectionStorageConfig.signedDownloads ?? false)\n : null\n\n if (signedDownloads === null) {\n signedDownloads = s3StorageOptions.signedDownloads ?? false\n }\n\n return signedDownloads\n }\n\n // Add adapter to each collection option object\n const collectionsWithAdapter: CloudStoragePluginOptions['collections'] = Object.entries(\n s3StorageOptions.collections,\n ).reduce(\n (acc, [slug, collOptions]) => ({\n ...acc,\n [slug]: {\n ...(collOptions === true ? {} : collOptions),\n adapter: createS3Adapter({\n acl: s3StorageOptions.acl,\n bucket: s3StorageOptions.bucket,\n clientUploads: s3StorageOptions.clientUploads,\n config: s3StorageOptions.config,\n getStorageClient,\n signedDownloads: resolveSignedDownloads(slug),\n useCompositePrefixes: s3StorageOptions.useCompositePrefixes,\n }),\n },\n }),\n {} as Record<string, CollectionOptions>,\n )\n\n // Set disableLocalStorage: true for collections specified in the plugin options\n const config = {\n ...incomingConfig,\n collections: (incomingConfig.collections || []).map((collection) => {\n if (!collectionsWithAdapter[collection.slug]) {\n return collection\n }\n\n return {\n ...collection,\n upload: {\n ...(typeof collection.upload === 'object' ? collection.upload : {}),\n disableLocalStorage: true,\n },\n }\n }),\n }\n\n return cloudStoragePlugin({\n alwaysInsertFields: s3StorageOptions.alwaysInsertFields,\n collections: collectionsWithAdapter,\n useCompositePrefixes: s3StorageOptions.useCompositePrefixes,\n })(config)\n },\n})\n"],"names":["S3","cloudStoragePlugin","initClientUploads","createS3Adapter","getGenerateSignedURLHandler","s3Clients","Map","defaultRequestHandlerOpts","httpAgent","keepAlive","maxSockets","httpsAgent","s3Storage","s3StorageOptions","name","collections","Object","keys","init","incomingConfig","cacheKey","clientCacheKey","bucket","isPluginDisabled","enabled","getStorageClient","has","get","set","requestHandler","config","clientHandler","Boolean","clientUploads","serverHandler","access","undefined","acl","useCompositePrefixes","serverHandlerPath","alwaysInsertFields","collectionsWithoutAdapter","entries","reduce","acc","slug","collOptions","adapter","resolveSignedDownloads","collectionStorageConfig","signedDownloads","collectionsWithAdapter","map","collection","upload","disableLocalStorage"],"mappings":"AASA,SAASA,EAAE,QAAQ,qBAAoB;AACvC,SAASC,kBAAkB,QAAQ,mCAAkC;AACrE,SAASC,iBAAiB,QAAQ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H,gFAAgF;YAChF,MAAMR,SAAS;gBACb,GAAGX,cAAc;gBACjBJ,aAAa,AAACI,CAAAA,eAAeJ,WAAW,IAAI,EAAE,AAAD,EAAGqC,GAAG,CAAC,CAACC;oBACnD,IAAI,CAACF,sBAAsB,CAACE,WAAWR,IAAI,CAAC,EAAE;wBAC5C,OAAOQ;oBACT;oBAEA,OAAO;wBACL,GAAGA,UAAU;wBACbC,QAAQ;4BACN,GAAI,OAAOD,WAAWC,MAAM,KAAK,WAAWD,WAAWC,MAAM,GAAG,CAAC,CAAC;4BAClEC,qBAAqB;wBACvB;oBACF;gBACF;YACF;YAEA,OAAOtD,mBAAmB;gBACxBuC,oBAAoB3B,iBAAiB2B,kBAAkB;gBACvDzB,aAAaoC;gBACbb,sBAAsBzB,iBAAiByB,oBAAoB;YAC7D,GAAGR;QACL;IACF,CAAA,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { S3ClientConfig } from '@aws-sdk/client-s3'\nimport type {\n ClientUploadsConfig,\n PluginOptions as CloudStoragePluginOptions,\n CollectionOptions,\n} from '@payloadcms/plugin-cloud-storage/types'\nimport type { NodeHttpHandlerOptions } from '@smithy/node-http-handler'\nimport type { Config, StorageAdapter, UploadCollectionSlug } from 'payload'\n\nimport { S3 } from '@aws-sdk/client-s3'\nimport { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage'\n\nimport type { SignedDownloadsConfig } from './getFile.js'\n\nimport { createS3Adapter } from './adapter.js'\n\nexport type S3StorageOptions = {\n /**\n * Access control list for uploaded files.\n */\n acl?: 'private' | 'public-read'\n\n /**\n * Bucket name to upload files to.\n *\n * Must follow [AWS S3 bucket naming conventions](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html).\n */\n\n bucket: string\n\n /**\n * Optional cache key to identify the S3 storage client instance.\n * If not provided, a default key will be used.\n *\n * @default `s3:containerName`\n */\n clientCacheKey?: string\n\n /**\n * Upload directly to S3 instead of through Payload. You must allow CORS PUT requests from your website.\n */\n clientUploads?: ClientUploadsConfig\n /**\n * Collection options to apply the S3 adapter to.\n */\n collections: Partial<\n Record<\n UploadCollectionSlug,\n | ({\n signedDownloads?: SignedDownloadsConfig\n } & Omit<CollectionOptions, 'adapter'>)\n | true\n >\n >\n /**\n * AWS S3 client configuration. Highly dependent on your AWS setup.\n *\n * [AWS.S3ClientConfig Docs](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-s3/interfaces/s3clientconfig.html)\n */\n config: S3ClientConfig\n\n /**\n * Whether or not to disable local storage\n *\n * @default true\n */\n disableLocalStorage?: boolean\n\n /**\n * Whether or not to enable the plugin\n *\n * Default: true\n */\n enabled?: boolean\n /**\n * Use pre-signed URLs for files downloading. Can be overriden per-collection.\n */\n signedDownloads?: SignedDownloadsConfig\n /**\n * When true, the collection-level prefix and document-level prefix are combined\n * (compositional). When false (default), a document prefix already within the\n * collection prefix is used as-is for new uploads; otherwise it is nested beneath it.\n * Existing files retain their stored prefixes for reads, URLs, and cleanup.\n *\n * Example with a document prefix already contained by the collection prefix:\n * - collection prefix: `uploads/`\n * - document prefix: `uploads/documents/`\n * - resulting prefix with useCompositePrefixes=true: `uploads/uploads/documents/`\n * - resulting prefix with useCompositePrefixes=false: `uploads/documents/`\n *\n * @default false\n */\n useCompositePrefixes?: boolean\n}\n\ntype S3StorageFactory = (storageS3Args: S3StorageOptions) => StorageAdapter\n\nconst s3Clients = new Map<string, S3>()\n\nconst defaultRequestHandlerOpts: NodeHttpHandlerOptions = {\n httpAgent: {\n keepAlive: true,\n maxSockets: 100,\n },\n httpsAgent: {\n keepAlive: true,\n maxSockets: 100,\n },\n}\n\nexport const s3Storage: S3StorageFactory = (\n s3StorageOptions: S3StorageOptions,\n): StorageAdapter => ({\n name: 's3',\n collections: Object.keys(s3StorageOptions.collections),\n init: (incomingConfig: Config): Config => {\n const cacheKey = s3StorageOptions.clientCacheKey || `s3:${s3StorageOptions.bucket}`\n\n const isPluginDisabled = s3StorageOptions.enabled === false\n\n const getStorageClient: () => S3 = () => {\n if (s3Clients.has(cacheKey)) {\n return s3Clients.get(cacheKey)!\n }\n\n s3Clients.set(\n cacheKey,\n new S3({\n requestHandler: defaultRequestHandlerOpts,\n ...(s3StorageOptions.config ?? {}),\n }),\n )\n\n return s3Clients.get(cacheKey)!\n }\n\n if (isPluginDisabled) {\n // Still call cloudStoragePlugin with adapter: null so fields (like prefix) are\n // inserted into the schema, keeping it consistent across environments.\n const collectionsWithoutAdapter: CloudStoragePluginOptions['collections'] = Object.entries(\n s3StorageOptions.collections,\n ).reduce(\n (acc, [slug, collOptions]) => ({\n ...acc,\n [slug]: {\n ...(collOptions === true ? {} : collOptions),\n adapter: null,\n },\n }),\n {} as Record<string, CollectionOptions>,\n )\n\n return cloudStoragePlugin({\n collections: collectionsWithoutAdapter,\n enabled: false,\n useCompositePrefixes: s3StorageOptions.useCompositePrefixes,\n })(incomingConfig)\n }\n\n // Determine signedDownloads for this collection\n const resolveSignedDownloads = (slug: string): SignedDownloadsConfig => {\n const collectionStorageConfig = s3StorageOptions.collections[slug]\n\n let signedDownloads: null | SignedDownloadsConfig =\n typeof collectionStorageConfig === 'object'\n ? (collectionStorageConfig.signedDownloads ?? false)\n : null\n\n if (signedDownloads === null) {\n signedDownloads = s3StorageOptions.signedDownloads ?? false\n }\n\n return signedDownloads\n }\n\n // Add adapter to each collection option object\n const collectionsWithAdapter: CloudStoragePluginOptions['collections'] = Object.entries(\n s3StorageOptions.collections,\n ).reduce(\n (acc, [slug, collOptions]) => ({\n ...acc,\n [slug]: {\n ...(collOptions === true ? {} : collOptions),\n adapter: createS3Adapter({\n acl: s3StorageOptions.acl,\n bucket: s3StorageOptions.bucket,\n clientUploads: s3StorageOptions.clientUploads,\n config: s3StorageOptions.config,\n getStorageClient,\n signedDownloads: resolveSignedDownloads(slug),\n useCompositePrefixes: s3StorageOptions.useCompositePrefixes,\n }),\n },\n }),\n {} as Record<string, CollectionOptions>,\n )\n\n // Set disableLocalStorage: true for collections specified in the plugin options\n const config = {\n ...incomingConfig,\n collections: (incomingConfig.collections || []).map((collection) => {\n if (!collectionsWithAdapter[collection.slug]) {\n return collection\n }\n\n return {\n ...collection,\n upload: {\n ...(typeof collection.upload === 'object' ? collection.upload : {}),\n disableLocalStorage: true,\n },\n }\n }),\n }\n\n return cloudStoragePlugin({\n collections: collectionsWithAdapter,\n useCompositePrefixes: s3StorageOptions.useCompositePrefixes,\n })(config)\n },\n})\n"],"names":["S3","cloudStoragePlugin","createS3Adapter","s3Clients","Map","defaultRequestHandlerOpts","httpAgent","keepAlive","maxSockets","httpsAgent","s3Storage","s3StorageOptions","name","collections","Object","keys","init","incomingConfig","cacheKey","clientCacheKey","bucket","isPluginDisabled","enabled","getStorageClient","has","get","set","requestHandler","config","collectionsWithoutAdapter","entries","reduce","acc","slug","collOptions","adapter","useCompositePrefixes","resolveSignedDownloads","collectionStorageConfig","signedDownloads","collectionsWithAdapter","acl","clientUploads","map","collection","upload","disableLocalStorage"],"mappings":"AASA,SAASA,EAAE,QAAQ,qBAAoB;AACvC,SAASC,kBAAkB,QAAQ,mCAAkC;AAIrE,SAASC,eAAe,QAAQ,eAAc;AAmF9C,MAAMC,YAAY,IAAIC;AAEtB,MAAMC,4BAAoD;IACxDC,WAAW;QACTC,WAAW;QACXC,YAAY;IACd;IACAC,YAAY;QACVF,WAAW;QACXC,YAAY;IACd;AACF;AAEA,OAAO,MAAME,YAA8B,CACzCC,mBACoB,CAAA;QACpBC,MAAM;QACNC,aAAaC,OAAOC,IAAI,CAACJ,iBAAiBE,WAAW;QACrDG,MAAM,CAACC;YACL,MAAMC,WAAWP,iBAAiBQ,cAAc,IAAI,CAAC,GAAG,EAAER,iBAAiBS,MAAM,EAAE;YAEnF,MAAMC,mBAAmBV,iBAAiBW,OAAO,KAAK;YAEtD,MAAMC,mBAA6B;gBACjC,IAAIpB,UAAUqB,GAAG,CAACN,WAAW;oBAC3B,OAAOf,UAAUsB,GAAG,CAACP;g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AAa;4BAC7Cd,QAAQjB,iBAAiBiB,MAAM;4BAC/BL;4BACAgB,iBAAiBF,uBAAuBJ;4BACxCG,sBAAsBzB,iBAAiByB,oBAAoB;wBAC7D;oBACF;gBACF,CAAA,GACA,CAAC;YAGH,gFAAgF;YAChF,MAAMR,SAAS;gBACb,GAAGX,cAAc;gBACjBJ,aAAa,AAACI,CAAAA,eAAeJ,WAAW,IAAI,EAAE,AAAD,EAAG8B,GAAG,CAAC,CAACC;oBACnD,IAAI,CAACJ,sBAAsB,CAACI,WAAWX,IAAI,CAAC,EAAE;wBAC5C,OAAOW;oBACT;oBAEA,OAAO;wBACL,GAAGA,UAAU;wBACbC,QAAQ;4BACN,GAAI,OAAOD,WAAWC,MAAM,KAAK,WAAWD,WAAWC,MAAM,GAAG,CAAC,CAAC;4BAClEC,qBAAqB;wBACvB;oBACF;gBACF;YACF;YAEA,OAAO7C,mBAAmB;gBACxBY,aAAa2B;gBACbJ,sBAAsBzB,iBAAiByB,oBAAoB;YAC7D,GAAGR;QACL;IACF,CAAA,EAAE"}
|
package/dist/uploadFile.d.ts
CHANGED
|
@@ -4,13 +4,10 @@ interface UploadArgs {
|
|
|
4
4
|
bucket: string;
|
|
5
5
|
buffer: Buffer;
|
|
6
6
|
client: AWS.S3;
|
|
7
|
-
collectionPrefix?: string;
|
|
8
|
-
docPrefix?: string;
|
|
9
|
-
filename: string;
|
|
10
7
|
mimeType: string;
|
|
8
|
+
storageFilePath: string;
|
|
11
9
|
tempFilePath?: string;
|
|
12
|
-
useCompositePrefixes?: boolean;
|
|
13
10
|
}
|
|
14
|
-
export declare function uploadFile({ acl, bucket, buffer, client,
|
|
11
|
+
export declare function uploadFile({ acl, bucket, buffer, client, mimeType, storageFilePath, tempFilePath, }: UploadArgs): Promise<void>;
|
|
15
12
|
export {};
|
|
16
13
|
//# sourceMappingURL=uploadFile.d.ts.map
|
package/dist/uploadFile.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uploadFile.d.ts","sourceRoot":"","sources":["../src/uploadFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,GAAG,MAAM,oBAAoB,CAAA;
|
|
1
|
+
{"version":3,"file":"uploadFile.d.ts","sourceRoot":"","sources":["../src/uploadFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,GAAG,MAAM,oBAAoB,CAAA;AAK9C,UAAU,UAAU;IAClB,GAAG,CAAC,EAAE,SAAS,GAAG,aAAa,CAAA;IAC/B,MAAM,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,GAAG,CAAC,EAAE,CAAA;IACd,QAAQ,EAAE,MAAM,CAAA;IAChB,eAAe,EAAE,MAAM,CAAA;IACvB,YAAY,CAAC,EAAE,MAAM,CAAA;CACtB;AAID,wBAAsB,UAAU,CAAC,EAC/B,GAAG,EACH,MAAM,EACN,MAAM,EACN,MAAM,EACN,QAAQ,EACR,eAAe,EACf,YAAY,GACb,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CA6B5B"}
|
package/dist/uploadFile.js
CHANGED
|
@@ -1,15 +1,8 @@
|
|
|
1
1
|
import { Upload } from '@aws-sdk/lib-storage';
|
|
2
|
-
import { getFileKey } from '@payloadcms/plugin-cloud-storage/utilities';
|
|
3
2
|
import fs from 'fs';
|
|
4
3
|
const multipartThreshold = 1024 * 1024 * 50 // 50MB
|
|
5
4
|
;
|
|
6
|
-
export async function uploadFile({ acl, bucket, buffer, client,
|
|
7
|
-
const { fileKey } = getFileKey({
|
|
8
|
-
collectionPrefix,
|
|
9
|
-
docPrefix,
|
|
10
|
-
filename,
|
|
11
|
-
useCompositePrefixes
|
|
12
|
-
});
|
|
5
|
+
export async function uploadFile({ acl, bucket, buffer, client, mimeType, storageFilePath, tempFilePath }) {
|
|
13
6
|
const fileBufferOrStream = tempFilePath ? fs.createReadStream(tempFilePath) : buffer;
|
|
14
7
|
if (buffer.length > 0 && buffer.length < multipartThreshold) {
|
|
15
8
|
await client.putObject({
|
|
@@ -17,7 +10,7 @@ export async function uploadFile({ acl, bucket, buffer, client, collectionPrefix
|
|
|
17
10
|
Body: fileBufferOrStream,
|
|
18
11
|
Bucket: bucket,
|
|
19
12
|
ContentType: mimeType,
|
|
20
|
-
Key:
|
|
13
|
+
Key: storageFilePath
|
|
21
14
|
});
|
|
22
15
|
return;
|
|
23
16
|
}
|
|
@@ -28,7 +21,7 @@ export async function uploadFile({ acl, bucket, buffer, client, collectionPrefix
|
|
|
28
21
|
Body: fileBufferOrStream,
|
|
29
22
|
Bucket: bucket,
|
|
30
23
|
ContentType: mimeType,
|
|
31
|
-
Key:
|
|
24
|
+
Key: storageFilePath
|
|
32
25
|
},
|
|
33
26
|
partSize: multipartThreshold,
|
|
34
27
|
queueSize: 4
|
package/dist/uploadFile.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/uploadFile.ts"],"sourcesContent":["import type * as AWS from '@aws-sdk/client-s3'\n\nimport { Upload } from '@aws-sdk/lib-storage'\nimport
|
|
1
|
+
{"version":3,"sources":["../src/uploadFile.ts"],"sourcesContent":["import type * as AWS from '@aws-sdk/client-s3'\n\nimport { Upload } from '@aws-sdk/lib-storage'\nimport fs from 'fs'\n\ninterface UploadArgs {\n acl?: 'private' | 'public-read'\n bucket: string\n buffer: Buffer\n client: AWS.S3\n mimeType: string\n storageFilePath: string\n tempFilePath?: string\n}\n\nconst multipartThreshold = 1024 * 1024 * 50 // 50MB\n\nexport async function uploadFile({\n acl,\n bucket,\n buffer,\n client,\n mimeType,\n storageFilePath,\n tempFilePath,\n}: UploadArgs): Promise<void> {\n const fileBufferOrStream = tempFilePath ? fs.createReadStream(tempFilePath) : buffer\n\n if (buffer.length > 0 && buffer.length < multipartThreshold) {\n await client.putObject({\n ACL: acl,\n Body: fileBufferOrStream,\n Bucket: bucket,\n ContentType: mimeType,\n Key: storageFilePath,\n })\n\n return\n }\n\n const parallelUploadS3 = new Upload({\n client,\n params: {\n ACL: acl,\n Body: fileBufferOrStream,\n Bucket: bucket,\n ContentType: mimeType,\n Key: storageFilePath,\n },\n partSize: multipartThreshold,\n queueSize: 4,\n })\n\n await parallelUploadS3.done()\n}\n"],"names":["Upload","fs","multipartThreshold","uploadFile","acl","bucket","buffer","client","mimeType","storageFilePath","tempFilePath","fileBufferOrStream","createReadStream","length","putObject","ACL","Body","Bucket","ContentType","Key","parallelUploadS3","params","partSize","queueSize","done"],"mappings":"AAEA,SAASA,MAAM,QAAQ,uBAAsB;AAC7C,OAAOC,QAAQ,KAAI;AAYnB,MAAMC,qBAAqB,OAAO,OAAO,GAAG,OAAO;;AAEnD,OAAO,eAAeC,WAAW,EAC/BC,GAAG,EACHC,MAAM,EACNC,MAAM,EACNC,MAAM,EACNC,QAAQ,EACRC,eAAe,EACfC,YAAY,EACD;IACX,MAAMC,qBAAqBD,eAAeT,GAAGW,gBAAgB,CAACF,gBAAgBJ;IAE9E,IAAIA,OAAOO,MAAM,GAAG,KAAKP,OAAOO,MAAM,GAAGX,oBAAoB;QAC3D,MAAMK,OAAOO,SAAS,CAAC;YACrBC,KAAKX;YACLY,MAAML;YACNM,QAAQZ;YACRa,aAAaV;YACbW,KAAKV;QACP;QAEA;IACF;IAEA,MAAMW,mBAAmB,IAAIpB,OAAO;QAClCO;QACAc,QAAQ;YACNN,KAAKX;YACLY,MAAML;YACNM,QAAQZ;YACRa,aAAaV;YACbW,KAAKV;QACP;QACAa,UAAUpB;QACVqB,WAAW;IACb;IAEA,MAAMH,iBAAiBI,IAAI;AAC7B"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@payloadcms/storage-s3",
|
|
3
|
-
"version": "4.0.0-internal.
|
|
3
|
+
"version": "4.0.0-internal.d21c039",
|
|
4
4
|
"description": "Payload storage adapter for Amazon S3",
|
|
5
5
|
"homepage": "https://payloadcms.com",
|
|
6
6
|
"repository": {
|
|
@@ -24,11 +24,6 @@
|
|
|
24
24
|
"import": "./dist/index.js",
|
|
25
25
|
"types": "./dist/index.d.ts",
|
|
26
26
|
"default": "./dist/index.js"
|
|
27
|
-
},
|
|
28
|
-
"./client": {
|
|
29
|
-
"import": "./dist/exports/client.js",
|
|
30
|
-
"types": "./dist/exports/client.d.ts",
|
|
31
|
-
"default": "./dist/exports/client.js"
|
|
32
27
|
}
|
|
33
28
|
},
|
|
34
29
|
"main": "./dist/index.js",
|
|
@@ -40,14 +35,14 @@
|
|
|
40
35
|
"@aws-sdk/client-s3": "^3.614.0",
|
|
41
36
|
"@aws-sdk/lib-storage": "^3.614.0",
|
|
42
37
|
"@aws-sdk/s3-request-presigner": "^3.614.0",
|
|
43
|
-
"@payloadcms/plugin-cloud-storage": "4.0.0-internal.
|
|
38
|
+
"@payloadcms/plugin-cloud-storage": "4.0.0-internal.d21c039"
|
|
44
39
|
},
|
|
45
40
|
"devDependencies": {
|
|
46
41
|
"@smithy/node-http-handler": "4.0.3",
|
|
47
|
-
"payload": "4.0.0-internal.
|
|
42
|
+
"payload": "4.0.0-internal.d21c039"
|
|
48
43
|
},
|
|
49
44
|
"peerDependencies": {
|
|
50
|
-
"payload": "4.0.0-internal.
|
|
45
|
+
"payload": "4.0.0-internal.d21c039"
|
|
51
46
|
},
|
|
52
47
|
"engines": {
|
|
53
48
|
"node": ">=24.15.0"
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
export declare const S3ClientUploadHandler: ({ children, collectionSlug, enabled, extra, prefix, serverHandlerPath, }: {
|
|
2
|
-
children: import("react").ReactNode;
|
|
3
|
-
collectionSlug: import("payload").UploadCollectionSlug;
|
|
4
|
-
enabled?: boolean;
|
|
5
|
-
extra: Record<string, unknown>;
|
|
6
|
-
prefix?: string;
|
|
7
|
-
serverHandlerPath: `/${string}`;
|
|
8
|
-
}) => import("react").JSX.Element;
|
|
9
|
-
//# sourceMappingURL=S3ClientUploadHandler.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"S3ClientUploadHandler.d.ts","sourceRoot":"","sources":["../../src/client/S3ClientUploadHandler.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,qBAAqB;;;;;;;iCA6DhC,CAAA"}
|
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
'use client';
|
|
2
|
-
import { createClientUploadHandler } from '@payloadcms/plugin-cloud-storage/client';
|
|
3
|
-
import { formatAdminURL } from 'payload/shared';
|
|
4
|
-
export const S3ClientUploadHandler = createClientUploadHandler({
|
|
5
|
-
handler: async ({ apiRoute, collectionSlug, docPrefix, file, serverHandlerPath, serverURL, updateFilename })=>{
|
|
6
|
-
const endpointRoute = formatAdminURL({
|
|
7
|
-
apiRoute,
|
|
8
|
-
path: serverHandlerPath,
|
|
9
|
-
serverURL
|
|
10
|
-
});
|
|
11
|
-
// get the signed URL from the server
|
|
12
|
-
const response = await fetch(endpointRoute, {
|
|
13
|
-
body: JSON.stringify({
|
|
14
|
-
collectionSlug,
|
|
15
|
-
docPrefix,
|
|
16
|
-
filename: file.name,
|
|
17
|
-
filesize: file.size,
|
|
18
|
-
mimeType: file.type
|
|
19
|
-
}),
|
|
20
|
-
credentials: 'include',
|
|
21
|
-
method: 'POST'
|
|
22
|
-
});
|
|
23
|
-
if (!response.ok) {
|
|
24
|
-
const { errors } = await response.json();
|
|
25
|
-
throw new Error(errors.reduce((acc, err)=>`${acc ? `${acc}, ` : ''}${err.message}`, ''));
|
|
26
|
-
}
|
|
27
|
-
const { docPrefix: sanitizedDocPrefix, filename: sanitizedFilename, url } = await response.json();
|
|
28
|
-
if (sanitizedFilename && sanitizedFilename !== file.name) {
|
|
29
|
-
updateFilename(sanitizedFilename);
|
|
30
|
-
}
|
|
31
|
-
// upload the file directly to S3 using the signed URL
|
|
32
|
-
await fetch(url, {
|
|
33
|
-
body: file,
|
|
34
|
-
headers: {
|
|
35
|
-
'Content-Length': file.size.toString(),
|
|
36
|
-
'Content-Type': file.type
|
|
37
|
-
},
|
|
38
|
-
method: 'PUT'
|
|
39
|
-
});
|
|
40
|
-
// return the docPrefix so the client can update the field value accordingly
|
|
41
|
-
return {
|
|
42
|
-
prefix: sanitizedDocPrefix
|
|
43
|
-
};
|
|
44
|
-
}
|
|
45
|
-
});
|
|
46
|
-
|
|
47
|
-
//# sourceMappingURL=S3ClientUploadHandler.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/client/S3ClientUploadHandler.ts"],"sourcesContent":["'use client'\nimport { createClientUploadHandler } from '@payloadcms/plugin-cloud-storage/client'\nimport { formatAdminURL } from 'payload/shared'\n\nexport const S3ClientUploadHandler = createClientUploadHandler({\n handler: async ({\n apiRoute,\n collectionSlug,\n docPrefix,\n file,\n serverHandlerPath,\n serverURL,\n updateFilename,\n }) => {\n const endpointRoute = formatAdminURL({\n apiRoute,\n path: serverHandlerPath,\n serverURL,\n })\n\n // get the signed URL from the server\n const response = await fetch(endpointRoute, {\n body: JSON.stringify({\n collectionSlug,\n docPrefix,\n filename: file.name,\n filesize: file.size,\n mimeType: file.type,\n }),\n credentials: 'include',\n method: 'POST',\n })\n\n if (!response.ok) {\n const { errors } = (await response.json()) as {\n errors: { message: string }[]\n }\n\n throw new Error(errors.reduce((acc, err) => `${acc ? `${acc}, ` : ''}${err.message}`, ''))\n }\n\n const {\n docPrefix: sanitizedDocPrefix,\n filename: sanitizedFilename,\n url,\n } = (await response.json()) as {\n docPrefix: string\n filename?: string\n url: string\n }\n\n if (sanitizedFilename && sanitizedFilename !== file.name) {\n updateFilename(sanitizedFilename)\n }\n\n // upload the file directly to S3 using the signed URL\n await fetch(url, {\n body: file,\n headers: { 'Content-Length': file.size.toString(), 'Content-Type': file.type },\n method: 'PUT',\n })\n\n // return the docPrefix so the client can update the field value accordingly\n return { prefix: sanitizedDocPrefix }\n },\n})\n"],"names":["createClientUploadHandler","formatAdminURL","S3ClientUploadHandler","handler","apiRoute","collectionSlug","docPrefix","file","serverHandlerPath","serverURL","updateFilename","endpointRoute","path","response","fetch","body","JSON","stringify","filename","name","filesize","size","mimeType","type","credentials","method","ok","errors","json","Error","reduce","acc","err","message","sanitizedDocPrefix","sanitizedFilename","url","headers","toString","prefix"],"mappings":"AAAA;AACA,SAASA,yBAAyB,QAAQ,0CAAyC;AACnF,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,OAAO,MAAMC,wBAAwBF,0BAA0B;IAC7DG,SAAS,OAAO,EACdC,QAAQ,EACRC,cAAc,EACdC,SAAS,EACTC,IAAI,EACJC,iBAAiB,EACjBC,SAAS,EACTC,cAAc,EACf;QACC,MAAMC,gBAAgBV,eAAe;YACnCG;YACAQ,MAAMJ;YACNC;QACF;QAEA,qCAAqC;QACrC,MAAMI,WAAW,MAAMC,MAAMH,eAAe;YAC1CI,MAAMC,KAAKC,SAAS,CAAC;gBACnBZ;gBACAC;gBACAY,UAAUX,KAAKY,IAAI;gBACnBC,UAAUb,KAAKc,IAAI;gBACnBC,UAAUf,KAAKgB,IAAI;YACrB;YACAC,aAAa;YACbC,QAAQ;QACV;QAEA,IAAI,CAACZ,SAASa,EAAE,EAAE;YAChB,MAAM,EAAEC,MAAM,EAAE,GAAI,MAAMd,SAASe,IAAI;YAIvC,MAAM,IAAIC,MAAMF,OAAOG,MAAM,CAAC,CAACC,KAAKC,MAAQ,GAAGD,MAAM,GAAGA,IAAI,EAAE,CAAC,GAAG,KAAKC,IAAIC,OAAO,EAAE,EAAE;QACxF;QAEA,MAAM,EACJ3B,WAAW4B,kBAAkB,EAC7BhB,UAAUiB,iBAAiB,EAC3BC,GAAG,EACJ,GAAI,MAAMvB,SAASe,IAAI;QAMxB,IAAIO,qBAAqBA,sBAAsB5B,KAAKY,IAAI,EAAE;YACxDT,eAAeyB;QACjB;QAEA,sDAAsD;QACtD,MAAMrB,MAAMsB,KAAK;YACfrB,MAAMR;YACN8B,SAAS;gBAAE,kBAAkB9B,KAAKc,IAAI,CAACiB,QAAQ;gBAAI,gBAAgB/B,KAAKgB,IAAI;YAAC;YAC7EE,QAAQ;QACV;QAEA,4EAA4E;QAC5E,OAAO;YAAEc,QAAQL;QAAmB;IACtC;AACF,GAAE"}
|
package/dist/exports/client.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/exports/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,oCAAoC,CAAA"}
|
package/dist/exports/client.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["export { S3ClientUploadHandler } from '../client/S3ClientUploadHandler.js'\n"],"names":["S3ClientUploadHandler"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,qCAAoC"}
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import type { S3 } from '@aws-sdk/client-s3';
|
|
2
|
-
import type { ClientUploadsAccess } from '@payloadcms/plugin-cloud-storage/types';
|
|
3
|
-
import type { PayloadHandler } from 'payload';
|
|
4
|
-
import type { S3StorageOptions } from './index.js';
|
|
5
|
-
interface Args {
|
|
6
|
-
access?: ClientUploadsAccess;
|
|
7
|
-
acl?: 'private' | 'public-read';
|
|
8
|
-
bucket: string;
|
|
9
|
-
collections: S3StorageOptions['collections'];
|
|
10
|
-
getStorageClient: () => S3;
|
|
11
|
-
useCompositePrefixes?: boolean;
|
|
12
|
-
}
|
|
13
|
-
export declare const getGenerateSignedURLHandler: ({ access, acl, bucket, collections, getStorageClient, useCompositePrefixes, }: Args) => PayloadHandler;
|
|
14
|
-
export {};
|
|
15
|
-
//# sourceMappingURL=generateSignedURL.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"generateSignedURL.d.ts","sourceRoot":"","sources":["../src/generateSignedURL.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,oBAAoB,CAAA;AAC5C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,wCAAwC,CAAA;AACjF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAO7C,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAMlD,UAAU,IAAI;IACZ,MAAM,CAAC,EAAE,mBAAmB,CAAA;IAC5B,GAAG,CAAC,EAAE,SAAS,GAAG,aAAa,CAAA;IAC/B,MAAM,EAAE,MAAM,CAAA;IACd,WAAW,EAAE,gBAAgB,CAAC,aAAa,CAAC,CAAA;IAC5C,gBAAgB,EAAE,MAAM,EAAE,CAAA;IAC1B,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B;AAID,eAAO,MAAM,2BAA2B,kFAOrC,IAAI,KAAG,cA4ET,CAAA"}
|
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import { PutObjectCommand } from '@aws-sdk/client-s3';
|
|
2
|
-
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
|
|
3
|
-
import { resolveSignedURLKey } from '@payloadcms/plugin-cloud-storage/utilities';
|
|
4
|
-
import { APIError, Forbidden } from 'payload';
|
|
5
|
-
const bytesToMB = (bytes)=>{
|
|
6
|
-
return bytes / 1024 / 1024;
|
|
7
|
-
};
|
|
8
|
-
const defaultAccess = ({ req })=>!!req.user;
|
|
9
|
-
export const getGenerateSignedURLHandler = ({ access = defaultAccess, acl, bucket, collections, getStorageClient, useCompositePrefixes = false })=>{
|
|
10
|
-
return async (req)=>{
|
|
11
|
-
if (!req.json) {
|
|
12
|
-
throw new APIError('Content-Type expected to be application/json', 400);
|
|
13
|
-
}
|
|
14
|
-
let filesizeLimit = req.payload.config.upload.limits?.fileSize;
|
|
15
|
-
if (filesizeLimit === Infinity) {
|
|
16
|
-
filesizeLimit = undefined;
|
|
17
|
-
}
|
|
18
|
-
const { collectionSlug, docPrefix, filename, filesize, mimeType } = await req.json();
|
|
19
|
-
const collectionS3Config = collections[collectionSlug];
|
|
20
|
-
if (!collectionS3Config) {
|
|
21
|
-
throw new APIError(`Collection ${collectionSlug} was not found in S3 options`);
|
|
22
|
-
}
|
|
23
|
-
const collectionPrefix = typeof collectionS3Config === 'object' && collectionS3Config.prefix || '';
|
|
24
|
-
if (!await access({
|
|
25
|
-
collectionSlug,
|
|
26
|
-
req
|
|
27
|
-
})) {
|
|
28
|
-
throw new Forbidden();
|
|
29
|
-
}
|
|
30
|
-
const { fileKey, sanitizedDocPrefix, sanitizedFilename } = await resolveSignedURLKey({
|
|
31
|
-
collectionPrefix,
|
|
32
|
-
collectionSlug,
|
|
33
|
-
docPrefix,
|
|
34
|
-
filename,
|
|
35
|
-
req,
|
|
36
|
-
useCompositePrefixes
|
|
37
|
-
});
|
|
38
|
-
const signableHeaders = new Set();
|
|
39
|
-
if (filesizeLimit) {
|
|
40
|
-
if (filesize > filesizeLimit) {
|
|
41
|
-
throw new APIError(`Exceeded file size limit. Limit: ${bytesToMB(filesizeLimit).toFixed(2)}MB, got: ${bytesToMB(filesize).toFixed(2)}MB`, 400);
|
|
42
|
-
}
|
|
43
|
-
// Still force S3 to validate
|
|
44
|
-
signableHeaders.add('content-length');
|
|
45
|
-
}
|
|
46
|
-
const url = await getSignedUrl(getStorageClient(), new PutObjectCommand({
|
|
47
|
-
ACL: acl,
|
|
48
|
-
Bucket: bucket,
|
|
49
|
-
ContentLength: filesizeLimit ? Math.min(filesize, filesizeLimit) : undefined,
|
|
50
|
-
ContentType: mimeType,
|
|
51
|
-
Key: fileKey
|
|
52
|
-
}), {
|
|
53
|
-
expiresIn: 600,
|
|
54
|
-
signableHeaders
|
|
55
|
-
});
|
|
56
|
-
return Response.json({
|
|
57
|
-
docPrefix: sanitizedDocPrefix,
|
|
58
|
-
filename: sanitizedFilename,
|
|
59
|
-
url
|
|
60
|
-
});
|
|
61
|
-
};
|
|
62
|
-
};
|
|
63
|
-
|
|
64
|
-
//# sourceMappingURL=generateSignedURL.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/generateSignedURL.ts"],"sourcesContent":["import type { S3 } from '@aws-sdk/client-s3'\nimport type { ClientUploadsAccess } from '@payloadcms/plugin-cloud-storage/types'\nimport type { PayloadHandler } from 'payload'\n\nimport { PutObjectCommand } from '@aws-sdk/client-s3'\nimport { getSignedUrl } from '@aws-sdk/s3-request-presigner'\nimport { resolveSignedURLKey } from '@payloadcms/plugin-cloud-storage/utilities'\nimport { APIError, Forbidden } from 'payload'\n\nimport type { S3StorageOptions } from './index.js'\n\nconst bytesToMB = (bytes: number) => {\n return bytes / 1024 / 1024\n}\n\ninterface Args {\n access?: ClientUploadsAccess\n acl?: 'private' | 'public-read'\n bucket: string\n collections: S3StorageOptions['collections']\n getStorageClient: () => S3\n useCompositePrefixes?: boolean\n}\n\nconst defaultAccess: Args['access'] = ({ req }) => !!req.user\n\nexport const getGenerateSignedURLHandler = ({\n access = defaultAccess,\n acl,\n bucket,\n collections,\n getStorageClient,\n useCompositePrefixes = false,\n}: Args): PayloadHandler => {\n return async (req) => {\n if (!req.json) {\n throw new APIError('Content-Type expected to be application/json', 400)\n }\n\n let filesizeLimit = req.payload.config.upload.limits?.fileSize\n\n if (filesizeLimit === Infinity) {\n filesizeLimit = undefined\n }\n\n const { collectionSlug, docPrefix, filename, filesize, mimeType } = (await req.json()) as {\n collectionSlug: string\n docPrefix?: string\n filename: string\n filesize: number\n mimeType: string\n }\n\n const collectionS3Config = collections[collectionSlug]\n if (!collectionS3Config) {\n throw new APIError(`Collection ${collectionSlug} was not found in S3 options`)\n }\n\n const collectionPrefix =\n (typeof collectionS3Config === 'object' && collectionS3Config.prefix) || ''\n\n if (!(await access({ collectionSlug, req }))) {\n throw new Forbidden()\n }\n\n const { fileKey, sanitizedDocPrefix, sanitizedFilename } = await resolveSignedURLKey({\n collectionPrefix,\n collectionSlug,\n docPrefix,\n filename,\n req,\n useCompositePrefixes,\n })\n\n const signableHeaders = new Set<string>()\n\n if (filesizeLimit) {\n if (filesize > filesizeLimit) {\n throw new APIError(\n `Exceeded file size limit. Limit: ${bytesToMB(filesizeLimit).toFixed(2)}MB, got: ${bytesToMB(filesize).toFixed(2)}MB`,\n 400,\n )\n }\n\n // Still force S3 to validate\n signableHeaders.add('content-length')\n }\n\n const url = await getSignedUrl(\n getStorageClient(),\n new PutObjectCommand({\n ACL: acl,\n Bucket: bucket,\n ContentLength: filesizeLimit ? Math.min(filesize, filesizeLimit) : undefined,\n ContentType: mimeType,\n Key: fileKey,\n }),\n {\n expiresIn: 600,\n signableHeaders,\n },\n )\n\n return Response.json({\n docPrefix: sanitizedDocPrefix,\n filename: sanitizedFilename,\n url,\n })\n }\n}\n"],"names":["PutObjectCommand","getSignedUrl","resolveSignedURLKey","APIError","Forbidden","bytesToMB","bytes","defaultAccess","req","user","getGenerateSignedURLHandler","access","acl","bucket","collections","getStorageClient","useCompositePrefixes","json","filesizeLimit","payload","config","upload","limits","fileSize","Infinity","undefined","collectionSlug","docPrefix","filename","filesize","mimeType","collectionS3Config","collectionPrefix","prefix","fileKey","sanitizedDocPrefix","sanitizedFilename","signableHeaders","Set","toFixed","add","url","ACL","Bucket","ContentLength","Math","min","ContentType","Key","expiresIn","Response"],"mappings":"AAIA,SAASA,gBAAgB,QAAQ,qBAAoB;AACrD,SAASC,YAAY,QAAQ,gCAA+B;AAC5D,SAASC,mBAAmB,QAAQ,6CAA4C;AAChF,SAASC,QAAQ,EAAEC,SAAS,QAAQ,UAAS;AAI7C,MAAMC,YAAY,CAACC;IACjB,OAAOA,QAAQ,OAAO;AACxB;AAWA,MAAMC,gBAAgC,CAAC,EAAEC,GAAG,EAAE,GAAK,CAAC,CAACA,IAAIC,IAAI;AAE7D,OAAO,MAAMC,8BAA8B,CAAC,EAC1CC,SAASJ,aAAa,EACtBK,GAAG,EACHC,MAAM,EACNC,WAAW,EACXC,gBAAgB,EAChBC,uBAAuB,KAAK,EACvB;IACL,OAAO,OAAOR;QACZ,IAAI,CAACA,IAAIS,IAAI,EAAE;YACb,MAAM,IAAId,SAAS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