@payloadcms/storage-s3 4.0.0-internal.cd69eef → 4.0.0-internal.ce66418

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/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, getFileKey } from '@payloadcms/plugin-cloud-storage/utilities';
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,8 @@ const abortRequestAndDestroyStream = ({ abortController, object })=>{
14
14
  object.Body.destroy();
15
15
  }
16
16
  };
17
- export async function getFile({ bucket, client, collection, collectionPrefix = '', directUpload, filename, incomingHeaders, prefixQueryParam, req, signedDownloads, useCompositePrefixes = false }) {
17
+ export async function getFile({ bucket, client, collection, collectionPrefix = '', doc, filename, incomingHeaders, isOriginal, operation = 'read', req, signedDownloads, uploadReference, useCompositePrefixes = false }) {
18
+ const isTransformSource = operation === 'transform';
18
19
  let object = undefined;
19
20
  let streamed = false;
20
21
  const abortController = new AbortController();
@@ -29,18 +30,21 @@ export async function getFile({ bucket, client, collection, collectionPrefix = '
29
30
  try {
30
31
  const docPrefix = await getDocPrefix({
31
32
  collection,
32
- directUpload,
33
+ collectionPrefix,
34
+ doc,
33
35
  filename,
34
- prefixQueryParam,
35
- req
36
+ isOriginal,
37
+ req,
38
+ uploadReference,
39
+ useCompositePrefixes
36
40
  });
37
- const { fileKey: key } = getFileKey({
41
+ const { storageFilePath } = buildStoragePathData({
38
42
  collectionPrefix,
39
43
  docPrefix,
40
44
  filename,
41
45
  useCompositePrefixes
42
46
  });
43
- if (signedDownloads && !directUpload) {
47
+ if (signedDownloads && !uploadReference && !isTransformSource) {
44
48
  let useSignedURL = true;
45
49
  if (typeof signedDownloads === 'object' && typeof signedDownloads.shouldUseSignedURL === 'function') {
46
50
  useSignedURL = await signedDownloads.shouldUseSignedURL({
@@ -52,7 +56,7 @@ export async function getFile({ bucket, client, collection, collectionPrefix = '
52
56
  if (useSignedURL) {
53
57
  const command = new GetObjectCommand({
54
58
  Bucket: bucket,
55
- Key: key
59
+ Key: storageFilePath
56
60
  });
57
61
  const signedUrl = await getSignedUrl(client, command, typeof signedDownloads === 'object' ? signedDownloads : {
58
62
  expiresIn: 7200
@@ -60,10 +64,9 @@ export async function getFile({ bucket, client, collection, collectionPrefix = '
60
64
  return Response.redirect(signedUrl, 302);
61
65
  }
62
66
  }
63
- // Get file size first for range validation and to set Content-Length header before streaming
64
67
  const headObject = await client.headObject({
65
68
  Bucket: bucket,
66
- Key: key
69
+ Key: storageFilePath
67
70
  });
68
71
  const fileSize = headObject.ContentLength;
69
72
  if (!fileSize) {
@@ -71,8 +74,7 @@ export async function getFile({ bucket, client, collection, collectionPrefix = '
71
74
  status: 500
72
75
  });
73
76
  }
74
- // Handle range request
75
- const rangeHeader = req.headers.get('range');
77
+ const rangeHeader = isTransformSource ? null : req.headers.get('range');
76
78
  const rangeResult = getRangeRequestInfo({
77
79
  fileSize,
78
80
  rangeHeader
@@ -85,7 +87,6 @@ export async function getFile({ bucket, client, collection, collectionPrefix = '
85
87
  }
86
88
  const rangeForS3 = rangeResult.type === 'partial' ? `bytes=${rangeResult.rangeStart}-${rangeResult.rangeEnd}` : undefined;
87
89
  let headers = new Headers(incomingHeaders);
88
- // Add range-related headers from the result
89
90
  for (const [headerKey, value] of Object.entries(rangeResult.headers)){
90
91
  headers.append(headerKey, value);
91
92
  }
@@ -93,18 +94,18 @@ export async function getFile({ bucket, client, collection, collectionPrefix = '
93
94
  if (headObject.ETag) {
94
95
  headers.append('ETag', headObject.ETag);
95
96
  }
96
- // Add Content-Security-Policy header for SVG files to prevent executable code
97
- if (headObject.ContentType === 'image/svg+xml') {
98
- headers.append('Content-Security-Policy', "script-src 'none'");
97
+ // Apply a restrictive policy to XML-family responses served through Payload.
98
+ if (isXmlMimeType(headObject.ContentType)) {
99
+ headers.append('Content-Security-Policy', uploadContentSecurityPolicy);
99
100
  }
100
101
  const etagFromHeaders = req.headers.get('etag') || req.headers.get('if-none-match');
101
102
  const objectEtag = headObject.ETag;
102
- if (collection.upload && typeof collection.upload === 'object' && typeof collection.upload.modifyResponseHeaders === 'function') {
103
+ if (!isTransformSource && collection.upload && typeof collection.upload === 'object' && typeof collection.upload.modifyResponseHeaders === 'function') {
103
104
  headers = collection.upload.modifyResponseHeaders({
104
105
  headers
105
106
  }) || headers;
106
107
  }
107
- if (etagFromHeaders && etagFromHeaders === objectEtag) {
108
+ if (!isTransformSource && etagFromHeaders && etagFromHeaders === objectEtag) {
108
109
  return new Response(null, {
109
110
  headers,
110
111
  status: 304
@@ -112,7 +113,7 @@ export async function getFile({ bucket, client, collection, collectionPrefix = '
112
113
  }
113
114
  object = await client.getObject({
114
115
  Bucket: bucket,
115
- Key: key,
116
+ Key: storageFilePath,
116
117
  Range: rangeForS3
117
118
  }, {
118
119
  abortSignal: abortController.signal
@@ -125,7 +126,7 @@ export async function getFile({ bucket, client, collection, collectionPrefix = '
125
126
  }
126
127
  if (!isNodeReadableStream(object.Body)) {
127
128
  req.payload.logger.error({
128
- key,
129
+ key: storageFilePath,
129
130
  msg: 'S3 object body is not a readable stream'
130
131
  });
131
132
  return new Response('Internal Server Error', {
@@ -136,7 +137,7 @@ export async function getFile({ bucket, client, collection, collectionPrefix = '
136
137
  stream.on('error', (err)=>{
137
138
  req.payload.logger.error({
138
139
  err,
139
- key,
140
+ key: storageFilePath,
140
141
  msg: 'Error while streaming S3 object (aborting)'
141
142
  });
142
143
  abortRequestAndDestroyStream({
@@ -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 collection: CollectionConfig\n collectionPrefix?: string\n directUpload?: unknown\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 collection,\n collectionPrefix = '',\n directUpload,\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 collection,\n directUpload,\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 && !directUpload) {\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","collection","collectionPrefix","directUpload","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,UAAU,EACVC,mBAAmB,EAAE,EACrBC,YAAY,EACZC,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;YACAE;YACAC;YACAE;YACAC;QACF;QAEA,MAAM,EAAES,SAASC,GAAG,EAAE,GAAG9B,WAAW;YAClCe;YACAa;YACAX;YACAK;QACF;QAEA,IAAID,mBAAmB,CAACL,cAAc;YACpC,IAAIe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,KAAK,CAAC;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, 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 isOriginal?: boolean\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 isOriginal,\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 isOriginal,\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","isOriginal","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;AA8BlG,MAAMC,uBAAuB,CAACC;IAC5B,OACE,OAAOA,SAAS,YAChBA,SAAS,QACT,UAAUA,QACV,OAAOA,KAAKC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ACA,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;QACAjD,IAAIkD,OAAO,CAACC,MAAM,CAACC,KAAK,CAACK;QACzB,OAAO,IAAItC,SAAS,yBAAyB;YAAEK,QAAQ;QAAI;IAC7D,SAAU;QACR,IAAI,CAAClB,UAAU;YACbrB,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,8 @@ export type S3StorageOptions = {
31
21
  */
32
22
  clientCacheKey?: string;
33
23
  /**
34
- * Upload directly to S3 instead of through Payload. You must allow CORS PUT requests from your website.
24
+ * Upload directly to S3 instead of through Payload. Large files use resumable multipart upload
25
+ * sessions. You must allow CORS PUT requests from your website.
35
26
  */
36
27
  clientUploads?: ClientUploadsConfig;
37
28
  /**
@@ -64,14 +55,15 @@ export type S3StorageOptions = {
64
55
  signedDownloads?: SignedDownloadsConfig;
65
56
  /**
66
57
  * When true, the collection-level prefix and document-level prefix are combined
67
- * (compositional). When false (default), document prefix overrides collection
68
- * prefix entirely.
58
+ * (compositional). When false (default), a document prefix already within the
59
+ * collection prefix is used as-is for new uploads; otherwise it is nested beneath it.
60
+ * Existing files retain their stored prefixes for reads, URLs, and cleanup.
69
61
  *
70
- * Example:
71
- * - collection prefix: `collection-prefix/`
72
- * - document prefix: `document-prefix/`
73
- * - resulting prefix with useCompositePrefixes=true: `collection-prefix/document-prefix/`
74
- * - resulting prefix with useCompositePrefixes=false: `document-prefix/`
62
+ * Example with a document prefix already contained by the collection prefix:
63
+ * - collection prefix: `uploads/`
64
+ * - document prefix: `uploads/documents/`
65
+ * - resulting prefix with useCompositePrefixes=true: `uploads/uploads/documents/`
66
+ * - resulting prefix with useCompositePrefixes=false: `uploads/documents/`
75
67
  *
76
68
  * @default false
77
69
  */
@@ -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;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;;;;;;;;OAQG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAE5B;;;;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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,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
@@ -29,24 +29,20 @@ export const s3Storage = (s3StorageOptions)=>({
29
29
  return s3Clients.get(cacheKey);
30
30
  };
31
31
  if (isPluginDisabled) {
32
- // If alwaysInsertFields is true, still call cloudStoragePlugin to insert fields
33
- if (s3StorageOptions.alwaysInsertFields) {
34
- // Build collections with adapter: null since plugin is disabled
35
- const collectionsWithoutAdapter = Object.entries(s3StorageOptions.collections).reduce((acc, [slug, collOptions])=>({
36
- ...acc,
37
- [slug]: {
38
- ...collOptions === true ? {} : collOptions,
39
- adapter: null
40
- }
41
- }), {});
42
- return cloudStoragePlugin({
43
- alwaysInsertFields: true,
44
- collections: collectionsWithoutAdapter,
45
- enabled: false,
46
- useCompositePrefixes: s3StorageOptions.useCompositePrefixes
47
- })(incomingConfig);
48
- }
49
- 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);
50
46
  }
51
47
  // Determine signedDownloads for this collection
52
48
  const resolveSignedDownloads = (slug)=>{
@@ -90,7 +86,6 @@ export const s3Storage = (s3StorageOptions)=>({
90
86
  })
91
87
  };
92
88
  return cloudStoragePlugin({
93
- alwaysInsertFields: s3StorageOptions.alwaysInsertFields,
94
89
  collections: collectionsWithAdapter,
95
90
  useCompositePrefixes: s3StorageOptions.useCompositePrefixes
96
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'\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 * 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 * 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), 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 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","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","alwaysInsertFields","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;AA6F9C,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;gBACvB;gBAEAf,UAAUuB,GAAG,CACXR,UACA,IAAIlB,GAAG;oBACL2B,gBAAgBtB;oBAChB,GAAIM,iBAAiBiB,MAAM,IAAI,CAAC,CAAC;gBACnC;gBAGF,OAAOzB,UA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uBAAuBJ;4BACxCG,sBAAsB1B,iBAAiB0B,oBAAoB;wBAC7D;oBACF;gBACF,CAAA,GACA,CAAC;YAGH,gFAAgF;YAChF,MAAMT,SAAS;gBACb,GAAGX,cAAc;gBACjBJ,aAAa,AAACI,CAAAA,eAAeJ,WAAW,IAAI,EAAE,AAAD,EAAG+B,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,OAAO9C,mBAAmB;gBACxB4B,oBAAoBlB,iBAAiBkB,kBAAkB;gBACvDhB,aAAa4B;gBACbJ,sBAAsB1B,iBAAiB0B,oBAAoB;YAC7D,GAAGT;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. Large files use resumable multipart upload\n * sessions. 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;AAoF9C,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,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,gBAAgB;4BACvBuC,KAAK9B,iBAAiB8B,GAAG;4BACzBrB,QAAQT,iBAAiBS,MAAM;4BAC/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"}
@@ -0,0 +1,17 @@
1
+ import type { S3 } from '@aws-sdk/client-s3';
2
+ import type { SegmentedUploadCapability, UploadInstructionsAccess } from 'payload';
3
+ type Args = {
4
+ access?: UploadInstructionsAccess;
5
+ acl?: 'private' | 'public-read';
6
+ bucket: string;
7
+ collectionPrefix: string;
8
+ getStorageClient: () => S3;
9
+ useCompositePrefixes?: boolean;
10
+ };
11
+ /**
12
+ * Native S3 multipart uploads for durable upload sessions. The server reconciles parts with
13
+ * ListParts, so the browser never needs to read ETag response headers.
14
+ */
15
+ export declare const createSegmentedUpload: ({ access, acl, bucket, collectionPrefix, getStorageClient, useCompositePrefixes, }: Args) => SegmentedUploadCapability;
16
+ export {};
17
+ //# sourceMappingURL=segmentedUpload.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"segmentedUpload.d.ts","sourceRoot":"","sources":["../src/segmentedUpload.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAiB,EAAE,EAAE,MAAM,oBAAoB,CAAA;AAC3D,OAAO,KAAK,EAGV,yBAAyB,EACzB,wBAAwB,EACzB,MAAM,SAAS,CAAA;AAkBhB,KAAK,IAAI,GAAG;IACV,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,CAAA;AAID;;;GAGG;AACH,eAAO,MAAM,qBAAqB,uFAO/B,IAAI,KAAG,yBA4IT,CAAA"}
@@ -0,0 +1,203 @@
1
+ import { AbortMultipartUploadCommand, CompleteMultipartUploadCommand, CreateMultipartUploadCommand, DeleteObjectCommand, HeadObjectCommand, ListPartsCommand, UploadPartCommand } 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 MiB = 1024 * 1024;
6
+ const GiB = 1024 * MiB;
7
+ /**
8
+ * Native S3 multipart uploads for durable upload sessions. The server reconciles parts with
9
+ * ListParts, so the browser never needs to read ETag response headers.
10
+ */ export const createSegmentedUpload = ({ access, acl, bucket, collectionPrefix, getStorageClient, useCompositePrefixes = false })=>{
11
+ return {
12
+ abort: async ({ object, providerState })=>{
13
+ const client = getStorageClient();
14
+ const { uploadId } = providerState;
15
+ await ignoreNotFound({
16
+ promise: client.send(new AbortMultipartUploadCommand({
17
+ Bucket: bucket,
18
+ Key: object.storageFilePath,
19
+ UploadId: uploadId
20
+ }))
21
+ });
22
+ // Core only aborts unclaimed sessions, so a committed object here is an orphan.
23
+ await ignoreNotFound({
24
+ promise: client.send(new DeleteObjectCommand({
25
+ Bucket: bucket,
26
+ Key: object.storageFilePath
27
+ }))
28
+ });
29
+ },
30
+ authorize: async ({ collectionSlug, req })=>{
31
+ if (access ? !await access({
32
+ collectionSlug,
33
+ req
34
+ }) : !req.user) {
35
+ throw new Forbidden(req.t);
36
+ }
37
+ },
38
+ complete: async ({ object, providerState })=>{
39
+ const client = getStorageClient();
40
+ const { uploadId } = providerState;
41
+ try {
42
+ const parts = await listParts({
43
+ bucket,
44
+ client,
45
+ object,
46
+ uploadId
47
+ });
48
+ await client.send(new CompleteMultipartUploadCommand({
49
+ Bucket: bucket,
50
+ Key: object.storageFilePath,
51
+ MultipartUpload: {
52
+ Parts: parts.map(({ ETag, PartNumber })=>({
53
+ ETag,
54
+ PartNumber
55
+ }))
56
+ },
57
+ UploadId: uploadId
58
+ }));
59
+ } catch (err) {
60
+ // A retry after a lost response: the multipart upload is gone but the object exists.
61
+ if (!isNotFound({
62
+ err
63
+ })) {
64
+ throw err;
65
+ }
66
+ }
67
+ const head = await client.send(new HeadObjectCommand({
68
+ Bucket: bucket,
69
+ Key: object.storageFilePath
70
+ }));
71
+ return {
72
+ size: head.ContentLength ?? -1
73
+ };
74
+ },
75
+ getSegmentRequests: async ({ expiresIn, object, providerState, segments })=>{
76
+ const client = getStorageClient();
77
+ const { uploadId } = providerState;
78
+ return Promise.all(segments.map(async (segment)=>({
79
+ method: 'PUT',
80
+ number: segment.number,
81
+ url: await getSignedUrl(client, new UploadPartCommand({
82
+ Bucket: bucket,
83
+ ContentLength: segment.end - segment.start,
84
+ Key: object.storageFilePath,
85
+ PartNumber: segment.number,
86
+ UploadId: uploadId
87
+ }), {
88
+ expiresIn,
89
+ signableHeaders: new Set([
90
+ 'content-length'
91
+ ])
92
+ })
93
+ })));
94
+ },
95
+ initiate: async ({ collectionSlug, docPrefix, filename, mimeType, req })=>{
96
+ const { sanitizedFilename, storageFilePath, uploadReference } = await resolveSignedURLKey({
97
+ collectionPrefix,
98
+ collectionSlug,
99
+ docPrefix,
100
+ filename,
101
+ req,
102
+ useCompositePrefixes
103
+ });
104
+ const { UploadId } = await withPermanentErrors({
105
+ operation: ()=>getStorageClient().send(new CreateMultipartUploadCommand({
106
+ ACL: acl,
107
+ Bucket: bucket,
108
+ ContentType: mimeType,
109
+ Key: storageFilePath
110
+ }))
111
+ });
112
+ if (!UploadId || !uploadReference._objectKey) {
113
+ throw new Error('S3 multipart upload could not be initiated.');
114
+ }
115
+ return {
116
+ object: {
117
+ _objectKey: uploadReference._objectKey,
118
+ filename: sanitizedFilename,
119
+ prefix: uploadReference.prefix,
120
+ storageFilePath
121
+ },
122
+ providerState: {
123
+ uploadId: UploadId
124
+ }
125
+ };
126
+ },
127
+ limits: {
128
+ maximumConcurrency: 8,
129
+ maximumObjectSize: 5 * 1024 * GiB,
130
+ maximumSegmentCount: 10_000,
131
+ maximumSegmentSize: 5 * GiB,
132
+ minimumSegmentSize: 5 * MiB,
133
+ segmentSizeGranularity: 1
134
+ },
135
+ reconcile: async ({ object, providerState })=>{
136
+ const { uploadId } = providerState;
137
+ const parts = await listParts({
138
+ bucket,
139
+ client: getStorageClient(),
140
+ object,
141
+ uploadId
142
+ });
143
+ return parts.map(({ PartNumber, Size })=>({
144
+ number: PartNumber,
145
+ size: Size
146
+ }));
147
+ }
148
+ };
149
+ };
150
+ const listParts = async ({ bucket, client, object, uploadId })=>{
151
+ const parts = [];
152
+ let partNumberMarker;
153
+ do {
154
+ const page = await client.send(new ListPartsCommand({
155
+ Bucket: bucket,
156
+ Key: object.storageFilePath,
157
+ PartNumberMarker: partNumberMarker,
158
+ UploadId: uploadId
159
+ }));
160
+ parts.push(...page.Parts ?? []);
161
+ partNumberMarker = page.IsTruncated ? page.NextPartNumberMarker : undefined;
162
+ }while (partNumberMarker)
163
+ return parts;
164
+ };
165
+ /**
166
+ * Converts S3 client faults (a missing bucket, denied access, an invalid request) into a 4xx
167
+ * `APIError`, so core marks the session failed instead of retrying it until it expires.
168
+ * Timeouts and throttling stay retryable.
169
+ */ const withPermanentErrors = async ({ operation })=>{
170
+ try {
171
+ return await operation();
172
+ } catch (err) {
173
+ const status = getClientFaultStatus(err);
174
+ if (status) {
175
+ throw new APIError(`Storage rejected the upload (${err.name}).`, status);
176
+ }
177
+ throw err;
178
+ }
179
+ };
180
+ const getClientFaultStatus = (err)=>{
181
+ if (typeof err !== 'object' || err === null || !('$fault' in err) || err.$fault !== 'client') {
182
+ return null;
183
+ }
184
+ const status = '$metadata' in err && typeof err.$metadata === 'object' && err.$metadata !== null ? err.$metadata.httpStatusCode : undefined;
185
+ if (status === 408 || status === 429) {
186
+ return null;
187
+ }
188
+ return status && status >= 400 && status < 500 ? status : 400;
189
+ };
190
+ const isNotFound = ({ err })=>typeof err === 'object' && err !== null && 'name' in err && (err.name === 'NoSuchUpload' || err.name === 'NoSuchKey' || err.name === 'NotFound');
191
+ const ignoreNotFound = async ({ promise })=>{
192
+ try {
193
+ await promise;
194
+ } catch (err) {
195
+ if (!isNotFound({
196
+ err
197
+ })) {
198
+ throw err;
199
+ }
200
+ }
201
+ };
202
+
203
+ //# sourceMappingURL=segmentedUpload.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/segmentedUpload.ts"],"sourcesContent":["import type { CompletedPart, S3 } from '@aws-sdk/client-s3'\nimport type {\n ReconciledSegments,\n ReservedObject,\n SegmentedUploadCapability,\n UploadInstructionsAccess,\n} from 'payload'\n\nimport {\n AbortMultipartUploadCommand,\n CompleteMultipartUploadCommand,\n CreateMultipartUploadCommand,\n DeleteObjectCommand,\n HeadObjectCommand,\n ListPartsCommand,\n UploadPartCommand,\n} 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\nconst MiB = 1024 * 1024\nconst GiB = 1024 * MiB\n\ntype Args = {\n access?: UploadInstructionsAccess\n acl?: 'private' | 'public-read'\n bucket: string\n collectionPrefix: string\n getStorageClient: () => S3\n useCompositePrefixes?: boolean\n}\n\ntype S3ProviderState = { uploadId: string }\n\n/**\n * Native S3 multipart uploads for durable upload sessions. The server reconciles parts with\n * ListParts, so the browser never needs to read ETag response headers.\n */\nexport const createSegmentedUpload = ({\n access,\n acl,\n bucket,\n collectionPrefix,\n getStorageClient,\n useCompositePrefixes = false,\n}: Args): SegmentedUploadCapability => {\n return {\n abort: async ({ object, providerState }) => {\n const client = getStorageClient()\n const { uploadId } = providerState as S3ProviderState\n\n await ignoreNotFound({\n promise: client.send(\n new AbortMultipartUploadCommand({\n Bucket: bucket,\n Key: object.storageFilePath,\n UploadId: uploadId,\n }),\n ),\n })\n\n // Core only aborts unclaimed sessions, so a committed object here is an orphan.\n await ignoreNotFound({\n promise: client.send(\n new DeleteObjectCommand({ Bucket: bucket, Key: object.storageFilePath }),\n ),\n })\n },\n\n authorize: async ({ collectionSlug, req }) => {\n if (access ? !(await access({ collectionSlug, req })) : !req.user) {\n throw new Forbidden(req.t)\n }\n },\n\n complete: async ({ object, providerState }) => {\n const client = getStorageClient()\n const { uploadId } = providerState as S3ProviderState\n\n try {\n const parts = await listParts({ bucket, client, object, uploadId })\n\n await client.send(\n new CompleteMultipartUploadCommand({\n Bucket: bucket,\n Key: object.storageFilePath,\n MultipartUpload: {\n Parts: parts.map(({ ETag, PartNumber }) => ({ ETag, PartNumber })),\n },\n UploadId: uploadId,\n }),\n )\n } catch (err) {\n // A retry after a lost response: the multipart upload is gone but the object exists.\n if (!isNotFound({ err })) {\n throw err\n }\n }\n\n const head = await client.send(\n new HeadObjectCommand({ Bucket: bucket, Key: object.storageFilePath }),\n )\n\n return { size: head.ContentLength ?? -1 }\n },\n\n getSegmentRequests: async ({ expiresIn, object, providerState, segments }) => {\n const client = getStorageClient()\n const { uploadId } = providerState as S3ProviderState\n\n return Promise.all(\n segments.map(async (segment) => ({\n method: 'PUT' as const,\n number: segment.number,\n url: await getSignedUrl(\n client,\n new UploadPartCommand({\n Bucket: bucket,\n ContentLength: segment.end - segment.start,\n Key: object.storageFilePath,\n PartNumber: segment.number,\n UploadId: uploadId,\n }),\n { expiresIn, signableHeaders: new Set(['content-length']) },\n ),\n })),\n )\n },\n\n initiate: async ({ collectionSlug, docPrefix, filename, mimeType, req }) => {\n const { sanitizedFilename, storageFilePath, uploadReference } = await resolveSignedURLKey({\n collectionPrefix,\n collectionSlug,\n docPrefix,\n filename,\n req,\n useCompositePrefixes,\n })\n\n const { UploadId } = await withPermanentErrors({\n operation: () =>\n getStorageClient().send(\n new CreateMultipartUploadCommand({\n ACL: acl,\n Bucket: bucket,\n ContentType: mimeType,\n Key: storageFilePath,\n }),\n ),\n })\n\n if (!UploadId || !uploadReference._objectKey) {\n throw new Error('S3 multipart upload could not be initiated.')\n }\n\n return {\n object: {\n _objectKey: uploadReference._objectKey,\n filename: sanitizedFilename,\n prefix: uploadReference.prefix,\n storageFilePath,\n },\n providerState: { uploadId: UploadId } satisfies S3ProviderState,\n }\n },\n\n limits: {\n maximumConcurrency: 8,\n maximumObjectSize: 5 * 1024 * GiB,\n maximumSegmentCount: 10_000,\n maximumSegmentSize: 5 * GiB,\n minimumSegmentSize: 5 * MiB,\n segmentSizeGranularity: 1,\n },\n\n reconcile: async ({ object, providerState }) => {\n const { uploadId } = providerState as S3ProviderState\n const parts = await listParts({ bucket, client: getStorageClient(), object, uploadId })\n\n return parts.map(({ PartNumber, Size }) => ({\n number: PartNumber!,\n size: Size!,\n })) satisfies ReconciledSegments\n },\n }\n}\n\nconst listParts = async ({\n bucket,\n client,\n object,\n uploadId,\n}: {\n bucket: string\n client: S3\n object: ReservedObject\n uploadId: string\n}): Promise<({ Size?: number } & CompletedPart)[]> => {\n const parts: ({ Size?: number } & CompletedPart)[] = []\n let partNumberMarker: string | undefined\n\n do {\n const page = await client.send(\n new ListPartsCommand({\n Bucket: bucket,\n Key: object.storageFilePath,\n PartNumberMarker: partNumberMarker,\n UploadId: uploadId,\n }),\n )\n\n parts.push(...(page.Parts ?? []))\n partNumberMarker = page.IsTruncated ? page.NextPartNumberMarker : undefined\n } while (partNumberMarker)\n\n return parts\n}\n\n/**\n * Converts S3 client faults (a missing bucket, denied access, an invalid request) into a 4xx\n * `APIError`, so core marks the session failed instead of retrying it until it expires.\n * Timeouts and throttling stay retryable.\n */\nconst withPermanentErrors = async <T>({\n operation,\n}: {\n operation: () => Promise<T>\n}): Promise<T> => {\n try {\n return await operation()\n } catch (err) {\n const status = getClientFaultStatus(err)\n\n if (status) {\n throw new APIError(`Storage rejected the upload (${(err as Error).name}).`, status)\n }\n\n throw err\n }\n}\n\nconst getClientFaultStatus = (err: unknown): null | number => {\n if (typeof err !== 'object' || err === null || !('$fault' in err) || err.$fault !== 'client') {\n return null\n }\n\n const status =\n '$metadata' in err && typeof err.$metadata === 'object' && err.$metadata !== null\n ? (err.$metadata as { httpStatusCode?: number }).httpStatusCode\n : undefined\n\n if (status === 408 || status === 429) {\n return null\n }\n\n return status && status >= 400 && status < 500 ? status : 400\n}\n\nconst isNotFound = ({ err }: { err: unknown }): boolean =>\n typeof err === 'object' &&\n err !== null &&\n 'name' in err &&\n (err.name === 'NoSuchUpload' || err.name === 'NoSuchKey' || err.name === 'NotFound')\n\nconst ignoreNotFound = async ({ promise }: { promise: Promise<unknown> }): Promise<void> => {\n try {\n await promise\n } catch (err) {\n if (!isNotFound({ err })) {\n throw err\n }\n }\n}\n"],"names":["AbortMultipartUploadCommand","CompleteMultipartUploadCommand","CreateMultipartUploadCommand","DeleteObjectCommand","HeadObjectCommand","ListPartsCommand","UploadPartCommand","getSignedUrl","resolveSignedURLKey","APIError","Forbidden","MiB","GiB","createSegmentedUpload","access","acl","bucket","collectionPrefix","getStorageClient","useCompositePrefixes","abort","object","providerState","client","uploadId","ignoreNotFound","promise","send","Bucket","Key","storageFilePath","UploadId","authorize","collectionSlug","req","user","t","complete","parts","listParts","MultipartUpload","Parts","map","ETag","PartNumber","err","isNotFound","head","size","ContentLength","getSegmentRequests","expiresIn","segments","Promise","all","segment","method","number","url","end","start","signableHeaders","Set","initiate","docPrefix","filename","mimeType","sanitizedFilename","uploadReference","withPermanentErrors","operation","ACL","ContentType","_objectKey","Error","prefix","limits","maximumConcurrency","maximumObjectSize","maximumSegmentCount","maximumSegmentSize","minimumSegmentSize","segmentSizeGranularity","reconcile","Size","partNumberMarker","page","PartNumberMarker","push","IsTruncated","NextPartNumberMarker","undefined","status","getClientFaultStatus","name","$fault","$metadata","httpStatusCode"],"mappings":"AAQA,SACEA,2BAA2B,EAC3BC,8BAA8B,EAC9BC,4BAA4B,EAC5BC,mBAAmB,EACnBC,iBAAiB,EACjBC,gBAAgB,EAChBC,iBAAiB,QACZ,qBAAoB;AAC3B,SAASC,YAAY,QAAQ,gCAA+B;AAC5D,SAASC,mBAAmB,QAAQ,6CAA4C;AAChF,SAASC,QAAQ,EAAEC,SAAS,QAAQ,UAAS;AAE7C,MAAMC,MAAM,OAAO;AACnB,MAAMC,MAAM,OAAOD;AAanB;;;CAGC,GACD,OAAO,MAAME,wBAAwB,CAAC,EACpCC,MAAM,EACNC,GAAG,EACHC,MAAM,EACNC,gBAAgB,EAChBC,gBAAgB,EAChBC,uBAAuB,KAAK,EACvB;IACL,OAAO;QACLC,OAAO,OAAO,EAAEC,MAAM,EAAEC,aAAa,EAAE;YACrC,MAAMC,SAASL;YACf,MAAM,EAAEM,QAAQ,EAAE,GAAGF;YAErB,MAAMG,eAAe;gBACnBC,SAASH,OAAOI,IAAI,CAClB,IAAI3B,4BAA4B;oBAC9B4B,QAAQZ;oBACRa,KAAKR,OAAOS,eAAe;oBAC3BC,UAAUP;gBACZ;YAEJ;YAEA,gFAAgF;YAChF,MAAMC,eAAe;gBACnBC,SAASH,OAAOI,IAAI,CAClB,IAAIxB,oBAAoB;oBAAEyB,QAAQZ;oBAAQa,KAAKR,OAAOS,eAAe;gBAAC;YAE1E;QACF;QAE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GAC7DN;IAEN,IAAIC,WAAW,OAAOA,WAAW,KAAK;QACpC,OAAO;IACT;IAEA,OAAOA,UAAUA,UAAU,OAAOA,SAAS,MAAMA,SAAS;AAC5D;AAEA,MAAM9C,aAAa,CAAC,EAAED,GAAG,EAAoB,GAC3C,OAAOA,QAAQ,YACfA,QAAQ,QACR,UAAUA,OACTA,CAAAA,IAAIiD,IAAI,KAAK,kBAAkBjD,IAAIiD,IAAI,KAAK,eAAejD,IAAIiD,IAAI,KAAK,UAAS;AAEpF,MAAMrE,iBAAiB,OAAO,EAAEC,OAAO,EAAiC;IACtE,IAAI;QACF,MAAMA;IACR,EAAE,OAAOmB,KAAK;QACZ,IAAI,CAACC,WAAW;YAAED;QAAI,IAAI;YACxB,MAAMA;QACR;IACF;AACF"}
@@ -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, collectionPrefix, docPrefix, filename, mimeType, tempFilePath, useCompositePrefixes, }: UploadArgs): Promise<void>;
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