@payloadcms/storage-vercel-blob 3.0.0-alpha.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2018-2022 Payload CMS, LLC <info@payloadcms.com>
4
+ Portions Copyright (c) Meta Platforms, Inc. and affiliates.
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # Vercel Blob Storage
@@ -0,0 +1,8 @@
1
+ import type { GenerateURL } from '@payloadcms/plugin-cloud-storage/types';
2
+ type GenerateUrlArgs = {
3
+ baseUrl: string;
4
+ prefix?: string;
5
+ };
6
+ export declare const getGenerateUrl: ({ baseUrl }: GenerateUrlArgs) => GenerateURL;
7
+ export {};
8
+ //# sourceMappingURL=generateURL.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateURL.d.ts","sourceRoot":"","sources":["../src/generateURL.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,wCAAwC,CAAA;AAIzE,KAAK,eAAe,GAAG;IACrB,OAAO,EAAE,MAAM,CAAA;IACf,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB,CAAA;AAED,eAAO,MAAM,cAAc,gBAAiB,eAAe,KAAG,WAI7D,CAAA"}
@@ -0,0 +1,8 @@
1
+ import path from 'path';
2
+ export const getGenerateUrl = ({ baseUrl })=>{
3
+ return ({ filename, prefix = '' })=>{
4
+ return `${baseUrl}/${path.posix.join(prefix, filename)}`;
5
+ };
6
+ };
7
+
8
+ //# sourceMappingURL=generateURL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/generateURL.ts"],"sourcesContent":["import type { GenerateURL } from '@payloadcms/plugin-cloud-storage/types'\n\nimport path from 'path'\n\ntype GenerateUrlArgs = {\n baseUrl: string\n prefix?: string\n}\n\nexport const getGenerateUrl = ({ baseUrl }: GenerateUrlArgs): GenerateURL => {\n return ({ filename, prefix = '' }) => {\n return `${baseUrl}/${path.posix.join(prefix, filename)}`\n }\n}\n"],"names":["path","getGenerateUrl","baseUrl","filename","prefix","posix","join"],"rangeMappings":";;;;;","mappings":"AAEA,OAAOA,UAAU,OAAM;AAOvB,OAAO,MAAMC,iBAAiB,CAAC,EAAEC,OAAO,EAAmB;IACzD,OAAO,CAAC,EAAEC,QAAQ,EAAEC,SAAS,EAAE,EAAE;QAC/B,OAAO,CAAC,EAAEF,QAAQ,CAAC,EAAEF,KAAKK,KAAK,CAACC,IAAI,CAACF,QAAQD,UAAU,CAAC;IAC1D;AACF,EAAC"}
@@ -0,0 +1,9 @@
1
+ import type { HandleDelete } from '@payloadcms/plugin-cloud-storage/types';
2
+ type HandleDeleteArgs = {
3
+ baseUrl: string;
4
+ prefix?: string;
5
+ token: string;
6
+ };
7
+ export declare const getHandleDelete: ({ baseUrl, token }: HandleDeleteArgs) => HandleDelete;
8
+ export {};
9
+ //# sourceMappingURL=handleDelete.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handleDelete.d.ts","sourceRoot":"","sources":["../src/handleDelete.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wCAAwC,CAAA;AAK1E,KAAK,gBAAgB,GAAG;IACtB,OAAO,EAAE,MAAM,CAAA;IACf,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,KAAK,EAAE,MAAM,CAAA;CACd,CAAA;AAED,eAAO,MAAM,eAAe,uBAAwB,gBAAgB,KAAG,YAOtE,CAAA"}
@@ -0,0 +1,13 @@
1
+ import { del } from '@vercel/blob';
2
+ import path from 'path';
3
+ export const getHandleDelete = ({ baseUrl, token })=>{
4
+ return async ({ doc: { prefix = '' }, filename })=>{
5
+ const fileUrl = `${baseUrl}/${path.posix.join(prefix, filename)}`;
6
+ const deletedBlob = await del(fileUrl, {
7
+ token
8
+ });
9
+ return deletedBlob;
10
+ };
11
+ };
12
+
13
+ //# sourceMappingURL=handleDelete.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/handleDelete.ts"],"sourcesContent":["import type { HandleDelete } from '@payloadcms/plugin-cloud-storage/types'\n\nimport { del } from '@vercel/blob'\nimport path from 'path'\n\ntype HandleDeleteArgs = {\n baseUrl: string\n prefix?: string\n token: string\n}\n\nexport const getHandleDelete = ({ baseUrl, token }: HandleDeleteArgs): HandleDelete => {\n return async ({ doc: { prefix = '' }, filename }) => {\n const fileUrl = `${baseUrl}/${path.posix.join(prefix, filename)}`\n const deletedBlob = await del(fileUrl, { token })\n\n return deletedBlob\n }\n}\n"],"names":["del","path","getHandleDelete","baseUrl","token","doc","prefix","filename","fileUrl","posix","join","deletedBlob"],"rangeMappings":";;;;;;;;;;","mappings":"AAEA,SAASA,GAAG,QAAQ,eAAc;AAClC,OAAOC,UAAU,OAAM;AAQvB,OAAO,MAAMC,kBAAkB,CAAC,EAAEC,OAAO,EAAEC,KAAK,EAAoB;IAClE,OAAO,OAAO,EAAEC,KAAK,EAAEC,SAAS,EAAE,EAAE,EAAEC,QAAQ,EAAE;QAC9C,MAAMC,UAAU,CAAC,EAAEL,QAAQ,CAAC,EAAEF,KAAKQ,KAAK,CAACC,IAAI,CAACJ,QAAQC,UAAU,CAAC;QACjE,MAAMI,cAAc,MAAMX,IAAIQ,SAAS;YAAEJ;QAAM;QAE/C,OAAOO;IACT;AACF,EAAC"}
@@ -0,0 +1,9 @@
1
+ import type { HandleUpload } from '@payloadcms/plugin-cloud-storage/types';
2
+ import type { VercelBlobStorageOptions } from './index.js';
3
+ type HandleUploadArgs = Omit<VercelBlobStorageOptions, 'collections'> & {
4
+ baseUrl: string;
5
+ prefix?: string;
6
+ };
7
+ export declare const getHandleUpload: ({ access, addRandomSuffix, baseUrl, cacheControlMaxAge, prefix, token, }: HandleUploadArgs) => HandleUpload;
8
+ export {};
9
+ //# sourceMappingURL=handleUpload.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handleUpload.d.ts","sourceRoot":"","sources":["../src/handleUpload.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wCAAwC,CAAA;AAK1E,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAA;AAE1D,KAAK,gBAAgB,GAAG,IAAI,CAAC,wBAAwB,EAAE,aAAa,CAAC,GAAG;IACtE,OAAO,EAAE,MAAM,CAAA;IACf,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB,CAAA;AAED,eAAO,MAAM,eAAe,6EAOzB,gBAAgB,KAAG,YAmBrB,CAAA"}
@@ -0,0 +1,21 @@
1
+ import { put } from '@vercel/blob';
2
+ import path from 'path';
3
+ export const getHandleUpload = ({ access = 'public', addRandomSuffix, baseUrl, cacheControlMaxAge, prefix = '', token })=>{
4
+ return async ({ data, file: { buffer, filename, mimeType } })=>{
5
+ const fileKey = path.posix.join(data.prefix || prefix, filename);
6
+ const result = await put(fileKey, buffer, {
7
+ access,
8
+ addRandomSuffix,
9
+ cacheControlMaxAge,
10
+ contentType: mimeType,
11
+ token
12
+ });
13
+ // Get filename with suffix from returned url
14
+ if (addRandomSuffix) {
15
+ data.filename = result.url.replace(`${baseUrl}/`, '');
16
+ }
17
+ return data;
18
+ };
19
+ };
20
+
21
+ //# sourceMappingURL=handleUpload.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/handleUpload.ts"],"sourcesContent":["import type { HandleUpload } from '@payloadcms/plugin-cloud-storage/types'\n\nimport { put } from '@vercel/blob'\nimport path from 'path'\n\nimport type { VercelBlobStorageOptions } from './index.js'\n\ntype HandleUploadArgs = Omit<VercelBlobStorageOptions, 'collections'> & {\n baseUrl: string\n prefix?: string\n}\n\nexport const getHandleUpload = ({\n access = 'public',\n addRandomSuffix,\n baseUrl,\n cacheControlMaxAge,\n prefix = '',\n token,\n}: HandleUploadArgs): HandleUpload => {\n return async ({ data, file: { buffer, filename, mimeType } }) => {\n const fileKey = path.posix.join(data.prefix || prefix, filename)\n\n const result = await put(fileKey, buffer, {\n access,\n addRandomSuffix,\n cacheControlMaxAge,\n contentType: mimeType,\n token,\n })\n\n // Get filename with suffix from returned url\n if (addRandomSuffix) {\n data.filename = result.url.replace(`${baseUrl}/`, '')\n }\n\n return data\n }\n}\n"],"names":["put","path","getHandleUpload","access","addRandomSuffix","baseUrl","cacheControlMaxAge","prefix","token","data","file","buffer","filename","mimeType","fileKey","posix","join","result","contentType","url","replace"],"rangeMappings":";;;;;;;;;;;;;;;;;;","mappings":"AAEA,SAASA,GAAG,QAAQ,eAAc;AAClC,OAAOC,UAAU,OAAM;AASvB,OAAO,MAAMC,kBAAkB,CAAC,EAC9BC,SAAS,QAAQ,EACjBC,eAAe,EACfC,OAAO,EACPC,kBAAkB,EAClBC,SAAS,EAAE,EACXC,KAAK,EACY;IACjB,OAAO,OAAO,EAAEC,IAAI,EAAEC,MAAM,EAAEC,MAAM,EAAEC,QAAQ,EAAEC,QAAQ,EAAE,EAAE;QAC1D,MAAMC,UAAUb,KAAKc,KAAK,CAACC,IAAI,CAACP,KAAKF,MAAM,IAAIA,QAAQK;QAEvD,MAAMK,SAAS,MAAMjB,IAAIc,SAASH,QAAQ;YACxCR;YACAC;YACAE;YACAY,aAAaL;YACbL;QACF;QAEA,6CAA6C;QAC7C,IAAIJ,iBAAiB;YACnBK,KAAKG,QAAQ,GAAGK,OAAOE,GAAG,CAACC,OAAO,CAAC,CAAC,EAAEf,QAAQ,CAAC,CAAC,EAAE;QACpD;QAEA,OAAOI;IACT;AACF,EAAC"}
@@ -0,0 +1,42 @@
1
+ import type { CollectionOptions } from '@payloadcms/plugin-cloud-storage/types';
2
+ import type { Plugin } from 'payload/config';
3
+ export type VercelBlobStorageOptions = {
4
+ /**
5
+ * Access control level
6
+ *
7
+ * @default 'public'
8
+ */
9
+ access?: 'public';
10
+ /**
11
+ * Add a random suffix to the uploaded file name
12
+ *
13
+ * @default false
14
+ */
15
+ addRandomSuffix?: boolean;
16
+ /**
17
+ * Cache-Control max-age in seconds
18
+ *
19
+ * @default 31536000 (1 year)
20
+ */
21
+ cacheControlMaxAge?: number;
22
+ /**
23
+ * Collections to apply the Vercel Blob adapter to
24
+ */
25
+ collections: Record<string, Omit<CollectionOptions, 'adapter'> | true>;
26
+ /**
27
+ * Whether or not to enable the plugin
28
+ *
29
+ * Default: true
30
+ */
31
+ enabled?: boolean;
32
+ /**
33
+ * Vercel Blob storage read/write token
34
+ *
35
+ * Usually process.env.BLOB_READ_WRITE_TOKEN set by Vercel
36
+ */
37
+ token: string;
38
+ };
39
+ type VercelBlobStoragePlugin = (vercelBlobStorageOpts: VercelBlobStorageOptions) => Plugin;
40
+ export declare const vercelBlobStorage: VercelBlobStoragePlugin;
41
+ export {};
42
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,iBAAiB,EAClB,MAAM,wCAAwC,CAAA;AAE/C,OAAO,KAAK,EAAU,MAAM,EAAE,MAAM,gBAAgB,CAAA;AASpD,MAAM,MAAM,wBAAwB,GAAG;IACrC;;;;OAIG;IACH,MAAM,CAAC,EAAE,QAAQ,CAAA;IAEjB;;;;OAIG;IACH,eAAe,CAAC,EAAE,OAAO,CAAA;IAEzB;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAE3B;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,iBAAiB,EAAE,SAAS,CAAC,GAAG,IAAI,CAAC,CAAA;IAEtE;;;;OAIG;IACH,OAAO,CAAC,EAAE,OAAO,CAAA;IAEjB;;;;OAIG;IACH,KAAK,EAAE,MAAM,CAAA;CACd,CAAA;AASD,KAAK,uBAAuB,GAAG,CAAC,qBAAqB,EAAE,wBAAwB,KAAK,MAAM,CAAA;AAE1F,eAAO,MAAM,iBAAiB,EAAE,uBA8C7B,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,74 @@
1
+ import { cloudStorage } from '@payloadcms/plugin-cloud-storage';
2
+ import { getGenerateUrl } from './generateURL.js';
3
+ import { getHandleDelete } from './handleDelete.js';
4
+ import { getHandleUpload } from './handleUpload.js';
5
+ import { getStaticHandler } from './staticHandler.js';
6
+ const defaultUploadOptions = {
7
+ access: 'public',
8
+ addRandomSuffix: false,
9
+ cacheControlMaxAge: 60 * 60 * 24 * 365,
10
+ enabled: true
11
+ };
12
+ export const vercelBlobStorage = (options)=>(incomingConfig)=>{
13
+ if (options.enabled === false) {
14
+ return incomingConfig;
15
+ }
16
+ if (!options.token) {
17
+ throw new Error('The token argument is required for the Vercel Blob adapter.');
18
+ }
19
+ // Parse storeId from token
20
+ const storeId = options.token.match(/^vercel_blob_rw_([a-z\d]+)_[a-z\d]+$/i)?.[1]?.toLowerCase();
21
+ if (!storeId) {
22
+ throw new Error('Invalid token format for Vercel Blob adapter. Should be vercel_blob_rw_<store_id>_<random_string>.');
23
+ }
24
+ const optionsWithDefaults = {
25
+ ...defaultUploadOptions,
26
+ ...options
27
+ };
28
+ const baseUrl = `https://${storeId}.${optionsWithDefaults.access}.blob.vercel-storage.com`;
29
+ const adapter = vercelBlobStorageInternal({
30
+ ...optionsWithDefaults,
31
+ baseUrl
32
+ });
33
+ // Add adapter to each collection option object
34
+ const collectionsWithAdapter = Object.entries(options.collections).reduce((acc, [slug, collOptions])=>({
35
+ ...acc,
36
+ [slug]: {
37
+ ...collOptions === true ? {} : collOptions,
38
+ adapter
39
+ }
40
+ }), {});
41
+ return cloudStorage({
42
+ collections: collectionsWithAdapter
43
+ })(incomingConfig);
44
+ };
45
+ function vercelBlobStorageInternal(options) {
46
+ return ({ collection, prefix })=>{
47
+ const { access, addRandomSuffix, baseUrl, cacheControlMaxAge, token } = options;
48
+ return {
49
+ generateURL: getGenerateUrl({
50
+ baseUrl,
51
+ prefix
52
+ }),
53
+ handleDelete: getHandleDelete({
54
+ baseUrl,
55
+ prefix,
56
+ token: options.token
57
+ }),
58
+ handleUpload: getHandleUpload({
59
+ access,
60
+ addRandomSuffix,
61
+ baseUrl,
62
+ cacheControlMaxAge,
63
+ prefix,
64
+ token
65
+ }),
66
+ staticHandler: getStaticHandler({
67
+ baseUrl,
68
+ token
69
+ }, collection)
70
+ };
71
+ };
72
+ }
73
+
74
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n PluginOptions as CloudStoragePluginOptions,\n CollectionOptions,\n} from '@payloadcms/plugin-cloud-storage/types'\nimport type { Adapter, GeneratedAdapter } from '@payloadcms/plugin-cloud-storage/types'\nimport type { Config, Plugin } from 'payload/config'\n\nimport { cloudStorage } from '@payloadcms/plugin-cloud-storage'\n\nimport { getGenerateUrl } from './generateURL.js'\nimport { getHandleDelete } from './handleDelete.js'\nimport { getHandleUpload } from './handleUpload.js'\nimport { getStaticHandler } from './staticHandler.js'\n\nexport type VercelBlobStorageOptions = {\n /**\n * Access control level\n *\n * @default 'public'\n */\n access?: 'public'\n\n /**\n * Add a random suffix to the uploaded file name\n *\n * @default false\n */\n addRandomSuffix?: boolean\n\n /**\n * Cache-Control max-age in seconds\n *\n * @default 31536000 (1 year)\n */\n cacheControlMaxAge?: number\n\n /**\n * Collections to apply the Vercel Blob adapter to\n */\n collections: Record<string, Omit<CollectionOptions, 'adapter'> | true>\n\n /**\n * Whether or not to enable the plugin\n *\n * Default: true\n */\n enabled?: boolean\n\n /**\n * Vercel Blob storage read/write token\n *\n * Usually process.env.BLOB_READ_WRITE_TOKEN set by Vercel\n */\n token: string\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 if (options.enabled === false) {\n return incomingConfig\n }\n\n if (!options.token) {\n throw new Error('The token argument is required for the Vercel Blob adapter.')\n }\n\n // Parse storeId from token\n const storeId = options.token.match(/^vercel_blob_rw_([a-z\\d]+)_[a-z\\d]+$/i)?.[1]?.toLowerCase()\n\n if (!storeId) {\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 const baseUrl = `https://${storeId}.${optionsWithDefaults.access}.blob.vercel-storage.com`\n\n const adapter = vercelBlobStorageInternal({ ...optionsWithDefaults, baseUrl })\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 return cloudStorage({\n collections: collectionsWithAdapter,\n })(incomingConfig)\n }\n\nfunction vercelBlobStorageInternal(\n options: VercelBlobStorageOptions & { baseUrl: string },\n): Adapter {\n return ({ collection, prefix }): GeneratedAdapter => {\n const { access, addRandomSuffix, baseUrl, cacheControlMaxAge, token } = options\n return {\n generateURL: getGenerateUrl({ baseUrl, prefix }),\n handleDelete: getHandleDelete({ baseUrl, prefix, token: options.token }),\n handleUpload: getHandleUpload({\n access,\n addRandomSuffix,\n baseUrl,\n cacheControlMaxAge,\n prefix,\n token,\n }),\n staticHandler: getStaticHandler({ baseUrl, token }, collection),\n }\n }\n}\n"],"names":["cloudStorage","getGenerateUrl","getHandleDelete","getHandleUpload","getStaticHandler","defaultUploadOptions","access","addRandomSuffix","cacheControlMaxAge","enabled","vercelBlobStorage","options","incomingConfig","token","Error","storeId","match","toLowerCase","optionsWithDefaults","baseUrl","adapter","vercelBlobStorageInternal","collectionsWithAdapter","Object","entries","collections","reduce","acc","slug","collOptions","collection","prefix","generateURL","handleDelete","handleUpload","staticHandler"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAOA,SAASA,YAAY,QAAQ,mCAAkC;AAE/D,SAASC,cAAc,QAAQ,mBAAkB;AACjD,SAASC,eAAe,QAAQ,oBAAmB;AACnD,SAASC,eAAe,QAAQ,oBAAmB;AACnD,SAASC,gBAAgB,QAAQ,qBAAoB;AA4CrD,MAAMC,uBAA0D;IAC9DC,QAAQ;IACRC,iBAAiB;IACjBC,oBAAoB,KAAK,KAAK,KAAK;IACnCC,SAAS;AACX;AAIA,OAAO,MAAMC,oBACX,CAACC,UACD,CAACC;QACC,IAAID,QAAQF,OAAO,KAAK,OAAO;YAC7B,OAAOG;QACT;QAEA,IAAI,CAACD,QAAQE,KAAK,EAAE;YAClB,MAAM,IAAIC,MAAM;QAClB;QAEA,2BAA2B;QAC3B,MAAMC,UAAUJ,QAAQE,KAAK,CAACG,KAAK,CAAC,0CAA0C,CAAC,EAAE,EAAEC;QAEnF,IAAI,CAACF,SAAS;YACZ,MAAM,IAAID,MACR;QAEJ;QAEA,MAAMI,sBAAsB;YAC1B,GAAGb,oBAAoB;YACvB,GAAGM,OAAO;QACZ;QAEA,MAAMQ,UAAU,CAAC,QAAQ,EAAEJ,QAAQ,CAAC,EAAEG,oBAAoBZ,MAAM,CAAC,wBAAwB,CAAC;QAE1F,MAAMc,UAAUC,0BAA0B;YAAE,GAAGH,mBAAmB;YAAEC;QAAQ;QAE5E,+CAA+C;QAC/C,MAAMG,yBAAmEC,OAAOC,OAAO,CACrFb,QAAQc,WAAW,EACnBC,MAAM,CACN,CAACC,KAAK,CAACC,MAAMC,YAAY,GAAM,CAAA;gBAC7B,GAAGF,GAAG;gBACN,CAACC,KAAK,EAAE;oBACN,GAAIC,gBAAgB,OAAO,CAAC,IAAIA,WAAW;oBAC3CT;gBACF;YACF,CAAA,GACA,CAAC;QAGH,OAAOpB,aAAa;YAClByB,aAAaH;QACf,GAAGV;IACL,EAAC;AAEH,SAASS,0BACPV,OAAuD;IAEvD,OAAO,CAAC,EAAEmB,UAAU,EAAEC,MAAM,EAAE;QAC5B,MAAM,EAAEzB,MAAM,EAAEC,eAAe,EAAEY,OAAO,EAAEX,kBAAkB,EAAEK,KAAK,EAAE,GAAGF;QACxE,OAAO;YACLqB,aAAa/B,eAAe;gBAAEkB;gBAASY;YAAO;YAC9CE,cAAc/B,gBAAgB;gBAAEiB;gBAASY;gBAAQlB,OAAOF,QAAQE,KAAK;YAAC;YACtEqB,cAAc/B,gBAAgB;gBAC5BG;gBACAC;gBACAY;gBACAX;gBACAuB;gBACAlB;YACF;YACAsB,eAAe/B,iBAAiB;gBAAEe;gBAASN;YAAM,GAAGiB;QACtD;IACF;AACF"}
@@ -0,0 +1,9 @@
1
+ import type { StaticHandler } from '@payloadcms/plugin-cloud-storage/types';
2
+ import type { CollectionConfig } from 'payload/types';
3
+ type StaticHandlerArgs = {
4
+ baseUrl: string;
5
+ token: string;
6
+ };
7
+ export declare const getStaticHandler: ({ baseUrl, token }: StaticHandlerArgs, collection: CollectionConfig) => StaticHandler;
8
+ export {};
9
+ //# sourceMappingURL=staticHandler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"staticHandler.d.ts","sourceRoot":"","sources":["../src/staticHandler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,wCAAwC,CAAA;AAC3E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAA;AAMrD,KAAK,iBAAiB,GAAG;IACvB,OAAO,EAAE,MAAM,CAAA;IACf,KAAK,EAAE,MAAM,CAAA;CACd,CAAA;AAED,eAAO,MAAM,gBAAgB,uBACP,iBAAiB,cACzB,gBAAgB,KAC3B,aAmCF,CAAA"}
@@ -0,0 +1,52 @@
1
+ import { getFilePrefix } from '@payloadcms/plugin-cloud-storage/utilities';
2
+ import { head } from '@vercel/blob';
3
+ import path from 'path';
4
+ export const getStaticHandler = ({ baseUrl, token }, collection)=>{
5
+ return async (req, { params: { filename } })=>{
6
+ try {
7
+ const prefix = await getFilePrefix({
8
+ collection,
9
+ filename,
10
+ req
11
+ });
12
+ const fileUrl = `${baseUrl}/${path.posix.join(prefix, filename)}`;
13
+ const blobMetadata = await head(fileUrl, {
14
+ token
15
+ });
16
+ if (!blobMetadata) {
17
+ return new Response(null, {
18
+ status: 404,
19
+ statusText: 'Not Found'
20
+ });
21
+ }
22
+ const { contentDisposition, contentType, size } = blobMetadata;
23
+ const response = await fetch(fileUrl);
24
+ const blob = await response.blob();
25
+ if (!blob) {
26
+ return new Response(null, {
27
+ status: 204,
28
+ statusText: 'No Content'
29
+ });
30
+ }
31
+ const bodyBuffer = await blob.arrayBuffer();
32
+ return new Response(bodyBuffer, {
33
+ headers: new Headers({
34
+ 'Content-Disposition': contentDisposition,
35
+ 'Content-Length': String(size),
36
+ 'Content-Type': contentType
37
+ }),
38
+ status: 200
39
+ });
40
+ } catch (err) {
41
+ req.payload.logger.error({
42
+ err,
43
+ msg: 'Unexpected error in staticHandler'
44
+ });
45
+ return new Response('Internal Server Error', {
46
+ status: 500
47
+ });
48
+ }
49
+ };
50
+ };
51
+
52
+ //# sourceMappingURL=staticHandler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/staticHandler.ts"],"sourcesContent":["import type { StaticHandler } from '@payloadcms/plugin-cloud-storage/types'\nimport type { CollectionConfig } from 'payload/types'\n\nimport { getFilePrefix } from '@payloadcms/plugin-cloud-storage/utilities'\nimport { head } from '@vercel/blob'\nimport path from 'path'\n\ntype StaticHandlerArgs = {\n baseUrl: string\n token: string\n}\n\nexport const getStaticHandler = (\n { baseUrl, token }: StaticHandlerArgs,\n collection: CollectionConfig,\n): StaticHandler => {\n return async (req, { params: { filename } }) => {\n try {\n const prefix = await getFilePrefix({ collection, filename, req })\n\n const fileUrl = `${baseUrl}/${path.posix.join(prefix, filename)}`\n\n const blobMetadata = await head(fileUrl, { token })\n if (!blobMetadata) {\n return new Response(null, { status: 404, statusText: 'Not Found' })\n }\n\n const { contentDisposition, contentType, size } = blobMetadata\n const response = await fetch(fileUrl)\n const blob = await response.blob()\n\n if (!blob) {\n return new Response(null, { status: 204, statusText: 'No Content' })\n }\n\n const bodyBuffer = await blob.arrayBuffer()\n\n return new Response(bodyBuffer, {\n headers: new Headers({\n 'Content-Disposition': contentDisposition,\n 'Content-Length': String(size),\n 'Content-Type': contentType,\n }),\n status: 200,\n })\n } catch (err: unknown) {\n req.payload.logger.error({ err, msg: 'Unexpected error in staticHandler' })\n return new Response('Internal Server Error', { status: 500 })\n }\n }\n}\n"],"names":["getFilePrefix","head","path","getStaticHandler","baseUrl","token","collection","req","params","filename","prefix","fileUrl","posix","join","blobMetadata","Response","status","statusText","contentDisposition","contentType","size","response","fetch","blob","bodyBuffer","arrayBuffer","headers","Headers","String","err","payload","logger","error","msg"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAGA,SAASA,aAAa,QAAQ,6CAA4C;AAC1E,SAASC,IAAI,QAAQ,eAAc;AACnC,OAAOC,UAAU,OAAM;AAOvB,OAAO,MAAMC,mBAAmB,CAC9B,EAAEC,OAAO,EAAEC,KAAK,EAAqB,EACrCC;IAEA,OAAO,OAAOC,KAAK,EAAEC,QAAQ,EAAEC,QAAQ,EAAE,EAAE;QACzC,IAAI;YACF,MAAMC,SAAS,MAAMV,cAAc;gBAAEM;gBAAYG;gBAAUF;YAAI;YAE/D,MAAMI,UAAU,CAAC,EAAEP,QAAQ,CAAC,EAAEF,KAAKU,KAAK,CAACC,IAAI,CAACH,QAAQD,UAAU,CAAC;YAEjE,MAAMK,eAAe,MAAMb,KAAKU,SAAS;gBAAEN;YAAM;YACjD,IAAI,CAACS,cAAc;gBACjB,OAAO,IAAIC,SAAS,MAAM;oBAAEC,QAAQ;oBAAKC,YAAY;gBAAY;YACnE;YAEA,MAAM,EAAEC,kBAAkB,EAAEC,WAAW,EAAEC,IAAI,EAAE,GAAGN;YAClD,MAAMO,WAAW,MAAMC,MAAMX;YAC7B,MAAMY,OAAO,MAAMF,SAASE,IAAI;YAEhC,IAAI,CAACA,MAAM;gBACT,OAAO,IAAIR,SAAS,MAAM;oBAAEC,QAAQ;oBAAKC,YAAY;gBAAa;YACpE;YAEA,MAAMO,aAAa,MAAMD,KAAKE,WAAW;YAEzC,OAAO,IAAIV,SAASS,YAAY;gBAC9BE,SAAS,IAAIC,QAAQ;oBACnB,uBAAuBT;oBACvB,kBAAkBU,OAAOR;oBACzB,gBAAgBD;gBAClB;gBACAH,QAAQ;YACV;QACF,EAAE,OAAOa,KAAc;YACrBtB,IAAIuB,OAAO,CAACC,MAAM,CAACC,KAAK,CAAC;gBAAEH;gBAAKI,KAAK;YAAoC;YACzE,OAAO,IAAIlB,SAAS,yBAAyB;gBAAEC,QAAQ;YAAI;QAC7D;IACF;AACF,EAAC"}
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@payloadcms/storage-vercel-blob",
3
+ "version": "3.0.0-alpha.62",
4
+ "description": "Payload storage adapter for Vercel Blob Storage",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/payloadcms/payload.git",
8
+ "directory": "packages/storage-vercel-blob"
9
+ },
10
+ "license": "MIT",
11
+ "homepage": "https://payloadcms.com",
12
+ "author": "Payload CMS, Inc.",
13
+ "main": "./dist/index.js",
14
+ "types": "./dist/index.d.ts",
15
+ "type": "module",
16
+ "exports": {
17
+ ".": {
18
+ "import": "./dist/index.js",
19
+ "require": "./dist/index.js",
20
+ "types": "./dist/index.d.ts"
21
+ }
22
+ },
23
+ "dependencies": {
24
+ "@payloadcms/plugin-cloud-storage": "3.0.0-alpha.62"
25
+ },
26
+ "devDependencies": {
27
+ "@vercel/blob": "^0.22.3",
28
+ "payload": "3.0.0-alpha.62"
29
+ },
30
+ "peerDependencies": {
31
+ "payload": "3.0.0-alpha.62"
32
+ },
33
+ "engines": {
34
+ "node": ">=18.20.2"
35
+ },
36
+ "files": [
37
+ "dist"
38
+ ],
39
+ "scripts": {
40
+ "build": "pnpm build:swc && pnpm build:types",
41
+ "build:swc": "swc ./src -d ./dist --config-file .swcrc",
42
+ "build:types": "tsc --emitDeclarationOnly --outDir dist",
43
+ "build:clean": "find . \\( -type d \\( -name build -o -name dist -o -name .cache \\) -o -type f -name tsconfig.tsbuildinfo \\) -exec rm -rf {} + && pnpm build",
44
+ "clean": "rimraf {dist,*.tsbuildinfo}"
45
+ }
46
+ }
package/src/index.ts ADDED
@@ -0,0 +1,133 @@
1
+ import type {
2
+ PluginOptions as CloudStoragePluginOptions,
3
+ CollectionOptions,
4
+ } from '@payloadcms/plugin-cloud-storage/types'
5
+ import type { Adapter, GeneratedAdapter } from '@payloadcms/plugin-cloud-storage/types'
6
+ import type { Config, Plugin } from 'payload/config'
7
+
8
+ import { cloudStorage } from '@payloadcms/plugin-cloud-storage'
9
+
10
+ import { getGenerateUrl } from './generateURL.js'
11
+ import { getHandleDelete } from './handleDelete.js'
12
+ import { getHandleUpload } from './handleUpload.js'
13
+ import { getStaticHandler } from './staticHandler.js'
14
+
15
+ export type VercelBlobStorageOptions = {
16
+ /**
17
+ * Access control level
18
+ *
19
+ * @default 'public'
20
+ */
21
+ access?: 'public'
22
+
23
+ /**
24
+ * Add a random suffix to the uploaded file name
25
+ *
26
+ * @default false
27
+ */
28
+ addRandomSuffix?: boolean
29
+
30
+ /**
31
+ * Cache-Control max-age in seconds
32
+ *
33
+ * @default 31536000 (1 year)
34
+ */
35
+ cacheControlMaxAge?: number
36
+
37
+ /**
38
+ * Collections to apply the Vercel Blob adapter to
39
+ */
40
+ collections: Record<string, Omit<CollectionOptions, 'adapter'> | true>
41
+
42
+ /**
43
+ * Whether or not to enable the plugin
44
+ *
45
+ * Default: true
46
+ */
47
+ enabled?: boolean
48
+
49
+ /**
50
+ * Vercel Blob storage read/write token
51
+ *
52
+ * Usually process.env.BLOB_READ_WRITE_TOKEN set by Vercel
53
+ */
54
+ token: string
55
+ }
56
+
57
+ const defaultUploadOptions: Partial<VercelBlobStorageOptions> = {
58
+ access: 'public',
59
+ addRandomSuffix: false,
60
+ cacheControlMaxAge: 60 * 60 * 24 * 365, // 1 year
61
+ enabled: true,
62
+ }
63
+
64
+ type VercelBlobStoragePlugin = (vercelBlobStorageOpts: VercelBlobStorageOptions) => Plugin
65
+
66
+ export const vercelBlobStorage: VercelBlobStoragePlugin =
67
+ (options: VercelBlobStorageOptions) =>
68
+ (incomingConfig: Config): Config => {
69
+ if (options.enabled === false) {
70
+ return incomingConfig
71
+ }
72
+
73
+ if (!options.token) {
74
+ throw new Error('The token argument is required for the Vercel Blob adapter.')
75
+ }
76
+
77
+ // Parse storeId from token
78
+ const storeId = options.token.match(/^vercel_blob_rw_([a-z\d]+)_[a-z\d]+$/i)?.[1]?.toLowerCase()
79
+
80
+ if (!storeId) {
81
+ throw new Error(
82
+ 'Invalid token format for Vercel Blob adapter. Should be vercel_blob_rw_<store_id>_<random_string>.',
83
+ )
84
+ }
85
+
86
+ const optionsWithDefaults = {
87
+ ...defaultUploadOptions,
88
+ ...options,
89
+ }
90
+
91
+ const baseUrl = `https://${storeId}.${optionsWithDefaults.access}.blob.vercel-storage.com`
92
+
93
+ const adapter = vercelBlobStorageInternal({ ...optionsWithDefaults, baseUrl })
94
+
95
+ // Add adapter to each collection option object
96
+ const collectionsWithAdapter: CloudStoragePluginOptions['collections'] = Object.entries(
97
+ options.collections,
98
+ ).reduce(
99
+ (acc, [slug, collOptions]) => ({
100
+ ...acc,
101
+ [slug]: {
102
+ ...(collOptions === true ? {} : collOptions),
103
+ adapter,
104
+ },
105
+ }),
106
+ {} as Record<string, CollectionOptions>,
107
+ )
108
+
109
+ return cloudStorage({
110
+ collections: collectionsWithAdapter,
111
+ })(incomingConfig)
112
+ }
113
+
114
+ function vercelBlobStorageInternal(
115
+ options: VercelBlobStorageOptions & { baseUrl: string },
116
+ ): Adapter {
117
+ return ({ collection, prefix }): GeneratedAdapter => {
118
+ const { access, addRandomSuffix, baseUrl, cacheControlMaxAge, token } = options
119
+ return {
120
+ generateURL: getGenerateUrl({ baseUrl, prefix }),
121
+ handleDelete: getHandleDelete({ baseUrl, prefix, token: options.token }),
122
+ handleUpload: getHandleUpload({
123
+ access,
124
+ addRandomSuffix,
125
+ baseUrl,
126
+ cacheControlMaxAge,
127
+ prefix,
128
+ token,
129
+ }),
130
+ staticHandler: getStaticHandler({ baseUrl, token }, collection),
131
+ }
132
+ }
133
+ }