@payloadcms/storage-vercel-blob 3.89.0-internal.95c9cba → 3.90.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter.d.ts.map +1 -1
- package/dist/adapter.js +9 -14
- package/dist/adapter.js.map +1 -1
- package/dist/authorizeFileOverwrite.d.ts +14 -0
- package/dist/authorizeFileOverwrite.d.ts.map +1 -0
- package/dist/authorizeFileOverwrite.js +116 -0
- package/dist/authorizeFileOverwrite.js.map +1 -0
- package/dist/authorizeFileOverwrite.spec.js +87 -0
- package/dist/authorizeFileOverwrite.spec.js.map +1 -0
- package/dist/client/VercelBlobClientUploadHandler.d.ts.map +1 -1
- package/dist/client/VercelBlobClientUploadHandler.js +27 -21
- package/dist/client/VercelBlobClientUploadHandler.js.map +1 -1
- package/dist/deleteFile.d.ts +2 -5
- package/dist/deleteFile.d.ts.map +1 -1
- package/dist/deleteFile.js +3 -10
- package/dist/deleteFile.js.map +1 -1
- package/dist/generateURL.d.ts +1 -0
- package/dist/generateURL.d.ts.map +1 -1
- package/dist/generateURL.js +13 -9
- package/dist/generateURL.js.map +1 -1
- package/dist/getClientUploadRoute.d.ts +4 -1
- package/dist/getClientUploadRoute.d.ts.map +1 -1
- package/dist/getClientUploadRoute.js +121 -8
- package/dist/getClientUploadRoute.js.map +1 -1
- package/dist/getFile.d.ts +3 -3
- package/dist/getFile.d.ts.map +1 -1
- package/dist/getFile.js +9 -7
- package/dist/getFile.js.map +1 -1
- package/dist/index.d.ts +8 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/staticHandler.spec.js +71 -0
- package/dist/staticHandler.spec.js.map +1 -0
- package/dist/uploadFile.d.ts +2 -5
- package/dist/uploadFile.d.ts.map +1 -1
- package/dist/uploadFile.js +2 -9
- package/dist/uploadFile.js.map +1 -1
- package/package.json +4 -4
package/dist/adapter.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,OAAO,EACP,mBAAmB,EAEpB,MAAM,wCAAwC,CAAA;AAO/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,
|
|
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;AAO/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,CAuDvC"}
|
package/dist/adapter.js
CHANGED
|
@@ -6,6 +6,7 @@ export function createVercelBlobAdapter({ access, addRandomSuffix, baseUrl, cach
|
|
|
6
6
|
return ({ collection, prefix = '' })=>({
|
|
7
7
|
name: 'vercel-blob',
|
|
8
8
|
clientUploads,
|
|
9
|
+
requiresClientUploadReceipt: true,
|
|
9
10
|
generateURL: ({ filename, prefix: urlPrefix = '' })=>generateURL({
|
|
10
11
|
baseUrl,
|
|
11
12
|
collectionPrefix: prefix,
|
|
@@ -13,41 +14,35 @@ export function createVercelBlobAdapter({ access, addRandomSuffix, baseUrl, cach
|
|
|
13
14
|
prefix: urlPrefix,
|
|
14
15
|
useCompositePrefixes
|
|
15
16
|
}),
|
|
16
|
-
handleDelete: ({
|
|
17
|
+
handleDelete: ({ storageFilePath })=>deleteFile({
|
|
17
18
|
baseUrl,
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
filename,
|
|
21
|
-
token,
|
|
22
|
-
useCompositePrefixes
|
|
19
|
+
storageFilePath,
|
|
20
|
+
token
|
|
23
21
|
}),
|
|
24
|
-
handleUpload: async ({ data, file: { buffer,
|
|
22
|
+
handleUpload: async ({ data, file: { buffer, mimeType }, storageFilePath })=>{
|
|
25
23
|
const result = await uploadFile({
|
|
26
24
|
access,
|
|
27
25
|
addRandomSuffix,
|
|
28
26
|
buffer,
|
|
29
27
|
cacheControlMaxAge,
|
|
30
|
-
collectionPrefix: prefix,
|
|
31
|
-
docPrefix: data.prefix,
|
|
32
|
-
filename,
|
|
33
28
|
mimeType,
|
|
34
|
-
|
|
35
|
-
|
|
29
|
+
storageFilePath,
|
|
30
|
+
token
|
|
36
31
|
});
|
|
37
32
|
if (result.filename) {
|
|
38
33
|
data.filename = result.filename;
|
|
39
34
|
}
|
|
40
35
|
return data;
|
|
41
36
|
},
|
|
42
|
-
staticHandler: (req, { headers, params: { clientUploadContext, filename
|
|
37
|
+
staticHandler: (req, { doc, headers, params: { clientUploadContext, filename } })=>getFile({
|
|
43
38
|
baseUrl,
|
|
44
39
|
cacheControlMaxAge,
|
|
45
40
|
clientUploadContext,
|
|
46
41
|
collection,
|
|
47
42
|
collectionPrefix: prefix,
|
|
43
|
+
doc,
|
|
48
44
|
filename,
|
|
49
45
|
incomingHeaders: headers,
|
|
50
|
-
prefixQueryParam,
|
|
51
46
|
req,
|
|
52
47
|
token,
|
|
53
48
|
useCompositePrefixes
|
package/dist/adapter.js.map
CHANGED
|
@@ -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 { 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 return ({ collection, prefix = '' }): GeneratedAdapter => ({\n name: 'vercel-blob',\n clientUploads,\n\n generateURL: ({ filename, prefix: urlPrefix = '' }) =>\n generateURL({\n baseUrl,\n collectionPrefix: prefix,\n filename,\n prefix: urlPrefix,\n useCompositePrefixes,\n }),\n\n handleDelete: ({
|
|
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 { 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 return ({ collection, prefix = '' }): GeneratedAdapter => ({\n name: 'vercel-blob',\n clientUploads,\n requiresClientUploadReceipt: true,\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: { clientUploadContext, filename } }) =>\n getFile({\n baseUrl,\n cacheControlMaxAge,\n clientUploadContext,\n collection,\n collectionPrefix: prefix,\n doc,\n filename,\n incomingHeaders: headers,\n req,\n token,\n useCompositePrefixes,\n }),\n })\n}\n"],"names":["deleteFile","generateURL","getFile","uploadFile","createVercelBlobAdapter","access","addRandomSuffix","baseUrl","cacheControlMaxAge","clientUploads","token","useCompositePrefixes","collection","prefix","name","requiresClientUploadReceipt","filename","urlPrefix","collectionPrefix","handleDelete","storageFilePath","handleUpload","data","file","buffer","mimeType","result","staticHandler","req","doc","headers","params","clientUploadContext","incomingHeaders"],"mappings":"AAMA,SAASA,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,OAAO,CAAC,EAAEC,UAAU,EAAEC,SAAS,EAAE,EAAE,GAAwB,CAAA;YACzDC,MAAM;YACNL;YACAM,6BAA6B;YAE7Bd,aAAa,CAAC,EAAEe,QAAQ,EAAEH,QAAQI,YAAY,EAAE,EAAE,GAChDhB,YAAY;oBACVM;oBACAW,kBAAkBL;oBAClBG;oBACAH,QAAQI;oBACRN;gBACF;YAEFQ,cAAc,CAAC,EAAEC,eAAe,EAAE,GAChCpB,WAAW;oBACTO;oBACAa;oBACAV;gBACF;YAEFW,cAAc,OAAO,EAAEC,IAAI,EAAEC,MAAM,EAAEC,MAAM,EAAEC,QAAQ,EAAE,EAAEL,eAAe,EAAE;gBACxE,MAAMM,SAAS,MAAMvB,WAAW;oBAC9BE;oBACAC;oBACAkB;oBACAhB;oBACAiB;oBACAL;oBACAV;gBACF;gBAEA,IAAIgB,OAAOV,QAAQ,EAAE;oBACnBM,KAAKN,QAAQ,GAAGU,OAAOV,QAAQ;gBACjC;gBAEA,OAAOM;YACT;YAEAK,eAAe,CAACC,KAAK,EAAEC,GAAG,EAAEC,OAAO,EAAEC,QAAQ,EAAEC,mBAAmB,EAAEhB,QAAQ,EAAE,EAAE,GAC9Ed,QAAQ;oBACNK;oBACAC;oBACAwB;oBACApB;oBACAM,kBAAkBL;oBAClBgB;oBACAb;oBACAiB,iBAAiBH;oBACjBF;oBACAlB;oBACAC;gBACF;QACJ,CAAA;AACF"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { PayloadRequest } from 'payload';
|
|
2
|
+
export type VercelBlobCollectionOptions = Record<string, {
|
|
3
|
+
prefix?: string;
|
|
4
|
+
} | true | undefined>;
|
|
5
|
+
export declare function authorizeClientOverwrite({ collectionPrefix: collectionPrefixArg, collections, req, requestedCollectionSlug, requestedFilename, requestedStorageFilePath, useCompositePrefixes, }: {
|
|
6
|
+
collectionPrefix: string;
|
|
7
|
+
collections: VercelBlobCollectionOptions;
|
|
8
|
+
req: PayloadRequest;
|
|
9
|
+
requestedCollectionSlug: string;
|
|
10
|
+
requestedFilename: string;
|
|
11
|
+
requestedStorageFilePath: string;
|
|
12
|
+
useCompositePrefixes?: boolean;
|
|
13
|
+
}): Promise<boolean>;
|
|
14
|
+
//# 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;AAQ1E,MAAM,MAAM,2BAA2B,GAAG,MAAM,CAAC,MAAM,EAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,GAAG,SAAS,CAAC,CAAA;AAqHhG,wBAAsB,wBAAwB,CAAC,EAC7C,gBAAgB,EAAE,mBAAmB,EACrC,WAAW,EACX,GAAG,EACH,uBAAuB,EACvB,iBAAiB,EACjB,wBAAwB,EACxB,oBAA4B,GAC7B,EAAE;IACD,gBAAgB,EAAE,MAAM,CAAA;IACxB,WAAW,EAAE,2BAA2B,CAAA;IACxC,GAAG,EAAE,cAAc,CAAA;IACnB,uBAAuB,EAAE,MAAM,CAAA;IAC/B,iBAAiB,EAAE,MAAM,CAAA;IACzB,wBAAwB,EAAE,MAAM,CAAA;IAChC,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B,GAAG,OAAO,CAAC,OAAO,CAAC,CA2CnB"}
|
|
@@ -0,0 +1,116 @@
|
|
|
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
|
+
disableErrors: true,
|
|
57
|
+
req
|
|
58
|
+
}, collection.config.access.update);
|
|
59
|
+
if (typeof accessResult === 'boolean') {
|
|
60
|
+
return accessResult;
|
|
61
|
+
}
|
|
62
|
+
const result = await req.payload.find({
|
|
63
|
+
collection: collectionSlug,
|
|
64
|
+
depth: 0,
|
|
65
|
+
draft: true,
|
|
66
|
+
limit: 1,
|
|
67
|
+
overrideAccess: true,
|
|
68
|
+
pagination: false,
|
|
69
|
+
req,
|
|
70
|
+
where: combineQueries({
|
|
71
|
+
id: {
|
|
72
|
+
equals: doc.id
|
|
73
|
+
}
|
|
74
|
+
}, accessResult)
|
|
75
|
+
});
|
|
76
|
+
return result.docs.length === 1;
|
|
77
|
+
}
|
|
78
|
+
export async function authorizeClientOverwrite({ collectionPrefix: collectionPrefixArg, collections, req, requestedCollectionSlug, requestedFilename, requestedStorageFilePath, useCompositePrefixes = false }) {
|
|
79
|
+
if (!isStoragePathWithinCollectionPrefix({
|
|
80
|
+
collectionPrefix: collectionPrefixArg,
|
|
81
|
+
docPrefix: requestedStorageFilePath
|
|
82
|
+
})) {
|
|
83
|
+
throw new Forbidden(req.t);
|
|
84
|
+
}
|
|
85
|
+
const matchedDocs = (await Promise.all(Object.entries(collections).map(async ([collectionSlug, options])=>{
|
|
86
|
+
const docs = await findMatchingDocs({
|
|
87
|
+
collectionPrefix: options === true ? '' : options?.prefix || '',
|
|
88
|
+
collectionSlug,
|
|
89
|
+
req,
|
|
90
|
+
requestedFilename,
|
|
91
|
+
requestedStorageFilePath,
|
|
92
|
+
useCompositePrefixes
|
|
93
|
+
});
|
|
94
|
+
return docs.map((doc)=>({
|
|
95
|
+
collectionSlug,
|
|
96
|
+
doc
|
|
97
|
+
}));
|
|
98
|
+
}))).flat();
|
|
99
|
+
if (matchedDocs.length === 0) {
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
const matchedDoc = matchedDocs[0];
|
|
103
|
+
if (matchedDocs.length !== 1 || matchedDoc.collectionSlug !== requestedCollectionSlug) {
|
|
104
|
+
throw new Forbidden(req.t);
|
|
105
|
+
}
|
|
106
|
+
if (!await canUpdateDoc({
|
|
107
|
+
collectionSlug: matchedDoc.collectionSlug,
|
|
108
|
+
doc: matchedDoc.doc,
|
|
109
|
+
req
|
|
110
|
+
})) {
|
|
111
|
+
throw new Forbidden(req.t);
|
|
112
|
+
}
|
|
113
|
+
return true;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
//# 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\nexport type VercelBlobCollectionOptions = Record<string, { prefix?: string } | true | undefined>\n\ntype OwnerDocument = { prefix?: string } & FileData & TypeWithID\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, 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 collections,\n req,\n requestedCollectionSlug,\n requestedFilename,\n requestedStorageFilePath,\n useCompositePrefixes = false,\n}: {\n collectionPrefix: string\n collections: VercelBlobCollectionOptions\n req: PayloadRequest\n requestedCollectionSlug: string\n requestedFilename: string\n requestedStorageFilePath: string\n useCompositePrefixes?: boolean\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 Object.entries(collections).map(async ([collectionSlug, options]): Promise<Owner[]> => {\n const docs = await findMatchingDocs({\n collectionPrefix: options === true ? '' : options?.prefix || '',\n collectionSlug,\n req,\n requestedFilename,\n requestedStorageFilePath,\n useCompositePrefixes,\n })\n\n return docs.map((doc) => ({ collectionSlug, doc }))\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 !(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","disableErrors","access","update","limit","length","authorizeClientOverwrite","collectionPrefixArg","requestedCollectionSlug","t","matchedDocs","Promise","all","entries","options","flat","matchedDoc"],"mappings":"AAEA,SACEA,oBAAoB,EACpBC,mCAAmC,QAC9B,6CAA4C;AACnD,SAASC,cAAc,EAAEC,aAAa,EAAEC,SAAS,QAAQ,UAAS;AAWlE,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,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B,gBAAgByC,WAAWzC,cAAc;QAAEb,KAAKsD,WAAWtD,GAAG;QAAEc;IAAI,IAC3F;QACA,MAAM,IAAIjB,UAAUiB,IAAIiC,CAAC;IAC3B;IAEA,OAAO;AACT"}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { authorizeClientOverwrite } from './authorizeFileOverwrite.js';
|
|
3
|
+
const owner = (id)=>({
|
|
4
|
+
filename: 'image.png',
|
|
5
|
+
id,
|
|
6
|
+
prefix: 'shared'
|
|
7
|
+
});
|
|
8
|
+
const createRequest = ({ protectedOwner = false } = {})=>({
|
|
9
|
+
payload: {
|
|
10
|
+
collections: {
|
|
11
|
+
media: {
|
|
12
|
+
config: {
|
|
13
|
+
access: {
|
|
14
|
+
update: async ()=>true
|
|
15
|
+
},
|
|
16
|
+
upload: true
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
protected: {
|
|
20
|
+
config: {
|
|
21
|
+
access: {
|
|
22
|
+
update: async ()=>false
|
|
23
|
+
},
|
|
24
|
+
upload: true
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
find: vi.fn(async ({ collection })=>({
|
|
29
|
+
docs: collection === 'media' ? [
|
|
30
|
+
owner(1)
|
|
31
|
+
] : protectedOwner ? [
|
|
32
|
+
owner(2)
|
|
33
|
+
] : []
|
|
34
|
+
}))
|
|
35
|
+
},
|
|
36
|
+
t: vi.fn()
|
|
37
|
+
});
|
|
38
|
+
describe('authorizeClientOverwrite', ()=>{
|
|
39
|
+
it('should reject a new key outside the requested collection prefix', async ()=>{
|
|
40
|
+
await expect(authorizeClientOverwrite({
|
|
41
|
+
collections: {
|
|
42
|
+
media: {
|
|
43
|
+
prefix: 'media'
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
requestedFilename: 'image.png',
|
|
47
|
+
requestedStorageFilePath: 'media-archive/image.png',
|
|
48
|
+
req: createRequest(),
|
|
49
|
+
requestedCollectionSlug: 'media',
|
|
50
|
+
collectionPrefix: 'media'
|
|
51
|
+
})).rejects.toMatchObject({
|
|
52
|
+
status: 403
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
it('allows an update when the requested collection is the only owner', async ()=>{
|
|
56
|
+
await expect(authorizeClientOverwrite({
|
|
57
|
+
collections: {
|
|
58
|
+
media: true,
|
|
59
|
+
protected: true
|
|
60
|
+
},
|
|
61
|
+
requestedFilename: 'image.png',
|
|
62
|
+
requestedStorageFilePath: 'shared/image.png',
|
|
63
|
+
req: createRequest(),
|
|
64
|
+
requestedCollectionSlug: 'media',
|
|
65
|
+
collectionPrefix: ''
|
|
66
|
+
})).resolves.toBe(true);
|
|
67
|
+
});
|
|
68
|
+
it('rejects an update when another collection owns the same key', async ()=>{
|
|
69
|
+
await expect(authorizeClientOverwrite({
|
|
70
|
+
collections: {
|
|
71
|
+
media: true,
|
|
72
|
+
protected: true
|
|
73
|
+
},
|
|
74
|
+
requestedFilename: 'image.png',
|
|
75
|
+
requestedStorageFilePath: 'shared/image.png',
|
|
76
|
+
req: createRequest({
|
|
77
|
+
protectedOwner: true
|
|
78
|
+
}),
|
|
79
|
+
requestedCollectionSlug: 'media',
|
|
80
|
+
collectionPrefix: ''
|
|
81
|
+
})).rejects.toMatchObject({
|
|
82
|
+
status: 403
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
//# sourceMappingURL=authorizeFileOverwrite.spec.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/authorizeFileOverwrite.spec.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { describe, expect, it, vi } from 'vitest'\n\nimport { authorizeClientOverwrite } from './authorizeFileOverwrite.js'\n\nconst owner = (id: number) => ({ filename: 'image.png', id, prefix: 'shared' })\n\nconst createRequest = ({ protectedOwner = false }: { protectedOwner?: boolean } = {}) =>\n ({\n payload: {\n collections: {\n media: {\n config: { access: { update: async () => true }, upload: true },\n },\n protected: {\n config: { access: { update: async () => false }, upload: true },\n },\n },\n find: vi.fn(async ({ collection }: { collection: string }) => ({\n docs: collection === 'media' ? [owner(1)] : protectedOwner ? [owner(2)] : [],\n })),\n },\n t: vi.fn(),\n }) as unknown as PayloadRequest\n\ndescribe('authorizeClientOverwrite', () => {\n it('should reject a new key outside the requested collection prefix', async () => {\n await expect(\n authorizeClientOverwrite({\n collections: { media: { prefix: 'media' } },\n requestedFilename: 'image.png',\n requestedStorageFilePath: 'media-archive/image.png',\n req: createRequest(),\n requestedCollectionSlug: 'media',\n collectionPrefix: 'media',\n }),\n ).rejects.toMatchObject({ status: 403 })\n })\n\n it('allows an update when the requested collection is the only owner', async () => {\n await expect(\n authorizeClientOverwrite({\n collections: { media: true, protected: true },\n requestedFilename: 'image.png',\n requestedStorageFilePath: 'shared/image.png',\n req: createRequest(),\n requestedCollectionSlug: 'media',\n collectionPrefix: '',\n }),\n ).resolves.toBe(true)\n })\n\n it('rejects an update when another collection owns the same key', async () => {\n await expect(\n authorizeClientOverwrite({\n collections: { media: true, protected: true },\n requestedFilename: 'image.png',\n requestedStorageFilePath: 'shared/image.png',\n req: createRequest({ protectedOwner: true }),\n requestedCollectionSlug: 'media',\n collectionPrefix: '',\n }),\n ).rejects.toMatchObject({ status: 403 })\n })\n})\n"],"names":["describe","expect","it","vi","authorizeClientOverwrite","owner","id","filename","prefix","createRequest","protectedOwner","payload","collections","media","config","access","update","upload","protected","find","fn","collection","docs","t","requestedFilename","requestedStorageFilePath","req","requestedCollectionSlug","collectionPrefix","rejects","toMatchObject","status","resolves","toBe"],"mappings":"AAEA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,EAAEC,EAAE,QAAQ,SAAQ;AAEjD,SAASC,wBAAwB,QAAQ,8BAA6B;AAEtE,MAAMC,QAAQ,CAACC,KAAgB,CAAA;QAAEC,UAAU;QAAaD;QAAIE,QAAQ;IAAS,CAAA;AAE7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1CiB,yBAAyB;YACzBC,kBAAkB;QACpB,IACAC,OAAO,CAACC,aAAa,CAAC;YAAEC,QAAQ;QAAI;IACxC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"VercelBlobClientUploadHandler.d.ts","sourceRoot":"","sources":["../../src/client/VercelBlobClientUploadHandler.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"VercelBlobClientUploadHandler.d.ts","sourceRoot":"","sources":["../../src/client/VercelBlobClientUploadHandler.ts"],"names":[],"mappings":"AAOA,MAAM,MAAM,kCAAkC,GAAG;IAC/C,eAAe,EAAE,OAAO,CAAA;IACxB,oBAAoB,EAAE,OAAO,CAAA;CAC9B,CAAA;AAED,eAAO,MAAM,6BAA6B;;;;;;;aAgBkB,OAAO,aAsC/D,CAAA"}
|
|
@@ -1,39 +1,45 @@
|
|
|
1
1
|
'use client';
|
|
2
|
-
import { createClientUploadHandler
|
|
2
|
+
import { createClientUploadHandler } from '@payloadcms/plugin-cloud-storage/client';
|
|
3
3
|
import { upload } from '@vercel/blob/client';
|
|
4
4
|
import { formatAdminURL } from 'payload/shared';
|
|
5
|
-
/** Last path segment only (POSIX), for keys like `folder/sub/file.png`. */ function posixBasename(key) {
|
|
6
|
-
const normalized = key.replace(/^\/+/, '');
|
|
7
|
-
const lastSlash = normalized.lastIndexOf('/');
|
|
8
|
-
return lastSlash === -1 ? normalized : normalized.slice(lastSlash + 1);
|
|
9
|
-
}
|
|
10
5
|
export const VercelBlobClientUploadHandler = createClientUploadHandler({
|
|
11
|
-
handler: async ({ apiRoute, collectionSlug, docPrefix,
|
|
6
|
+
handler: async ({ apiRoute, collectionSlug, docPrefix, file, serverHandlerPath, serverURL, updateFilename })=>{
|
|
12
7
|
const endpointRoute = formatAdminURL({
|
|
13
8
|
apiRoute,
|
|
14
9
|
path: serverHandlerPath,
|
|
15
10
|
serverURL
|
|
16
11
|
});
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
12
|
+
const issued = await fetch(`${endpointRoute}?issue-client-upload=1`, {
|
|
13
|
+
body: JSON.stringify({
|
|
14
|
+
collectionSlug,
|
|
15
|
+
docPrefix,
|
|
16
|
+
filename: file.name,
|
|
17
|
+
mimeType: file.type
|
|
18
|
+
}),
|
|
19
|
+
credentials: 'include',
|
|
20
|
+
headers: {
|
|
21
|
+
'Content-Type': 'application/json'
|
|
22
|
+
},
|
|
23
|
+
method: 'POST'
|
|
22
24
|
});
|
|
23
|
-
|
|
24
|
-
|
|
25
|
+
if (!issued.ok) {
|
|
26
|
+
throw new Error('Failed to initialize Vercel Blob client upload');
|
|
27
|
+
}
|
|
28
|
+
const { clientUploadContext, filename, pathname } = await issued.json();
|
|
29
|
+
updateFilename(filename);
|
|
30
|
+
await upload(pathname, file, {
|
|
25
31
|
access: 'public',
|
|
26
|
-
clientPayload:
|
|
32
|
+
clientPayload: JSON.stringify({
|
|
33
|
+
collectionSlug,
|
|
34
|
+
mimeType: file.type,
|
|
35
|
+
signedReceipt: clientUploadContext.signedReceipt
|
|
36
|
+
}),
|
|
27
37
|
contentType: file.type,
|
|
28
38
|
handleUploadUrl: endpointRoute
|
|
29
39
|
});
|
|
30
|
-
// Match server uploadFile: document `filename` is basename only; prefixes are separate.
|
|
31
|
-
if (addRandomSuffix) {
|
|
32
|
-
const pathname = result.pathname.replace(/^\/+/, '');
|
|
33
|
-
updateFilename(decodeURIComponent(posixBasename(pathname)));
|
|
34
|
-
}
|
|
35
40
|
return {
|
|
36
|
-
prefix:
|
|
41
|
+
prefix: clientUploadContext.prefix,
|
|
42
|
+
signedReceipt: clientUploadContext.signedReceipt
|
|
37
43
|
};
|
|
38
44
|
}
|
|
39
45
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/client/VercelBlobClientUploadHandler.ts"],"sourcesContent":["'use client'\nimport { createClientUploadHandler
|
|
1
|
+
{"version":3,"sources":["../../src/client/VercelBlobClientUploadHandler.ts"],"sourcesContent":["'use client'\nimport type { ClientUploadContext } from '@payloadcms/plugin-cloud-storage/types'\n\nimport { createClientUploadHandler } from '@payloadcms/plugin-cloud-storage/client'\nimport { upload } from '@vercel/blob/client'\nimport { formatAdminURL } from 'payload/shared'\n\nexport type VercelBlobClientUploadHandlerExtra = {\n addRandomSuffix: boolean\n useCompositePrefixes: boolean\n}\n\nexport const VercelBlobClientUploadHandler =\n createClientUploadHandler<VercelBlobClientUploadHandlerExtra>({\n handler: async ({\n apiRoute,\n collectionSlug,\n docPrefix,\n file,\n serverHandlerPath,\n serverURL,\n updateFilename,\n }): Promise<ClientUploadContext> => {\n const endpointRoute = formatAdminURL({\n apiRoute,\n path: serverHandlerPath,\n serverURL,\n })\n const issued = await fetch(`${endpointRoute}?issue-client-upload=1`, {\n body: JSON.stringify({\n collectionSlug,\n docPrefix,\n filename: file.name,\n mimeType: file.type,\n }),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n })\n if (!issued.ok) {\n throw new Error('Failed to initialize Vercel Blob client upload')\n }\n\n const { clientUploadContext, filename, pathname } = (await issued.json()) as {\n clientUploadContext: ClientUploadContext\n filename: string\n pathname: string\n }\n updateFilename(filename)\n\n await upload(pathname, file, {\n access: 'public',\n clientPayload: JSON.stringify({\n collectionSlug,\n mimeType: file.type,\n signedReceipt: clientUploadContext.signedReceipt,\n }),\n contentType: file.type,\n handleUploadUrl: endpointRoute,\n })\n\n return {\n prefix: clientUploadContext.prefix,\n signedReceipt: clientUploadContext.signedReceipt,\n }\n },\n })\n"],"names":["createClientUploadHandler","upload","formatAdminURL","VercelBlobClientUploadHandler","handler","apiRoute","collectionSlug","docPrefix","file","serverHandlerPath","serverURL","updateFilename","endpointRoute","path","issued","fetch","body","JSON","stringify","filename","name","mimeType","type","credentials","headers","method","ok","Error","clientUploadContext","pathname","json","access","clientPayload","signedReceipt","contentType","handleUploadUrl","prefix"],"mappings":"AAAA;AAGA,SAASA,yBAAyB,QAAQ,0CAAyC;AACnF,SAASC,MAAM,QAAQ,sBAAqB;AAC5C,SAASC,cAAc,QAAQ,iBAAgB;AAO/C,OAAO,MAAMC,gCACXH,0BAA8D;IAC5DI,SAAS,OAAO,EACdC,QAAQ,EACRC,cAAc,EACdC,SAAS,EACTC,IAAI,EACJC,iBAAiB,EACjBC,SAAS,EACTC,cAAc,EACf;QACC,MAAMC,gBAAgBV,eAAe;YACnCG;YACAQ,MAAMJ;YACNC;QACF;QACA,MAAMI,SAAS,MAAMC,MAAM,GAAGH,cAAc,sBAAsB,CAAC,EAAE;YACnEI,MAAMC,KAAKC,SAAS,CAAC;gBACnBZ;gBACAC;gBACAY,UAAUX,KAAKY,IAAI;gBACnBC,UAAUb,KAAKc,IAAI;YACrB;YACAC,aAAa;YACbC,SAAS;gBAAE,gBAAgB;YAAmB;YAC9CC,QAAQ;QACV;QACA,IAAI,CAACX,OAAOY,EAAE,EAAE;YACd,MAAM,IAAIC,MAAM;QAClB;QAEA,MAAM,EAAEC,mBAAmB,EAAET,QAAQ,EAAEU,QAAQ,EAAE,GAAI,MAAMf,OAAOgB,IAAI;QAKtEnB,eAAeQ;QAEf,MAAMlB,OAAO4B,UAAUrB,MAAM;YAC3BuB,QAAQ;YACRC,eAAef,KAAKC,SAAS,CAAC;gBAC5BZ;gBACAe,UAAUb,KAAKc,IAAI;gBACnBW,eAAeL,oBAAoBK,aAAa;YAClD;YACAC,aAAa1B,KAAKc,IAAI;YACtBa,iBAAiBvB;QACnB;QAEA,OAAO;YACLwB,QAAQR,oBAAoBQ,MAAM;YAClCH,eAAeL,oBAAoBK,aAAa;QAClD;IACF;AACF,GAAE"}
|
package/dist/deleteFile.d.ts
CHANGED
|
@@ -1,11 +1,8 @@
|
|
|
1
1
|
interface DeleteFileArgs {
|
|
2
2
|
baseUrl: string;
|
|
3
|
-
|
|
4
|
-
docPrefix: string;
|
|
5
|
-
filename: string;
|
|
3
|
+
storageFilePath: string;
|
|
6
4
|
token: string;
|
|
7
|
-
useCompositePrefixes?: boolean;
|
|
8
5
|
}
|
|
9
|
-
export declare function deleteFile({ baseUrl,
|
|
6
|
+
export declare function deleteFile({ baseUrl, storageFilePath, token, }: DeleteFileArgs): Promise<void>;
|
|
10
7
|
export {};
|
|
11
8
|
//# sourceMappingURL=deleteFile.d.ts.map
|
package/dist/deleteFile.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"deleteFile.d.ts","sourceRoot":"","sources":["../src/deleteFile.ts"],"names":[],"mappings":"AAIA,UAAU,cAAc;IACtB,OAAO,EAAE,MAAM,CAAA;IACf,
|
|
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"}
|
package/dist/deleteFile.js
CHANGED
|
@@ -1,14 +1,7 @@
|
|
|
1
1
|
import { del } from '@vercel/blob';
|
|
2
|
-
import {
|
|
3
|
-
export async function deleteFile({ baseUrl,
|
|
4
|
-
|
|
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
|
}
|
package/dist/deleteFile.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/deleteFile.ts"],"sourcesContent":["import { del } from '@vercel/blob'\n\nimport {
|
|
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"}
|
package/dist/generateURL.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ interface GenerateURLArgs {
|
|
|
5
5
|
prefix: string;
|
|
6
6
|
useCompositePrefixes?: boolean;
|
|
7
7
|
}
|
|
8
|
+
export declare function buildBlobUrl(baseUrl: string, fileKey: 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,
|
|
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,OAAO,EAAE,MAAM,GAAG,MAAM,CAUrE;AAED,wBAAgB,WAAW,CAAC,EAC1B,OAAO,EACP,gBAAqB,EACrB,QAAQ,EACR,MAAM,EACN,oBAA4B,GAC7B,EAAE,eAAe,GAAG,MAAM,CAS1B"}
|
package/dist/generateURL.js
CHANGED
|
@@ -1,19 +1,23 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { buildStoragePathData } from '@payloadcms/plugin-cloud-storage/utilities';
|
|
2
2
|
import path from 'path';
|
|
3
|
+
// Builds the public blob URL for a storage key, URL-encoding only the filename segment.
|
|
4
|
+
export function buildBlobUrl(baseUrl, fileKey) {
|
|
5
|
+
// example: "my-collection/my-doc/my file.jpg" -> "my-collection/my-doc"
|
|
6
|
+
const dir = path.posix.dirname(fileKey);
|
|
7
|
+
// example: "my file.jpg" -> "my%20file.jpg"
|
|
8
|
+
const encodedFilename = encodeURIComponent(path.posix.basename(fileKey));
|
|
9
|
+
// example: "my-collection/my-doc/my%20file.jpg"
|
|
10
|
+
const fileKeyWithEncodedFilename = dir === '.' ? encodedFilename : path.posix.join(dir, encodedFilename);
|
|
11
|
+
return `${baseUrl}/${fileKeyWithEncodedFilename}`;
|
|
12
|
+
}
|
|
3
13
|
export function generateURL({ baseUrl, collectionPrefix = '', filename, prefix, useCompositePrefixes = false }) {
|
|
4
|
-
const {
|
|
14
|
+
const { storageFilePath } = buildStoragePathData({
|
|
5
15
|
collectionPrefix,
|
|
6
16
|
docPrefix: prefix,
|
|
7
17
|
filename,
|
|
8
18
|
useCompositePrefixes
|
|
9
19
|
});
|
|
10
|
-
|
|
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
|
package/dist/generateURL.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/generateURL.ts"],"sourcesContent":["import {
|
|
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 key, URL-encoding only the filename segment.\nexport function buildBlobUrl(baseUrl: string, fileKey: string): string {\n // example: \"my-collection/my-doc/my file.jpg\" -> \"my-collection/my-doc\"\n const dir = path.posix.dirname(fileKey)\n // example: \"my file.jpg\" -> \"my%20file.jpg\"\n const encodedFilename = encodeURIComponent(path.posix.basename(fileKey))\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\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","fileKey","dir","posix","dirname","encodedFilename","encodeURIComponent","basename","fileKeyWithEncodedFilename","join","generateURL","collectionPrefix","filename","prefix","useCompositePrefixes","storageFilePath","docPrefix"],"mappings":"AAAA,SAASA,oBAAoB,QAAQ,6CAA4C;AACjF,OAAOC,UAAU,OAAM;AAUvB,wFAAwF;AACxF,OAAO,SAASC,aAAaC,OAAe,EAAEC,OAAe;IAC3D,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,6BACJN,QAAQ,MAAMG,kBAAkBP,KAAKK,KAAK,CAACM,IAAI,CAACP,KAAKG;IAEvD,OAAO,GAAGL,QAAQ,CAAC,EAAEQ,4BAA4B;AACnD;AAEA,OAAO,SAASE,YAAY,EAC1BV,OAAO,EACPW,mBAAmB,EAAE,EACrBC,QAAQ,EACRC,MAAM,EACNC,uBAAuB,KAAK,EACZ;IAChB,MAAM,EAAEC,eAAe,EAAE,GAAGlB,qBAAqB;QAC/Cc;QACAK,WAAWH;QACXD;QACAE;IACF;IAEA,OAAOf,aAAaC,SAASe;AAC/B"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { PayloadHandler, PayloadRequest, UploadCollectionSlug } from 'payload';
|
|
2
|
+
import type { VercelBlobCollectionOptions } from './authorizeFileOverwrite.js';
|
|
2
3
|
type Args = {
|
|
3
4
|
access?: (args: {
|
|
4
5
|
collectionSlug: UploadCollectionSlug;
|
|
@@ -6,8 +7,10 @@ type Args = {
|
|
|
6
7
|
}) => boolean | Promise<boolean>;
|
|
7
8
|
addRandomSuffix?: boolean;
|
|
8
9
|
cacheControlMaxAge?: number;
|
|
10
|
+
collections: VercelBlobCollectionOptions;
|
|
9
11
|
token: string;
|
|
12
|
+
useCompositePrefixes?: boolean;
|
|
10
13
|
};
|
|
11
|
-
export declare const getClientUploadRoute: ({ access,
|
|
14
|
+
export declare const getClientUploadRoute: ({ access, cacheControlMaxAge, collections, token, useCompositePrefixes, }: Args) => PayloadHandler;
|
|
12
15
|
export {};
|
|
13
16
|
//# sourceMappingURL=getClientUploadRoute.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getClientUploadRoute.d.ts","sourceRoot":"","sources":["../src/getClientUploadRoute.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"getClientUploadRoute.d.ts","sourceRoot":"","sources":["../src/getClientUploadRoute.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAenF,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAA;AAI9E,KAAK,IAAI,GAAG;IACV,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE;QACd,cAAc,EAAE,oBAAoB,CAAA;QACpC,GAAG,EAAE,cAAc,CAAA;KACpB,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;IAChC,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B,WAAW,EAAE,2BAA2B,CAAA;IACxC,KAAK,EAAE,MAAM,CAAA;IACb,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B,CAAA;AAID,eAAO,MAAM,oBAAoB,8EAO5B,IAAI,KAAG,cA8JT,CAAA"}
|
|
@@ -1,26 +1,136 @@
|
|
|
1
|
+
import { buildStoragePathData, resolveSignedURLKey, verifyClientUploadReceiptForFileKey } from '@payloadcms/plugin-cloud-storage/utilities';
|
|
1
2
|
import { handleUpload } from '@vercel/blob/client';
|
|
2
3
|
import { APIError, Forbidden } from 'payload';
|
|
4
|
+
import { assertClientUploadAccess, assertClientUploadAllowed, createClientUploadReceipt } from 'payload/internal';
|
|
5
|
+
import { authorizeClientOverwrite } from './authorizeFileOverwrite.js';
|
|
3
6
|
const defaultAccess = ({ req })=>!!req.user;
|
|
4
|
-
export const getClientUploadRoute = ({ access = defaultAccess,
|
|
5
|
-
const body = await req.json();
|
|
7
|
+
export const getClientUploadRoute = ({ access = defaultAccess, cacheControlMaxAge, collections, token, useCompositePrefixes })=>async (req)=>{
|
|
6
8
|
try {
|
|
9
|
+
if (req.searchParams.get('issue-client-upload') === '1') {
|
|
10
|
+
const { collectionSlug, docPrefix, filename, mimeType } = await req.json();
|
|
11
|
+
if (typeof collectionSlug !== 'string' || typeof filename !== 'string' || typeof mimeType !== 'string' || docPrefix !== undefined && typeof docPrefix !== 'string' || !Object.hasOwn(collections, collectionSlug)) {
|
|
12
|
+
throw new APIError('Invalid upload payload', 400);
|
|
13
|
+
}
|
|
14
|
+
await assertClientUploadAccess({
|
|
15
|
+
collectionSlug,
|
|
16
|
+
req
|
|
17
|
+
});
|
|
18
|
+
if (!await access({
|
|
19
|
+
collectionSlug,
|
|
20
|
+
req
|
|
21
|
+
})) {
|
|
22
|
+
throw new Forbidden();
|
|
23
|
+
}
|
|
24
|
+
assertClientUploadAllowed({
|
|
25
|
+
collection: req.payload.collections[collectionSlug]?.config,
|
|
26
|
+
filename,
|
|
27
|
+
mimeType
|
|
28
|
+
});
|
|
29
|
+
const collectionConfig = collections[collectionSlug];
|
|
30
|
+
const collectionPrefix = typeof collectionConfig === 'object' && collectionConfig.prefix || '';
|
|
31
|
+
const requested = buildStoragePathData({
|
|
32
|
+
collectionPrefix,
|
|
33
|
+
docPrefix,
|
|
34
|
+
filename,
|
|
35
|
+
useCompositePrefixes
|
|
36
|
+
});
|
|
37
|
+
const allowOverwrite = await authorizeClientOverwrite({
|
|
38
|
+
collectionPrefix,
|
|
39
|
+
collections,
|
|
40
|
+
req,
|
|
41
|
+
requestedCollectionSlug: collectionSlug,
|
|
42
|
+
requestedFilename: requested.sanitizedFilename,
|
|
43
|
+
requestedStorageFilePath: requested.storageFilePath,
|
|
44
|
+
useCompositePrefixes
|
|
45
|
+
});
|
|
46
|
+
const resolved = allowOverwrite ? {
|
|
47
|
+
...requested,
|
|
48
|
+
clientUploadContext: {
|
|
49
|
+
allowOverwrite: true,
|
|
50
|
+
prefix: requested.sanitizedDocPrefix,
|
|
51
|
+
signedReceipt: createClientUploadReceipt({
|
|
52
|
+
collectionSlug,
|
|
53
|
+
context: {
|
|
54
|
+
allowOverwrite: true,
|
|
55
|
+
prefix: requested.sanitizedDocPrefix
|
|
56
|
+
},
|
|
57
|
+
filename: requested.sanitizedFilename,
|
|
58
|
+
req
|
|
59
|
+
})
|
|
60
|
+
}
|
|
61
|
+
} : await resolveSignedURLKey({
|
|
62
|
+
collectionPrefix,
|
|
63
|
+
collectionSlug,
|
|
64
|
+
docPrefix,
|
|
65
|
+
filename,
|
|
66
|
+
req,
|
|
67
|
+
useCompositePrefixes
|
|
68
|
+
});
|
|
69
|
+
return Response.json({
|
|
70
|
+
clientUploadContext: resolved.clientUploadContext,
|
|
71
|
+
filename: resolved.sanitizedFilename,
|
|
72
|
+
pathname: resolved.storageFilePath
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
const body = await req.json();
|
|
7
76
|
const jsonResponse = await handleUpload({
|
|
8
77
|
body,
|
|
9
|
-
onBeforeGenerateToken: async (
|
|
10
|
-
if (!
|
|
78
|
+
onBeforeGenerateToken: async (pathname, clientPayload)=>{
|
|
79
|
+
if (!clientPayload) {
|
|
11
80
|
throw new APIError('No payload was provided');
|
|
12
81
|
}
|
|
82
|
+
let parsed;
|
|
83
|
+
try {
|
|
84
|
+
parsed = JSON.parse(clientPayload);
|
|
85
|
+
} catch {
|
|
86
|
+
parsed = {
|
|
87
|
+
collectionSlug: clientPayload
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
if (typeof parsed.collectionSlug !== 'string' || !parsed.collectionSlug || parsed.mimeType !== undefined && typeof parsed.mimeType !== 'string' || typeof parsed.signedReceipt !== 'string') {
|
|
91
|
+
throw new APIError('Invalid upload payload', 400);
|
|
92
|
+
}
|
|
93
|
+
const { collectionSlug, mimeType, signedReceipt } = parsed;
|
|
94
|
+
await assertClientUploadAccess({
|
|
95
|
+
collectionSlug,
|
|
96
|
+
req
|
|
97
|
+
});
|
|
98
|
+
if (!Object.hasOwn(collections, collectionSlug)) {
|
|
99
|
+
throw new APIError('Invalid upload payload', 400);
|
|
100
|
+
}
|
|
13
101
|
if (!await access({
|
|
14
102
|
collectionSlug,
|
|
15
103
|
req
|
|
16
104
|
})) {
|
|
17
105
|
throw new Forbidden();
|
|
18
106
|
}
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
107
|
+
const collectionConfig = collections[collectionSlug];
|
|
108
|
+
const collectionPrefix = typeof collectionConfig === 'object' && collectionConfig.prefix || '';
|
|
109
|
+
const receipt = verifyClientUploadReceiptForFileKey({
|
|
110
|
+
collectionPrefix,
|
|
111
|
+
collectionSlug,
|
|
112
|
+
expectedFileKey: pathname,
|
|
113
|
+
req,
|
|
114
|
+
signedReceipt,
|
|
115
|
+
useCompositePrefixes
|
|
116
|
+
});
|
|
117
|
+
assertClientUploadAllowed({
|
|
118
|
+
collection: req.payload.collections[collectionSlug]?.config,
|
|
119
|
+
filename: pathname,
|
|
120
|
+
mimeType
|
|
23
121
|
});
|
|
122
|
+
return {
|
|
123
|
+
addRandomSuffix: false,
|
|
124
|
+
...mimeType ? {
|
|
125
|
+
allowedContentTypes: [
|
|
126
|
+
mimeType
|
|
127
|
+
]
|
|
128
|
+
} : {},
|
|
129
|
+
...receipt.context.allowOverwrite === true && {
|
|
130
|
+
allowOverwrite: true
|
|
131
|
+
},
|
|
132
|
+
cacheControlMaxAge
|
|
133
|
+
};
|
|
24
134
|
},
|
|
25
135
|
onUploadCompleted: async ()=>{},
|
|
26
136
|
request: req,
|
|
@@ -28,6 +138,9 @@ export const getClientUploadRoute = ({ access = defaultAccess, addRandomSuffix,
|
|
|
28
138
|
});
|
|
29
139
|
return Response.json(jsonResponse);
|
|
30
140
|
} catch (error) {
|
|
141
|
+
if (error instanceof APIError) {
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
31
144
|
req.payload.logger.error(error);
|
|
32
145
|
throw new APIError('storage-vercel-blob client upload route error');
|
|
33
146
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/getClientUploadRoute.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest, UploadCollectionSlug } from 'payload'\n\nimport { handleUpload, type HandleUploadBody } from '@vercel/blob/client'\nimport { APIError, Forbidden } from 'payload'\n\ntype Args = {\n access?: (args: {\n collectionSlug: UploadCollectionSlug\n req: PayloadRequest\n }) => boolean | Promise<boolean>\n addRandomSuffix?: boolean\n cacheControlMaxAge?: number\n token: string\n}\n\nconst defaultAccess: Args['access'] = ({ req }) => !!req.user\n\nexport const getClientUploadRoute =\n ({ access = defaultAccess, addRandomSuffix, cacheControlMaxAge, token }: Args): PayloadHandler =>\n async (req) => {\n const body = (await req.json!()) as HandleUploadBody\n\n try {\n const jsonResponse = await handleUpload({\n body,\n onBeforeGenerateToken: async (_pathname: string, collectionSlug: null | string) => {\n if (!collectionSlug) {\n throw new APIError('No payload was provided')\n }\n\n if (!(await access({ collectionSlug, req }))) {\n throw new Forbidden()\n }\n\n return Promise.resolve({\n addRandomSuffix,\n allowOverwrite: true,\n cacheControlMaxAge,\n })\n },\n onUploadCompleted: async () => {},\n request: req as Request,\n token,\n })\n\n return Response.json(jsonResponse)\n } catch (error) {\n req.payload.logger.error(error)\n throw new APIError('storage-vercel-blob client upload route error')\n }\n }\n"],"names":["handleUpload","APIError","Forbidden","defaultAccess","req","user","getClientUploadRoute","access","addRandomSuffix","cacheControlMaxAge","token","body","json","jsonResponse","onBeforeGenerateToken","_pathname","collectionSlug","Promise","resolve","allowOverwrite","onUploadCompleted","request","Response","error","payload","logger"],"mappings":"AAEA,SAASA,YAAY,QAA+B,sBAAqB;AACzE,SAASC,QAAQ,EAAEC,SAAS,QAAQ,UAAS;AAY7C,MAAMC,gBAAgC,CAAC,EAAEC,GAAG,EAAE,GAAK,CAAC,CAACA,IAAIC,IAAI;AAE7D,OAAO,MAAMC,uBACX,CAAC,EAAEC,SAASJ,aAAa,EAAEK,eAAe,EAAEC,kBAAkB,EAAEC,KAAK,EAAQ,GAC7E,OAAON;QACL,MAAMO,OAAQ,MAAMP,IAAIQ,IAAI;QAE5B,IAAI;YACF,MAAMC,eAAe,MAAMb,aAAa;gBACtCW;gBACAG,uBAAuB,OAAOC,WAAmBC;oBAC/C,IAAI,CAACA,gBAAgB;wBACnB,MAAM,IAAIf,SAAS;oBACrB;oBAEA,IAAI,CAAE,MAAMM,OAAO;wBAAES;wBAAgBZ;oBAAI,IAAK;wBAC5C,MAAM,IAAIF;oBACZ;oBAEA,OAAOe,QAAQC,OAAO,CAAC;wBACrBV;wBACAW,gBAAgB;wBAChBV;oBACF;gBACF;gBACAW,mBAAmB,WAAa;gBAChCC,SAASjB;gBACTM;YACF;YAEA,OAAOY,SAASV,IAAI,CAACC;QACvB,EAAE,OAAOU,OAAO;YACdnB,IAAIoB,OAAO,CAACC,MAAM,CAACF,KAAK,CAACA;YACzB,MAAM,IAAItB,SAAS;QACrB;IACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../src/getClientUploadRoute.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest, UploadCollectionSlug } from 'payload'\n\nimport {\n buildStoragePathData,\n resolveSignedURLKey,\n verifyClientUploadReceiptForFileKey,\n} from '@payloadcms/plugin-cloud-storage/utilities'\nimport { handleUpload, type HandleUploadBody } from '@vercel/blob/client'\nimport { APIError, Forbidden } from 'payload'\nimport {\n assertClientUploadAccess,\n assertClientUploadAllowed,\n createClientUploadReceipt,\n} from 'payload/internal'\n\nimport type { VercelBlobCollectionOptions } from './authorizeFileOverwrite.js'\n\nimport { authorizeClientOverwrite } from './authorizeFileOverwrite.js'\n\ntype Args = {\n access?: (args: {\n collectionSlug: UploadCollectionSlug\n req: PayloadRequest\n }) => boolean | Promise<boolean>\n addRandomSuffix?: boolean\n cacheControlMaxAge?: number\n collections: VercelBlobCollectionOptions\n token: string\n useCompositePrefixes?: boolean\n}\n\nconst defaultAccess: Args['access'] = ({ req }) => !!req.user\n\nexport const getClientUploadRoute =\n ({\n access = defaultAccess,\n cacheControlMaxAge,\n collections,\n token,\n useCompositePrefixes,\n }: Args): PayloadHandler =>\n async (req) => {\n try {\n if (req.searchParams.get('issue-client-upload') === '1') {\n const { collectionSlug, docPrefix, filename, mimeType } = (await req.json!()) as {\n collectionSlug?: unknown\n docPrefix?: unknown\n filename?: unknown\n mimeType?: unknown\n }\n if (\n typeof collectionSlug !== 'string' ||\n typeof filename !== 'string' ||\n typeof mimeType !== 'string' ||\n (docPrefix !== undefined && typeof docPrefix !== 'string') ||\n !Object.hasOwn(collections, collectionSlug)\n ) {\n throw new APIError('Invalid upload payload', 400)\n }\n\n await assertClientUploadAccess({ collectionSlug, req })\n\n if (!(await access({ collectionSlug, req }))) {\n throw new Forbidden()\n }\n assertClientUploadAllowed({\n collection: req.payload.collections[collectionSlug]?.config,\n filename,\n mimeType,\n })\n const collectionConfig = collections[collectionSlug]\n const collectionPrefix =\n (typeof collectionConfig === 'object' && collectionConfig.prefix) || ''\n const requested = buildStoragePathData({\n collectionPrefix,\n docPrefix,\n filename,\n useCompositePrefixes,\n })\n const allowOverwrite = await authorizeClientOverwrite({\n collectionPrefix,\n collections,\n req,\n requestedCollectionSlug: collectionSlug,\n requestedFilename: requested.sanitizedFilename,\n requestedStorageFilePath: requested.storageFilePath,\n useCompositePrefixes,\n })\n const resolved = allowOverwrite\n ? {\n ...requested,\n clientUploadContext: {\n allowOverwrite: true,\n prefix: requested.sanitizedDocPrefix,\n signedReceipt: createClientUploadReceipt({\n collectionSlug,\n context: {\n allowOverwrite: true,\n prefix: requested.sanitizedDocPrefix,\n },\n filename: requested.sanitizedFilename,\n req,\n }),\n },\n }\n : await resolveSignedURLKey({\n collectionPrefix,\n collectionSlug,\n docPrefix,\n filename,\n req,\n useCompositePrefixes,\n })\n return Response.json({\n clientUploadContext: resolved.clientUploadContext,\n filename: resolved.sanitizedFilename,\n pathname: resolved.storageFilePath,\n })\n }\n\n const body = (await req.json!()) as HandleUploadBody\n const jsonResponse = await handleUpload({\n body,\n onBeforeGenerateToken: async (pathname: string, clientPayload: null | string) => {\n if (!clientPayload) {\n throw new APIError('No payload was provided')\n }\n\n let parsed: { collectionSlug?: unknown; mimeType?: unknown; signedReceipt?: unknown }\n try {\n parsed = JSON.parse(clientPayload) as {\n collectionSlug?: unknown\n mimeType?: unknown\n signedReceipt?: unknown\n }\n } catch {\n parsed = { collectionSlug: clientPayload }\n }\n\n if (\n typeof parsed.collectionSlug !== 'string' ||\n !parsed.collectionSlug ||\n (parsed.mimeType !== undefined && typeof parsed.mimeType !== 'string') ||\n typeof parsed.signedReceipt !== 'string'\n ) {\n throw new APIError('Invalid upload payload', 400)\n }\n\n const { collectionSlug, mimeType, signedReceipt } = parsed\n\n await assertClientUploadAccess({ collectionSlug, req })\n\n if (!Object.hasOwn(collections, collectionSlug)) {\n throw new APIError('Invalid upload payload', 400)\n }\n\n if (!(await access({ collectionSlug, req }))) {\n throw new Forbidden()\n }\n const collectionConfig = collections[collectionSlug]\n const collectionPrefix =\n (typeof collectionConfig === 'object' && collectionConfig.prefix) || ''\n const receipt = verifyClientUploadReceiptForFileKey({\n collectionPrefix,\n collectionSlug,\n expectedFileKey: pathname,\n req,\n signedReceipt,\n useCompositePrefixes,\n })\n\n assertClientUploadAllowed({\n collection: req.payload.collections[collectionSlug]?.config,\n filename: pathname,\n mimeType,\n })\n\n return {\n addRandomSuffix: false,\n ...(mimeType ? { allowedContentTypes: [mimeType] } : {}),\n ...(receipt.context.allowOverwrite === true && { allowOverwrite: true }),\n cacheControlMaxAge,\n }\n },\n onUploadCompleted: async () => {},\n request: req as Request,\n token,\n })\n\n return Response.json(jsonResponse)\n } catch (error) {\n if (error instanceof APIError) {\n throw error\n }\n\n req.payload.logger.error(error)\n throw new APIError('storage-vercel-blob client upload route error')\n }\n }\n"],"names":["buildStoragePathData","resolveSignedURLKey","verifyClientUploadReceiptForFileKey","handleUpload","APIError","Forbidden","assertClientUploadAccess","assertClientUploadAllowed","createClientUploadReceipt","authorizeClientOverwrite","defaultAccess","req","user","getClientUploadRoute","access","cacheControlMaxAge","collections","token","useCompositePrefixes","searchParams","get","collectionSlug","docPrefix","filename","mimeType","json","undefined","Object","hasOwn","collection","payload","config","collectionConfig","collectionPrefix","prefix","requested","allowOverwrite","requestedCollectionSlug","requestedFilename","sanitizedFilename","requestedStorageFilePath","storageFilePath","resolved","clientUploadContext","sanitizedDocPrefix","signedReceipt","context","Response","pathname","body","jsonResponse","onBeforeGenerateToken","clientPayload","parsed","JSON","parse","receipt","expectedFileKey","addRandomSuffix","allowedContentTypes","onUploadCompleted","request","error","logger"],"mappings":"AAEA,SACEA,oBAAoB,EACpBC,mBAAmB,EACnBC,mCAAmC,QAC9B,6CAA4C;AACnD,SAASC,YAAY,QAA+B,sBAAqB;AACzE,SAASC,QAAQ,EAAEC,SAAS,QAAQ,UAAS;AAC7C,SACEC,wBAAwB,EACxBC,yBAAyB,EACzBC,yBAAyB,QACpB,mBAAkB;AAIzB,SAASC,wBAAwB,QAAQ,8BAA6B;AActE,MAAMC,gBAAgC,CAAC,EAAEC,GAAG,EAAE,GAAK,CAAC,CAACA,IAAIC,IAAI;AAE7D,OAAO,MAAMC,uBACX,CAAC,EACCC,SAASJ,aAAa,EACtBK,kBAAkB,EAClBC,WAAW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sB,UAAUtD,oCAAoC;wBAClD+B;wBACAZ;wBACAoC,iBAAiBT;wBACjBrC;wBACAkC;wBACA3B;oBACF;oBAEAX,0BAA0B;wBACxBsB,YAAYlB,IAAImB,OAAO,CAACd,WAAW,CAACK,eAAe,EAAEU;wBACrDR,UAAUyB;wBACVxB;oBACF;oBAEA,OAAO;wBACLkC,iBAAiB;wBACjB,GAAIlC,WAAW;4BAAEmC,qBAAqB;gCAACnC;6BAAS;wBAAC,IAAI,CAAC,CAAC;wBACvD,GAAIgC,QAAQV,OAAO,CAACV,cAAc,KAAK,QAAQ;4BAAEA,gBAAgB;wBAAK,CAAC;wBACvErB;oBACF;gBACF;gBACA6C,mBAAmB,WAAa;gBAChCC,SAASlD;gBACTM;YACF;YAEA,OAAO8B,SAAStB,IAAI,CAACyB;QACvB,EAAE,OAAOY,OAAO;YACd,IAAIA,iBAAiB1D,UAAU;gBAC7B,MAAM0D;YACR;YAEAnD,IAAImB,OAAO,CAACiC,MAAM,CAACD,KAAK,CAACA;YACzB,MAAM,IAAI1D,SAAS;QACrB;IACF,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
|
clientUploadContext?: unknown;
|
|
6
6
|
collection: CollectionConfig;
|
|
7
7
|
collectionPrefix?: string;
|
|
8
|
+
doc?: TypeWithID;
|
|
8
9
|
filename: string;
|
|
9
10
|
incomingHeaders?: Headers;
|
|
10
|
-
prefixQueryParam?: string;
|
|
11
11
|
req: PayloadRequest;
|
|
12
12
|
token: string;
|
|
13
13
|
useCompositePrefixes?: boolean;
|
|
14
14
|
}
|
|
15
|
-
export declare function getFile({ baseUrl, cacheControlMaxAge, clientUploadContext, collection, collectionPrefix, filename, incomingHeaders,
|
|
15
|
+
export declare function getFile({ baseUrl, cacheControlMaxAge, clientUploadContext, collection, collectionPrefix, doc, filename, incomingHeaders, req, token, useCompositePrefixes, }: GetFileArgs): Promise<Response>;
|
|
16
16
|
export {};
|
|
17
17
|
//# sourceMappingURL=getFile.d.ts.map
|
package/dist/getFile.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getFile.d.ts","sourceRoot":"","sources":["../src/getFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"getFile.d.ts","sourceRoot":"","sources":["../src/getFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAY3E,UAAU,WAAW;IACnB,OAAO,EAAE,MAAM,CAAA;IACf,kBAAkB,EAAE,MAAM,CAAA;IAC1B,mBAAmB,CAAC,EAAE,OAAO,CAAA;IAC7B,UAAU,EAAE,gBAAgB,CAAA;IAC5B,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,GAAG,CAAC,EAAE,UAAU,CAAA;IAChB,QAAQ,EAAE,MAAM,CAAA;IAChB,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,GAAG,EAAE,cAAc,CAAA;IACnB,KAAK,EAAE,MAAM,CAAA;IACb,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B;AAED,wBAAsB,OAAO,CAAC,EAC5B,OAAO,EACP,kBAAkB,EAClB,mBAAmB,EACnB,UAAU,EACV,gBAAqB,EACrB,GAAG,EACH,QAAQ,EACR,eAAe,EACf,GAAG,EACH,KAAK,EACL,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, UPLOAD_CONTENT_SECURITY_POLICY } from 'payload/internal';
|
|
4
4
|
import { generateURL } from './generateURL.js';
|
|
5
|
-
export async function getFile({ baseUrl, cacheControlMaxAge, clientUploadContext, collection, collectionPrefix = '', filename, incomingHeaders,
|
|
5
|
+
export async function getFile({ baseUrl, cacheControlMaxAge, clientUploadContext, collection, collectionPrefix = '', doc, filename, incomingHeaders, req, token, useCompositePrefixes = false }) {
|
|
6
6
|
try {
|
|
7
7
|
const docPrefix = await getDocPrefix({
|
|
8
8
|
clientUploadContext,
|
|
9
9
|
collection,
|
|
10
|
+
collectionPrefix,
|
|
11
|
+
doc,
|
|
10
12
|
filename,
|
|
11
|
-
|
|
12
|
-
|
|
13
|
+
req,
|
|
14
|
+
useCompositePrefixes
|
|
13
15
|
});
|
|
14
16
|
const fileUrl = generateURL({
|
|
15
17
|
baseUrl,
|
|
@@ -47,9 +49,9 @@ export async function getFile({ baseUrl, cacheControlMaxAge, clientUploadContext
|
|
|
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
|
|
51
|
-
if (contentType
|
|
52
|
-
headers.append('Content-Security-Policy',
|
|
52
|
+
// Add Content-Security-Policy header for XML-family files
|
|
53
|
+
if (isXmlMimeType(contentType)) {
|
|
54
|
+
headers.append('Content-Security-Policy', UPLOAD_CONTENT_SECURITY_POLICY);
|
|
53
55
|
}
|
|
54
56
|
if (collection.upload && typeof collection.upload === 'object' && typeof collection.upload.modifyResponseHeaders === 'function') {
|
|
55
57
|
headers = collection.upload.modifyResponseHeaders({
|
package/dist/getFile.js.map
CHANGED
|
@@ -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 {
|
|
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 {\n getRangeRequestInfo,\n isXmlMimeType,\n UPLOAD_CONTENT_SECURITY_POLICY,\n} from 'payload/internal'\n\nimport { generateURL } from './generateURL.js'\n\ninterface GetFileArgs {\n baseUrl: string\n cacheControlMaxAge: number\n clientUploadContext?: unknown\n collection: CollectionConfig\n collectionPrefix?: string\n doc?: TypeWithID\n filename: string\n incomingHeaders?: Headers\n req: PayloadRequest\n token: string\n useCompositePrefixes?: boolean\n}\n\nexport async function getFile({\n baseUrl,\n cacheControlMaxAge,\n clientUploadContext,\n collection,\n collectionPrefix = '',\n doc,\n filename,\n incomingHeaders,\n req,\n token,\n useCompositePrefixes = false,\n}: GetFileArgs): Promise<Response> {\n try {\n const docPrefix = await getDocPrefix({\n clientUploadContext,\n collection,\n collectionPrefix,\n doc,\n filename,\n req,\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 // Add Content-Security-Policy header for XML-family files\n if (isXmlMimeType(contentType)) {\n headers.append('Content-Security-Policy', UPLOAD_CONTENT_SECURITY_POLICY)\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","UPLOAD_CONTENT_SECURITY_POLICY","generateURL","getFile","baseUrl","cacheControlMaxAge","clientUploadContext","collection","collectionPrefix","doc","filename","incomingHeaders","req","token","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,SACEC,mBAAmB,EACnBC,aAAa,EACbC,8BAA8B,QACzB,mBAAkB;AAEzB,SAASC,WAAW,QAAQ,mBAAkB;AAgB9C,OAAO,eAAeC,QAAQ,EAC5BC,OAAO,EACPC,kBAAkB,EAClBC,mBAAmB,EACnBC,UAAU,EACVC,mBAAmB,EAAE,EACrBC,GAAG,EACHC,QAAQ,EACRC,eAAe,EACfC,GAAG,EACHC,KAAK,EACLC,uBAAuB,KAAK,EAChB;IACZ,IAAI;QACF,MAAMC,YAAY,MAAMnB,aAAa;YACnCU;YACAC;YACAC;YACAC;YACAC;YACAE;YACAE;QACF;QAEA,MAAME,UAAUd,YAAY;YAC1BE;YACAI;YACAE;YACAO,QAAQF;YACRD;QACF;QACA,MAAMI,kBAAkBN,IAAIO,OAAO,CAACC,GAAG,CAAC,WAAWR,IAAIO,OAAO,CAACC,GAAG,CAAC;QACnE,MAAMC,eAAe,MAAMvB,KAAKkB,SAAS;YAAEH;QAAM;QACjD,MAAM,EAAES,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;QAEtD,uBAAuB;QAC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B,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;QACAzC,IAAI2C,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
|
@@ -54,14 +54,15 @@ export type VercelBlobStorageOptions = {
|
|
|
54
54
|
token: string | undefined;
|
|
55
55
|
/**
|
|
56
56
|
* When true, the collection-level prefix and document-level prefix are combined
|
|
57
|
-
* (compositional). When false (default), document prefix
|
|
58
|
-
* prefix
|
|
57
|
+
* (compositional). When false (default), a document prefix already within the
|
|
58
|
+
* collection prefix is used as-is for new uploads; otherwise it is nested beneath it.
|
|
59
|
+
* Existing files retain their stored prefixes for reads, URLs, and cleanup.
|
|
59
60
|
*
|
|
60
|
-
* Example:
|
|
61
|
-
* - collection prefix: `
|
|
62
|
-
* - document prefix: `
|
|
63
|
-
* - resulting prefix with useCompositePrefixes=true: `
|
|
64
|
-
* - resulting prefix with useCompositePrefixes=false: `
|
|
61
|
+
* Example with a document prefix already contained by the collection prefix:
|
|
62
|
+
* - collection prefix: `uploads/`
|
|
63
|
+
* - document prefix: `uploads/documents/`
|
|
64
|
+
* - resulting prefix with useCompositePrefixes=true: `uploads/uploads/documents/`
|
|
65
|
+
* - resulting prefix with useCompositePrefixes=false: `uploads/documents/`
|
|
65
66
|
*
|
|
66
67
|
* @default false
|
|
67
68
|
*/
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EAEnB,iBAAiB,EAClB,MAAM,wCAAwC,CAAA;AAC/C,OAAO,KAAK,EAAU,MAAM,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAUnE,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
|
|
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,MAAM,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAUnE,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;;;;;;;;;;;;;OAaG;IACH,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B,CAAA;AASD,KAAK,uBAAuB,GAAG,CAAC,qBAAqB,EAAE,wBAAwB,KAAK,MAAM,CAAA;AAE1F,eAAO,MAAM,iBAAiB,EAAE,uBAwH7B,CAAA"}
|
package/dist/index.js
CHANGED
|
@@ -35,7 +35,9 @@ export const vercelBlobStorage = (options)=>(incomingConfig)=>{
|
|
|
35
35
|
access: typeof options.clientUploads === 'object' ? options.clientUploads.access : undefined,
|
|
36
36
|
addRandomSuffix: optionsWithDefaults.addRandomSuffix,
|
|
37
37
|
cacheControlMaxAge: options.cacheControlMaxAge,
|
|
38
|
-
|
|
38
|
+
collections: options.collections,
|
|
39
|
+
token: options.token ?? '',
|
|
40
|
+
useCompositePrefixes: optionsWithDefaults.useCompositePrefixes
|
|
39
41
|
}),
|
|
40
42
|
serverHandlerPath: '/vercel-blob-client-upload-route'
|
|
41
43
|
});
|
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, Plugin, UploadCollectionSlug } from 'payload'\n\nimport { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage'\nimport { initClientUploads } from '@payloadcms/plugin-cloud-storage/utilities'\n\nimport type { VercelBlobClientUploadHandlerExtra } from './client/VercelBlobClientUploadHandler.js'\n\nimport { createVercelBlobAdapter } from './adapter.js'\nimport { getClientUploadRoute } from './getClientUploadRoute.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 * Do uploads directly on the client, to bypass limits on Vercel.\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 VercelBlobStoragePlugin = (vercelBlobStorageOpts: VercelBlobStorageOptions) => Plugin\n\nexport const vercelBlobStorage: VercelBlobStoragePlugin =\n (options: VercelBlobStorageOptions) =>\n (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 initClientUploads<\n VercelBlobClientUploadHandlerExtra,\n VercelBlobStorageOptions['collections'][string]\n >({\n clientHandler: '@payloadcms/storage-vercel-blob/client#VercelBlobClientUploadHandler',\n collections: options.collections,\n config: incomingConfig,\n enabled: !isPluginDisabled && Boolean(options.clientUploads),\n extraClientHandlerProps: () => ({\n addRandomSuffix: !!optionsWithDefaults.addRandomSuffix,\n useCompositePrefixes: !!options.useCompositePrefixes,\n }),\n serverHandler: getClientUploadRoute({\n access:\n typeof options.clientUploads === 'object' ? options.clientUploads.access : undefined,\n addRandomSuffix: optionsWithDefaults.addRandomSuffix,\n cacheControlMaxAge: options.cacheControlMaxAge,\n token: options.token ?? '',\n }),\n serverHandlerPath: '/vercel-blob-client-upload-route',\n })\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"],"names":["cloudStoragePlugin","initClientUploads","createVercelBlobAdapter","getClientUploadRoute","defaultUploadOptions","access","addRandomSuffix","cacheControlMaxAge","enabled","vercelBlobStorage","options","incomingConfig","storeId","token","match","toLowerCase","isPluginDisabled","Error","optionsWithDefaults","baseUrl","process","env","STORAGE_VERCEL_BLOB_BASE_URL","clientHandler","collections","config","Boolean","clientUploads","extraClientHandlerProps","useCompositePrefixes","serverHandler","undefined","serverHandlerPath","alwaysInsertFields","collectionsWithoutAdapter","Object","entries","reduce","acc","slug","collOptions","adapter","collectionsWithAdapter","map","collection","upload","disableLocalStorage"],"mappings":"AAOA,SAASA,kBAAkB,QAAQ,mCAAkC;AACrE,SAASC,iBAAiB,QAAQ,6CAA4C;AAI9E,SAASC,uBAAuB,QAAQ,eAAc;AACtD,SAASC,oBAAoB,QAAQ,4BAA2B;AA6EhE,MAAMC,uBAA0D;IAC9DC,QAAQ;IACRC,iBAAiB;IACjBC,oBAAoB,KAAK,KAAK,KAAK;IACnCC,SAAS;AACX;AAIA,OAAO,MAAMC,oBACX,CAACC,UACD,CAACC;QACC,2BAA2B;QAC3B,MAAMC,UAAUF,QAAQG,KAAK,EACzBC,MAAM,0CAA0C,CAAC,EAAE,EACnDC;QAEJ,MAAMC,mBAAmBN,QAAQF,OAAO,KAAK,SAAS,CAACE,QAAQG,KAAK;QAEpE,wCAAwC;QACxC,IAAI,CAACD,WAAW,CAACI,kBAAkB;YACjC,MAAM,IAAIC,MACR;QAEJ;QAEA,MAAMC,sBAAsB;YAC1B,GAAGd,oBAAoB;YACvB,GAAGM,OAAO;QACZ;QAEA,kGAAkG;QAClG,MAAMS,UACJC,QAAQC,GAAG,CAACC,4BAA4B,IACxC,CAAC,QAAQ,EAAEV,QAAQ,CAAC,EAAEM,oBAAoBb,MAAM,CAAC,wBAAwB,CAAC;QAE5EJ,kBAGE;YACAsB,eAAe;YACfC,aAAad,QAAQc,WAAW;YAChCC,QAAQd;YACRH,SAAS,CAACQ,oBAAoBU,QAAQhB,QAAQiB,aAAa;YAC3DC,yBAAyB,IAAO,CAAA;oBAC9BtB,iBAAiB,CAAC,CAACY,oBAAoBZ,eAAe;oBACtDuB,sBAAsB,CAAC,CAACnB,QAAQmB,oBAAoB;gBACtD,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C3CC;gBACF;YACF,CAAA,GACA,CAAC;QAGH,gFAAgF;QAChF,MAAMhB,SAAS;YACb,GAAGd,cAAc;YACjBa,aAAa,AAACb,CAAAA,eAAea,WAAW,IAAI,EAAE,AAAD,EAAGmB,GAAG,CAAC,CAACC;gBACnD,IAAI,CAACF,sBAAsB,CAACE,WAAWL,IAAI,CAAC,EAAE;oBAC5C,OAAOK;gBACT;gBAEA,OAAO;oBACL,GAAGA,UAAU;oBACbC,QAAQ;wBACN,GAAI,OAAOD,WAAWC,MAAM,KAAK,WAAWD,WAAWC,MAAM,GAAG,CAAC,CAAC;wBAClEC,qBAAqB;oBACvB;gBACF;YACF;QACF;QAEA,OAAO9C,mBAAmB;YACxBiC,oBAAoBvB,QAAQuB,kBAAkB;YAC9CT,aAAakB;YACbb,sBAAsBnB,QAAQmB,oBAAoB;QACpD,GAAGJ;IACL,EAAC"}
|
|
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, Plugin, UploadCollectionSlug } from 'payload'\n\nimport { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage'\nimport { initClientUploads } from '@payloadcms/plugin-cloud-storage/utilities'\n\nimport type { VercelBlobClientUploadHandlerExtra } from './client/VercelBlobClientUploadHandler.js'\n\nimport { createVercelBlobAdapter } from './adapter.js'\nimport { getClientUploadRoute } from './getClientUploadRoute.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 * Do uploads directly on the client, to bypass limits on Vercel.\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 VercelBlobStoragePlugin = (vercelBlobStorageOpts: VercelBlobStorageOptions) => Plugin\n\nexport const vercelBlobStorage: VercelBlobStoragePlugin =\n (options: VercelBlobStorageOptions) =>\n (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 initClientUploads<\n VercelBlobClientUploadHandlerExtra,\n VercelBlobStorageOptions['collections'][string]\n >({\n clientHandler: '@payloadcms/storage-vercel-blob/client#VercelBlobClientUploadHandler',\n collections: options.collections,\n config: incomingConfig,\n enabled: !isPluginDisabled && Boolean(options.clientUploads),\n extraClientHandlerProps: () => ({\n addRandomSuffix: !!optionsWithDefaults.addRandomSuffix,\n useCompositePrefixes: !!options.useCompositePrefixes,\n }),\n serverHandler: getClientUploadRoute({\n access:\n typeof options.clientUploads === 'object' ? options.clientUploads.access : undefined,\n addRandomSuffix: optionsWithDefaults.addRandomSuffix,\n cacheControlMaxAge: options.cacheControlMaxAge,\n collections: options.collections,\n token: options.token ?? '',\n useCompositePrefixes: optionsWithDefaults.useCompositePrefixes,\n }),\n serverHandlerPath: '/vercel-blob-client-upload-route',\n })\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"],"names":["cloudStoragePlugin","initClientUploads","createVercelBlobAdapter","getClientUploadRoute","defaultUploadOptions","access","addRandomSuffix","cacheControlMaxAge","enabled","vercelBlobStorage","options","incomingConfig","storeId","token","match","toLowerCase","isPluginDisabled","Error","optionsWithDefaults","baseUrl","process","env","STORAGE_VERCEL_BLOB_BASE_URL","clientHandler","collections","config","Boolean","clientUploads","extraClientHandlerProps","useCompositePrefixes","serverHandler","undefined","serverHandlerPath","alwaysInsertFields","collectionsWithoutAdapter","Object","entries","reduce","acc","slug","collOptions","adapter","collectionsWithAdapter","map","collection","upload","disableLocalStorage"],"mappings":"AAOA,SAASA,kBAAkB,QAAQ,mCAAkC;AACrE,SAASC,iBAAiB,QAAQ,6CAA4C;AAI9E,SAASC,uBAAuB,QAAQ,eAAc;AACtD,SAASC,oBAAoB,QAAQ,4BAA2B;AA8EhE,MAAMC,uBAA0D;IAC9DC,QAAQ;IACRC,iBAAiB;IACjBC,oBAAoB,KAAK,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AAqB;oBACvB;gBACF;YACF;QACF;QAEA,OAAO9C,mBAAmB;YACxBiC,oBAAoBvB,QAAQuB,kBAAkB;YAC9CT,aAAakB;YACbb,sBAAsBnB,QAAQmB,oBAAoB;QACpD,GAAGJ;IACL,EAAC"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { head } from '@vercel/blob';
|
|
3
|
+
vi.mock('@vercel/blob', async (importOriginal)=>({
|
|
4
|
+
...await importOriginal(),
|
|
5
|
+
head: vi.fn(async ()=>({
|
|
6
|
+
contentDisposition: 'inline',
|
|
7
|
+
contentType: 'image/png',
|
|
8
|
+
size: 4,
|
|
9
|
+
uploadedAt: new Date('2026-01-01')
|
|
10
|
+
}))
|
|
11
|
+
}));
|
|
12
|
+
afterEach(()=>{
|
|
13
|
+
vi.unstubAllGlobals();
|
|
14
|
+
vi.clearAllMocks();
|
|
15
|
+
});
|
|
16
|
+
import { createVercelBlobAdapter } from './adapter.js';
|
|
17
|
+
describe('static handler document locations', ()=>{
|
|
18
|
+
it('should read the checked document without another lookup', async ()=>{
|
|
19
|
+
const fetchMock = vi.fn(async ()=>new Response('file'));
|
|
20
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
21
|
+
const adapter = createVercelBlobAdapter({
|
|
22
|
+
access: 'public',
|
|
23
|
+
baseUrl: 'https://example.com',
|
|
24
|
+
cacheControlMaxAge: 60,
|
|
25
|
+
token: 'token'
|
|
26
|
+
});
|
|
27
|
+
const find = vi.fn(async ()=>({
|
|
28
|
+
docs: [
|
|
29
|
+
{
|
|
30
|
+
prefix: 'database'
|
|
31
|
+
}
|
|
32
|
+
]
|
|
33
|
+
}));
|
|
34
|
+
const generatedAdapter = adapter({
|
|
35
|
+
collection: {
|
|
36
|
+
fields: [],
|
|
37
|
+
slug: 'media',
|
|
38
|
+
upload: {}
|
|
39
|
+
},
|
|
40
|
+
prefix: 'media'
|
|
41
|
+
});
|
|
42
|
+
const doc = {
|
|
43
|
+
id: 'authorized',
|
|
44
|
+
prefix: 'legacy'
|
|
45
|
+
};
|
|
46
|
+
const response = await generatedAdapter.staticHandler({
|
|
47
|
+
headers: new Headers(),
|
|
48
|
+
payload: {
|
|
49
|
+
find,
|
|
50
|
+
logger: {
|
|
51
|
+
error: vi.fn()
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}, {
|
|
55
|
+
doc,
|
|
56
|
+
params: {
|
|
57
|
+
collection: 'media',
|
|
58
|
+
filename: 'original.png'
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
expect(response.status).toBe(200);
|
|
62
|
+
expect(await response.text()).toBe('file');
|
|
63
|
+
expect(head).toHaveBeenCalledWith(`https://example.com/legacy/original.png`, {
|
|
64
|
+
token: 'token'
|
|
65
|
+
});
|
|
66
|
+
expect(fetchMock).toHaveBeenCalledWith(`https://example.com/legacy/original.png?2026-01-01T00:00:00.000Z`, expect.any(Object));
|
|
67
|
+
expect(find).not.toHaveBeenCalled();
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
//# sourceMappingURL=staticHandler.spec.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/staticHandler.spec.ts"],"sourcesContent":["import { afterEach, describe, expect, it, vi } from 'vitest'\n\nimport { head } from '@vercel/blob'\n\nvi.mock('@vercel/blob', async (importOriginal) => ({\n ...(await importOriginal<typeof import('@vercel/blob')>()),\n head: vi.fn(async () => ({\n contentDisposition: 'inline',\n contentType: 'image/png',\n size: 4,\n uploadedAt: new Date('2026-01-01'),\n })),\n}))\n\nafterEach(() => {\n vi.unstubAllGlobals()\n vi.clearAllMocks()\n})\n\nimport { createVercelBlobAdapter } from './adapter.js'\n\ndescribe('static handler document locations', () => {\n it('should read the checked document without another lookup', async () => {\n const fetchMock = vi.fn(async () => new Response('file'))\n\n vi.stubGlobal('fetch', fetchMock)\n const adapter = createVercelBlobAdapter({\n access: 'public',\n baseUrl: 'https://example.com',\n cacheControlMaxAge: 60,\n token: 'token',\n })\n const find = vi.fn(async () => ({ docs: [{ prefix: 'database' }] }))\n const generatedAdapter = adapter({\n collection: {\n fields: [],\n slug: 'media',\n upload: {},\n },\n prefix: 'media',\n })\n const doc = {\n id: 'authorized',\n prefix: 'legacy',\n }\n const response = await generatedAdapter.staticHandler(\n {\n headers: new Headers(),\n payload: { find, logger: { error: vi.fn() } },\n } as never,\n {\n doc,\n params: { collection: 'media', filename: 'original.png' },\n },\n )\n\n expect(response.status).toBe(200)\n expect(await response.text()).toBe('file')\n expect(head).toHaveBeenCalledWith(`https://example.com/legacy/original.png`, { token: 'token' })\n expect(fetchMock).toHaveBeenCalledWith(\n `https://example.com/legacy/original.png?2026-01-01T00:00:00.000Z`,\n expect.any(Object),\n )\n expect(find).not.toHaveBeenCalled()\n })\n})\n"],"names":["afterEach","describe","expect","it","vi","head","mock","importOriginal","fn","contentDisposition","contentType","size","uploadedAt","Date","unstubAllGlobals","clearAllMocks","createVercelBlobAdapter","fetchMock","Response","stubGlobal","adapter","access","baseUrl","cacheControlMaxAge","token","find","docs","prefix","generatedAdapter","collection","fields","slug","upload","doc","id","response","staticHandler","headers","Headers","payload","logger","error","params","filename","status","toBe","text","toHaveBeenCalledWith","any","Object","not","toHaveBeenCalled"],"mappings":"AAAA,SAASA,SAAS,EAAEC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,EAAEC,EAAE,QAAQ,SAAQ;AAE5D,SAASC,IAAI,QAAQ,eAAc;AAEnCD,GAAGE,IAAI,CAAC,gBAAgB,OAAOC,iBAAoB,CAAA;QACjD,GAAI,MAAMA,gBAA+C;QACzDF,MAAMD,GAAGI,EAAE,CAAC,UAAa,CAAA;gBACvBC,oBAAoB;gBACpBC,aAAa;gBACbC,MAAM;gBACNC,YAAY,IAAIC,KAAK;YACvB,CAAA;IACF,CAAA;AAEAb,UAAU;IACRI,GAAGU,gBAAgB;IACnBV,GAAGW,aAAa;AAClB;AAE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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,
|
|
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
|
package/dist/uploadFile.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uploadFile.d.ts","sourceRoot":"","sources":["../src/uploadFile.ts"],"names":[],"mappings":"
|
|
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"}
|
package/dist/uploadFile.js
CHANGED
|
@@ -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,
|
|
5
|
-
const
|
|
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,
|
package/dist/uploadFile.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/uploadFile.ts"],"sourcesContent":["import {
|
|
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": "3.
|
|
3
|
+
"version": "3.90.0",
|
|
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": "3.
|
|
41
|
+
"@payloadcms/plugin-cloud-storage": "3.90.0"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
|
-
"payload": "3.
|
|
44
|
+
"payload": "3.90.0"
|
|
45
45
|
},
|
|
46
46
|
"peerDependencies": {
|
|
47
|
-
"payload": "3.
|
|
47
|
+
"payload": "3.90.0"
|
|
48
48
|
},
|
|
49
49
|
"engines": {
|
|
50
50
|
"node": "^18.20.2 || >=20.9.0"
|