@payloadcms/storage-vercel-blob 4.0.0-internal.d1cc1d3 → 4.0.0-internal.d21c039

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/adapter.d.ts CHANGED
@@ -1,13 +1,15 @@
1
1
  import type { Adapter, ClientUploadsConfig } from '@payloadcms/plugin-cloud-storage/types';
2
+ import type { VercelBlobCollectionSource } from './authorizeFileOverwrite.js';
2
3
  interface CreateVercelBlobAdapterArgs {
3
4
  access: 'public';
4
5
  addRandomSuffix?: boolean;
5
6
  baseUrl: string;
6
7
  cacheControlMaxAge: number;
7
8
  clientUploads?: ClientUploadsConfig;
9
+ collectionSources: VercelBlobCollectionSource[];
8
10
  token: string;
9
11
  useCompositePrefixes?: boolean;
10
12
  }
11
- export declare function createVercelBlobAdapter({ access, addRandomSuffix, baseUrl, cacheControlMaxAge, clientUploads, token, useCompositePrefixes, }: CreateVercelBlobAdapterArgs): Adapter;
13
+ export declare function createVercelBlobAdapter({ access, addRandomSuffix, baseUrl, cacheControlMaxAge, clientUploads, collectionSources, token, useCompositePrefixes, }: CreateVercelBlobAdapterArgs): Adapter;
12
14
  export {};
13
15
  //# sourceMappingURL=adapter.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,OAAO,EACP,mBAAmB,EAEpB,MAAM,wCAAwC,CAAA;AAW/C,UAAU,2BAA2B;IACnC,MAAM,EAAE,QAAQ,CAAA;IAChB,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,OAAO,EAAE,MAAM,CAAA;IACf,kBAAkB,EAAE,MAAM,CAAA;IAC1B,aAAa,CAAC,EAAE,mBAAmB,CAAA;IACnC,KAAK,EAAE,MAAM,CAAA;IACb,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B;AAED,wBAAgB,uBAAuB,CAAC,EACtC,MAAM,EACN,eAAe,EACf,OAAO,EACP,kBAAkB,EAClB,aAAa,EACb,KAAK,EACL,oBAA4B,GAC7B,EAAE,2BAA2B,GAAG,OAAO,CAwHvC"}
