@payloadcms/storage-s3 3.91.0-internal.6e3dc85 → 4.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +1 -1
- package/README.md +2 -2
- package/dist/adapter.d.ts +3 -3
- package/dist/adapter.d.ts.map +1 -1
- package/dist/adapter.js +44 -11
- package/dist/adapter.js.map +1 -1
- package/dist/copyFile.d.ts +13 -0
- package/dist/copyFile.d.ts.map +1 -0
- package/dist/copyFile.js +145 -0
- package/dist/copyFile.js.map +1 -0
- 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 -3
- package/dist/getFile.d.ts.map +1 -1
- package/dist/getFile.js +23 -19
- package/dist/getFile.js.map +1 -1
- package/dist/index.d.ts +6 -16
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +64 -82
- package/dist/index.js.map +1 -1
- package/package.json +9 -9
- package/dist/client/S3ClientUploadHandler.d.ts +0 -9
- package/dist/client/S3ClientUploadHandler.d.ts.map +0 -1
- package/dist/client/S3ClientUploadHandler.js +0 -48
- 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 -85
- package/dist/generateSignedURL.js.map +0 -1
- package/dist/staticHandler.spec.js +0 -72
- package/dist/staticHandler.spec.js.map +0 -1
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, 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 { getStorageFilePath } from '@payloadcms/plugin-cloud-storage/utilities'\nimport {\n getRangeRequestInfo,\n isXmlMimeType,\n UPLOAD_CONTENT_SECURITY_POLICY,\n} 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 doc?: TypeWithID\n filename: string\n incomingHeaders?: Headers\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 doc,\n filename,\n incomingHeaders,\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 filePath = await getStorageFilePath({\n clientUploadContext,\n collection,\n collectionPrefix,\n doc,\n filename,\n req,\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: filePath })\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: filePath,\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 XML-family files\n if (isXmlMimeType(headObject.ContentType)) {\n headers.append('Content-Security-Policy', UPLOAD_CONTENT_SECURITY_POLICY)\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: filePath,\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: filePath,\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: filePath,\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","getStorageFilePath","getRangeRequestInfo","isXmlMimeType","UPLOAD_CONTENT_SECURITY_POLICY","isNodeReadableStream","body","pipe","destroy","abortRequestAndDestroyStream","abortController","object","abort","Body","getFile","bucket","client","clientUploadContext","collection","collectionPrefix","doc","filename","incomingHeaders","req","signedDownloads","useCompositePrefixes","undefined","streamed","AbortController","signal","addEventListener","filePath","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,QA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7B;YAASF,QAAQI,YAAYJ,MAAM;QAAC;IACpE,EAAE,OAAOiC,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,IAAIxC,SAAS,MAAM;gBAAEK,QAAQ;gBAAKyB,YAAY;YAAY;QACnE;QACA9C,IAAI+C,OAAO,CAACC,MAAM,CAACC,KAAK,CAACK;QACzB,OAAO,IAAItC,SAAS,yBAAyB;YAAEK,QAAQ;QAAI;IAC7D,SAAU;QACR,IAAI,CAACjB,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, FileHandlerOperation, 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 operation?: FileHandlerOperation\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 operation = 'read',\n req,\n signedDownloads,\n uploadReference,\n useCompositePrefixes = false,\n}: GetFileArgs): Promise<Response> {\n const isTransformSource = operation === 'transform'\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 && !isTransformSource) {\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 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 const rangeHeader = isTransformSource ? null : 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 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 !isTransformSource &&\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 (!isTransformSource && 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","operation","req","signedDownloads","uploadReference","useCompositePrefixes","isTransformSource","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;AA6BlG,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,QA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,QAAQ;gBAAKyB,YAAY;YAAY;QACnE;QACAjD,IAAIkD,OAAO,CAACC,MAAM,CAACC,KAAK,CAACK;QACzB,OAAO,IAAItC,SAAS,yBAAyB;YAAEK,QAAQ;QAAI;IAC7D,SAAU;QACR,IAAI,CAAClB,UAAU;YACbpB,6BAA6B;gBAAEC;gBAAiBC;YAAO;QACzD;IACF;AACF"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,22 +1,12 @@
|
|
|
1
|
+
import type { S3ClientConfig } from '@aws-sdk/client-s3';
|
|
1
2
|
import type { ClientUploadsConfig, CollectionOptions } from '@payloadcms/plugin-cloud-storage/types';
|
|
2
|
-
import type {
|
|
3
|
-
import * as AWS from '@aws-sdk/client-s3';
|
|
3
|
+
import type { StorageAdapter, UploadCollectionSlug } from 'payload';
|
|
4
4
|
import type { SignedDownloadsConfig } from './getFile.js';
|
|
5
5
|
export type S3StorageOptions = {
|
|
6
6
|
/**
|
|
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
|
/**
|
|
@@ -45,7 +35,7 @@ export type S3StorageOptions = {
|
|
|
45
35
|
*
|
|
46
36
|
* [AWS.S3ClientConfig Docs](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-s3/interfaces/s3clientconfig.html)
|
|
47
37
|
*/
|
|
48
|
-
config:
|
|
38
|
+
config: S3ClientConfig;
|
|
49
39
|
/**
|
|
50
40
|
* Whether or not to disable local storage
|
|
51
41
|
*
|
|
@@ -78,7 +68,7 @@ export type S3StorageOptions = {
|
|
|
78
68
|
*/
|
|
79
69
|
useCompositePrefixes?: boolean;
|
|
80
70
|
};
|
|
81
|
-
type
|
|
82
|
-
export declare const s3Storage:
|
|
71
|
+
type S3StorageFactory = (storageS3Args: S3StorageOptions) => StorageAdapter;
|
|
72
|
+
export declare const s3Storage: S3StorageFactory;
|
|
83
73
|
export {};
|
|
84
74
|
//# sourceMappingURL=index.d.ts.map
|
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,EACV,mBAAmB,EAEnB,iBAAiB,EAClB,MAAM,wCAAwC,CAAA;AAE/C,OAAO,KAAK,EAAU,
|
|
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
|
-
import
|
|
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: {
|
|
@@ -14,38 +12,25 @@ const defaultRequestHandlerOpts = {
|
|
|
14
12
|
maxSockets: 100
|
|
15
13
|
}
|
|
16
14
|
};
|
|
17
|
-
export const s3Storage = (s3StorageOptions)=>(
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
15
|
+
export const s3Storage = (s3StorageOptions)=>({
|
|
16
|
+
name: 's3',
|
|
17
|
+
collections: Object.keys(s3StorageOptions.collections),
|
|
18
|
+
init: (incomingConfig)=>{
|
|
19
|
+
const cacheKey = s3StorageOptions.clientCacheKey || `s3:${s3StorageOptions.bucket}`;
|
|
20
|
+
const isPluginDisabled = s3StorageOptions.enabled === false;
|
|
21
|
+
const getStorageClient = ()=>{
|
|
22
|
+
if (s3Clients.has(cacheKey)) {
|
|
23
|
+
return s3Clients.get(cacheKey);
|
|
24
|
+
}
|
|
25
|
+
s3Clients.set(cacheKey, new S3({
|
|
26
|
+
requestHandler: defaultRequestHandlerOpts,
|
|
27
|
+
...s3StorageOptions.config ?? {}
|
|
28
|
+
}));
|
|
21
29
|
return s3Clients.get(cacheKey);
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
}));
|
|
27
|
-
return s3Clients.get(cacheKey);
|
|
28
|
-
};
|
|
29
|
-
const isPluginDisabled = s3StorageOptions.enabled === false;
|
|
30
|
-
initClientUploads({
|
|
31
|
-
clientHandler: '@payloadcms/storage-s3/client#S3ClientUploadHandler',
|
|
32
|
-
collections: s3StorageOptions.collections,
|
|
33
|
-
config: incomingConfig,
|
|
34
|
-
enabled: !isPluginDisabled && Boolean(s3StorageOptions.clientUploads),
|
|
35
|
-
serverHandler: getGenerateSignedURLHandler({
|
|
36
|
-
access: typeof s3StorageOptions.clientUploads === 'object' ? s3StorageOptions.clientUploads.access : undefined,
|
|
37
|
-
acl: s3StorageOptions.acl,
|
|
38
|
-
bucket: s3StorageOptions.bucket,
|
|
39
|
-
collections: s3StorageOptions.collections,
|
|
40
|
-
getStorageClient,
|
|
41
|
-
useCompositePrefixes: s3StorageOptions.useCompositePrefixes
|
|
42
|
-
}),
|
|
43
|
-
serverHandlerPath: '/storage-s3-generate-signed-url'
|
|
44
|
-
});
|
|
45
|
-
if (isPluginDisabled) {
|
|
46
|
-
// If alwaysInsertFields is true, still call cloudStoragePlugin to insert fields
|
|
47
|
-
if (s3StorageOptions.alwaysInsertFields) {
|
|
48
|
-
// Build collections with adapter: null since plugin is disabled
|
|
30
|
+
};
|
|
31
|
+
if (isPluginDisabled) {
|
|
32
|
+
// Still call cloudStoragePlugin with adapter: null so fields (like prefix) are
|
|
33
|
+
// inserted into the schema, keeping it consistent across environments.
|
|
49
34
|
const collectionsWithoutAdapter = Object.entries(s3StorageOptions.collections).reduce((acc, [slug, collOptions])=>({
|
|
50
35
|
...acc,
|
|
51
36
|
[slug]: {
|
|
@@ -54,60 +39,57 @@ export const s3Storage = (s3StorageOptions)=>(incomingConfig)=>{
|
|
|
54
39
|
}
|
|
55
40
|
}), {});
|
|
56
41
|
return cloudStoragePlugin({
|
|
57
|
-
alwaysInsertFields: true,
|
|
58
42
|
collections: collectionsWithoutAdapter,
|
|
59
43
|
enabled: false,
|
|
60
44
|
useCompositePrefixes: s3StorageOptions.useCompositePrefixes
|
|
61
45
|
})(incomingConfig);
|
|
62
46
|
}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
if (signedDownloads === null) {
|
|
70
|
-
signedDownloads = s3StorageOptions.signedDownloads ?? false;
|
|
71
|
-
}
|
|
72
|
-
return signedDownloads;
|
|
73
|
-
};
|
|
74
|
-
// Add adapter to each collection option object
|
|
75
|
-
const collectionsWithAdapter = Object.entries(s3StorageOptions.collections).reduce((acc, [slug, collOptions])=>({
|
|
76
|
-
...acc,
|
|
77
|
-
[slug]: {
|
|
78
|
-
...collOptions === true ? {} : collOptions,
|
|
79
|
-
adapter: createS3Adapter({
|
|
80
|
-
acl: s3StorageOptions.acl,
|
|
81
|
-
bucket: s3StorageOptions.bucket,
|
|
82
|
-
clientUploads: s3StorageOptions.clientUploads,
|
|
83
|
-
config: s3StorageOptions.config,
|
|
84
|
-
getStorageClient,
|
|
85
|
-
signedDownloads: resolveSignedDownloads(slug),
|
|
86
|
-
useCompositePrefixes: s3StorageOptions.useCompositePrefixes
|
|
87
|
-
})
|
|
47
|
+
// Determine signedDownloads for this collection
|
|
48
|
+
const resolveSignedDownloads = (slug)=>{
|
|
49
|
+
const collectionStorageConfig = s3StorageOptions.collections[slug];
|
|
50
|
+
let signedDownloads = typeof collectionStorageConfig === 'object' ? collectionStorageConfig.signedDownloads ?? false : null;
|
|
51
|
+
if (signedDownloads === null) {
|
|
52
|
+
signedDownloads = s3StorageOptions.signedDownloads ?? false;
|
|
88
53
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
54
|
+
return signedDownloads;
|
|
55
|
+
};
|
|
56
|
+
// Add adapter to each collection option object
|
|
57
|
+
const collectionsWithAdapter = Object.entries(s3StorageOptions.collections).reduce((acc, [slug, collOptions])=>({
|
|
58
|
+
...acc,
|
|
59
|
+
[slug]: {
|
|
60
|
+
...collOptions === true ? {} : collOptions,
|
|
61
|
+
adapter: createS3Adapter({
|
|
62
|
+
acl: s3StorageOptions.acl,
|
|
63
|
+
bucket: s3StorageOptions.bucket,
|
|
64
|
+
clientUploads: s3StorageOptions.clientUploads,
|
|
65
|
+
config: s3StorageOptions.config,
|
|
66
|
+
getStorageClient,
|
|
67
|
+
signedDownloads: resolveSignedDownloads(slug),
|
|
68
|
+
useCompositePrefixes: s3StorageOptions.useCompositePrefixes
|
|
69
|
+
})
|
|
70
|
+
}
|
|
71
|
+
}), {});
|
|
72
|
+
// Set disableLocalStorage: true for collections specified in the plugin options
|
|
73
|
+
const config = {
|
|
74
|
+
...incomingConfig,
|
|
75
|
+
collections: (incomingConfig.collections || []).map((collection)=>{
|
|
76
|
+
if (!collectionsWithAdapter[collection.slug]) {
|
|
77
|
+
return collection;
|
|
102
78
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
79
|
+
return {
|
|
80
|
+
...collection,
|
|
81
|
+
upload: {
|
|
82
|
+
...typeof collection.upload === 'object' ? collection.upload : {},
|
|
83
|
+
disableLocalStorage: true
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
})
|
|
87
|
+
};
|
|
88
|
+
return cloudStoragePlugin({
|
|
89
|
+
collections: collectionsWithAdapter,
|
|
90
|
+
useCompositePrefixes: s3StorageOptions.useCompositePrefixes
|
|
91
|
+
})(config);
|
|
92
|
+
}
|
|
93
|
+
});
|
|
112
94
|
|
|
113
95
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import 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, Plugin, UploadCollectionSlug } from 'payload'\n\nimport * as AWS 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: AWS.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 S3StoragePlugin = (storageS3Args: S3StorageOptions) => Plugin\n\nconst s3Clients = new Map<string, AWS.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: S3StoragePlugin =\n (s3StorageOptions: S3StorageOptions) =>\n (incomingConfig: Config): Config => {\n const cacheKey = s3StorageOptions.clientCacheKey || `s3:${s3StorageOptions.bucket}`\n\n const getStorageClient: () => AWS.S3 = () => {\n if (s3Clients.has(cacheKey)) {\n return s3Clients.get(cacheKey)!\n }\n\n s3Clients.set(\n cacheKey,\n new AWS.S3({\n requestHandler: defaultRequestHandlerOpts,\n ...(s3StorageOptions.config ?? {}),\n }),\n )\n\n return s3Clients.get(cacheKey)!\n }\n\n const isPluginDisabled = s3StorageOptions.enabled === false\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"],"names":["AWS","cloudStoragePlugin","initClientUploads","createS3Adapter","getGenerateSignedURLHandler","s3Clients","Map","defaultRequestHandlerOpts","httpAgent","keepAlive","maxSockets","httpsAgent","s3Storage","s3StorageOptions","incomingConfig","cacheKey","clientCacheKey","bucket","getStorageClient","has","get","set","S3","requestHandler","config","isPluginDisabled","enabled","clientHandler","collections","Boolean","clientUploads","serverHandler","access","undefined","acl","useCompositePrefixes","serverHandlerPath","alwaysInsertFields","collectionsWithoutAdapter","Object","entries","reduce","acc","slug","collOptions","adapter","resolveSignedDownloads","collectionStorageConfig","signedDownloads","collectionsWithAdapter","map","collection","upload","disableLocalStorage"],"mappings":"AAQA,YAAYA,SAAS,qBAAoB;AACzC,SAASC,kBAAkB,QAAQ,mCAAkC;AACrE,SAASC,iBAAiB,QAAQ,6CAA4C;AAI9E,SAASC,eAAe,QAAQ,eAAc;AAC9C,SAASC,2BAA2B,QAAQ,yBAAwB;AA8FpE,MAAMC,YAAY,IAAIC;AAEtB,MAAMC,4BAAoD;IACxDC,WAAW;QACTC,WAAW;QACXC,YAAY;IACd;IACAC,YAAY;QACVF,WAAW;QACXC,YAAY;IACd;AACF;AAEA,OAAO,MAAME,YACX,CAACC,mBACD,CAACC;QACC,MAAMC,WAAWF,iBAAiBG,cAAc,IAAI,CAAC,GAAG,EAAEH,iBAAiBI,MAAM,EAAE;QAEnF,MAAMC,mBAAiC;YACrC,IAAIb,UAAUc,GAAG,CAACJ,WAAW;gBAC3B,OAAOV,UAAUe,GAAG,CAACL;YACvB;YAEAV,UAAUgB,GAAG,CACXN,UACA,IAAIf,IAAIsB,EAAE,CAAC;gBACTC,gBAAgBhB;gBAChB,GAAIM,iBAAiBW,MAAM,IAAI,CAAC,CAAC;YACnC;YAGF,OAAOnB,UAAUe,GAAG,CAACL;QACvB;QAEA,MAAMU,mBAAmBZ,iBAAiBa,OAAO,KAAK;QAEtDxB,kBAAkB;YAChByB,eAAe;YACfC,aAAaf,iBAAiBe,WAAW;YACzCJ,QAAQV;YACRY,SAAS,CAACD,oBAAoBI,QAAQhB,iBAAiBiB,aAAa;YACpEC,eAAe3B,4BAA4B;gBACzC4B,QACE,OAAOnB,iBAAiBiB,aAAa,KAAK,WACtCjB,iBAAiBiB,aAAa,CAACE,MAAM,GACrCC;gBACNC,KAAKrB,iBAAiBqB,GAAG;gBACzBjB,QAAQJ,iBAAiBI,MAAM;gBAC/BW,aAAaf,iBAAiBe,WAAW;gBACzCV;gBACAiB,sBAAsBtB,iBAAiBsB,oBAAoB;YAC7D;YACAC,mBAAmB;QACr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BAAoB;oBAC7D;gBACF;YACF,CAAA,GACA,CAAC;QAGH,gFAAgF;QAChF,MAAMX,SAAS;YACb,GAAGV,cAAc;YACjBc,aAAa,AAACd,CAAAA,eAAec,WAAW,IAAI,EAAE,AAAD,EAAGsB,GAAG,CAAC,CAACC;gBACnD,IAAI,CAACF,sBAAsB,CAACE,WAAWR,IAAI,CAAC,EAAE;oBAC5C,OAAOQ;gBACT;gBAEA,OAAO;oBACL,GAAGA,UAAU;oBACbC,QAAQ;wBACN,GAAI,OAAOD,WAAWC,MAAM,KAAK,WAAWD,WAAWC,MAAM,GAAG,CAAC,CAAC;wBAClEC,qBAAqB;oBACvB;gBACF;YACF;QACF;QAEA,OAAOpD,mBAAmB;YACxBoC,oBAAoBxB,iBAAiBwB,kBAAkB;YACvDT,aAAaqB;YACbd,sBAAsBtB,iBAAiBsB,oBAAoB;QAC7D,GAAGX;IACL,EAAC"}
|
|
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,OAA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BsB,eAAe/B,iBAAiB+B,aAAa;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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@payloadcms/storage-s3",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "4.0.0-beta.0",
|
|
4
4
|
"description": "Payload storage adapter for Amazon S3",
|
|
5
5
|
"homepage": "https://payloadcms.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,10 +25,10 @@
|
|
|
25
25
|
"types": "./dist/index.d.ts",
|
|
26
26
|
"default": "./dist/index.js"
|
|
27
27
|
},
|
|
28
|
-
"./
|
|
29
|
-
"import": "./dist/
|
|
30
|
-
"types": "./dist/
|
|
31
|
-
"default": "./dist/
|
|
28
|
+
"./copy-file": {
|
|
29
|
+
"import": "./dist/copyFile.js",
|
|
30
|
+
"types": "./dist/copyFile.d.ts",
|
|
31
|
+
"default": "./dist/copyFile.js"
|
|
32
32
|
}
|
|
33
33
|
},
|
|
34
34
|
"main": "./dist/index.js",
|
|
@@ -40,17 +40,17 @@
|
|
|
40
40
|
"@aws-sdk/client-s3": "^3.614.0",
|
|
41
41
|
"@aws-sdk/lib-storage": "^3.614.0",
|
|
42
42
|
"@aws-sdk/s3-request-presigner": "^3.614.0",
|
|
43
|
-
"@payloadcms/plugin-cloud-storage": "
|
|
43
|
+
"@payloadcms/plugin-cloud-storage": "4.0.0-beta.0"
|
|
44
44
|
},
|
|
45
45
|
"devDependencies": {
|
|
46
46
|
"@smithy/node-http-handler": "4.0.3",
|
|
47
|
-
"payload": "
|
|
47
|
+
"payload": "4.0.0-beta.0"
|
|
48
48
|
},
|
|
49
49
|
"peerDependencies": {
|
|
50
|
-
"payload": "
|
|
50
|
+
"payload": "4.0.0-beta.0"
|
|
51
51
|
},
|
|
52
52
|
"engines": {
|
|
53
|
-
"node": "
|
|
53
|
+
"node": ">=24.15.0"
|
|
54
54
|
},
|
|
55
55
|
"scripts": {
|
|
56
56
|
"build": "pnpm build:types && pnpm build:swc",
|
|
@@ -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":"AAMA,eAAO,MAAM,qBAAqB;;;;;;;aA0B5B,OAAC,aAyCL,CAAA"}
|
|
@@ -1,48 +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 { clientUploadContext, filename: sanitizedFilename, headers, 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
|
-
const upload = await fetch(url, {
|
|
33
|
-
body: file,
|
|
34
|
-
headers,
|
|
35
|
-
method: 'PUT'
|
|
36
|
-
});
|
|
37
|
-
if (!upload.ok) {
|
|
38
|
-
throw new Error(`Upload failed with status ${upload.status}`);
|
|
39
|
-
}
|
|
40
|
-
// Return the server-issued upload context for the document request.
|
|
41
|
-
return {
|
|
42
|
-
prefix: clientUploadContext.prefix,
|
|
43
|
-
signedReceipt: clientUploadContext.signedReceipt
|
|
44
|
-
};
|
|
45
|
-
}
|
|
46
|
-
});
|
|
47
|
-
|
|
48
|
-
//# sourceMappingURL=S3ClientUploadHandler.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/client/S3ClientUploadHandler.ts"],"sourcesContent":["'use client'\nimport type { ClientUploadContext } from '@payloadcms/plugin-cloud-storage/types'\n\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 }): Promise<ClientUploadContext> => {\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 clientUploadContext,\n filename: sanitizedFilename,\n headers,\n url,\n } = (await response.json()) as {\n clientUploadContext: ClientUploadContext\n filename?: string\n headers: Record<string, 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 const upload = await fetch(url, {\n body: file,\n headers,\n method: 'PUT',\n })\n\n if (!upload.ok) {\n throw new Error(`Upload failed with status ${upload.status}`)\n }\n\n // Return the server-issued upload context for the document request.\n return { prefix: clientUploadContext.prefix, signedReceipt: clientUploadContext.signedReceipt }\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","clientUploadContext","sanitizedFilename","headers","url","upload","status","prefix","signedReceipt"],"mappings":"AAAA;AAGA,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,EACJC,mBAAmB,EACnBhB,UAAUiB,iBAAiB,EAC3BC,OAAO,EACPC,GAAG,EACJ,GAAI,MAAMxB,SAASe,IAAI;QAOxB,IAAIO,qBAAqBA,sBAAsB5B,KAAKY,IAAI,EAAE;YACxDT,eAAeyB;QACjB;QAEA,sDAAsD;QACtD,MAAMG,SAAS,MAAMxB,MAAMuB,KAAK;YAC9BtB,MAAMR;YACN6B;YACAX,QAAQ;QACV;QAEA,IAAI,CAACa,OAAOZ,EAAE,EAAE;YACd,MAAM,IAAIG,MAAM,CAAC,0BAA0B,EAAES,OAAOC,MAAM,EAAE;QAC9D;QAEA,oEAAoE;QACpE,OAAO;YAAEC,QAAQN,oBAAoBM,MAAM;YAAEC,eAAeP,oBAAoBO,aAAa;QAAC;IAChG;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 { ClientUploadsAccess } from '@payloadcms/plugin-cloud-storage/types';
|
|
2
|
-
import type { PayloadHandler } from 'payload';
|
|
3
|
-
import * as AWS from '@aws-sdk/client-s3';
|
|
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: () => AWS.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,mBAAmB,EAAE,MAAM,wCAAwC,CAAA;AACjF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAE7C,OAAO,KAAK,GAAG,MAAM,oBAAoB,CAAA;AAUzC,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,GAAG,CAAC,EAAE,CAAA;IAC9B,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B;AAID,eAAO,MAAM,2BAA2B,kFAOrC,IAAI,KAAG,cAkGT,CAAA"}
|
|
@@ -1,85 +0,0 @@
|
|
|
1
|
-
import * as AWS 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
|
-
import { assertClientUploadAccess, assertClientUploadAllowed, assertClientUploadFileSize } from 'payload/internal';
|
|
6
|
-
const bytesToMB = (bytes)=>{
|
|
7
|
-
return bytes / 1024 / 1024;
|
|
8
|
-
};
|
|
9
|
-
const defaultAccess = ({ req })=>!!req.user;
|
|
10
|
-
export const getGenerateSignedURLHandler = ({ access = defaultAccess, acl, bucket, collections, getStorageClient, useCompositePrefixes = false })=>{
|
|
11
|
-
return async (req)=>{
|
|
12
|
-
if (!req.json) {
|
|
13
|
-
throw new APIError('Content-Type expected to be application/json', 400);
|
|
14
|
-
}
|
|
15
|
-
let filesizeLimit = req.payload.config.upload.limits?.fileSize;
|
|
16
|
-
if (filesizeLimit === Infinity) {
|
|
17
|
-
filesizeLimit = undefined;
|
|
18
|
-
}
|
|
19
|
-
const { collectionSlug, docPrefix, filename, filesize, mimeType } = await req.json();
|
|
20
|
-
await assertClientUploadAccess({
|
|
21
|
-
collectionSlug,
|
|
22
|
-
req
|
|
23
|
-
});
|
|
24
|
-
const collectionS3Config = collections[collectionSlug];
|
|
25
|
-
if (!collectionS3Config) {
|
|
26
|
-
throw new APIError(`Collection ${collectionSlug} was not found in S3 options`);
|
|
27
|
-
}
|
|
28
|
-
const collectionPrefix = typeof collectionS3Config === 'object' && collectionS3Config.prefix || '';
|
|
29
|
-
if (!await access({
|
|
30
|
-
collectionSlug,
|
|
31
|
-
req
|
|
32
|
-
})) {
|
|
33
|
-
throw new Forbidden();
|
|
34
|
-
}
|
|
35
|
-
assertClientUploadAllowed({
|
|
36
|
-
collection: req.payload.collections[collectionSlug]?.config,
|
|
37
|
-
filename,
|
|
38
|
-
mimeType
|
|
39
|
-
});
|
|
40
|
-
const { clientUploadContext, fileKey, sanitizedDocPrefix, sanitizedFilename } = await resolveSignedURLKey({
|
|
41
|
-
collectionPrefix,
|
|
42
|
-
collectionSlug,
|
|
43
|
-
docPrefix,
|
|
44
|
-
filename,
|
|
45
|
-
req,
|
|
46
|
-
useCompositePrefixes
|
|
47
|
-
});
|
|
48
|
-
const signableHeaders = new Set();
|
|
49
|
-
if (typeof mimeType === 'string' && mimeType) {
|
|
50
|
-
signableHeaders.add('content-type');
|
|
51
|
-
}
|
|
52
|
-
if (filesizeLimit) {
|
|
53
|
-
assertClientUploadFileSize(filesize);
|
|
54
|
-
if (filesize > filesizeLimit) {
|
|
55
|
-
throw new APIError(`Exceeded file size limit. Limit: ${bytesToMB(filesizeLimit).toFixed(2)}MB, got: ${bytesToMB(filesize).toFixed(2)}MB`, 400);
|
|
56
|
-
}
|
|
57
|
-
// Still force S3 to validate
|
|
58
|
-
signableHeaders.add('content-length');
|
|
59
|
-
}
|
|
60
|
-
const url = await getSignedUrl(getStorageClient(), new AWS.PutObjectCommand({
|
|
61
|
-
ACL: acl,
|
|
62
|
-
Bucket: bucket,
|
|
63
|
-
ContentLength: filesizeLimit ? Math.min(filesize, filesizeLimit) : undefined,
|
|
64
|
-
ContentType: mimeType,
|
|
65
|
-
IfNoneMatch: '*',
|
|
66
|
-
Key: fileKey
|
|
67
|
-
}), {
|
|
68
|
-
expiresIn: 600,
|
|
69
|
-
signableHeaders
|
|
70
|
-
});
|
|
71
|
-
return Response.json({
|
|
72
|
-
clientUploadContext,
|
|
73
|
-
docPrefix: sanitizedDocPrefix,
|
|
74
|
-
filename: sanitizedFilename,
|
|
75
|
-
headers: {
|
|
76
|
-
'Content-Length': String(filesize),
|
|
77
|
-
'Content-Type': mimeType,
|
|
78
|
-
'If-None-Match': '*'
|
|
79
|
-
},
|
|
80
|
-
url
|
|
81
|
-
});
|
|
82
|
-
};
|
|
83
|
-
};
|
|
84
|
-
|
|
85
|
-
//# sourceMappingURL=generateSignedURL.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/generateSignedURL.ts"],"sourcesContent":["import type { ClientUploadsAccess } from '@payloadcms/plugin-cloud-storage/types'\nimport type { PayloadHandler } from 'payload'\n\nimport * as AWS 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'\nimport {\n assertClientUploadAccess,\n assertClientUploadAllowed,\n assertClientUploadFileSize,\n} from 'payload/internal'\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: () => AWS.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 await assertClientUploadAccess({ collectionSlug, req })\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 assertClientUploadAllowed({\n collection: req.payload.collections[collectionSlug]?.config,\n filename,\n mimeType,\n })\n\n const { clientUploadContext, fileKey, sanitizedDocPrefix, sanitizedFilename } =\n 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 (typeof mimeType === 'string' && mimeType) {\n signableHeaders.add('content-type')\n }\n\n if (filesizeLimit) {\n assertClientUploadFileSize(filesize)\n\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 AWS.PutObjectCommand({\n ACL: acl,\n Bucket: bucket,\n ContentLength: filesizeLimit ? Math.min(filesize, filesizeLimit) : undefined,\n ContentType: mimeType,\n IfNoneMatch: '*',\n Key: fileKey,\n }),\n {\n expiresIn: 600,\n signableHeaders,\n },\n )\n\n return Response.json({\n clientUploadContext,\n docPrefix: sanitizedDocPrefix,\n filename: sanitizedFilename,\n headers: {\n 'Content-Length': String(filesize),\n 'Content-Type': mimeType,\n 'If-None-Match': '*',\n },\n url,\n })\n }\n}\n"],"names":["AWS","getSignedUrl","resolveSignedURLKey","APIError","Forbidden","assertClientUploadAccess","assertClientUploadAllowed","assertClientUploadFileSize","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","collection","clientUploadContext","fileKey","sanitizedDocPrefix","sanitizedFilename","signableHeaders","Set","add","toFixed","url","PutObjectCommand","ACL","Bucket","ContentLength","Math","min","ContentType","IfNoneMatch","Key","expiresIn","Response","headers","String"],"mappings":"AAGA,YAAYA,SAAS,qBAAoB;AACzC,SAASC,YAAY,QAAQ,gCAA+B;AAC5D,SAASC,mBAAmB,QAAQ,6CAA4C;AAChF,SAASC,QAAQ,EAAEC,SAAS,QAAQ,UAAS;AAC7C,SACEC,wBAAwB,EACxBC,yBAAyB,EACzBC,0BAA0B,QACrB,mBAAkB;AAIzB,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,IAAIjB,SAAS,gDAAgD;QACrE;QAEA,IAAIkB,gBAAgBV,IAAIW,OAAO,CAACC,MAAM,CAACC,MAAM,CAACC,MAAM,EAAEC;QAEtD,IAAIL,kBAAkBM,UAAU;YAC9BN,gBAAgBO;QAClB;QAEA,MAAM,EAAEC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