1
+ {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,OAAO,EACP,mBAAmB,EAEpB,MAAM,wCAAwC,CAAA;AAU/C,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAA;AAQ7E,UAAU,2BAA2B;IACnC,MAAM,EAAE,QAAQ,CAAA;IAChB,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,OAAO,EAAE,MAAM,CAAA;IACf,kBAAkB,EAAE,MAAM,CAAA;IAC1B,aAAa,CAAC,EAAE,mBAAmB,CAAA;IACnC,iBAAiB,EAAE,0BAA0B,EAAE,CAAA;IAC/C,KAAK,EAAE,MAAM,CAAA;IACb,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B;AAED,wBAAgB,uBAAuB,CAAC,EACtC,MAAM,EACN,eAAe,EACf,OAAO,EACP,kBAAkB,EAClB,aAAa,EACb,iBAAiB,EACjB,KAAK,EACL,oBAA4B,GAC7B,EAAE,2BAA2B,GAAG,OAAO,CAgJvC"}
package/dist/adapter.js CHANGED
@@ -1,11 +1,13 @@
1
- import { resolveSignedURLKey } from '@payloadcms/plugin-cloud-storage/utilities';
1
+ import { buildUploadStoragePathData, resolveSignedURLKey } from '@payloadcms/plugin-cloud-storage/utilities';
2
2
  import { generateClientTokenFromReadWriteToken } from '@vercel/blob/client';
3
3
  import { Forbidden } from 'payload';
4
+ import { assertClientUploadAllowed, createClientUploadReceipt } from 'payload/internal';
5
+ import { authorizeClientOverwrite } from './authorizeFileOverwrite.js';
4
6
  import { deleteFile } from './deleteFile.js';
5
7
  import { generateURL } from './generateURL.js';
6
8
  import { getFile } from './getFile.js';
7
9
  import { uploadFile } from './uploadFile.js';
8
- export function createVercelBlobAdapter({ access, addRandomSuffix, baseUrl, cacheControlMaxAge, clientUploads, token, useCompositePrefixes = false }) {
10
+ export function createVercelBlobAdapter({ access, addRandomSuffix, baseUrl, cacheControlMaxAge, clientUploads, collectionSources, token, useCompositePrefixes = false }) {
9
11
  const clientUploadsAccess = typeof clientUploads === 'object' ? clientUploads.access : undefined;
10
12
  return ({ collection, prefix = '' })=>({
11
13
  name: 'vercel-blob',
@@ -21,7 +23,40 @@ export function createVercelBlobAdapter({ access, addRandomSuffix, baseUrl, cach
21
23
  }) : !req.user)) {
22
24
  throw new Forbidden(req.t);
23
25
  }
24
- const resolved = await resolveSignedURLKey({
26
+ assertClientUploadAllowed({
27
+ collection,
28
+ filename,
29
+ mimeType
30
+ });
31
+ const requested = buildUploadStoragePathData({
32
+ collectionPrefix: prefix,
33
+ docPrefix,
34
+ filename,
35
+ useCompositePrefixes
36
+ });
37
+ const allowOverwrite = await authorizeClientOverwrite({
38
+ collectionPrefix: prefix,
39
+ collectionSources,
40
+ overrideAccess,
41
+ req,
42
+ requestedCollectionSlug: collectionSlug,
43
+ requestedFilename: requested.sanitizedFilename,
44
+ requestedStorageFilePath: requested.storageFilePath
45
+ });
46
+ const resolved = allowOverwrite ? {
47
+ ...requested,
48
+ uploadReference: {
49
+ prefix: requested.sanitizedDocPrefix,
50
+ signedReceipt: createClientUploadReceipt({
51
+ allowOverwrite: true,
52
+ collectionSlug,
53
+ filename: requested.sanitizedFilename,
54
+ filePrefix: requested.sanitizedDocPrefix,
55
+ req,
56
+ storageFilePath: requested.storageFilePath
57
+ })
58
+ }
59
+ } : await resolveSignedURLKey({
25
60
  collectionPrefix: prefix,
26
61
  collectionSlug,
27
62
  docPrefix,
@@ -33,16 +68,18 @@ export function createVercelBlobAdapter({ access, addRandomSuffix, baseUrl, cach
33
68
  name: 'uploadToVercelBlob',
34
69
  type: 'dispatch',
35
70
  data: {
36
- pathname: resolved.fileKey,
71
+ pathname: resolved.storageFilePath,
37
72
  token: await generateClientTokenFromReadWriteToken({
38
- addRandomSuffix,
73
+ addRandomSuffix: false,
39
74
  allowedContentTypes: mimeType ? [
40
75
  mimeType
41
76
  ] : undefined,
42
- allowOverwrite: true,
77
+ ...allowOverwrite && {
78
+ allowOverwrite: true
79
+ },
43
80
  cacheControlMaxAge,
44
81
  maximumSizeInBytes: filesize,
45
- pathname: resolved.fileKey,
82
+ pathname: resolved.storageFilePath,
46
83
  token
47
84
  })
48
85
  },
@@ -50,12 +87,11 @@ export function createVercelBlobAdapter({ access, addRandomSuffix, baseUrl, cach
50
87
  filename: resolved.sanitizedFilename,
51
88
  mimeType,
52
89
  size: filesize,
53
- uploadReference: {
54
- prefix: resolved.sanitizedDocPrefix
55
- }
90
+ uploadReference: resolved.uploadReference
56
91
  }
57
92
  };
58
93
  },
94
+ requiresUploadReceipt: true,
59
95
  useInAdmin: true
60
96
  },
61
97
  generateURL: ({ filename, prefix: urlPrefix = '' })=>generateURL({
@@ -65,40 +101,34 @@ export function createVercelBlobAdapter({ access, addRandomSuffix, baseUrl, cach
65
101
  prefix: urlPrefix,
66
102
  useCompositePrefixes
67
103
  }),
68
- handleDelete: ({ doc: { prefix: docPrefix = '' }, filename })=>deleteFile({
104
+ handleDelete: ({ storageFilePath })=>deleteFile({
69
105
  baseUrl,
70
- collectionPrefix: prefix,
71
- docPrefix,
72
- filename,
73
- token,
74
- useCompositePrefixes
106
+ storageFilePath,
107
+ token
75
108
  }),
76
- handleUpload: async ({ data, file: { buffer, filename, mimeType } })=>{
109
+ handleUpload: async ({ data, file: { buffer, mimeType }, storageFilePath })=>{
77
110
  const result = await uploadFile({
78
111
  access,
79
112
  addRandomSuffix,
80
113
  buffer,
81
114
  cacheControlMaxAge,
82
- collectionPrefix: prefix,
83
- docPrefix: data.prefix,
84
- filename,
85
115
  mimeType,
86
- token,
87
- useCompositePrefixes
116
+ storageFilePath,
117
+ token
88
118
  });
89
119
  if (result.filename) {
90
120
  data.filename = result.filename;
91
121
  }
92
122
  return data;
93
123
  },
94
- staticHandler: (req, { headers, params: { filename, prefix: prefixQueryParam, uploadReference } })=>getFile({
124
+ staticHandler: (req, { doc, headers, params: { filename, uploadReference } })=>getFile({
95
125
  baseUrl,
96
126
  cacheControlMaxAge,
97
127
  collection,
98
128
  collectionPrefix: prefix,
129
+ doc,
99
130
  filename,
100
131
  incomingHeaders: headers,
101
- prefixQueryParam,
102
132
  req,
103
133
  token,
104
134
  uploadReference,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/adapter.ts"],"sourcesContent":["import type {\n Adapter,\n ClientUploadsConfig,\n GeneratedAdapter,\n} from '@payloadcms/plugin-cloud-storage/types'\n\nimport { resolveSignedURLKey } from '@payloadcms/plugin-cloud-storage/utilities'\nimport { generateClientTokenFromReadWriteToken } from '@vercel/blob/client'\nimport { Forbidden } from 'payload'\n\nimport { deleteFile } from './deleteFile.js'\nimport { generateURL } from './generateURL.js'\nimport { getFile } from './getFile.js'\nimport { uploadFile } from './uploadFile.js'\n\ninterface CreateVercelBlobAdapterArgs {\n access: 'public'\n addRandomSuffix?: boolean\n baseUrl: string\n cacheControlMaxAge: number\n clientUploads?: ClientUploadsConfig\n token: string\n useCompositePrefixes?: boolean\n}\n\nexport function createVercelBlobAdapter({\n access,\n addRandomSuffix,\n baseUrl,\n cacheControlMaxAge,\n clientUploads,\n token,\n useCompositePrefixes = false,\n}: CreateVercelBlobAdapterArgs): Adapter {\n const clientUploadsAccess = typeof clientUploads === 'object' ? clientUploads.access : undefined\n\n return ({ collection, prefix = '' }): GeneratedAdapter => ({\n name: 'vercel-blob',\n\n uploadInstructions: {\n adminHandler: {\n path: '@payloadcms/storage-vercel-blob/client#VercelBlobClientUploadHandler',\n },\n enabled: Boolean(clientUploads),\n generate: async ({\n collectionSlug,\n docPrefix,\n filename,\n filesize,\n mimeType,\n overrideAccess,\n req,\n }) => {\n if (\n !overrideAccess &&\n (clientUploadsAccess ? !(await clientUploadsAccess({ collectionSlug, req })) : !req.user)\n ) {\n throw new Forbidden(req.t)\n }\n\n const resolved = await resolveSignedURLKey({\n collectionPrefix: prefix,\n collectionSlug,\n docPrefix,\n filename,\n req,\n useCompositePrefixes,\n })\n\n return {\n name: 'uploadToVercelBlob',\n type: 'dispatch',\n data: {\n pathname: resolved.fileKey,\n token: await generateClientTokenFromReadWriteToken({\n addRandomSuffix,\n allowedContentTypes: mimeType ? [mimeType] : undefined,\n allowOverwrite: true,\n cacheControlMaxAge,\n maximumSizeInBytes: filesize,\n pathname: resolved.fileKey,\n token,\n }),\n },\n file: {\n filename: resolved.sanitizedFilename,\n mimeType,\n size: filesize,\n uploadReference: { prefix: resolved.sanitizedDocPrefix },\n },\n }\n },\n useInAdmin: true,\n },\n\n generateURL: ({ filename, prefix: urlPrefix = '' }) =>\n generateURL({\n baseUrl,\n collectionPrefix: prefix,\n filename,\n prefix: urlPrefix,\n useCompositePrefixes,\n }),\n\n handleDelete: ({ doc: { prefix: docPrefix = '' }, filename }) =>\n deleteFile({\n baseUrl,\n collectionPrefix: prefix,\n docPrefix,\n filename,\n token,\n useCompositePrefixes,\n }),\n\n handleUpload: async ({ data, file: { buffer, filename, mimeType } }) => {\n const result = await uploadFile({\n access,\n addRandomSuffix,\n buffer,\n cacheControlMaxAge,\n collectionPrefix: prefix,\n docPrefix: data.prefix,\n filename,\n mimeType,\n token,\n useCompositePrefixes,\n })\n\n if (result.filename) {\n data.filename = result.filename\n }\n\n return data\n },\n\n staticHandler: (\n req,\n { headers, params: { filename, prefix: prefixQueryParam, uploadReference } },\n ) =>\n getFile({\n baseUrl,\n cacheControlMaxAge,\n collection,\n collectionPrefix: prefix,\n filename,\n incomingHeaders: headers,\n prefixQueryParam,\n req,\n token,\n uploadReference,\n useCompositePrefixes,\n }),\n })\n}\n"],"names":["resolveSignedURLKey","generateClientTokenFromReadWriteToken","Forbidden","deleteFile","generateURL","getFile","uploadFile","createVercelBlobAdapter","access","addRandomSuffix","baseUrl","cacheControlMaxAge","clientUploads","token","useCompositePrefixes","clientUploadsAccess","undefined","collection","prefix","name","uploadInstructions","adminHandler","path","enabled","Boolean","generate","collectionSlug","docPrefix","filename","filesize","mimeType","overrideAccess","req","user","t","resolved","collectionPrefix","type","data","pathname","fileKey","allowedContentTypes","allowOverwrite","maximumSizeInBytes","file","sanitizedFilename","size","uploadReference","sanitizedDocPrefix","useInAdmin","urlPrefix","handleDelete","doc","handleUpload","buffer","result","staticHandler","headers","params","prefixQueryParam","incomingHeaders"],"mappings":"AAMA,SAASA,mBAAmB,QAAQ,6CAA4C;AAChF,SAASC,qCAAqC,QAAQ,sBAAqB;AAC3E,SAASC,SAAS,QAAQ,UAAS;AAEnC,SAASC,UAAU,QAAQ,kBAAiB;AAC5C,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,OAAO,QAAQ,eAAc;AACtC,SAASC,UAAU,QAAQ,kBAAiB;AAY5C,OAAO,SAASC,wBAAwB,EACtCC,MAAM,EACNC,eAAe,EACfC,OAAO,EACPC,kBAAkB,EAClBC,aAAa,EACbC,KAAK,EACLC,uBAAuB,KAAK,EACA;IAC5B,MAAMC,sBAAsB,OAAOH,kBAAkB,WAAWA,cAAcJ,MAAM,GAAGQ;IAEvF,OAAO,CAAC,EAAEC,UAAU,EAAEC,SAAS,EAAE,EAAE,GAAwB,CAAA;YACzDC,MAAM;YAENC,oBAAoB;gBAClBC,cAAc;oBACZC,MAAM;gBACR;gBACAC,SAASC,QAAQZ;gBACjBa,UAAU,OAAO,EACfC,cAAc,EACdC,SAAS,EACTC,QAAQ,EACRC,QAAQ,EACRC,QAAQ,EACRC,cAAc,EACdC,GAAG,EACJ;oBACC,IACE,CAACD,kBACAhB,CAAAA,sBAAsB,CAAE,MAAMA,oBAAoB;wBAAEW;wBAAgBM;oBAAI,KAAM,CAACA,IAAIC,IAAI,AAAD,GACvF;wBACA,MAAM,IAAI/B,UAAU8B,IAAIE,CAAC;oBAC3B;oBAEA,MAAMC,WAAW,MAAMnC,oBAAoB;wBACzCoC,kBAAkBlB;wBAClBQ;wBACAC;wBACAC;wBACAI;w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,eAAe,EAAE,EAAE,GAE5E1C,QAAQ;oBACNK;oBACAC;oBACAM;oBACAmB,kBAAkBlB;oBAClBU;oBACAgC,iBAAiBH;oBACjBE;oBACA3B;oBACAnB;oBACAkC;oBACAjC;gBACF;QACJ,CAAA;AACF"}
1
+ {"version":3,"sources":["../src/adapter.ts"],"sourcesContent":["import type {\n Adapter,\n ClientUploadsConfig,\n GeneratedAdapter,\n} from '@payloadcms/plugin-cloud-storage/types'\n\nimport {\n buildUploadStoragePathData,\n resolveSignedURLKey,\n} from '@payloadcms/plugin-cloud-storage/utilities'\nimport { generateClientTokenFromReadWriteToken } from '@vercel/blob/client'\nimport { Forbidden } from 'payload'\nimport { assertClientUploadAllowed, createClientUploadReceipt } from 'payload/internal'\n\nimport type { VercelBlobCollectionSource } from './authorizeFileOverwrite.js'\n\nimport { authorizeClientOverwrite } from './authorizeFileOverwrite.js'\nimport { deleteFile } from './deleteFile.js'\nimport { generateURL } from './generateURL.js'\nimport { getFile } from './getFile.js'\nimport { uploadFile } from './uploadFile.js'\n\ninterface CreateVercelBlobAdapterArgs {\n access: 'public'\n addRandomSuffix?: boolean\n baseUrl: string\n cacheControlMaxAge: number\n clientUploads?: ClientUploadsConfig\n collectionSources: VercelBlobCollectionSource[]\n token: string\n useCompositePrefixes?: boolean\n}\n\nexport function createVercelBlobAdapter({\n access,\n addRandomSuffix,\n baseUrl,\n cacheControlMaxAge,\n clientUploads,\n collectionSources,\n token,\n useCompositePrefixes = false,\n}: CreateVercelBlobAdapterArgs): Adapter {\n const clientUploadsAccess = typeof clientUploads === 'object' ? clientUploads.access : undefined\n\n return ({ collection, prefix = '' }): GeneratedAdapter => ({\n name: 'vercel-blob',\n\n uploadInstructions: {\n adminHandler: {\n path: '@payloadcms/storage-vercel-blob/client#VercelBlobClientUploadHandler',\n },\n enabled: Boolean(clientUploads),\n generate: async ({\n collectionSlug,\n docPrefix,\n filename,\n filesize,\n mimeType,\n overrideAccess,\n req,\n }) => {\n if (\n !overrideAccess &&\n (clientUploadsAccess ? !(await clientUploadsAccess({ collectionSlug, req })) : !req.user)\n ) {\n throw new Forbidden(req.t)\n }\n\n assertClientUploadAllowed({ collection, filename, mimeType })\n\n const requested = buildUploadStoragePathData({\n collectionPrefix: prefix,\n docPrefix,\n filename,\n useCompositePrefixes,\n })\n const allowOverwrite = await authorizeClientOverwrite({\n collectionPrefix: prefix,\n collectionSources,\n overrideAccess,\n req,\n requestedCollectionSlug: collectionSlug,\n requestedFilename: requested.sanitizedFilename,\n requestedStorageFilePath: requested.storageFilePath,\n })\n const resolved = allowOverwrite\n ? {\n ...requested,\n uploadReference: {\n prefix: requested.sanitizedDocPrefix,\n signedReceipt: createClientUploadReceipt({\n allowOverwrite: true,\n collectionSlug,\n filename: requested.sanitizedFilename,\n filePrefix: requested.sanitizedDocPrefix,\n req,\n storageFilePath: requested.storageFilePath,\n }),\n },\n }\n : await resolveSignedURLKey({\n collectionPrefix: prefix,\n collectionSlug,\n docPrefix,\n filename,\n req,\n useCompositePrefixes,\n })\n\n return {\n name: 'uploadToVercelBlob',\n type: 'dispatch',\n data: {\n pathname: resolved.storageFilePath,\n token: await generateClientTokenFromReadWriteToken({\n addRandomSuffix: false,\n allowedContentTypes: mimeType ? [mimeType] : undefined,\n ...(allowOverwrite && { allowOverwrite: true }),\n cacheControlMaxAge,\n maximumSizeInBytes: filesize,\n pathname: resolved.storageFilePath,\n token,\n }),\n },\n file: {\n filename: resolved.sanitizedFilename,\n mimeType,\n size: filesize,\n uploadReference: resolved.uploadReference,\n },\n }\n },\n requiresUploadReceipt: true,\n useInAdmin: true,\n },\n\n generateURL: ({ filename, prefix: urlPrefix = '' }) =>\n generateURL({\n baseUrl,\n collectionPrefix: prefix,\n filename,\n prefix: urlPrefix,\n useCompositePrefixes,\n }),\n\n handleDelete: ({ storageFilePath }) =>\n deleteFile({\n baseUrl,\n storageFilePath,\n token,\n }),\n\n handleUpload: async ({ data, file: { buffer, mimeType }, storageFilePath }) => {\n const result = await uploadFile({\n access,\n addRandomSuffix,\n buffer,\n cacheControlMaxAge,\n mimeType,\n storageFilePath,\n token,\n })\n\n if (result.filename) {\n data.filename = result.filename\n }\n\n return data\n },\n\n staticHandler: (req, { doc, headers, params: { filename, uploadReference } }) =>\n getFile({\n baseUrl,\n cacheControlMaxAge,\n collection,\n collectionPrefix: prefix,\n doc,\n filename,\n incomingHeaders: headers,\n req,\n token,\n uploadReference,\n useCompositePrefixes,\n }),\n })\n}\n"],"names":["buildUploadStoragePathData","resolveSignedURLKey","generateClientTokenFromReadWriteToken","Forbidden","assertClientUploadAllowed","createClientUploadReceipt","authorizeClientOverwrite","deleteFile","generateURL","getFile","uploadFile","createVercelBlobAdapter","access","addRandomSuffix","baseUrl","cacheControlMaxAge","clientUploads","collectionSources","token","useCompositePrefixes","clientUploadsAccess","undefined","collection","prefix","name","uploadInstructions","adminHandler","path","enabled","Boolean","generate","collectionSlug","docPrefix","filename","filesize","mimeType","overrideAccess","req","user","t","requested","collectionPrefix","allowOverwrite","requestedCollectionSlug","requestedFilename","sanitizedFilename","requestedStorageFilePath","storageFilePath","resolved","uploadReference","sanitizedDocPrefix","signedReceipt","filePrefix","type","data","pathname","allowedContentTypes","maximumSizeInBytes","file","size","requiresUploadReceipt","useInAdmin","urlPrefix","handleDelete","handleUpload","buffer","result","staticHandler","doc","headers","params","incomingHeaders"],"mappings":"AAMA,SACEA,0BAA0B,EAC1BC,mBAAmB,QACd,6CAA4C;AACnD,SAASC,qCAAqC,QAAQ,sBAAqB;AAC3E,SAASC,SAAS,QAAQ,UAAS;AACnC,SAASC,yBAAyB,EAAEC,yBAAyB,QAAQ,mBAAkB;AAIvF,SAASC,wBAAwB,QAAQ,8BAA6B;AACtE,SAASC,UAAU,QAAQ,kBAAiB;AAC5C,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,OAAO,QAAQ,eAAc;AACtC,SAASC,UAAU,QAAQ,kBAAiB;AAa5C,OAAO,SAASC,wBAAwB,EACtCC,MAAM,EACNC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BAClB6C;oBACAnC;oBACAsC,iBAAiBF;oBACjBhC;oBACAnB;oBACA+B;oBACA9B;gBACF;QACJ,CAAA;AACF"}
@@ -0,0 +1,16 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ export type VercelBlobCollectionSource = {
3
+ collectionPrefix: string;
4
+ collectionSlug: string;
5
+ useCompositePrefixes: boolean;
6
+ };
7
+ export declare function authorizeClientOverwrite({ collectionPrefix: collectionPrefixArg, collectionSources, overrideAccess, req, requestedCollectionSlug, requestedFilename, requestedStorageFilePath, }: {
8
+ collectionPrefix: string;
9
+ collectionSources: VercelBlobCollectionSource[];
10
+ overrideAccess?: boolean;
11
+ req: PayloadRequest;
12
+ requestedCollectionSlug: string;
13
+ requestedFilename: string;
14
+ requestedStorageFilePath: string;
15
+ }): Promise<boolean>;
16
+ //# sourceMappingURL=authorizeFileOverwrite.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authorizeFileOverwrite.d.ts","sourceRoot":"","sources":["../src/authorizeFileOverwrite.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAY,cAAc,EAAqB,MAAM,SAAS,CAAA;AAU1E,MAAM,MAAM,0BAA0B,GAAG;IACvC,gBAAgB,EAAE,MAAM,CAAA;IACxB,cAAc,EAAE,MAAM,CAAA;IACtB,oBAAoB,EAAE,OAAO,CAAA;CAC9B,CAAA;AAmHD,wBAAsB,wBAAwB,CAAC,EAC7C,gBAAgB,EAAE,mBAAmB,EACrC,iBAAiB,EACjB,cAAsB,EACtB,GAAG,EACH,uBAAuB,EACvB,iBAAiB,EACjB,wBAAwB,GACzB,EAAE;IACD,gBAAgB,EAAE,MAAM,CAAA;IACxB,iBAAiB,EAAE,0BAA0B,EAAE,CAAA;IAC/C,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,GAAG,EAAE,cAAc,CAAA;IACnB,uBAAuB,EAAE,MAAM,CAAA;IAC/B,iBAAiB,EAAE,MAAM,CAAA;IACzB,wBAAwB,EAAE,MAAM,CAAA;CACjC,GAAG,OAAO,CAAC,OAAO,CAAC,CA8CnB"}
@@ -0,0 +1,117 @@
1
+ import { buildStoragePathData, isStoragePathWithinCollectionPrefix } from '@payloadcms/plugin-cloud-storage/utilities';
2
+ import { combineQueries, executeAccess, Forbidden } from 'payload';
3
+ function getDocumentFileKeys({ collectionPrefix, doc, useCompositePrefixes }) {
4
+ return [
5
+ doc.filename,
6
+ ...Object.values(doc.sizes || {}).map((size)=>size?.filename)
7
+ ].filter((filename)=>typeof filename === 'string').map((filename)=>buildStoragePathData({
8
+ collectionPrefix,
9
+ docPrefix: doc.prefix,
10
+ filename,
11
+ useCompositePrefixes
12
+ }).storageFilePath);
13
+ }
14
+ async function findMatchingDocs({ collectionPrefix, collectionSlug, req, requestedFilename, requestedStorageFilePath, useCompositePrefixes }) {
15
+ const collection = req.payload.collections[collectionSlug];
16
+ if (!collection) {
17
+ return [];
18
+ }
19
+ const imageSizes = collection.config.upload && typeof collection.config.upload === 'object' ? collection.config.upload.imageSizes || [] : [];
20
+ const filenameQueries = [
21
+ {
22
+ filename: {
23
+ equals: requestedFilename
24
+ }
25
+ },
26
+ ...imageSizes.map(({ name })=>({
27
+ [`sizes.${name}.filename`]: {
28
+ equals: requestedFilename
29
+ }
30
+ }))
31
+ ];
32
+ const result = await req.payload.find({
33
+ collection: collectionSlug,
34
+ depth: 0,
35
+ draft: true,
36
+ overrideAccess: true,
37
+ pagination: false,
38
+ req,
39
+ where: {
40
+ or: filenameQueries
41
+ }
42
+ });
43
+ return result.docs.filter((doc)=>getDocumentFileKeys({
44
+ collectionPrefix,
45
+ doc,
46
+ useCompositePrefixes
47
+ }).includes(requestedStorageFilePath));
48
+ }
49
+ async function canUpdateDoc({ collectionSlug, doc, req }) {
50
+ const collection = req.payload.collections[collectionSlug];
51
+ if (!collection) {
52
+ return false;
53
+ }
54
+ const accessResult = await executeAccess({
55
+ id: doc.id,
56
+ slug: collectionSlug,
57
+ disableErrors: true,
58
+ req
59
+ }, collection.config.access.update);
60
+ if (typeof accessResult === 'boolean') {
61
+ return accessResult;
62
+ }
63
+ const result = await req.payload.find({
64
+ collection: collectionSlug,
65
+ depth: 0,
66
+ draft: true,
67
+ limit: 1,
68
+ overrideAccess: true,
69
+ pagination: false,
70
+ req,
71
+ where: combineQueries({
72
+ id: {
73
+ equals: doc.id
74
+ }
75
+ }, accessResult)
76
+ });
77
+ return result.docs.length === 1;
78
+ }
79
+ export async function authorizeClientOverwrite({ collectionPrefix: collectionPrefixArg, collectionSources, overrideAccess = false, req, requestedCollectionSlug, requestedFilename, requestedStorageFilePath }) {
80
+ if (!isStoragePathWithinCollectionPrefix({
81
+ collectionPrefix: collectionPrefixArg,
82
+ docPrefix: requestedStorageFilePath
83
+ })) {
84
+ throw new Forbidden(req.t);
85
+ }
86
+ const matchedDocs = (await Promise.all(collectionSources.map(async ({ collectionPrefix, collectionSlug, useCompositePrefixes })=>{
87
+ const docs = await findMatchingDocs({
88
+ collectionPrefix,
89
+ collectionSlug,
90
+ req,
91
+ requestedFilename,
92
+ requestedStorageFilePath,
93
+ useCompositePrefixes
94
+ });
95
+ return docs.map((doc)=>({
96
+ collectionSlug,
97
+ doc
98
+ }));
99
+ }))).flat();
100
+ if (matchedDocs.length === 0) {
101
+ return false;
102
+ }
103
+ const matchedDoc = matchedDocs[0];
104
+ if (matchedDocs.length !== 1 || matchedDoc.collectionSlug !== requestedCollectionSlug) {
105
+ throw new Forbidden(req.t);
106
+ }
107
+ if (!overrideAccess && !await canUpdateDoc({
108
+ collectionSlug: matchedDoc.collectionSlug,
109
+ doc: matchedDoc.doc,
110
+ req
111
+ })) {
112
+ throw new Forbidden(req.t);
113
+ }
114
+ return true;
115
+ }
116
+
117
+ //# sourceMappingURL=authorizeFileOverwrite.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/authorizeFileOverwrite.ts"],"sourcesContent":["import type { FileData, PayloadRequest, TypeWithID, Where } from 'payload'\n\nimport {\n buildStoragePathData,\n isStoragePathWithinCollectionPrefix,\n} from '@payloadcms/plugin-cloud-storage/utilities'\nimport { combineQueries, executeAccess, Forbidden } from 'payload'\n\ntype OwnerDocument = { prefix?: string } & FileData & TypeWithID\n\nexport type VercelBlobCollectionSource = {\n collectionPrefix: string\n collectionSlug: string\n useCompositePrefixes: boolean\n}\n\ntype Owner = {\n collectionSlug: string\n doc: OwnerDocument\n}\n\nfunction getDocumentFileKeys({\n collectionPrefix,\n doc,\n useCompositePrefixes,\n}: {\n collectionPrefix: string\n doc: OwnerDocument\n useCompositePrefixes: boolean\n}): string[] {\n return [doc.filename, ...Object.values(doc.sizes || {}).map((size) => size?.filename)]\n .filter((filename): filename is string => typeof filename === 'string')\n .map(\n (filename) =>\n buildStoragePathData({\n collectionPrefix,\n docPrefix: doc.prefix,\n filename,\n useCompositePrefixes,\n }).storageFilePath,\n )\n}\n\nasync function findMatchingDocs({\n collectionPrefix,\n collectionSlug,\n req,\n requestedFilename,\n requestedStorageFilePath,\n useCompositePrefixes,\n}: {\n collectionPrefix: string\n collectionSlug: string\n req: PayloadRequest\n requestedFilename: string\n requestedStorageFilePath: string\n useCompositePrefixes: boolean\n}): Promise<OwnerDocument[]> {\n const collection = req.payload.collections[collectionSlug]\n\n if (!collection) {\n return []\n }\n\n const imageSizes =\n collection.config.upload && typeof collection.config.upload === 'object'\n ? collection.config.upload.imageSizes || []\n : []\n const filenameQueries: Where[] = [\n { filename: { equals: requestedFilename } },\n ...imageSizes.map(({ name }) => ({\n [`sizes.${name}.filename`]: { equals: requestedFilename },\n })),\n ]\n const result = await req.payload.find({\n collection: collectionSlug,\n depth: 0,\n draft: true,\n overrideAccess: true,\n pagination: false,\n req,\n where: { or: filenameQueries },\n })\n\n return (result.docs as OwnerDocument[]).filter((doc) =>\n getDocumentFileKeys({ collectionPrefix, doc, useCompositePrefixes }).includes(\n requestedStorageFilePath,\n ),\n )\n}\n\nasync function canUpdateDoc({\n collectionSlug,\n doc,\n req,\n}: {\n collectionSlug: string\n doc: OwnerDocument\n req: PayloadRequest\n}): Promise<boolean> {\n const collection = req.payload.collections[collectionSlug]\n\n if (!collection) {\n return false\n }\n\n const accessResult = await executeAccess(\n { id: doc.id, slug: collectionSlug, disableErrors: true, req },\n collection.config.access.update,\n )\n\n if (typeof accessResult === 'boolean') {\n return accessResult\n }\n\n const result = await req.payload.find({\n collection: collectionSlug,\n depth: 0,\n draft: true,\n limit: 1,\n overrideAccess: true,\n pagination: false,\n req,\n where: combineQueries({ id: { equals: doc.id } }, accessResult),\n })\n\n return result.docs.length === 1\n}\n\nexport async function authorizeClientOverwrite({\n collectionPrefix: collectionPrefixArg,\n collectionSources,\n overrideAccess = false,\n req,\n requestedCollectionSlug,\n requestedFilename,\n requestedStorageFilePath,\n}: {\n collectionPrefix: string\n collectionSources: VercelBlobCollectionSource[]\n overrideAccess?: boolean\n req: PayloadRequest\n requestedCollectionSlug: string\n requestedFilename: string\n requestedStorageFilePath: string\n}): Promise<boolean> {\n if (\n !isStoragePathWithinCollectionPrefix({\n collectionPrefix: collectionPrefixArg,\n docPrefix: requestedStorageFilePath,\n })\n ) {\n throw new Forbidden(req.t)\n }\n\n const matchedDocs = (\n await Promise.all(\n collectionSources.map(\n async ({ collectionPrefix, collectionSlug, useCompositePrefixes }): Promise<Owner[]> => {\n const docs = await findMatchingDocs({\n collectionPrefix,\n collectionSlug,\n req,\n requestedFilename,\n requestedStorageFilePath,\n useCompositePrefixes,\n })\n\n return docs.map((doc) => ({ collectionSlug, doc }))\n },\n ),\n )\n ).flat()\n\n if (matchedDocs.length === 0) {\n return false\n }\n\n const matchedDoc = matchedDocs[0]!\n if (matchedDocs.length !== 1 || matchedDoc.collectionSlug !== requestedCollectionSlug) {\n throw new Forbidden(req.t)\n }\n\n if (\n !overrideAccess &&\n !(await canUpdateDoc({ collectionSlug: matchedDoc.collectionSlug, doc: matchedDoc.doc, req }))\n ) {\n throw new Forbidden(req.t)\n }\n\n return true\n}\n"],"names":["buildStoragePathData","isStoragePathWithinCollectionPrefix","combineQueries","executeAccess","Forbidden","getDocumentFileKeys","collectionPrefix","doc","useCompositePrefixes","filename","Object","values","sizes","map","size","filter","docPrefix","prefix","storageFilePath","findMatchingDocs","collectionSlug","req","requestedFilename","requestedStorageFilePath","collection","payload","collections","imageSizes","config","upload","filenameQueries","equals","name","result","find","depth","draft","overrideAccess","pagination","where","or","docs","includes","canUpdateDoc","accessResult","id","slug","disableErrors","access","update","limit","length","authorizeClientOverwrite","collectionPrefixArg","collectionSources","requestedCollectionSlug","t","matchedDocs","Promise","all","flat","matchedDoc"],"mappings":"AAEA,SACEA,oBAAoB,EACpBC,mCAAmC,QAC9B,6CAA4C;AACnD,SAASC,cAAc,EAAEC,aAAa,EAAEC,SAAS,QAAQ,UAAS;AAelE,SAASC,oBAAoB,EAC3BC,gBAAgB,EAChBC,GAAG,EACHC,oBAAoB,EAKrB;IACC,OAAO;QAACD,IAAIE,QAAQ;WAAKC,OAAOC,MAAM,CAACJ,IAAIK,KAAK,IAAI,CAAC,GAAGC,GAAG,CAAC,CAACC,OAASA,MAAML;KAAU,CACnFM,MAAM,CAAC,CAACN,WAAiC,OAAOA,aAAa,UAC7DI,GAAG,CACF,CAACJ,WACCT,qBAAqB;YACnBM;YACAU,WAAWT,IAAIU,MAAM;YACrBR;YACAD;QACF,GAAGU,eAAe;AAE1B;AAEA,eAAeC,iBAAiB,EAC9Bb,gBAAgB,EAChBc,cAAc,EACdC,GAAG,EACHC,iBAAiB,EACjBC,wBAAwB,EACxBf,oBAAoB,EAQrB;IACC,MAAMgB,aAAaH,IAAII,OAAO,CAACC,WAAW,CAACN,eAAe;IAE1D,IAAI,CAACI,YAAY;QACf,OAAO,EAAE;IACX;IAEA,MAAMG,aACJH,WAAWI,MAAM,CAACC,MAAM,IAAI,OAAOL,WAAWI,MAAM,CAACC,MAAM,KAAK,WAC5DL,WAAWI,MAAM,CAACC,MAAM,CAACF,UAAU,IAAI,EAAE,GACzC,EAAE;IACR,MAAMG,kBAA2B;QAC/B;YAAErB,UAAU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EACrCC,iBAAiB,EACjBjB,iBAAiB,KAAK,EACtBhB,GAAG,EACHkC,uBAAuB,EACvBjC,iBAAiB,EACjBC,wBAAwB,EASzB;IACC,IACE,CAACtB,oCAAoC;QACnCK,kBAAkB+C;QAClBrC,WAAWO;IACb,IACA;QACA,MAAM,IAAInB,UAAUiB,IAAImC,CAAC;IAC3B;IAEA,MAAMC,cAAc,AAClB,CAAA,MAAMC,QAAQC,GAAG,CACfL,kBAAkBzC,GAAG,CACnB,OAAO,EAAEP,gBAAgB,EAAEc,cAAc,EAAEZ,oBAAoB,EAAE;QAC/D,MAAMiC,OAAO,MAAMtB,iBAAiB;YAClCb;YACAc;YACAC;YACAC;YACAC;YACAf;QACF;QAEA,OAAOiC,KAAK5B,GAAG,CAAC,CAACN,MAAS,CAAA;gBAAEa;gBAAgBb;YAAI,CAAA;IAClD,GAEJ,EACAqD,IAAI;IAEN,IAAIH,YAAYN,MAAM,KAAK,GAAG;QAC5B,OAAO;IACT;IAEA,MAAMU,aAAaJ,WAAW,CAAC,EAAE;IACjC,IAAIA,YAAYN,MAAM,KAAK,KAAKU,WAAWzC,cAAc,KAAKmC,yBAAyB;QACrF,MAAM,IAAInD,UAAUiB,IAAImC,CAAC;IAC3B;IAEA,IACE,CAACnB,kBACD,CAAE,MAAMM,aAAa;QAAEvB,gBAAgByC,WAAWzC,cAAc;QAAEb,KAAKsD,WAAWtD,GAAG;QAAEc;IAAI,IAC3F;QACA,MAAM,IAAIjB,UAAUiB,IAAImC,CAAC;IAC3B;IAEA,OAAO;AACT"}
@@ -1,11 +1,8 @@
1
1
  interface DeleteFileArgs {
2
2
  baseUrl: string;
3
- collectionPrefix?: string;
4
- docPrefix: string;
5
- filename: string;
3
+ storageFilePath: string;
6
4
  token: string;
7
- useCompositePrefixes?: boolean;
8
5
  }
9
- export declare function deleteFile({ baseUrl, collectionPrefix, docPrefix, filename, token, useCompositePrefixes, }: DeleteFileArgs): Promise<void>;
6
+ export declare function deleteFile({ baseUrl, storageFilePath, token, }: DeleteFileArgs): Promise<void>;
10
7
  export {};
11
8
  //# sourceMappingURL=deleteFile.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"deleteFile.d.ts","sourceRoot":"","sources":["../src/deleteFile.ts"],"names":[],"mappings":"AAIA,UAAU,cAAc;IACtB,OAAO,EAAE,MAAM,CAAA;IACf,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,SAAS,EAAE,MAAM,CAAA;IACjB,QAAQ,EAAE,MAAM,CAAA;IAChB,KAAK,EAAE,MAAM,CAAA;IACb,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B;AAED,wBAAsB,UAAU,CAAC,EAC/B,OAAO,EACP,gBAAqB,EACrB,SAAS,EACT,QAAQ,EACR,KAAK,EACL,oBAA4B,GAC7B,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAUhC"}
1
+ {"version":3,"file":"deleteFile.d.ts","sourceRoot":"","sources":["../src/deleteFile.ts"],"names":[],"mappings":"AAIA,UAAU,cAAc;IACtB,OAAO,EAAE,MAAM,CAAA;IACf,eAAe,EAAE,MAAM,CAAA;IACvB,KAAK,EAAE,MAAM,CAAA;CACd;AAED,wBAAsB,UAAU,CAAC,EAC/B,OAAO,EACP,eAAe,EACf,KAAK,GACN,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAEhC"}
@@ -1,14 +1,7 @@
1
1
  import { del } from '@vercel/blob';
2
- import { generateURL } from './generateURL.js';
3
- export async function deleteFile({ baseUrl, collectionPrefix = '', docPrefix, filename, token, useCompositePrefixes = false }) {
4
- const fileUrl = generateURL({
5
- baseUrl,
6
- collectionPrefix,
7
- filename,
8
- prefix: docPrefix,
9
- useCompositePrefixes
10
- });
11
- await del(fileUrl, {
2
+ import { buildBlobUrl } from './generateURL.js';
3
+ export async function deleteFile({ baseUrl, storageFilePath, token }) {
4
+ await del(buildBlobUrl(baseUrl, storageFilePath), {
12
5
  token
13
6
  });
14
7
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/deleteFile.ts"],"sourcesContent":["import { del } from '@vercel/blob'\n\nimport { generateURL } from './generateURL.js'\n\ninterface DeleteFileArgs {\n baseUrl: string\n collectionPrefix?: string\n docPrefix: string\n filename: string\n token: string\n useCompositePrefixes?: boolean\n}\n\nexport async function deleteFile({\n baseUrl,\n collectionPrefix = '',\n docPrefix,\n filename,\n token,\n useCompositePrefixes = false,\n}: DeleteFileArgs): Promise<void> {\n const fileUrl = generateURL({\n baseUrl,\n collectionPrefix,\n filename,\n prefix: docPrefix,\n useCompositePrefixes,\n })\n\n await del(fileUrl, { token })\n}\n"],"names":["del","generateURL","deleteFile","baseUrl","collectionPrefix","docPrefix","filename","token","useCompositePrefixes","fileUrl","prefix"],"mappings":"AAAA,SAASA,GAAG,QAAQ,eAAc;AAElC,SAASC,WAAW,QAAQ,mBAAkB;AAW9C,OAAO,eAAeC,WAAW,EAC/BC,OAAO,EACPC,mBAAmB,EAAE,EACrBC,SAAS,EACTC,QAAQ,EACRC,KAAK,EACLC,uBAAuB,KAAK,EACb;IACf,MAAMC,UAAUR,YAAY;QAC1BE;QACAC;QACAE;QACAI,QAAQL;QACRG;IACF;IAEA,MAAMR,IAAIS,SAAS;QAAEF;IAAM;AAC7B"}
1
+ {"version":3,"sources":["../src/deleteFile.ts"],"sourcesContent":["import { del } from '@vercel/blob'\n\nimport { buildBlobUrl } from './generateURL.js'\n\ninterface DeleteFileArgs {\n baseUrl: string\n storageFilePath: string\n token: string\n}\n\nexport async function deleteFile({\n baseUrl,\n storageFilePath,\n token,\n}: DeleteFileArgs): Promise<void> {\n await del(buildBlobUrl(baseUrl, storageFilePath), { token })\n}\n"],"names":["del","buildBlobUrl","deleteFile","baseUrl","storageFilePath","token"],"mappings":"AAAA,SAASA,GAAG,QAAQ,eAAc;AAElC,SAASC,YAAY,QAAQ,mBAAkB;AAQ/C,OAAO,eAAeC,WAAW,EAC/BC,OAAO,EACPC,eAAe,EACfC,KAAK,EACU;IACf,MAAML,IAAIC,aAAaE,SAASC,kBAAkB;QAAEC;IAAM;AAC5D"}
@@ -5,6 +5,7 @@ interface GenerateURLArgs {
5
5
  prefix: string;
6
6
  useCompositePrefixes?: boolean;
7
7
  }
8
+ export declare function buildBlobUrl(baseUrl: string, storageFilePath: string): string;
8
9
  export declare function generateURL({ baseUrl, collectionPrefix, filename, prefix, useCompositePrefixes, }: GenerateURLArgs): string;
9
10
  export {};
10
11
  //# sourceMappingURL=generateURL.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"generateURL.d.ts","sourceRoot":"","sources":["../src/generateURL.ts"],"names":[],"mappings":"AAGA,UAAU,eAAe;IACvB,OAAO,EAAE,MAAM,CAAA;IACf,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;IACd,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B;AAED,wBAAgB,WAAW,CAAC,EAC1B,OAAO,EACP,gBAAqB,EACrB,QAAQ,EACR,MAAM,EACN,oBAA4B,GAC7B,EAAE,eAAe,GAAG,MAAM,CAgB1B"}
1
+ {"version":3,"file":"generateURL.d.ts","sourceRoot":"","sources":["../src/generateURL.ts"],"names":[],"mappings":"AAGA,UAAU,eAAe;IACvB,OAAO,EAAE,MAAM,CAAA;IACf,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;IACd,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B;AAGD,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,GAAG,MAAM,CAU7E;AAED,wBAAgB,WAAW,CAAC,EAC1B,OAAO,EACP,gBAAqB,EACrB,QAAQ,EACR,MAAM,EACN,oBAA4B,GAC7B,EAAE,eAAe,GAAG,MAAM,CAS1B"}
@@ -1,19 +1,23 @@
1
- import { getFileKey } from '@payloadcms/plugin-cloud-storage/utilities';
1
+ import { buildStoragePathData } from '@payloadcms/plugin-cloud-storage/utilities';
2
2
  import path from 'path';
3
+ // Builds the public blob URL for a storage path, URL-encoding only the filename segment.
4
+ export function buildBlobUrl(baseUrl, storageFilePath) {
5
+ // example: "my-collection/my-doc/my file.jpg" -> "my-collection/my-doc"
6
+ const dir = path.posix.dirname(storageFilePath);
7
+ // example: "my file.jpg" -> "my%20file.jpg"
8
+ const encodedFilename = encodeURIComponent(path.posix.basename(storageFilePath));
9
+ // example: "my-collection/my-doc/my%20file.jpg"
10
+ const storageFilePathWithEncodedFilename = dir === '.' ? encodedFilename : path.posix.join(dir, encodedFilename);
11
+ return `${baseUrl}/${storageFilePathWithEncodedFilename}`;
12
+ }
3
13
  export function generateURL({ baseUrl, collectionPrefix = '', filename, prefix, useCompositePrefixes = false }) {
4
- const { fileKey: fileKeyWithPrefix } = getFileKey({
14
+ const { storageFilePath } = buildStoragePathData({
5
15
  collectionPrefix,
6
16
  docPrefix: prefix,
7
17
  filename,
8
18
  useCompositePrefixes
9
19
  });
10
- // example: "my-collection/my-doc/my file.jpg" -> "my-collection/my-doc"
11
- const dir = path.posix.dirname(fileKeyWithPrefix);
12
- // example: "my file.jpg" -> "my%20file.jpg"
13
- const encodedFilename = encodeURIComponent(path.posix.basename(fileKeyWithPrefix));
14
- // example: "my-collection/my-doc/my%20file.jpg"
15
- const fileKeyWithEncodedFilename = dir === '.' ? encodedFilename : path.posix.join(dir, encodedFilename);
16
- return `${baseUrl}/${fileKeyWithEncodedFilename}`;
20
+ return buildBlobUrl(baseUrl, storageFilePath);
17
21
  }
18
22
 
19
23
  //# sourceMappingURL=generateURL.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/generateURL.ts"],"sourcesContent":["import { getFileKey } from '@payloadcms/plugin-cloud-storage/utilities'\nimport path from 'path'\n\ninterface GenerateURLArgs {\n baseUrl: string\n collectionPrefix?: string\n filename: string\n prefix: string\n useCompositePrefixes?: boolean\n}\n\nexport function generateURL({\n baseUrl,\n collectionPrefix = '',\n filename,\n prefix,\n useCompositePrefixes = false,\n}: GenerateURLArgs): string {\n const { fileKey: fileKeyWithPrefix } = getFileKey({\n collectionPrefix,\n docPrefix: prefix,\n filename,\n useCompositePrefixes,\n })\n // example: \"my-collection/my-doc/my file.jpg\" -> \"my-collection/my-doc\"\n const dir = path.posix.dirname(fileKeyWithPrefix)\n // example: \"my file.jpg\" -> \"my%20file.jpg\"\n const encodedFilename = encodeURIComponent(path.posix.basename(fileKeyWithPrefix))\n // example: \"my-collection/my-doc/my%20file.jpg\"\n const fileKeyWithEncodedFilename =\n dir === '.' ? encodedFilename : path.posix.join(dir, encodedFilename)\n\n return `${baseUrl}/${fileKeyWithEncodedFilename}`\n}\n"],"names":["getFileKey","path","generateURL","baseUrl","collectionPrefix","filename","prefix","useCompositePrefixes","fileKey","fileKeyWithPrefix","docPrefix","dir","posix","dirname","encodedFilename","encodeURIComponent","basename","fileKeyWithEncodedFilename","join"],"mappings":"AAAA,SAASA,UAAU,QAAQ,6CAA4C;AACvE,OAAOC,UAAU,OAAM;AAUvB,OAAO,SAASC,YAAY,EAC1BC,OAAO,EACPC,mBAAmB,EAAE,EACrBC,QAAQ,EACRC,MAAM,EACNC,uBAAuB,KAAK,EACZ;IAChB,MAAM,EAAEC,SAASC,iBAAiB,EAAE,GAAGT,WAAW;QAChDI;QACAM,WAAWJ;QACXD;QACAE;IACF;IACA,wEAAwE;IACxE,MAAMI,MAAMV,KAAKW,KAAK,CAACC,OAAO,CAACJ;IAC/B,4CAA4C;IAC5C,MAAMK,kBAAkBC,mBAAmBd,KAAKW,KAAK,CAACI,QAAQ,CAACP;IAC/D,gDAAgD;IAChD,MAAMQ,6BACJN,QAAQ,MAAMG,kBAAkBb,KAAKW,KAAK,CAACM,IAAI,CAACP,KAAKG;IAEvD,OAAO,GAAGX,QAAQ,CAAC,EAAEc,4BAA4B;AACnD"}
1
+ {"version":3,"sources":["../src/generateURL.ts"],"sourcesContent":["import { buildStoragePathData } from '@payloadcms/plugin-cloud-storage/utilities'\nimport path from 'path'\n\ninterface GenerateURLArgs {\n baseUrl: string\n collectionPrefix?: string\n filename: string\n prefix: string\n useCompositePrefixes?: boolean\n}\n\n// Builds the public blob URL for a storage path, URL-encoding only the filename segment.\nexport function buildBlobUrl(baseUrl: string, storageFilePath: string): string {\n // example: \"my-collection/my-doc/my file.jpg\" -> \"my-collection/my-doc\"\n const dir = path.posix.dirname(storageFilePath)\n // example: \"my file.jpg\" -> \"my%20file.jpg\"\n const encodedFilename = encodeURIComponent(path.posix.basename(storageFilePath))\n // example: \"my-collection/my-doc/my%20file.jpg\"\n const storageFilePathWithEncodedFilename =\n dir === '.' ? encodedFilename : path.posix.join(dir, encodedFilename)\n\n return `${baseUrl}/${storageFilePathWithEncodedFilename}`\n}\n\nexport function generateURL({\n baseUrl,\n collectionPrefix = '',\n filename,\n prefix,\n useCompositePrefixes = false,\n}: GenerateURLArgs): string {\n const { storageFilePath } = buildStoragePathData({\n collectionPrefix,\n docPrefix: prefix,\n filename,\n useCompositePrefixes,\n })\n\n return buildBlobUrl(baseUrl, storageFilePath)\n}\n"],"names":["buildStoragePathData","path","buildBlobUrl","baseUrl","storageFilePath","dir","posix","dirname","encodedFilename","encodeURIComponent","basename","storageFilePathWithEncodedFilename","join","generateURL","collectionPrefix","filename","prefix","useCompositePrefixes","docPrefix"],"mappings":"AAAA,SAASA,oBAAoB,QAAQ,6CAA4C;AACjF,OAAOC,UAAU,OAAM;AAUvB,yFAAyF;AACzF,OAAO,SAASC,aAAaC,OAAe,EAAEC,eAAuB;IACnE,wEAAwE;IACxE,MAAMC,MAAMJ,KAAKK,KAAK,CAACC,OAAO,CAACH;IAC/B,4CAA4C;IAC5C,MAAMI,kBAAkBC,mBAAmBR,KAAKK,KAAK,CAACI,QAAQ,CAACN;IAC/D,gDAAgD;IAChD,MAAMO,qCACJN,QAAQ,MAAMG,kBAAkBP,KAAKK,KAAK,CAACM,IAAI,CAACP,KAAKG;IAEvD,OAAO,GAAGL,QAAQ,CAAC,EAAEQ,oCAAoC;AAC3D;AAEA,OAAO,SAASE,YAAY,EAC1BV,OAAO,EACPW,mBAAmB,EAAE,EACrBC,QAAQ,EACRC,MAAM,EACNC,uBAAuB,KAAK,EACZ;IAChB,MAAM,EAAEb,eAAe,EAAE,GAAGJ,qBAAqB;QAC/Cc;QACAI,WAAWF;QACXD;QACAE;IACF;IAEA,OAAOf,aAAaC,SAASC;AAC/B"}
@@ -0,0 +1,20 @@
1
+ import type { StorageAdapter } from 'payload';
2
+ import type { VercelBlobCollectionSource } from './authorizeFileOverwrite.js';
3
+ type VercelBlobStorageMetadata = {
4
+ collections: Record<string, {
5
+ prefix?: string;
6
+ } | true | undefined>;
7
+ enabled: boolean;
8
+ storeId?: string;
9
+ useCompositePrefixes: boolean;
10
+ };
11
+ export declare const vercelBlobStorageMetadata: unique symbol;
12
+ export type InternalVercelBlobStorageAdapter = {
13
+ [vercelBlobStorageMetadata]: VercelBlobStorageMetadata;
14
+ } & StorageAdapter;
15
+ export declare const getCollectionSources: ({ currentAdapter, storageAdapters, }: {
16
+ currentAdapter: InternalVercelBlobStorageAdapter;
17
+ storageAdapters?: StorageAdapter[];
18
+ }) => VercelBlobCollectionSource[];
19
+ export {};
20
+ //# sourceMappingURL=getCollectionSources.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getCollectionSources.d.ts","sourceRoot":"","sources":["../src/getCollectionSources.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAE7C,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAA;AAE7E,KAAK,yBAAyB,GAAG;IAC/B,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,GAAG,SAAS,CAAC,CAAA;IACnE,OAAO,EAAE,OAAO,CAAA;IAChB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,oBAAoB,EAAE,OAAO,CAAA;CAC9B,CAAA;AAED,eAAO,MAAM,yBAAyB,eAAsC,CAAA;AAE5E,MAAM,MAAM,gCAAgC,GAAG;IAC7C,CAAC,yBAAyB,CAAC,EAAE,yBAAyB,CAAA;CACvD,GAAG,cAAc,CAAA;AAMlB,eAAO,MAAM,oBAAoB,yCAG9B;IACD,cAAc,EAAE,gCAAgC,CAAA;IAChD,eAAe,CAAC,EAAE,cAAc,EAAE,CAAA;CACnC,KAAG,0BAA0B,EAoB7B,CAAA"}
@@ -0,0 +1,27 @@
1
+ export const vercelBlobStorageMetadata = Symbol('vercelBlobStorageMetadata');
2
+ const isInternalVercelBlobStorageAdapter = (adapter)=>vercelBlobStorageMetadata in adapter;
3
+ export const getCollectionSources = ({ currentAdapter, storageAdapters = [] })=>{
4
+ const currentMetadata = currentAdapter[vercelBlobStorageMetadata];
5
+ const adapters = new Set([
6
+ currentAdapter,
7
+ ...storageAdapters
8
+ ]);
9
+ return [
10
+ ...adapters
11
+ ].flatMap((adapter)=>{
12
+ if (!isInternalVercelBlobStorageAdapter(adapter)) {
13
+ return [];
14
+ }
15
+ const metadata = adapter[vercelBlobStorageMetadata];
16
+ if (!metadata.enabled || metadata.storeId !== currentMetadata.storeId) {
17
+ return [];
18
+ }
19
+ return Object.entries(metadata.collections).map(([collectionSlug, options])=>({
20
+ collectionPrefix: options === true ? '' : options?.prefix || '',
21
+ collectionSlug,
22
+ useCompositePrefixes: metadata.useCompositePrefixes
23
+ }));
24
+ });
25
+ };
26
+
27
+ //# sourceMappingURL=getCollectionSources.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/getCollectionSources.ts"],"sourcesContent":["import type { StorageAdapter } from 'payload'\n\nimport type { VercelBlobCollectionSource } from './authorizeFileOverwrite.js'\n\ntype VercelBlobStorageMetadata = {\n collections: Record<string, { prefix?: string } | true | undefined>\n enabled: boolean\n storeId?: string\n useCompositePrefixes: boolean\n}\n\nexport const vercelBlobStorageMetadata = Symbol('vercelBlobStorageMetadata')\n\nexport type InternalVercelBlobStorageAdapter = {\n [vercelBlobStorageMetadata]: VercelBlobStorageMetadata\n} & StorageAdapter\n\nconst isInternalVercelBlobStorageAdapter = (\n adapter: StorageAdapter,\n): adapter is InternalVercelBlobStorageAdapter => vercelBlobStorageMetadata in adapter\n\nexport const getCollectionSources = ({\n currentAdapter,\n storageAdapters = [],\n}: {\n currentAdapter: InternalVercelBlobStorageAdapter\n storageAdapters?: StorageAdapter[]\n}): VercelBlobCollectionSource[] => {\n const currentMetadata = currentAdapter[vercelBlobStorageMetadata]\n const adapters = new Set([currentAdapter, ...storageAdapters])\n\n return [...adapters].flatMap((adapter) => {\n if (!isInternalVercelBlobStorageAdapter(adapter)) {\n return []\n }\n\n const metadata = adapter[vercelBlobStorageMetadata]\n if (!metadata.enabled || metadata.storeId !== currentMetadata.storeId) {\n return []\n }\n\n return Object.entries(metadata.collections).map(([collectionSlug, options]) => ({\n collectionPrefix: options === true ? '' : options?.prefix || '',\n collectionSlug,\n useCompositePrefixes: metadata.useCompositePrefixes,\n }))\n })\n}\n"],"names":["vercelBlobStorageMetadata","Symbol","isInternalVercelBlobStorageAdapter","adapter","getCollectionSources","currentAdapter","storageAdapters","currentMetadata","adapters","Set","flatMap","metadata","enabled","storeId","Object","entries","collections","map","collectionSlug","options","collectionPrefix","prefix","useCompositePrefixes"],"mappings":"AAWA,OAAO,MAAMA,4BAA4BC,OAAO,6BAA4B;AAM5E,MAAMC,qCAAqC,CACzCC,UACgDH,6BAA6BG;AAE/E,OAAO,MAAMC,uBAAuB,CAAC,EACnCC,cAAc,EACdC,kBAAkB,EAAE,EAIrB;IACC,MAAMC,kBAAkBF,cAAc,CAACL,0BAA0B;IACjE,MAAMQ,WAAW,IAAIC,IAAI;QAACJ;WAAmBC;KAAgB;IAE7D,OAAO;WAAIE;KAAS,CAACE,OAAO,CAAC,CAACP;QAC5B,IAAI,CAACD,mCAAmCC,UAAU;YAChD,OAAO,EAAE;QACX;QAEA,MAAMQ,WAAWR,OAAO,CAACH,0BAA0B;QACnD,IAAI,CAACW,SAASC,OAAO,IAAID,SAASE,OAAO,KAAKN,gBAAgBM,OAAO,EAAE;YACrE,OAAO,EAAE;QACX;QAEA,OAAOC,OAAOC,OAAO,CAACJ,SAASK,WAAW,EAAEC,GAAG,CAAC,CAAC,CAACC,gBAAgBC,QAAQ,GAAM,CAAA;gBAC9EC,kBAAkBD,YAAY,OAAO,KAAKA,SAASE,UAAU;gBAC7DH;gBACAI,sBAAsBX,SAASW,oBAAoB;YACrD,CAAA;IACF;AACF,EAAC"}
package/dist/getFile.d.ts CHANGED
@@ -1,17 +1,17 @@
1
- import type { CollectionConfig, PayloadRequest } from 'payload';
1
+ import type { CollectionConfig, PayloadRequest, TypeWithID } from 'payload';
2
2
  interface GetFileArgs {
3
3
  baseUrl: string;
4
4
  cacheControlMaxAge: number;
5
5
  collection: CollectionConfig;
6
6
  collectionPrefix?: string;
7
+ doc?: TypeWithID;
7
8
  filename: string;
8
9
  incomingHeaders?: Headers;
9
- prefixQueryParam?: string;
10
10
  req: PayloadRequest;
11
11
  token: string;
12
12
  uploadReference?: unknown;
13
13
  useCompositePrefixes?: boolean;
14
14
  }
15
- export declare function getFile({ baseUrl, cacheControlMaxAge, collection, collectionPrefix, filename, incomingHeaders, prefixQueryParam, req, token, uploadReference, useCompositePrefixes, }: GetFileArgs): Promise<Response>;
15
+ export declare function getFile({ baseUrl, cacheControlMaxAge, collection, collectionPrefix, doc, filename, incomingHeaders, req, token, uploadReference, useCompositePrefixes, }: GetFileArgs): Promise<Response>;
16
16
  export {};
17
17
  //# sourceMappingURL=getFile.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"getFile.d.ts","sourceRoot":"","sources":["../src/getFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAQ/D,UAAU,WAAW;IACnB,O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AG,EACH,QAAQ,EACR,eAAe,EACf,GAAG,EACH,KAAK,EACL,eAAe,EACf,oBAA4B,GAC7B,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC,CAgGjC"}
package/dist/getFile.js CHANGED
@@ -1,15 +1,17 @@
1
1
  import { getFilePrefix as getDocPrefix } from '@payloadcms/plugin-cloud-storage/utilities';
2
2
  import { BlobNotFoundError, head } from '@vercel/blob';
3
- import { getRangeRequestInfo } from 'payload/internal';
3
+ import { getRangeRequestInfo, isXmlMimeType, uploadContentSecurityPolicy } from 'payload/internal';
4
4
  import { generateURL } from './generateURL.js';
5
- export async function getFile({ baseUrl, cacheControlMaxAge, collection, collectionPrefix = '', filename, incomingHeaders, prefixQueryParam, req, token, uploadReference, useCompositePrefixes = false }) {
5
+ export async function getFile({ baseUrl, cacheControlMaxAge, collection, collectionPrefix = '', doc, filename, incomingHeaders, req, token, uploadReference, useCompositePrefixes = false }) {
6
6
  try {
7
7
  const docPrefix = await getDocPrefix({
8
8
  collection,
9
+ collectionPrefix,
10
+ doc,
9
11
  filename,
10
- prefixQueryParam,
11
12
  req,
12
- uploadReference
13
+ uploadReference,
14
+ useCompositePrefixes
13
15
  });
14
16
  const fileUrl = generateURL({
15
17
  baseUrl,
@@ -47,9 +49,9 @@ export async function getFile({ baseUrl, cacheControlMaxAge, collection, collect
47
49
  headers.append('Content-Disposition', contentDisposition);
48
50
  headers.append('Content-Type', contentType);
49
51
  headers.append('ETag', ETag);
50
- // Add Content-Security-Policy header for SVG files to prevent executable code
51
- if (contentType === 'image/svg+xml') {
52
- headers.append('Content-Security-Policy', "script-src 'none'");
52
+ // Apply a restrictive policy to XML-family responses served through Payload.
53
+ if (isXmlMimeType(contentType)) {
54
+ headers.append('Content-Security-Policy', uploadContentSecurityPolicy);
53
55
  }
54
56
  if (collection.upload && typeof collection.upload === 'object' && typeof collection.upload.modifyResponseHeaders === 'function') {
55
57
  headers = collection.upload.modifyResponseHeaders({
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/getFile.ts"],"sourcesContent":["import type { CollectionConfig, PayloadRequest } from 'payload'\n\nimport { getFilePrefix as getDocPrefix } from '@payloadcms/plugin-cloud-storage/utilities'\nimport { BlobNotFoundError, head } from '@vercel/blob'\nimport { getRangeRequestInfo } from 'payload/internal'\n\nimport { generateURL } from './generateURL.js'\n\ninterface GetFileArgs {\n baseUrl: string\n cacheControlMaxAge: number\n collection: CollectionConfig\n collectionPrefix?: string\n filename: string\n incomingHeaders?: Headers\n prefixQueryParam?: string\n req: PayloadRequest\n token: string\n uploadReference?: unknown\n useCompositePrefixes?: boolean\n}\n\nexport async function getFile({\n baseUrl,\n cacheControlMaxAge,\n collection,\n collectionPrefix = '',\n filename,\n incomingHeaders,\n prefixQueryParam,\n req,\n token,\n uploadReference,\n useCompositePrefixes = false,\n}: GetFileArgs): Promise<Response> {\n try {\n const docPrefix = await getDocPrefix({\n collection,\n filename,\n prefixQueryParam,\n req,\n uploadReference,\n })\n\n const fileUrl = generateURL({\n baseUrl,\n collectionPrefix,\n filename,\n prefix: docPrefix,\n useCompositePrefixes,\n })\n const etagFromHeaders = req.headers.get('etag') || req.headers.get('if-none-match')\n const blobMetadata = await head(fileUrl, { token })\n const { contentDisposition, contentType, size, uploadedAt } = blobMetadata\n const uploadedAtString = uploadedAt.toISOString()\n const fileKeyForETag = fileUrl.replace(`${baseUrl}/`, '')\n const ETag = `\"${fileKeyForETag}-${uploadedAtString}\"`\n\n // Handle range request\n const rangeHeader = req.headers.get('range')\n const rangeResult = getRangeRequestInfo({ fileSize: size, 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 let headers = new Headers(incomingHeaders)\n\n // Add range-related headers from the result\n for (const [key, value] of Object.entries(rangeResult.headers)) {\n headers.append(key, value)\n }\n\n headers.append('Cache-Control', `public, max-age=${cacheControlMaxAge}`)\n headers.append('Content-Disposition', contentDisposition)\n headers.append('Content-Type', contentType)\n headers.append('ETag', ETag)\n\n // Add Content-Security-Policy header for SVG files to prevent executable code\n if (contentType === 'image/svg+xml') {\n headers.append('Content-Security-Policy', \"script-src 'none'\")\n }\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 === ETag) {\n return new Response(null, {\n headers,\n status: 304,\n })\n }\n\n const response = await fetch(`${fileUrl}?${uploadedAtString}`, {\n headers: {\n 'Cache-Control': 'no-store, no-cache, must-revalidate',\n Pragma: 'no-cache',\n ...(rangeResult.type === 'partial' && {\n Range: `bytes=${rangeResult.rangeStart}-${rangeResult.rangeEnd}`,\n }),\n },\n })\n\n if (!response.ok || !response.body) {\n return new Response(null, { status: 204, statusText: 'No Content' })\n }\n\n headers.append('Last-Modified', uploadedAtString)\n\n return new Response(response.body, {\n headers,\n status: rangeResult.status,\n })\n } catch (err: unknown) {\n if (err instanceof BlobNotFoundError) {\n return new Response(null, { status: 404, statusText: 'Not Found' })\n }\n req.payload.logger.error({ err, msg: 'Unexpected error in staticHandler' })\n return new Response('Internal Server Error', { status: 500 })\n }\n}\n"],"names":["getFilePrefix","getDocPrefix","BlobNotFoundError","head","getRangeRequestInfo","generateURL","getFile","baseUrl","cacheControlMaxAge","collection","collectionPrefix","filename","incomingHeaders","prefixQueryParam","req","token","uploadReference","useCompositePrefixes","docPrefix","fileUrl","prefix","etagFromHeaders","headers","get","blobMetadata","contentDisposition","contentType","size","uploadedAt","uploadedAtString","toISOString","fileKeyForETag","replace","ETag","rangeHeader","rangeResult","fileSize","type","Response","Headers","status","key","value","Object","entries","append","upload","modifyResponseHeaders","response","fetch","Pragma","Range","rangeStart","rangeEnd","ok","body","statusText","err","payload","logger","error","msg"],"mappings":"AAEA,SAASA,iBAAiBC,YAAY,QAAQ,6CAA4C;AAC1F,SAASC,iBAAiB,EAAEC,IAAI,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B,KAAc;QACrB,IAAIA,eAAevD,mBAAmB;YACpC,OAAO,IAAIoC,SAAS,MAAM;gBAAEE,QAAQ;gBAAKgB,YAAY;YAAY;QACnE;QACA1C,IAAI4C,OAAO,CAACC,MAAM,CAACC,KAAK,CAAC;YAAEH;YAAKI,KAAK;QAAoC;QACzE,OAAO,IAAIvB,SAAS,yBAAyB;YAAEE,QAAQ;QAAI;IAC7D;AACF"}
1
+ {"version":3,"sources":["../src/getFile.ts"],"sourcesContent":["import type { CollectionConfig, PayloadRequest, TypeWithID } from 'payload'\n\nimport { getFilePrefix as getDocPrefix } from '@payloadcms/plugin-cloud-storage/utilities'\nimport { BlobNotFoundError, head } from '@vercel/blob'\nimport { getRangeRequestInfo, isXmlMimeType, uploadContentSecurityPolicy } from 'payload/internal'\n\nimport { generateURL } from './generateURL.js'\n\ninterface GetFileArgs {\n baseUrl: string\n cacheControlMaxAge: number\n collection: CollectionConfig\n collectionPrefix?: string\n doc?: TypeWithID\n filename: string\n incomingHeaders?: Headers\n req: PayloadRequest\n token: string\n uploadReference?: unknown\n useCompositePrefixes?: boolean\n}\n\nexport async function getFile({\n baseUrl,\n cacheControlMaxAge,\n collection,\n collectionPrefix = '',\n doc,\n filename,\n incomingHeaders,\n req,\n token,\n uploadReference,\n useCompositePrefixes = false,\n}: GetFileArgs): Promise<Response> {\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 fileUrl = generateURL({\n baseUrl,\n collectionPrefix,\n filename,\n prefix: docPrefix,\n useCompositePrefixes,\n })\n const etagFromHeaders = req.headers.get('etag') || req.headers.get('if-none-match')\n const blobMetadata = await head(fileUrl, { token })\n const { contentDisposition, contentType, size, uploadedAt } = blobMetadata\n const uploadedAtString = uploadedAt.toISOString()\n const fileKeyForETag = fileUrl.replace(`${baseUrl}/`, '')\n const ETag = `\"${fileKeyForETag}-${uploadedAtString}\"`\n\n // Handle range request\n const rangeHeader = req.headers.get('range')\n const rangeResult = getRangeRequestInfo({ fileSize: size, 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 let headers = new Headers(incomingHeaders)\n\n // Add range-related headers from the result\n for (const [key, value] of Object.entries(rangeResult.headers)) {\n headers.append(key, value)\n }\n\n headers.append('Cache-Control', `public, max-age=${cacheControlMaxAge}`)\n headers.append('Content-Disposition', contentDisposition)\n headers.append('Content-Type', contentType)\n headers.append('ETag', ETag)\n\n // Apply a restrictive policy to XML-family responses served through Payload.\n if (isXmlMimeType(contentType)) {\n headers.append('Content-Security-Policy', uploadContentSecurityPolicy)\n }\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 === ETag) {\n return new Response(null, {\n headers,\n status: 304,\n })\n }\n\n const response = await fetch(`${fileUrl}?${uploadedAtString}`, {\n headers: {\n 'Cache-Control': 'no-store, no-cache, must-revalidate',\n Pragma: 'no-cache',\n ...(rangeResult.type === 'partial' && {\n Range: `bytes=${rangeResult.rangeStart}-${rangeResult.rangeEnd}`,\n }),\n },\n })\n\n if (!response.ok || !response.body) {\n return new Response(null, { status: 204, statusText: 'No Content' })\n }\n\n headers.append('Last-Modified', uploadedAtString)\n\n return new Response(response.body, {\n headers,\n status: rangeResult.status,\n })\n } catch (err: unknown) {\n if (err instanceof BlobNotFoundError) {\n return new Response(null, { status: 404, statusText: 'Not Found' })\n }\n req.payload.logger.error({ err, msg: 'Unexpected error in staticHandler' })\n return new Response('Internal Server Error', { status: 500 })\n }\n}\n"],"names":["getFilePrefix","getDocPrefix","BlobNotFoundError","head","getRangeRequestInfo","isXmlMimeType","uploadContentSecurityPolicy","generateURL","getFile","baseUrl","cacheControlMaxAge","collection","collectionPrefix","doc","filename","incomingHeaders","req","token","uploadReference","useCompositePrefixes","docPrefix","fileUrl","prefix","etagFromHeaders","headers","get","blobMetadata","contentDisposition","contentType","size","uploadedAt","uploadedAtString","toISOString","fileKeyForETag","replace","ETag","rangeHeader","rangeResult","fileSize","type","Response","Headers","status","key","value","Object","entries","append","upload","modifyResponseHeaders","response","fetch","Pragma","Range","rangeStart","rangeEnd","ok","body","statusText","err","payload","logger","error","msg"],"mappings":"AAEA,SAASA,iBAAiBC,YAAY,QAAQ,6CAA4C;AAC1F,SAASC,iBAAiB,EAAEC,IAAI,QAAQ,eAAc;AACtD,SAASC,mBAAmB,EAAEC,aAAa,EAAEC,2BAA2B,QAAQ,mBAAkB;AAElG,SAASC,WAAW,QAAQ,mBAAkB;AAgB9C,OAAO,eAAeC,QAAQ,EAC5BC,OAAO,EACPC,kBAAkB,EAClBC,UAAU,EACVC,mBAAmB,EAAE,EACrBC,GAAG,EACHC,QAAQ,EACRC,eAAe,EACfC,GAAG,EACHC,KAAK,EACLC,eAAe,EACfC,uBAAuB,KAAK,EAChB;IACZ,IAAI;QACF,MAAMC,YAAY,MAAMnB,aAAa;YACnCU;YACAC;YACAC;YACAC;YACAE;YACAE;YACAC;QACF;QAEA,MAAME,UAAUd,YAAY;YAC1BE;YACAG;YACAE;YACAQ,QAAQF;YACRD;QACF;QACA,MAAMI,kBAAkBP,IAAIQ,OAAO,CAACC,GAAG,CAAC,WAAWT,IAAIQ,OAAO,CAACC,GAAG,CAAC;QACnE,MAAMC,eAAe,MAAMvB,KAAKkB,SAAS;YAAEJ;QAAM;QACjD,MAAM,EAAEU,kBAAkB,EAAEC,WAAW,EAAEC,IAAI,EAAEC,UAAU,EAAE,GAAGJ;QAC9D,MAAMK,mBAAmBD,WAAWE,WAAW;QAC/C,MAAMC,iBAAiBZ,QAAQa,OAAO,CAAC,GAAGzB,QAAQ,CAAC,CAAC,EAAE;QACtD,MAAM0B,OAAO,CAAC,CAAC,EAAEF,eAAe,CAAC,EAAEF,iBAAiB,CAAC,CAAC;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AAM,EAAEhB,YAAYiB,UAAU,CAAC,CAAC,EAAEjB,YAAYkB,QAAQ,EAAE;gBAClE,CAAC;YACH;QACF;QAEA,IAAI,CAACL,SAASM,EAAE,IAAI,CAACN,SAASO,IAAI,EAAE;YAClC,OAAO,IAAIjB,SAAS,MAAM;gBAAEE,QAAQ;gBAAKgB,YAAY;YAAa;QACpE;QAEAlC,QAAQuB,MAAM,CAAC,iBAAiBhB;QAEhC,OAAO,IAAIS,SAASU,SAASO,IAAI,EAAE;YACjCjC;YACAkB,QAAQL,YAAYK,MAAM;QAC5B;IACF,EAAE,OAAOiB,KAAc;QACrB,IAAIA,eAAezD,mBAAmB;YACpC,OAAO,IAAIsC,SAAS,MAAM;gBAAEE,QAAQ;gBAAKgB,YAAY;YAAY;QACnE;QACA1C,IAAI4C,OAAO,CAACC,MAAM,CAACC,KAAK,CAAC;YAAEH;YAAKI,KAAK;QAAoC;QACzE,OAAO,IAAIvB,SAAS,yBAAyB;YAAEE,QAAQ;QAAI;IAC7D;AACF"}
package/dist/index.d.ts CHANGED
@@ -14,16 +14,6 @@ export type VercelBlobStorageOptions = {
14
14
  * @default false
15
15
  */
16
16
  addRandomSuffix?: boolean;
17
- /**
18
- * When enabled, fields (like the prefix field) will always be inserted into
19
- * the collection schema regardless of whether the plugin is enabled. This
20
- * ensures a consistent schema across all environments.
21
- *
22
- * This will be enabled by default in Payload v4.
23
- *
24
- * @default false
25
- */
26
- alwaysInsertFields?: boolean;
27
17
  /**
28
18
  * Cache-Control max-age in seconds
29
19
  *
@@ -54,14 +44,15 @@ export type VercelBlobStorageOptions = {
54
44
  token: string | undefined;
55
45
  /**
56
46
  * When true, the collection-level prefix and document-level prefix are combined
57
- * (compositional). When false (default), document prefix overrides collection
58
- * prefix entirely.
47
+ * (compositional). When false (default), a document prefix already within the
48
+ * collection prefix is used as-is for new uploads; otherwise it is nested beneath it.
49
+ * Existing files retain their stored prefixes for reads, URLs, and cleanup.
59
50
  *
60
- * Example:
61
- * - collection prefix: `collection-prefix/`
62
- * - document prefix: `document-prefix/`
63
- * - resulting prefix with useCompositePrefixes=true: `collection-prefix/document-prefix/`
64
- * - resulting prefix with useCompositePrefixes=false: `document-prefix/`
51
+ * Example with a document prefix already contained by the collection prefix:
52
+ * - collection prefix: `uploads/`
53
+ * - document prefix: `uploads/documents/`
54
+ * - resulting prefix with useCompositePrefixes=true: `uploads/uploads/documents/`
55
+ * - resulting prefix with useCompositePrefixes=false: `uploads/documents/`
65
56
  *
66
57
  * @default false
67
58
  */
@@ -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;AAC/C,OAAO,KAAK,EAAU,cAAc,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAM3E,MAAM,MAAM,wBAAwB,GAAG;IACrC;;;;;OAKG;IACH,MAAM,CAAC,EAAE,QAAQ,CAAA;IAEjB;;;;OAIG;IACH,eAAe,CAAC,EAAE,OAAO,CAAA;IAEzB;;;;;;;;OAQG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAE5B;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAE3B;;OAEG;IACH,aAAa,CAAC,EAAE,mBAAmB,CAAA;IAEnC;;OAEG;IACH,WAAW,EAAE,OAAO,CAAC,MAAM,CAAC,oBAAoB,EAAE,IAAI,CAAC,iBAAiB,EAAE,SAAS,CAAC,GAAG,IAAI,CAAC,CAAC,CAAA;IAE7F;;;;OAIG;IACH,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB;;;;;;OAMG;IACH,KAAK,EAAE,MAAM,GAAG,SAAS,CAAA;IAEzB;;;;;;;;;;;;OAYG;IACH,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B,CAAA;AASD,KAAK,wBAAwB,GAAG,CAAC,qBAAqB,EAAE,wBAAwB,KAAK,cAAc,CAAA;AAEnG,eAAO,MAAM,iBAAiB,EAAE,wBAoG9B,CAAA"}
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;AAC/C,OAAO,KAAK,EAAU,cAAc,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAW3E,MAAM,MAAM,wBAAwB,GAAG;IACrC;;;;;OAKG;IACH,MAAM,CAAC,EAAE,QAAQ,CAAA;IAEjB;;;;OAIG;IACH,eAAe,CAAC,EAAE,OAAO,CAAA;IAEzB;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAE3B;;OAEG;IACH,aAAa,CAAC,EAAE,mBAAmB,CAAA;IAEnC;;OAEG;IACH,WAAW,EAAE,OAAO,CAAC,MAAM,CAAC,oBAAoB,EAAE,IAAI,CAAC,iBAAiB,EAAE,SAAS,CAAC,GAAG,IAAI,CAAC,CAAC,CAAA;IAE7F;;;;OAIG;IACH,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB;;;;;;OAMG;IACH,KAAK,EAAE,MAAM,GAAG,SAAS,CAAA;IAEzB;;;;;;;;;;;;;OAaG;IACH,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B,CAAA;AASD,KAAK,wBAAwB,GAAG,CAAC,qBAAqB,EAAE,wBAAwB,KAAK,cAAc,CAAA;AAEnG,eAAO,MAAM,iBAAiB,EAAE,wBAwG/B,CAAA"}
package/dist/index.js CHANGED
@@ -1,18 +1,19 @@
1
1
  import { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage';
2
2
  import { createVercelBlobAdapter } from './adapter.js';
3
+ import { getCollectionSources, vercelBlobStorageMetadata } from './getCollectionSources.js';
3
4
  const defaultUploadOptions = {
4
5
  access: 'public',
5
6
  addRandomSuffix: false,
6
7
  cacheControlMaxAge: 60 * 60 * 24 * 365,
7
8
  enabled: true
8
9
  };
9
- export const vercelBlobStorage = (options)=>({
10
+ export const vercelBlobStorage = (options)=>{
11
+ const storeId = options.token?.match(/^vercel_blob_rw_([a-z\d]+)_[a-z\d]+$/i)?.[1]?.toLowerCase();
12
+ const isPluginDisabled = options.enabled === false || !options.token;
13
+ const storageAdapter = {
10
14
  name: 'vercel-blob',
11
15
  collections: Object.keys(options.collections),
12
16
  init: (incomingConfig)=>{
13
- // Parse storeId from token
14
- const storeId = options.token?.match(/^vercel_blob_rw_([a-z\d]+)_[a-z\d]+$/i)?.[1]?.toLowerCase();
15
- const isPluginDisabled = options.enabled === false || !options.token;
16
17
  // Don't throw if the plugin is disabled
17
18
  if (!storeId && !isPluginDisabled) {
18
19
  throw new Error('Invalid token format for Vercel Blob adapter. Should be vercel_blob_rw_<store_id>_<random_string>.');
@@ -25,22 +26,18 @@ export const vercelBlobStorage = (options)=>({
25
26
  const baseUrl = process.env.STORAGE_VERCEL_BLOB_BASE_URL || `https://${storeId}.${optionsWithDefaults.access}.blob.vercel-storage.com`;
26
27
  // If the plugin is disabled or no token is provided, do not enable the plugin
27
28
  if (isPluginDisabled) {
28
- if (options.alwaysInsertFields) {
29
- const collectionsWithoutAdapter = Object.entries(options.collections).reduce((acc, [slug, collOptions])=>({
30
- ...acc,
31
- [slug]: {
32
- ...collOptions === true ? {} : collOptions,
33
- adapter: null
34
- }
35
- }), {});
36
- return cloudStoragePlugin({
37
- alwaysInsertFields: true,
38
- collections: collectionsWithoutAdapter,
39
- enabled: false,
40
- useCompositePrefixes: options.useCompositePrefixes
41
- })(incomingConfig);
42
- }
43
- return incomingConfig;
29
+ const collectionsWithoutAdapter = Object.entries(options.collections).reduce((acc, [slug, collOptions])=>({
30
+ ...acc,
31
+ [slug]: {
32
+ ...collOptions === true ? {} : collOptions,
33
+ adapter: null
34
+ }
35
+ }), {});
36
+ return cloudStoragePlugin({
37
+ collections: collectionsWithoutAdapter,
38
+ enabled: false,
39
+ useCompositePrefixes: options.useCompositePrefixes
40
+ })(incomingConfig);
44
41
  }
45
42
  const adapter = createVercelBlobAdapter({
46
43
  access: optionsWithDefaults.access ?? 'public',
@@ -48,6 +45,10 @@ export const vercelBlobStorage = (options)=>({
48
45
  baseUrl,
49
46
  cacheControlMaxAge: optionsWithDefaults.cacheControlMaxAge ?? 60 * 60 * 24 * 365,
50
47
  clientUploads: optionsWithDefaults.clientUploads,
48
+ collectionSources: getCollectionSources({
49
+ currentAdapter: storageAdapter,
50
+ storageAdapters: incomingConfig.storage
51
+ }),
51
52
  token: options.token,
52
53
  useCompositePrefixes: options.useCompositePrefixes
53
54
  });
@@ -76,11 +77,18 @@ export const vercelBlobStorage = (options)=>({
76
77
  })
77
78
  };
78
79
  return cloudStoragePlugin({
79
- alwaysInsertFields: options.alwaysInsertFields,
80
80
  collections: collectionsWithAdapter,
81
81
  useCompositePrefixes: options.useCompositePrefixes
82
82
  })(config);
83
+ },
84
+ [vercelBlobStorageMetadata]: {
85
+ collections: options.collections,
86
+ enabled: !isPluginDisabled,
87
+ storeId,
88
+ useCompositePrefixes: Boolean(options.useCompositePrefixes)
83
89
  }
84
- });
90
+ };
91
+ return storageAdapter;
92
+ };
85
93
 
86
94
  //# 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 { Config, StorageAdapter, UploadCollectionSlug } from 'payload'\n\nimport { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage'\n\nimport { createVercelBlobAdapter } from './adapter.js'\n\nexport type VercelBlobStorageOptions = {\n /**\n * Access control level. Currently, only 'public' is supported.\n * Vercel plans on adding support for private blobs in the future.\n *\n * @default 'public'\n */\n access?: 'public'\n\n /**\n * Add a random suffix to the uploaded file name in Vercel Blob storage\n *\n * @default false\n */\n addRandomSuffix?: boolean\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 * Cache-Control max-age in seconds\n *\n * @default 365 * 24 * 60 * 60 // (1 Year)\n */\n cacheControlMaxAge?: number\n\n /**\n * Upload directly to Vercel Blob instead of through Payload.\n */\n clientUploads?: ClientUploadsConfig\n\n /**\n * Collections to apply the Vercel Blob adapter to\n */\n collections: Partial<Record<UploadCollectionSlug, Omit<CollectionOptions, 'adapter'> | true>>\n\n /**\n * Whether or not to enable the plugin\n *\n * Default: true\n */\n enabled?: boolean\n /**\n * Vercel Blob storage read/write token\n *\n * Usually process.env.BLOB_READ_WRITE_TOKEN set by Vercel\n *\n * If unset, the plugin will be disabled and will fallback to local storage\n */\n token: string | undefined\n\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\nconst defaultUploadOptions: Partial<VercelBlobStorageOptions> = {\n access: 'public',\n addRandomSuffix: false,\n cacheControlMaxAge: 60 * 60 * 24 * 365, // 1 year\n enabled: true,\n}\n\ntype VercelBlobStorageFactory = (vercelBlobStorageOpts: VercelBlobStorageOptions) => StorageAdapter\n\nexport const vercelBlobStorage: VercelBlobStorageFactory = (\n options: VercelBlobStorageOptions,\n): StorageAdapter => ({\n name: 'vercel-blob',\n collections: Object.keys(options.collections),\n init: (incomingConfig: Config): Config => {\n // Parse storeId from token\n const storeId = options.token\n ?.match(/^vercel_blob_rw_([a-z\\d]+)_[a-z\\d]+$/i)?.[1]\n ?.toLowerCase()\n\n const isPluginDisabled = options.enabled === false || !options.token\n\n // Don't throw if the plugin is disabled\n if (!storeId && !isPluginDisabled) {\n throw new Error(\n 'Invalid token format for Vercel Blob adapter. Should be vercel_blob_rw_<store_id>_<random_string>.',\n )\n }\n\n const optionsWithDefaults = {\n ...defaultUploadOptions,\n ...options,\n }\n\n // support overriding the base URL for emulator https://github.com/payloadcms/vercel-blob-emulator\n const baseUrl =\n process.env.STORAGE_VERCEL_BLOB_BASE_URL ||\n `https://${storeId}.${optionsWithDefaults.access}.blob.vercel-storage.com`\n\n // If the plugin is disabled or no token is provided, do not enable the plugin\n if (isPluginDisabled) {\n if (options.alwaysInsertFields) {\n const collectionsWithoutAdapter: CloudStoragePluginOptions['collections'] = Object.entries(\n options.collections,\n ).reduce(\n (acc, [slug, collOptions]) => ({\n ...acc,\n [slug]: { ...(collOptions === true ? {} : collOptions), adapter: null },\n }),\n {} as Record<string, CollectionOptions>,\n )\n return cloudStoragePlugin({\n alwaysInsertFields: true,\n collections: collectionsWithoutAdapter,\n enabled: false,\n useCompositePrefixes: options.useCompositePrefixes,\n })(incomingConfig)\n }\n return incomingConfig\n }\n\n const adapter = createVercelBlobAdapter({\n access: optionsWithDefaults.access ?? 'public',\n addRandomSuffix: optionsWithDefaults.addRandomSuffix,\n baseUrl,\n cacheControlMaxAge: optionsWithDefaults.cacheControlMaxAge ?? 60 * 60 * 24 * 365,\n clientUploads: optionsWithDefaults.clientUploads,\n token: options.token!,\n useCompositePrefixes: options.useCompositePrefixes,\n })\n\n // Add adapter to each collection option object\n const collectionsWithAdapter: CloudStoragePluginOptions['collections'] = Object.entries(\n options.collections,\n ).reduce(\n (acc, [slug, collOptions]) => ({\n ...acc,\n [slug]: {\n ...(collOptions === true ? {} : collOptions),\n adapter,\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: options.alwaysInsertFields,\n collections: collectionsWithAdapter,\n useCompositePrefixes: options.useCompositePrefixes,\n })(config)\n },\n})\n"],"names":["cloudStoragePlugin","createVercelBlobAdapter","defaultUploadOptions","access","addRandomSuffix","cacheControlMaxAge","enabled","vercelBlobStorage","options","name","collections","Object","keys","init","incomingConfig","storeId","token","match","toLowerCase","isPluginDisabled","Error","optionsWithDefaults","baseUrl","process","env","STORAGE_VERCEL_BLOB_BASE_URL","alwaysInsertFields","collectionsWithoutAdapter","entries","reduce","acc","slug","collOptions","adapter","useCompositePrefixes","clientUploads","collectionsWithAdapter","config","map","collection","upload","disableLocalStorage"],"mappings":"AAOA,SAASA,kBAAkB,QAAQ,mCAAkC;AAErE,SAASC,uBAAuB,QAAQ,eAAc;AA6EtD,MAAMC,uBAA0D;IAC9DC,QAAQ;IACRC,iBAAiB;IACjBC,oBAAoB,KAAK,KAAK,KAAK;IACnCC,SAAS;AACX;AAIA,OAAO,MAAMC,oBAA8C,CACzDC,UACoB,CAAA;QACpBC,MAAM;QACNC,aAAaC,OAAOC,IAAI,CAACJ,QAAQE,WAAW;QAC5CG,MAAM,CAACC;YACL,2BAA2B;YAC3B,MAAMC,UAAUP,QAAQQ,KAAK,EACzBC,MAAM,0CAA0C,CAAC,EAAE,EACnDC;YAEJ,MAAMC,mBAAmBX,QAAQF,OAAO,KAAK,SAAS,CAACE,QAAQQ,KAAK;YAEpE,wCAAwC;YACxC,IAAI,CAACD,WAAW,CAACI,kBAAkB;gBACjC,MAAM,IAAIC,MACR;YAEJ;YAEA,MAAMC,sBAAsB;gBAC1B,GAAGnB,oBAAoB;gBACvB,GAAGM,OAAO;YACZ;YAEA,kGAAkG;YAClG,MAAMc,UACJC,QAAQC,GAAG,CAACC,4BAA4B,IACxC,CAAC,QAAQ,EAAEV,QA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G,CAAC,CAACC;oBACnD,IAAI,CAACH,sBAAsB,CAACG,WAAWR,IAAI,CAAC,EAAE;wBAC5C,OAAOQ;oBACT;oBAEA,OAAO;wBACL,GAAGA,UAAU;wBACbC,QAAQ;4BACN,GAAI,OAAOD,WAAWC,MAAM,KAAK,WAAWD,WAAWC,MAAM,GAAG,CAAC,CAAC;4BAClEC,qBAAqB;wBACvB;oBACF;gBACF;YACF;YAEA,OAAOzC,mBAAmB;gBACxB0B,oBAAoBlB,QAAQkB,kBAAkB;gBAC9ChB,aAAa0B;gBACbF,sBAAsB1B,QAAQ0B,oBAAoB;YACpD,GAAGG;QACL;IACF,CAAA,EAAE"}
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 { Config, StorageAdapter, UploadCollectionSlug } from 'payload'\n\nimport { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage'\n\nimport { createVercelBlobAdapter } from './adapter.js'\nimport {\n getCollectionSources,\n type InternalVercelBlobStorageAdapter,\n vercelBlobStorageMetadata,\n} from './getCollectionSources.js'\n\nexport type VercelBlobStorageOptions = {\n /**\n * Access control level. Currently, only 'public' is supported.\n * Vercel plans on adding support for private blobs in the future.\n *\n * @default 'public'\n */\n access?: 'public'\n\n /**\n * Add a random suffix to the uploaded file name in Vercel Blob storage\n *\n * @default false\n */\n addRandomSuffix?: boolean\n\n /**\n * Cache-Control max-age in seconds\n *\n * @default 365 * 24 * 60 * 60 // (1 Year)\n */\n cacheControlMaxAge?: number\n\n /**\n * Upload directly to Vercel Blob instead of through Payload.\n */\n clientUploads?: ClientUploadsConfig\n\n /**\n * Collections to apply the Vercel Blob adapter to\n */\n collections: Partial<Record<UploadCollectionSlug, Omit<CollectionOptions, 'adapter'> | true>>\n\n /**\n * Whether or not to enable the plugin\n *\n * Default: true\n */\n enabled?: boolean\n /**\n * Vercel Blob storage read/write token\n *\n * Usually process.env.BLOB_READ_WRITE_TOKEN set by Vercel\n *\n * If unset, the plugin will be disabled and will fallback to local storage\n */\n token: string | undefined\n\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\nconst defaultUploadOptions: Partial<VercelBlobStorageOptions> = {\n access: 'public',\n addRandomSuffix: false,\n cacheControlMaxAge: 60 * 60 * 24 * 365, // 1 year\n enabled: true,\n}\n\ntype VercelBlobStorageFactory = (vercelBlobStorageOpts: VercelBlobStorageOptions) => StorageAdapter\n\nexport const vercelBlobStorage: VercelBlobStorageFactory = (\n options: VercelBlobStorageOptions,\n): StorageAdapter => {\n const storeId = options.token?.match(/^vercel_blob_rw_([a-z\\d]+)_[a-z\\d]+$/i)?.[1]?.toLowerCase()\n const isPluginDisabled = options.enabled === false || !options.token\n const storageAdapter: InternalVercelBlobStorageAdapter = {\n name: 'vercel-blob',\n collections: Object.keys(options.collections),\n init: (incomingConfig: Config): Config => {\n // Don't throw if the plugin is disabled\n if (!storeId && !isPluginDisabled) {\n throw new Error(\n 'Invalid token format for Vercel Blob adapter. Should be vercel_blob_rw_<store_id>_<random_string>.',\n )\n }\n\n const optionsWithDefaults = {\n ...defaultUploadOptions,\n ...options,\n }\n\n // support overriding the base URL for emulator https://github.com/payloadcms/vercel-blob-emulator\n const baseUrl =\n process.env.STORAGE_VERCEL_BLOB_BASE_URL ||\n `https://${storeId}.${optionsWithDefaults.access}.blob.vercel-storage.com`\n\n // If the plugin is disabled or no token is provided, do not enable the plugin\n if (isPluginDisabled) {\n const collectionsWithoutAdapter: CloudStoragePluginOptions['collections'] = Object.entries(\n options.collections,\n ).reduce(\n (acc, [slug, collOptions]) => ({\n ...acc,\n [slug]: { ...(collOptions === true ? {} : collOptions), adapter: null },\n }),\n {} as Record<string, CollectionOptions>,\n )\n return cloudStoragePlugin({\n collections: collectionsWithoutAdapter,\n enabled: false,\n useCompositePrefixes: options.useCompositePrefixes,\n })(incomingConfig)\n }\n\n const adapter = createVercelBlobAdapter({\n access: optionsWithDefaults.access ?? 'public',\n addRandomSuffix: optionsWithDefaults.addRandomSuffix,\n baseUrl,\n cacheControlMaxAge: optionsWithDefaults.cacheControlMaxAge ?? 60 * 60 * 24 * 365,\n clientUploads: optionsWithDefaults.clientUploads,\n collectionSources: getCollectionSources({\n currentAdapter: storageAdapter,\n storageAdapters: incomingConfig.storage,\n }),\n token: options.token!,\n useCompositePrefixes: options.useCompositePrefixes,\n })\n\n // Add adapter to each collection option object\n const collectionsWithAdapter: CloudStoragePluginOptions['collections'] = Object.entries(\n options.collections,\n ).reduce(\n (acc, [slug, collOptions]) => ({\n ...acc,\n [slug]: {\n ...(collOptions === true ? {} : collOptions),\n adapter,\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: options.useCompositePrefixes,\n })(config)\n },\n [vercelBlobStorageMetadata]: {\n collections: options.collections,\n enabled: !isPluginDisabled,\n storeId,\n useCompositePrefixes: Boolean(options.useCompositePrefixes),\n },\n }\n\n return storageAdapter\n}\n"],"names":["cloudStoragePlugin","createVercelBlobAdapter","getCollectionSources","vercelBlobStorageMetadata","defaultUploadOptions","access","addRandomSuffix","cacheControlMaxAge","enabled","vercelBlobStorage","options","storeId","token","match","toLowerCase","isPluginDisabled","storageAdapter","name","collections","Object","keys","init","incomingConfig","Error","optionsWithDefaults","baseUrl","process","env","STORAGE_VERCEL_BLOB_BASE_URL","collectionsWithoutAdapter","entries","reduce","acc","slug","collOptions","adapter","useCompositePrefixes","clientUploads","collectionSources","currentAdapter","storageAdapters","storage","collectionsWithAdapter","config","map","collection","upload","disableLocalStorage","Boolean"],"mappings":"AAOA,SAASA,kBAAkB,QAAQ,mCAAkC;AAErE,SAASC,uBAAuB,QAAQ,eAAc;AACtD,SACEC,oBAAoB,EAEpBC,yBAAyB,QACpB,4BAA2B;AAmElC,MAAMC,uBAA0D;IAC9DC,QAAQ;IACRC,iBAAiB;IACjBC,oBAAoB,KAAK,KAAK,KAAK;IACnCC,SAAS;AACX;AAIA,OAAO,MAAMC,oBAA8C,CACzDC;IAEA,MAAMC,UAAUD,QAAQE,KAAK,EAAEC,MAAM,0CAA0C,CAAC,EAAE,EAAEC;IACpF,MAAMC,mBAAmBL,QAAQF,OAAO,KAAK,SAAS,CAACE,QAAQE,KAAK;IACpE,MAAMI,iBAAmD;QACvDC,MAAM;QACNC,aAAaC,OAAOC,IAAI,CAACV,QAAQQ,WAAW;QAC5CG,MAAM,CAACC;YACL,wCAAwC;YACxC,IAAI,CAACX,WAAW,CAACI,kBAAkB;gBACjC,MAAM,IAAIQ,MACR;YAEJ;YAEA,MAAMC,sBAAsB;gBAC1B,GAAGpB,oBAAoB;gBACvB,GAAGM,OAAO;YACZ;YAEA,kGAAkG;YAClG,MAAMe,UACJC,QAAQC,GAAG,CAACC,4BAA4B,IACxC,CAAC,QAAQ,EAAEjB,QAAQ,CAAC,EAAEa,oBAAoBnB,MAAM,CAAC,wBAAwB,CAAC;YAE5E,8EAA8E;YAC9E,IAAIU,kBAAkB;gBACpB,MAAMc,4BAAsEV,OAAOW,OAAO,CACxFpB,QAAQQ,WAAW,EACnBa,M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AAOD,WAAWC,MAAM,KAAK,WAAWD,WAAWC,MAAM,GAAG,CAAC,CAAC;4BAClEC,qBAAqB;wBACvB;oBACF;gBACF;YACF;YAEA,OAAO/C,mBAAmB;gBACxBkB,aAAawB;gBACbN,sBAAsB1B,QAAQ0B,oBAAoB;YACpD,GAAGO;QACL;QACA,CAACxC,0BAA0B,EAAE;YAC3Be,aAAaR,QAAQQ,WAAW;YAChCV,SAAS,CAACO;YACVJ;YACAyB,sBAAsBY,QAAQtC,QAAQ0B,oBAAoB;QAC5D;IACF;IAEA,OAAOpB;AACT,EAAC"}
@@ -3,16 +3,13 @@ interface UploadFileArgs {
3
3
  addRandomSuffix?: boolean;
4
4
  buffer: Buffer;
5
5
  cacheControlMaxAge?: number;
6
- collectionPrefix?: string;
7
- docPrefix?: string;
8
- filename: string;
9
6
  mimeType: string;
7
+ storageFilePath: string;
10
8
  token: string;
11
- useCompositePrefixes?: boolean;
12
9
  }
13
10
  interface UploadFileResult {
14
11
  filename?: string;
15
12
  }
16
- export declare function uploadFile({ access, addRandomSuffix, buffer, cacheControlMaxAge, collectionPrefix, docPrefix, filename, mimeType, token, useCompositePrefixes, }: UploadFileArgs): Promise<UploadFileResult>;
13
+ export declare function uploadFile({ access, addRandomSuffix, buffer, cacheControlMaxAge, mimeType, storageFilePath, token, }: UploadFileArgs): Promise<UploadFileResult>;
17
14
  export {};
18
15
  //# sourceMappingURL=uploadFile.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"uploadFile.d.ts","sourceRoot":"","sources":["../src/uploadFile.ts"],"names":[],"mappings":"AAIA,UAAU,cAAc;IACtB,MAAM,EAAE,QAAQ,CAAA;IAChB,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,MAAM,EAAE,MAAM,CAAA;IACd,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,QAAQ,EAAE,MAAM,CAAA;IAChB,QAAQ,EAAE,MAAM,CAAA;IAChB,KAAK,EAAE,MAAM,CAAA;IACb,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B;AAED,UAAU,gBAAgB;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB;AAED,wBAAsB,UAAU,CAAC,EAC/B,MAAM,EACN,eAAe,EACf,MAAM,EACN,kBAAkB,EAClB,gBAAqB,EACrB,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,KAAK,EACL,oBAA4B,GAC7B,EAAE,cAAc,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAwB5C"}
1
+ {"version":3,"file":"uploadFile.d.ts","sourceRoot":"","sources":["../src/uploadFile.ts"],"names":[],"mappings":"AAGA,UAAU,cAAc;IACtB,MAAM,EAAE,QAAQ,CAAA;IAChB,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,MAAM,EAAE,MAAM,CAAA;IACd,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B,QAAQ,EAAE,MAAM,CAAA;IAChB,eAAe,EAAE,MAAM,CAAA;IACvB,KAAK,EAAE,MAAM,CAAA;CACd;AAED,UAAU,gBAAgB;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB;AAED,wBAAsB,UAAU,CAAC,EAC/B,MAAM,EACN,eAAe,EACf,MAAM,EACN,kBAAkB,EAClB,QAAQ,EACR,eAAe,EACf,KAAK,GACN,EAAE,cAAc,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAiB5C"}
@@ -1,14 +1,7 @@
1
- import { getFileKey } from '@payloadcms/plugin-cloud-storage/utilities';
2
1
  import { put } from '@vercel/blob';
3
2
  import path from 'path';
4
- export async function uploadFile({ access, addRandomSuffix, buffer, cacheControlMaxAge, collectionPrefix = '', docPrefix, filename, mimeType, token, useCompositePrefixes = false }) {
5
- const { fileKey } = getFileKey({
6
- collectionPrefix,
7
- docPrefix,
8
- filename,
9
- useCompositePrefixes
10
- });
11
- const result = await put(fileKey, buffer, {
3
+ export async function uploadFile({ access, addRandomSuffix, buffer, cacheControlMaxAge, mimeType, storageFilePath, token }) {
4
+ const result = await put(storageFilePath, buffer, {
12
5
  access,
13
6
  addRandomSuffix,
14
7
  allowOverwrite: true,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/uploadFile.ts"],"sourcesContent":["import { getFileKey } from '@payloadcms/plugin-cloud-storage/utilities'\nimport { put } from '@vercel/blob'\nimport path from 'path'\n\ninterface UploadFileArgs {\n access: 'public'\n addRandomSuffix?: boolean\n buffer: Buffer\n cacheControlMaxAge?: number\n collectionPrefix?: string\n docPrefix?: string\n filename: string\n mimeType: string\n token: string\n useCompositePrefixes?: boolean\n}\n\ninterface UploadFileResult {\n filename?: string\n}\n\nexport async function uploadFile({\n access,\n addRandomSuffix,\n buffer,\n cacheControlMaxAge,\n collectionPrefix = '',\n docPrefix,\n filename,\n mimeType,\n token,\n useCompositePrefixes = false,\n}: UploadFileArgs): Promise<UploadFileResult> {\n const { fileKey } = getFileKey({\n collectionPrefix,\n docPrefix,\n filename,\n useCompositePrefixes,\n })\n\n const result = await put(fileKey, buffer, {\n access,\n addRandomSuffix,\n allowOverwrite: true,\n cacheControlMaxAge,\n contentType: mimeType,\n token,\n })\n\n if (addRandomSuffix) {\n const pathname = result.pathname.replace(/^\\/+/, '')\n const basename = path.posix.basename(pathname)\n return { filename: decodeURIComponent(basename) }\n }\n\n return {}\n}\n"],"names":["getFileKey","put","path","uploadFile","access","addRandomSuffix","buffer","cacheControlMaxAge","collectionPrefix","docPrefix","filename","mimeType","token","useCompositePrefixes","fileKey","result","allowOverwrite","contentType","pathname","replace","basename","posix","decodeURIComponent"],"mappings":"AAAA,SAASA,UAAU,QAAQ,6CAA4C;AACvE,SAASC,GAAG,QAAQ,eAAc;AAClC,OAAOC,UAAU,OAAM;AAmBvB,OAAO,eAAeC,WAAW,EAC/BC,MAAM,EACNC,eAAe,EACfC,MAAM,EACNC,kBAAkB,EAClBC,mBAAmB,EAAE,EACrBC,SAAS,EACTC,QAAQ,EACRC,QAAQ,EACRC,KAAK,EACLC,uBAAuB,KAAK,EACb;IACf,MAAM,EAAEC,OAAO,EAAE,GAAGd,WAAW;QAC7BQ;QACAC;QACAC;QACAG;IACF;IAEA,MAAME,SAAS,MAAMd,IAAIa,SAASR,QAAQ;QACxCF;QACAC;QACAW,gBAAgB;QAChBT;QACAU,aAAaN;QACbC;IACF;IAEA,IAAIP,iBAAiB;QACnB,MAAMa,WAAWH,OAAOG,QAAQ,CAACC,OAAO,CAAC,QAAQ;QACjD,MAAMC,WAAWlB,KAAKmB,KAAK,CAACD,QAAQ,CAACF;QACrC,OAAO;YAAER,UAAUY,mBAAmBF;QAAU;IAClD;IAEA,OAAO,CAAC;AACV"}
1
+ {"version":3,"sources":["../src/uploadFile.ts"],"sourcesContent":["import { put } from '@vercel/blob'\nimport path from 'path'\n\ninterface UploadFileArgs {\n access: 'public'\n addRandomSuffix?: boolean\n buffer: Buffer\n cacheControlMaxAge?: number\n mimeType: string\n storageFilePath: string\n token: string\n}\n\ninterface UploadFileResult {\n filename?: string\n}\n\nexport async function uploadFile({\n access,\n addRandomSuffix,\n buffer,\n cacheControlMaxAge,\n mimeType,\n storageFilePath,\n token,\n}: UploadFileArgs): Promise<UploadFileResult> {\n const result = await put(storageFilePath, buffer, {\n access,\n addRandomSuffix,\n allowOverwrite: true,\n cacheControlMaxAge,\n contentType: mimeType,\n token,\n })\n\n if (addRandomSuffix) {\n const pathname = result.pathname.replace(/^\\/+/, '')\n const basename = path.posix.basename(pathname)\n return { filename: decodeURIComponent(basename) }\n }\n\n return {}\n}\n"],"names":["put","path","uploadFile","access","addRandomSuffix","buffer","cacheControlMaxAge","mimeType","storageFilePath","token","result","allowOverwrite","contentType","pathname","replace","basename","posix","filename","decodeURIComponent"],"mappings":"AAAA,SAASA,GAAG,QAAQ,eAAc;AAClC,OAAOC,UAAU,OAAM;AAgBvB,OAAO,eAAeC,WAAW,EAC/BC,MAAM,EACNC,eAAe,EACfC,MAAM,EACNC,kBAAkB,EAClBC,QAAQ,EACRC,eAAe,EACfC,KAAK,EACU;IACf,MAAMC,SAAS,MAAMV,IAAIQ,iBAAiBH,QAAQ;QAChDF;QACAC;QACAO,gBAAgB;QAChBL;QACAM,aAAaL;QACbE;IACF;IAEA,IAAIL,iBAAiB;QACnB,MAAMS,WAAWH,OAAOG,QAAQ,CAACC,OAAO,CAAC,QAAQ;QACjD,MAAMC,WAAWd,KAAKe,KAAK,CAACD,QAAQ,CAACF;QACrC,OAAO;YAAEI,UAAUC,mBAAmBH;QAAU;IAClD;IAEA,OAAO,CAAC;AACV"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/storage-vercel-blob",
3
- "version": "4.0.0-internal.d1cc1d3",
3
+ "version": "4.0.0-internal.d21c039",
4
4
  "description": "Payload storage adapter for Vercel Blob Storage",
5
5
  "homepage": "https://payloadcms.com",
6
6
  "repository": {
@@ -38,13 +38,13 @@
38
38
  ],
39
39
  "dependencies": {
40
40
  "@vercel/blob": "2.3.1",
41
- "@payloadcms/plugin-cloud-storage": "4.0.0-internal.d1cc1d3"
41
+ "@payloadcms/plugin-cloud-storage": "4.0.0-internal.d21c039"
42
42
  },
43
43
  "devDependencies": {
44
- "payload": "4.0.0-internal.d1cc1d3"
44
+ "payload": "4.0.0-internal.d21c039"
45
45
  },
46
46
  "peerDependencies": {
47
- "payload": "4.0.0-internal.d1cc1d3"
47
+ "payload": "4.0.0-internal.d21c039"
48
48
  },
49
49
  "engines": {
50
50
  "node": ">=24.15.0"