@payloadcms/storage-azure 4.0.0-internal.e387174 → 4.0.0-internal.e55ccef

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/README.md CHANGED
@@ -14,7 +14,23 @@ pnpm add @payloadcms/storage-azure
14
14
 
15
15
  - Configure the `collections` object to specify which collections should use the Azure Blob Storage adapter. The slug _must_ match one of your existing collection slugs.
16
16
  - When enabled, this package will automatically set `disableLocalStorage` to `true` for each collection.
17
- - When deploying to Vercel, server uploads are limited with 4.5MB. Set `clientUploads` to `true` to do uploads directly on the client. You must allow CORS PUT method to your website.
17
+ - When deploying to Vercel, server uploads are limited with 4.5MB. Set `clientUploads` to `true` to do uploads directly on the client.
18
+
19
+ ### Client uploads and CORS
20
+
21
+ Client uploads (`clientUploads: true`) use the Azure Blob SDK, which splits large files into blocks and therefore avoids the ~5GB limit of a single upload request. Because the SDK sends `x-ms-*` headers, the browser issues a CORS preflight, so your storage account's CORS rules must allow the `OPTIONS` and `PUT` methods **and** the required headers.
22
+
23
+ Configure a CORS rule on the Blob service (Storage account → **Resource sharing (CORS)**):
24
+
25
+ | Field | Value |
26
+ | --------------- | -------------------------------------------------------- |
27
+ | Allowed origins | Your site origin (e.g. `https://example.com`) |
28
+ | Allowed methods | `GET,PUT,OPTIONS` (add `HEAD` if reading in-browser) |
29
+ | Allowed headers | `*` (or at minimum `x-ms-*,content-type,content-length`) |
30
+ | Exposed headers | `*` |
31
+ | Max age | `3600` |
32
+
33
+ > If you previously configured CORS for the older single-`PUT` upload flow, broaden `Allowed headers` to include the `x-ms-*` headers when upgrading.
18
34
 
19
35
  ```ts
20
36
  import { azureStorage } from '@payloadcms/storage-azure'
@@ -1 +1 @@
1
- {"version":3,"file":"AzureClientUploadHandler.d.ts","sourceRoot":"","sources":["../../src/client/AzureClientUploadHandler.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,wBAAwB;;;;;;;iCAqDnC,CAAA"}
1
+ {"version":3,"file":"AzureClientUploadHandler.d.ts","sourceRoot":"","sources":["../../src/client/AzureClientUploadHandler.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,wBAAwB;;;;;;;iCAoBnC,CAAA"}
@@ -1,40 +1,17 @@
1
1
  'use client';
2
2
  import { createClientUploadHandler } from '@payloadcms/plugin-cloud-storage/client';
3
- import { formatAdminURL } from 'payload/shared';
3
+ import { handleAzureUpload } from './handleAzureUpload.js';
4
4
  export const AzureClientUploadHandler = createClientUploadHandler({
5
5
  handler: async ({ apiRoute, collectionSlug, docPrefix, file, serverHandlerPath, serverURL, updateFilename })=>{
6
- const endpointRoute = formatAdminURL({
6
+ return handleAzureUpload({
7
7
  apiRoute,
8
- path: serverHandlerPath,
9
- serverURL
8
+ collectionSlug,
9
+ docPrefix,
10
+ file,
11
+ serverHandlerPath,
12
+ serverURL,
13
+ updateFilename
10
14
  });
11
- const response = await fetch(endpointRoute, {
12
- body: JSON.stringify({
13
- collectionSlug,
14
- docPrefix,
15
- filename: file.name,
16
- mimeType: file.type
17
- }),
18
- credentials: 'include',
19
- method: 'POST'
20
- });
21
- const { docPrefix: sanitizedDocPrefix, filename: sanitizedFilename, url } = await response.json();
22
- if (sanitizedFilename && sanitizedFilename !== file.name) {
23
- updateFilename(sanitizedFilename);
24
- }
25
- await fetch(url, {
26
- body: file,
27
- headers: {
28
- 'Content-Length': file.size.toString(),
29
- 'Content-Type': file.type,
30
- // Required for azure
31
- 'x-ms-blob-type': 'BlockBlob'
32
- },
33
- method: 'PUT'
34
- });
35
- return {
36
- prefix: sanitizedDocPrefix
37
- };
38
15
  }
39
16
  });
40
17
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/client/AzureClientUploadHandler.ts"],"sourcesContent":["'use client'\nimport { createClientUploadHandler } from '@payloadcms/plugin-cloud-storage/client'\nimport { formatAdminURL } from 'payload/shared'\n\nexport const AzureClientUploadHandler = createClientUploadHandler({\n handler: async ({\n apiRoute,\n collectionSlug,\n docPrefix,\n file,\n serverHandlerPath,\n serverURL,\n updateFilename,\n }) => {\n const endpointRoute = formatAdminURL({\n apiRoute,\n path: serverHandlerPath,\n serverURL,\n })\n const response = await fetch(endpointRoute, {\n body: JSON.stringify({\n collectionSlug,\n docPrefix,\n filename: file.name,\n mimeType: file.type,\n }),\n credentials: 'include',\n method: 'POST',\n })\n\n const {\n docPrefix: sanitizedDocPrefix,\n filename: sanitizedFilename,\n url,\n } = (await response.json()) as {\n docPrefix: string\n filename?: string\n url: string\n }\n\n if (sanitizedFilename && sanitizedFilename !== file.name) {\n updateFilename(sanitizedFilename)\n }\n\n await fetch(url, {\n body: file,\n headers: {\n 'Content-Length': file.size.toString(),\n 'Content-Type': file.type,\n // Required for azure\n 'x-ms-blob-type': 'BlockBlob',\n },\n method: 'PUT',\n })\n\n return { prefix: sanitizedDocPrefix }\n },\n})\n"],"names":["createClientUploadHandler","formatAdminURL","AzureClientUploadHandler","handler","apiRoute","collectionSlug","docPrefix","file","serverHandlerPath","serverURL","updateFilename","endpointRoute","path","response","fetch","body","JSON","stringify","filename","name","mimeType","type","credentials","method","sanitizedDocPrefix","sanitizedFilename","url","json","headers","size","toString","prefix"],"mappings":"AAAA;AACA,SAASA,yBAAyB,QAAQ,0CAAyC;AACnF,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,OAAO,MAAMC,2BAA2BF,0BAA0B;IAChEG,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,WAAW,MAAMC,MAAMH,eAAe;YAC1CI,MAAMC,KAAKC,SAAS,CAAC;gBACnBZ;gBACAC;gBACAY,UAAUX,KAAKY,IAAI;gBACnBC,UAAUb,KAAKc,IAAI;YACrB;YACAC,aAAa;YACbC,QAAQ;QACV;QAEA,MAAM,EACJjB,WAAWkB,kBAAkB,EAC7BN,UAAUO,iBAAiB,EAC3BC,GAAG,EACJ,GAAI,MAAMb,SAASc,IAAI;QAMxB,IAAIF,qBAAqBA,sBAAsBlB,KAAKY,IAAI,EAAE;YACxDT,eAAee;QACjB;QAEA,MAAMX,MAAMY,KAAK;YACfX,MAAMR;YACNqB,SAAS;gBACP,kBAAkBrB,KAAKsB,IAAI,CAACC,QAAQ;gBACpC,gBAAgBvB,KAAKc,IAAI;gBACzB,qBAAqB;gBACrB,kBAAkB;YACpB;YACAE,QAAQ;QACV;QAEA,OAAO;YAAEQ,QAAQP;QAAmB;IACtC;AACF,GAAE"}
1
+ {"version":3,"sources":["../../src/client/AzureClientUploadHandler.ts"],"sourcesContent":["'use client'\nimport { createClientUploadHandler } from '@payloadcms/plugin-cloud-storage/client'\n\nimport { handleAzureUpload } from './handleAzureUpload.js'\n\nexport const AzureClientUploadHandler = createClientUploadHandler({\n handler: async ({\n apiRoute,\n collectionSlug,\n docPrefix,\n file,\n serverHandlerPath,\n serverURL,\n updateFilename,\n }) => {\n return handleAzureUpload({\n apiRoute,\n collectionSlug,\n docPrefix,\n file,\n serverHandlerPath,\n serverURL,\n updateFilename,\n })\n },\n})\n"],"names":["createClientUploadHandler","handleAzureUpload","AzureClientUploadHandler","handler","apiRoute","collectionSlug","docPrefix","file","serverHandlerPath","serverURL","updateFilename"],"mappings":"AAAA;AACA,SAASA,yBAAyB,QAAQ,0CAAyC;AAEnF,SAASC,iBAAiB,QAAQ,yBAAwB;AAE1D,OAAO,MAAMC,2BAA2BF,0BAA0B;IAChEG,SAAS,OAAO,EACdC,QAAQ,EACRC,cAAc,EACdC,SAAS,EACTC,IAAI,EACJC,iBAAiB,EACjBC,SAAS,EACTC,cAAc,EACf;QACC,OAAOT,kBAAkB;YACvBG;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;QACF;IACF;AACF,GAAE"}
@@ -0,0 +1,14 @@
1
+ type HandleAzureUploadArgs = {
2
+ apiRoute: string;
3
+ collectionSlug: string;
4
+ docPrefix?: string;
5
+ file: File;
6
+ serverHandlerPath: `/${string}`;
7
+ serverURL: string;
8
+ updateFilename: (value: string) => void;
9
+ };
10
+ export declare const handleAzureUpload: ({ apiRoute, collectionSlug, docPrefix, file, serverHandlerPath, serverURL, updateFilename, }: HandleAzureUploadArgs) => Promise<{
11
+ prefix: string;
12
+ }>;
13
+ export {};
14
+ //# sourceMappingURL=handleAzureUpload.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handleAzureUpload.d.ts","sourceRoot":"","sources":["../../src/client/handleAzureUpload.ts"],"names":[],"mappings":"AAUA,KAAK,qBAAqB,GAAG;IAC3B,QAAQ,EAAE,MAAM,CAAA;IAChB,cAAc,EAAE,MAAM,CAAA;IACtB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,IAAI,EAAE,IAAI,CAAA;IACV,iBAAiB,EAAE,IAAI,MAAM,EAAE,CAAA;IAC/B,SAAS,EAAE,MAAM,CAAA;IACjB,cAAc,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAA;CACxC,CAAA;AAED,eAAO,MAAM,iBAAiB,iGAQ3B,qBAAqB,KAAG,OAAO,CAAC;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,CAiDpD,CAAA"}
@@ -0,0 +1,48 @@
1
+ 'use client';
2
+ import { formatAdminURL } from 'payload/shared';
3
+ // Balances upload parallelism against browser memory: `blockSize * concurrency`
4
+ // bytes are buffered in flight. The SDK uses a single Put Blob for small files
5
+ // and switches to Put Block + Put Block List above its single-shot threshold,
6
+ // lifting the ~5 GB single-request ceiling to Azure's block-blob maximum.
7
+ const BLOCK_SIZE = 64 * 1024 * 1024;
8
+ const CONCURRENCY = 4;
9
+ export const handleAzureUpload = async ({ apiRoute, collectionSlug, docPrefix, file, serverHandlerPath, serverURL, updateFilename })=>{
10
+ const endpointRoute = formatAdminURL({
11
+ apiRoute,
12
+ path: serverHandlerPath,
13
+ serverURL
14
+ });
15
+ const response = await fetch(endpointRoute, {
16
+ body: JSON.stringify({
17
+ collectionSlug,
18
+ docPrefix,
19
+ filename: file.name,
20
+ mimeType: file.type
21
+ }),
22
+ credentials: 'include',
23
+ method: 'POST'
24
+ });
25
+ if (!response.ok) {
26
+ throw new Error('Failed to retrieve signed URL for Azure client upload');
27
+ }
28
+ const { docPrefix: sanitizedDocPrefix, filename: sanitizedFilename, url } = await response.json();
29
+ if (sanitizedFilename && sanitizedFilename !== file.name) {
30
+ updateFilename(sanitizedFilename);
31
+ }
32
+ // Loaded on demand so @azure/storage-blob is only pulled into the client bundle
33
+ // when a client upload actually runs, rather than for every Azure adapter user.
34
+ const { BlockBlobClient } = await import('@azure/storage-blob');
35
+ const blockBlobClient = new BlockBlobClient(url);
36
+ await blockBlobClient.uploadData(file, {
37
+ blobHTTPHeaders: {
38
+ blobContentType: file.type
39
+ },
40
+ blockSize: BLOCK_SIZE,
41
+ concurrency: CONCURRENCY
42
+ });
43
+ return {
44
+ prefix: sanitizedDocPrefix
45
+ };
46
+ };
47
+
48
+ //# sourceMappingURL=handleAzureUpload.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/client/handleAzureUpload.ts"],"sourcesContent":["'use client'\nimport { formatAdminURL } from 'payload/shared'\n\n// Balances upload parallelism against browser memory: `blockSize * concurrency`\n// bytes are buffered in flight. The SDK uses a single Put Blob for small files\n// and switches to Put Block + Put Block List above its single-shot threshold,\n// lifting the ~5 GB single-request ceiling to Azure's block-blob maximum.\nconst BLOCK_SIZE = 64 * 1024 * 1024\nconst CONCURRENCY = 4\n\ntype HandleAzureUploadArgs = {\n apiRoute: string\n collectionSlug: string\n docPrefix?: string\n file: File\n serverHandlerPath: `/${string}`\n serverURL: string\n updateFilename: (value: string) => void\n}\n\nexport const handleAzureUpload = async ({\n apiRoute,\n collectionSlug,\n docPrefix,\n file,\n serverHandlerPath,\n serverURL,\n updateFilename,\n}: HandleAzureUploadArgs): Promise<{ prefix: string }> => {\n const endpointRoute = formatAdminURL({\n apiRoute,\n path: serverHandlerPath,\n serverURL,\n })\n\n const response = await fetch(endpointRoute, {\n body: JSON.stringify({\n collectionSlug,\n docPrefix,\n filename: file.name,\n mimeType: file.type,\n }),\n credentials: 'include',\n method: 'POST',\n })\n\n if (!response.ok) {\n throw new Error('Failed to retrieve signed URL for Azure client upload')\n }\n\n const {\n docPrefix: sanitizedDocPrefix,\n filename: sanitizedFilename,\n url,\n } = (await response.json()) as {\n docPrefix: string\n filename?: string\n url: string\n }\n\n if (sanitizedFilename && sanitizedFilename !== file.name) {\n updateFilename(sanitizedFilename)\n }\n\n // Loaded on demand so @azure/storage-blob is only pulled into the client bundle\n // when a client upload actually runs, rather than for every Azure adapter user.\n const { BlockBlobClient } = await import('@azure/storage-blob')\n\n const blockBlobClient = new BlockBlobClient(url)\n\n await blockBlobClient.uploadData(file, {\n blobHTTPHeaders: { blobContentType: file.type },\n blockSize: BLOCK_SIZE,\n concurrency: CONCURRENCY,\n })\n\n return { prefix: sanitizedDocPrefix }\n}\n"],"names":["formatAdminURL","BLOCK_SIZE","CONCURRENCY","handleAzureUpload","apiRoute","collectionSlug","docPrefix","file","serverHandlerPath","serverURL","updateFilename","endpointRoute","path","response","fetch","body","JSON","stringify","filename","name","mimeType","type","credentials","method","ok","Error","sanitizedDocPrefix","sanitizedFilename","url","json","BlockBlobClient","blockBlobClient","uploadData","blobHTTPHeaders","blobContentType","blockSize","concurrency","prefix"],"mappings":"AAAA;AACA,SAASA,cAAc,QAAQ,iBAAgB;AAE/C,gFAAgF;AAChF,+EAA+E;AAC/E,8EAA8E;AAC9E,0EAA0E;AAC1E,MAAMC,aAAa,KAAK,OAAO;AAC/B,MAAMC,cAAc;AAYpB,OAAO,MAAMC,oBAAoB,OAAO,EACtCC,QAAQ,EACRC,cAAc,EACdC,SAAS,EACTC,IAAI,EACJC,iBAAiB,EACjBC,SAAS,EACTC,cAAc,EACQ;IACtB,MAAMC,gBAAgBX,eAAe;QACnCI;QACAQ,MAAMJ;QACNC;IACF;IAEA,MAAMI,WAAW,MAAMC,MAAMH,eAAe;QAC1CI,MAAMC,KAAKC,SAAS,CAAC;YACnBZ;YACAC;YACAY,UAAUX,KAAKY,IAAI;YACnBC,UAAUb,KAAKc,IAAI;QACrB;QACAC,aAAa;QACbC,QAAQ;IACV;IAEA,IAAI,CAACV,SAASW,EAAE,EAAE;QAChB,MAAM,IAAIC,MAAM;IAClB;IAEA,MAAM,EACJnB,WAAWoB,kBAAkB,EAC7BR,UAAUS,iBAAiB,EAC3BC,GAAG,EACJ,GAAI,MAAMf,SAASgB,IAAI;IAMxB,IAAIF,qBAAqBA,sBAAsBpB,KAAKY,IAAI,EAAE;QACxDT,eAAeiB;IACjB;IAEA,gFAAgF;IAChF,gFAAgF;IAChF,MAAM,EAAEG,eAAe,EAAE,GAAG,MAAM,MAAM,CAAC;IAEzC,MAAMC,kBAAkB,IAAID,gBAAgBF;IAE5C,MAAMG,gBAAgBC,UAAU,CAACzB,MAAM;QACrC0B,iBAAiB;YAAEC,iBAAiB3B,KAAKc,IAAI;QAAC;QAC9Cc,WAAWlC;QACXmC,aAAalC;IACf;IAEA,OAAO;QAAEmC,QAAQX;IAAmB;AACtC,EAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=handleAzureUpload.spec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handleAzureUpload.spec.d.ts","sourceRoot":"","sources":["../../src/client/handleAzureUpload.spec.ts"],"names":[],"mappings":""}
@@ -0,0 +1,185 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+ const uploadDataMock = vi.fn();
3
+ const blockBlobClientMock = vi.fn(function() {
4
+ return {
5
+ uploadData: uploadDataMock
6
+ };
7
+ });
8
+ vi.mock('@azure/storage-blob', ()=>({
9
+ BlockBlobClient: blockBlobClientMock
10
+ }));
11
+ import { handleAzureUpload } from './handleAzureUpload.js';
12
+ const serverURL = 'https://example.com';
13
+ const apiRoute = '/api';
14
+ const serverHandlerPath = '/storage-azure-generate-signed-url';
15
+ const signedURL = 'https://account.blob.core.windows.net/container/file.png?sig=abc';
16
+ const createFile = ()=>new File([
17
+ new Uint8Array([
18
+ 1,
19
+ 2,
20
+ 3
21
+ ])
22
+ ], 'file.png', {
23
+ type: 'image/png'
24
+ });
25
+ const mockSignedURLResponse = (body, ok = true)=>{
26
+ const fetchMock = vi.fn().mockResolvedValue({
27
+ json: ()=>Promise.resolve(body),
28
+ ok
29
+ });
30
+ vi.stubGlobal('fetch', fetchMock);
31
+ return fetchMock;
32
+ };
33
+ describe('handleAzureUpload', ()=>{
34
+ beforeEach(()=>{
35
+ vi.clearAllMocks();
36
+ vi.unstubAllGlobals();
37
+ uploadDataMock.mockResolvedValue(undefined);
38
+ });
39
+ it('should request a signed URL from the server handler', async ()=>{
40
+ const fetchMock = mockSignedURLResponse({
41
+ docPrefix: 'docs',
42
+ url: signedURL
43
+ });
44
+ await handleAzureUpload({
45
+ apiRoute,
46
+ collectionSlug: 'media',
47
+ docPrefix: 'docs',
48
+ file: createFile(),
49
+ serverHandlerPath,
50
+ serverURL,
51
+ updateFilename: vi.fn()
52
+ });
53
+ expect(fetchMock).toHaveBeenCalledTimes(1);
54
+ const [calledURL, init] = fetchMock.mock.calls[0];
55
+ expect(calledURL).toBe(`${serverURL}${apiRoute}${serverHandlerPath}`);
56
+ expect(init.method).toBe('POST');
57
+ expect(JSON.parse(init.body)).toEqual({
58
+ collectionSlug: 'media',
59
+ docPrefix: 'docs',
60
+ filename: 'file.png',
61
+ mimeType: 'image/png'
62
+ });
63
+ });
64
+ it('should upload via BlockBlobClient.uploadData rather than a raw PUT', async ()=>{
65
+ const fetchMock = mockSignedURLResponse({
66
+ docPrefix: 'docs',
67
+ url: signedURL
68
+ });
69
+ const file = createFile();
70
+ await handleAzureUpload({
71
+ apiRoute,
72
+ collectionSlug: 'media',
73
+ file,
74
+ serverHandlerPath,
75
+ serverURL,
76
+ updateFilename: vi.fn()
77
+ });
78
+ expect(blockBlobClientMock).toHaveBeenCalledWith(signedURL);
79
+ expect(uploadDataMock).toHaveBeenCalledTimes(1);
80
+ const [uploadedFile, options] = uploadDataMock.mock.calls[0];
81
+ expect(uploadedFile).toBe(file);
82
+ expect(options.blockSize).toBeGreaterThan(0);
83
+ expect(options.concurrency).toBeGreaterThan(0);
84
+ // Only the signed-URL request should hit fetch; no raw PUT to the blob URL.
85
+ expect(fetchMock).toHaveBeenCalledTimes(1);
86
+ });
87
+ it('should pass the file content type to the blob headers', async ()=>{
88
+ mockSignedURLResponse({
89
+ docPrefix: 'docs',
90
+ url: signedURL
91
+ });
92
+ await handleAzureUpload({
93
+ apiRoute,
94
+ collectionSlug: 'media',
95
+ file: createFile(),
96
+ serverHandlerPath,
97
+ serverURL,
98
+ updateFilename: vi.fn()
99
+ });
100
+ const [, options] = uploadDataMock.mock.calls[0];
101
+ expect(options.blobHTTPHeaders).toEqual({
102
+ blobContentType: 'image/png'
103
+ });
104
+ });
105
+ it('should call updateFilename when the server returns a sanitized filename', async ()=>{
106
+ mockSignedURLResponse({
107
+ docPrefix: 'docs',
108
+ filename: 'file-1.png',
109
+ url: signedURL
110
+ });
111
+ const updateFilename = vi.fn();
112
+ await handleAzureUpload({
113
+ apiRoute,
114
+ collectionSlug: 'media',
115
+ file: createFile(),
116
+ serverHandlerPath,
117
+ serverURL,
118
+ updateFilename
119
+ });
120
+ expect(updateFilename).toHaveBeenCalledWith('file-1.png');
121
+ });
122
+ it('should not call updateFilename when the filename is unchanged', async ()=>{
123
+ mockSignedURLResponse({
124
+ docPrefix: 'docs',
125
+ filename: 'file.png',
126
+ url: signedURL
127
+ });
128
+ const updateFilename = vi.fn();
129
+ await handleAzureUpload({
130
+ apiRoute,
131
+ collectionSlug: 'media',
132
+ file: createFile(),
133
+ serverHandlerPath,
134
+ serverURL,
135
+ updateFilename
136
+ });
137
+ expect(updateFilename).not.toHaveBeenCalled();
138
+ });
139
+ it('should return the sanitized doc prefix', async ()=>{
140
+ mockSignedURLResponse({
141
+ docPrefix: 'sanitized-docs',
142
+ url: signedURL
143
+ });
144
+ const result = await handleAzureUpload({
145
+ apiRoute,
146
+ collectionSlug: 'media',
147
+ file: createFile(),
148
+ serverHandlerPath,
149
+ serverURL,
150
+ updateFilename: vi.fn()
151
+ });
152
+ expect(result).toEqual({
153
+ prefix: 'sanitized-docs'
154
+ });
155
+ });
156
+ it('should throw when the signed URL request fails', async ()=>{
157
+ mockSignedURLResponse({}, false);
158
+ await expect(handleAzureUpload({
159
+ apiRoute,
160
+ collectionSlug: 'media',
161
+ file: createFile(),
162
+ serverHandlerPath,
163
+ serverURL,
164
+ updateFilename: vi.fn()
165
+ })).rejects.toThrow();
166
+ expect(uploadDataMock).not.toHaveBeenCalled();
167
+ });
168
+ it('should propagate errors from uploadData', async ()=>{
169
+ mockSignedURLResponse({
170
+ docPrefix: 'docs',
171
+ url: signedURL
172
+ });
173
+ uploadDataMock.mockRejectedValue(new Error('block upload failed'));
174
+ await expect(handleAzureUpload({
175
+ apiRoute,
176
+ collectionSlug: 'media',
177
+ file: createFile(),
178
+ serverHandlerPath,
179
+ serverURL,
180
+ updateFilename: vi.fn()
181
+ })).rejects.toThrow('block upload failed');
182
+ });
183
+ });
184
+
185
+ //# sourceMappingURL=handleAzureUpload.spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/client/handleAzureUpload.spec.ts"],"sourcesContent":["import { beforeEach, describe, expect, it, vi } from 'vitest'\n\nconst uploadDataMock = vi.fn()\nconst blockBlobClientMock = vi.fn(function () {\n return { uploadData: uploadDataMock }\n})\n\nvi.mock('@azure/storage-blob', () => ({\n BlockBlobClient: blockBlobClientMock,\n}))\n\nimport { handleAzureUpload } from './handleAzureUpload.js'\n\nconst serverURL = 'https://example.com'\nconst apiRoute = '/api'\nconst serverHandlerPath = '/storage-azure-generate-signed-url' as const\nconst signedURL = 'https://account.blob.core.windows.net/container/file.png?sig=abc'\n\nconst createFile = () => new File([new Uint8Array([1, 2, 3])], 'file.png', { type: 'image/png' })\n\nconst mockSignedURLResponse = (body: Record<string, unknown>, ok = true) => {\n const fetchMock = vi.fn().mockResolvedValue({\n json: () => Promise.resolve(body),\n ok,\n })\n vi.stubGlobal('fetch', fetchMock)\n return fetchMock\n}\n\ndescribe('handleAzureUpload', () => {\n beforeEach(() => {\n vi.clearAllMocks()\n vi.unstubAllGlobals()\n uploadDataMock.mockResolvedValue(undefined)\n })\n\n it('should request a signed URL from the server handler', async () => {\n const fetchMock = mockSignedURLResponse({ docPrefix: 'docs', url: signedURL })\n\n await handleAzureUpload({\n apiRoute,\n collectionSlug: 'media',\n docPrefix: 'docs',\n file: createFile(),\n serverHandlerPath,\n serverURL,\n updateFilename: vi.fn(),\n })\n\n expect(fetchMock).toHaveBeenCalledTimes(1)\n const [calledURL, init] = fetchMock.mock.calls[0]!\n\n expect(calledURL).toBe(`${serverURL}${apiRoute}${serverHandlerPath}`)\n expect(init.method).toBe('POST')\n expect(JSON.parse(init.body)).toEqual({\n collectionSlug: 'media',\n docPrefix: 'docs',\n filename: 'file.png',\n mimeType: 'image/png',\n })\n })\n\n it('should upload via BlockBlobClient.uploadData rather than a raw PUT', async () => {\n const fetchMock = mockSignedURLResponse({ docPrefix: 'docs', url: signedURL })\n const file = createFile()\n\n await handleAzureUpload({\n apiRoute,\n collectionSlug: 'media',\n file,\n serverHandlerPath,\n serverURL,\n updateFilename: vi.fn(),\n })\n\n expect(blockBlobClientMock).toHaveBeenCalledWith(signedURL)\n expect(uploadDataMock).toHaveBeenCalledTimes(1)\n\n const [uploadedFile, options] = uploadDataMock.mock.calls[0]!\n expect(uploadedFile).toBe(file)\n expect(options.blockSize).toBeGreaterThan(0)\n expect(options.concurrency).toBeGreaterThan(0)\n\n // Only the signed-URL request should hit fetch; no raw PUT to the blob URL.\n expect(fetchMock).toHaveBeenCalledTimes(1)\n })\n\n it('should pass the file content type to the blob headers', async () => {\n mockSignedURLResponse({ docPrefix: 'docs', url: signedURL })\n\n await handleAzureUpload({\n apiRoute,\n collectionSlug: 'media',\n file: createFile(),\n serverHandlerPath,\n serverURL,\n updateFilename: vi.fn(),\n })\n\n const [, options] = uploadDataMock.mock.calls[0]!\n expect(options.blobHTTPHeaders).toEqual({ blobContentType: 'image/png' })\n })\n\n it('should call updateFilename when the server returns a sanitized filename', async () => {\n mockSignedURLResponse({ docPrefix: 'docs', filename: 'file-1.png', url: signedURL })\n const updateFilename = vi.fn()\n\n await handleAzureUpload({\n apiRoute,\n collectionSlug: 'media',\n file: createFile(),\n serverHandlerPath,\n serverURL,\n updateFilename,\n })\n\n expect(updateFilename).toHaveBeenCalledWith('file-1.png')\n })\n\n it('should not call updateFilename when the filename is unchanged', async () => {\n mockSignedURLResponse({ docPrefix: 'docs', filename: 'file.png', url: signedURL })\n const updateFilename = vi.fn()\n\n await handleAzureUpload({\n apiRoute,\n collectionSlug: 'media',\n file: createFile(),\n serverHandlerPath,\n serverURL,\n updateFilename,\n })\n\n expect(updateFilename).not.toHaveBeenCalled()\n })\n\n it('should return the sanitized doc prefix', async () => {\n mockSignedURLResponse({ docPrefix: 'sanitized-docs', url: signedURL })\n\n const result = await handleAzureUpload({\n apiRoute,\n collectionSlug: 'media',\n file: createFile(),\n serverHandlerPath,\n serverURL,\n updateFilename: vi.fn(),\n })\n\n expect(result).toEqual({ prefix: 'sanitized-docs' })\n })\n\n it('should throw when the signed URL request fails', async () => {\n mockSignedURLResponse({}, false)\n\n await expect(\n handleAzureUpload({\n apiRoute,\n collectionSlug: 'media',\n file: createFile(),\n serverHandlerPath,\n serverURL,\n updateFilename: vi.fn(),\n }),\n ).rejects.toThrow()\n\n expect(uploadDataMock).not.toHaveBeenCalled()\n })\n\n it('should propagate errors from uploadData', async () => {\n mockSignedURLResponse({ docPrefix: 'docs', url: signedURL })\n uploadDataMock.mockRejectedValue(new Error('block upload failed'))\n\n await expect(\n handleAzureUpload({\n apiRoute,\n collectionSlug: 'media',\n file: createFile(),\n serverHandlerPath,\n serverURL,\n updateFilename: vi.fn(),\n }),\n ).rejects.toThrow('block upload failed')\n })\n})\n"],"names":["beforeEach","describe","expect","it","vi","uploadDataMock","fn","blockBlobClientMock","uploadData","mock","BlockBlobClient","handleAzureUpload","serverURL","apiRoute","serverHandlerPath","signedURL","createFile","File","Uint8Array","type","mockSignedURLResponse","body","ok","fetchMock","mockResolvedValue","json","Promise","resolve","stubGlobal","clearAllMocks","unstubAllGlobals","undefined","docPrefix","url","collectionSlug","file","updateFilename","toHaveBeenCalledTimes","calledURL","init","calls","toBe","method","JSON","parse","toEqual","filename","mimeType","toHaveBeenCalledWith","uploadedFile","options","blockSize","toBeGreaterThan","concurrency","blobHTTPHeaders","blobContentType","not","toHaveBeenCalled","result","prefix","rejects","toThrow","mockRejectedValue","Error"],"mappings":"AAAA,SAASA,UAAU,EAAEC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,EAAEC,EAAE,QAAQ,SAAQ;AAE7D,MAAMC,iBAAiBD,GAAGE,EAAE;AAC5B,MAAMC,sBAAsBH,GAAGE,EAAE,CAAC;IAChC,OAAO;QAAEE,YAAYH;IAAe;AACtC;AAEAD,GAAGK,IAAI,CAAC,uBAAuB,IAAO,CAAA;QACpCC,iBAAiBH;IACnB,CAAA;AAEA,SAASI,iBAAiB,QAAQ,yBAAwB;AAE1D,MAAMC,YAAY;AAClB,MAAMC,WAAW;AACjB,MAAMC,oBAAoB;AAC1B,MAAMC,YAAY;AAElB,MAAMC,aAAa,IAAM,IAAIC,KAAK;QAAC,IAAIC,WAAW;YAAC;YAAG;YAAG;SAAE;KAAE,EAAE,YAAY;QAAEC,MAAM;IAAY;AAE/F,MAAMC,wBAAwB,CAACC,MAA+BC,KAAK,IAAI;IACrE,MAAMC,YAAYnB,GAAGE,EAAE,GAAGkB,iBAAiB,CAAC;QAC1CC,MAAM,IAAMC,QAAQC,OAAO,CAACN;QAC5BC;IACF;IACAlB,GAAGwB,UAAU,CAAC,SAASL;IACvB,OAAOA;AACT;AAEAtB,SAAS,qBAAqB;IAC5BD,WAAW;QACTI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AAgB;YAChBC,MAAMnB;YACNF;YACAF;YACAwB,gBAAgBhC,GAAGE,EAAE;QACvB,IACAsD,OAAO,CAACC,OAAO;QAEjB3D,OAAOG,gBAAgBmD,GAAG,CAACC,gBAAgB;IAC7C;IAEAtD,GAAG,2CAA2C;QAC5CiB,sBAAsB;YAAEY,WAAW;YAAQC,KAAKlB;QAAU;QAC1DV,eAAeyD,iBAAiB,CAAC,IAAIC,MAAM;QAE3C,MAAM7D,OACJS,kBAAkB;YAChBE;YACAqB,gBAAgB;YAChBC,MAAMnB;YACNF;YACAF;YACAwB,gBAAgBhC,GAAGE,EAAE;QACvB,IACAsD,OAAO,CAACC,OAAO,CAAC;IACpB;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"generateSignedURL.d.ts","sourceRoot":"","sources":["../src/generateSignedURL.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAA8B,MAAM,qBAAqB,CAAA;AACtF,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,wCAAwC,CAAA;AACjF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAM7C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAA;AAErD,UAAU,IAAI;IACZ,MAAM,CAAC,EAAE,mBAAmB,CAAA;IAC5B,WAAW,EAAE,mBAAmB,CAAC,aAAa,CAAC,CAAA;IAC/C,aAAa,EAAE,MAAM,CAAA;IACrB,gBAAgB,EAAE,MAAM,eAAe,CAAA;IACvC,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B;AAID,eAAO,MAAM,2BAA2B,GAAI,iFAMzC,IAAI,KAAG,cAsDT,CAAA"}
1
+ {"version":3,"file":"generateSignedURL.d.ts","sourceRoot":"","sources":["../src/generateSignedURL.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAA8B,MAAM,qBAAqB,CAAA;AACtF,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,wCAAwC,CAAA;AACjF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAM7C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAA;AAErD,UAAU,IAAI;IACZ,MAAM,CAAC,EAAE,mBAAmB,CAAA;IAC5B,WAAW,EAAE,mBAAmB,CAAC,aAAa,CAAC,CAAA;IAC/C,aAAa,EAAE,MAAM,CAAA;IACrB,gBAAgB,EAAE,MAAM,eAAe,CAAA;IACvC,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B;AAID,eAAO,MAAM,2BAA2B,oFAMrC,IAAI,KAAG,cAsDT,CAAA"}
@@ -32,7 +32,7 @@ export const getGenerateSignedURLHandler = ({ access = defaultAccess, collection
32
32
  blobName: fileKey,
33
33
  containerName,
34
34
  contentType: mimeType,
35
- expiresOn: new Date(Date.now() + 30 * 60 * 1000),
35
+ expiresOn: new Date(Date.now() + 3 * 60 * 60 * 1000),
36
36
  permissions: BlobSASPermissions.parse('w'),
37
37
  startsOn: new Date()
38
38
  }, getStorageClient().credential);
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/generateSignedURL.ts"],"sourcesContent":["import type { ContainerClient, StorageSharedKeyCredential } from '@azure/storage-blob'\nimport type { ClientUploadsAccess } from '@payloadcms/plugin-cloud-storage/types'\nimport type { PayloadHandler } from 'payload'\n\nimport { BlobSASPermissions, generateBlobSASQueryParameters } from '@azure/storage-blob'\nimport { resolveSignedURLKey } from '@payloadcms/plugin-cloud-storage/utilities'\nimport { APIError, Forbidden } from 'payload'\n\nimport type { AzureStorageOptions } from './index.js'\n\ninterface Args {\n access?: ClientUploadsAccess\n collections: AzureStorageOptions['collections']\n containerName: string\n getStorageClient: () => ContainerClient\n useCompositePrefixes?: boolean\n}\n\nconst defaultAccess: Args['access'] = ({ req }) => !!req.user\n\nexport const getGenerateSignedURLHandler = ({\n access = defaultAccess,\n collections,\n containerName,\n getStorageClient,\n useCompositePrefixes = false,\n}: Args): PayloadHandler => {\n return async (req) => {\n if (!req.json) {\n throw new APIError('Unreachable')\n }\n\n const { collectionSlug, docPrefix, filename, mimeType } = (await req.json()) as {\n collectionSlug: string\n docPrefix?: string\n filename: string\n mimeType: string\n }\n\n const collectionStorageConfig = collections[collectionSlug]\n if (!collectionStorageConfig) {\n throw new APIError(`Collection ${collectionSlug} was not found in Azure storage options`)\n }\n\n const collectionPrefix =\n (typeof collectionStorageConfig === 'object' && collectionStorageConfig.prefix) || ''\n\n if (!(await access({ collectionSlug, req }))) {\n throw new Forbidden()\n }\n\n const { fileKey, sanitizedDocPrefix, sanitizedFilename } = await resolveSignedURLKey({\n collectionPrefix,\n collectionSlug,\n docPrefix,\n filename,\n req,\n useCompositePrefixes,\n })\n\n const blobClient = getStorageClient().getBlobClient(fileKey)\n\n const sasToken = generateBlobSASQueryParameters(\n {\n blobName: fileKey,\n containerName,\n contentType: mimeType,\n expiresOn: new Date(Date.now() + 30 * 60 * 1000),\n permissions: BlobSASPermissions.parse('w'),\n startsOn: new Date(),\n },\n getStorageClient().credential as StorageSharedKeyCredential,\n )\n\n return Response.json({\n docPrefix: sanitizedDocPrefix,\n filename: sanitizedFilename,\n url: `${blobClient.url}?${sasToken.toString()}`,\n })\n }\n}\n"],"names":["BlobSASPermissions","generateBlobSASQueryParameters","resolveSignedURLKey","APIError","Forbidden","defaultAccess","req","user","getGenerateSignedURLHandler","access","collections","containerName","getStorageClient","useCompositePrefixes","json","collectionSlug","docPrefix","filename","mimeType","collectionStorageConfig","collectionPrefix","prefix","fileKey","sanitizedDocPrefix","sanitizedFilename","blobClient","getBlobClient","sasToken","blobName","contentType","expiresOn","Date","now","permissions","parse","startsOn","credential","Response","url","toString"],"mappings":"AAIA,SAASA,kBAAkB,EAAEC,8BAA8B,QAAQ,sBAAqB;AACxF,SAASC,mBAAmB,QAAQ,6CAA4C;AAChF,SAASC,QAAQ,EAAEC,SAAS,QAAQ,UAAS;AAY7C,MAAMC,gBAAgC,CAAC,EAAEC,GAAG,E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esContent":["import type { ContainerClient, StorageSharedKeyCredential } from '@azure/storage-blob'\nimport type { ClientUploadsAccess } from '@payloadcms/plugin-cloud-storage/types'\nimport type { PayloadHandler } from 'payload'\n\nimport { BlobSASPermissions, generateBlobSASQueryParameters } from '@azure/storage-blob'\nimport { resolveSignedURLKey } from '@payloadcms/plugin-cloud-storage/utilities'\nimport { APIError, Forbidden } from 'payload'\n\nimport type { AzureStorageOptions } from './index.js'\n\ninterface Args {\n access?: ClientUploadsAccess\n collections: AzureStorageOptions['collections']\n containerName: string\n getStorageClient: () => ContainerClient\n useCompositePrefixes?: boolean\n}\n\nconst defaultAccess: Args['access'] = ({ req }) => !!req.user\n\nexport const getGenerateSignedURLHandler = ({\n access = defaultAccess,\n collections,\n containerName,\n getStorageClient,\n useCompositePrefixes = false,\n}: Args): PayloadHandler => {\n return async (req) => {\n if (!req.json) {\n throw new APIError('Unreachable')\n }\n\n const { collectionSlug, docPrefix, filename, mimeType } = (await req.json()) as {\n collectionSlug: string\n docPrefix?: string\n filename: string\n mimeType: string\n }\n\n const collectionStorageConfig = collections[collectionSlug]\n if (!collectionStorageConfig) {\n throw new APIError(`Collection ${collectionSlug} was not found in Azure storage options`)\n }\n\n const collectionPrefix =\n (typeof collectionStorageConfig === 'object' && collectionStorageConfig.prefix) || ''\n\n if (!(await access({ collectionSlug, req }))) {\n throw new Forbidden()\n }\n\n const { fileKey, sanitizedDocPrefix, sanitizedFilename } = await resolveSignedURLKey({\n collectionPrefix,\n collectionSlug,\n docPrefix,\n filename,\n req,\n useCompositePrefixes,\n })\n\n const blobClient = getStorageClient().getBlobClient(fileKey)\n\n const sasToken = generateBlobSASQueryParameters(\n {\n blobName: fileKey,\n containerName,\n contentType: mimeType,\n expiresOn: new Date(Date.now() + 3 * 60 * 60 * 1000),\n permissions: BlobSASPermissions.parse('w'),\n startsOn: new Date(),\n },\n getStorageClient().credential as StorageSharedKeyCredential,\n )\n\n return Response.json({\n docPrefix: sanitizedDocPrefix,\n filename: sanitizedFilename,\n url: `${blobClient.url}?${sasToken.toString()}`,\n })\n }\n}\n"],"names":["BlobSASPermissions","generateBlobSASQueryParameters","resolveSignedURLKey","APIError","Forbidden","defaultAccess","req","user","getGenerateSignedURLHandler","access","collections","containerName","getStorageClient","useCompositePrefixes","json","collectionSlug","docPrefix","filename","mimeType","collectionStorageConfig","collectionPrefix","prefix","fileKey","sanitizedDocPrefix","sanitizedFilename","blobClient","getBlobClient","sasToken","blobName","contentType","expiresOn","Date","now","permissions","parse","startsOn","credential","Response","url","toString"],"mappings":"AAIA,SAASA,kBAAkB,EAAEC,8BAA8B,QAAQ,sBAAqB;AACxF,SAASC,mBAAmB,QAAQ,6CAA4C;AAChF,SAASC,QAAQ,EAAEC,SAAS,QAAQ,UAAS;AAY7C,MAAMC,gBAAgC,CAAC,EAAEC,GAAG,EAAE,GAAK,CAAC,CAACA,IAAIC,IAAI;AAE7D,OAAO,MAAMC,8BAA8B,CAAC,EAC1CC,SAASJ,aAAa,EACtBK,WAAW,EACXC,aAAa,EACbC,gBAAgB,EAChBC,uBAAuB,KAAK,EACvB;IACL,OAAO,OAAOP;QACZ,IAAI,CAACA,IAAIQ,IAAI,EAAE;YACb,MAAM,IAAIX,SAAS;QACrB;QAEA,MAAM,EAAEY,cAAc,EAAEC,SAAS,EAAEC,QAAQ,EAAEC,QAAQ,EAAE,GAAI,MAAMZ,IAAIQ,IAAI;QAOzE,MAAMK,0BAA0BT,WAAW,CAACK,eAAe;QAC3D,IAAI,CAACI,yBAAyB;YAC5B,MAAM,IAAIhB,SAAS,CAAC,WAAW,EAAEY,eAAe,uCAAuC,CAAC;QAC1F;QAEA,MAAMK,mBACJ,AAAC,OAAOD,4BAA4B,YAAYA,wBAAwBE,MAAM,IAAK;QAErF,IAAI,CAAE,MAAMZ,OAAO;YAAEM;YAAgBT;QAAI,IAAK;YAC5C,MAAM,IAAIF;QACZ;QAEA,MAAM,EAAEkB,OAAO,EAAEC,kBAAkB,EAAEC,iBAAiB,EAAE,GAAG,MAAMtB,oBAAoB;YACnFkB;YACAL;YACAC;YACAC;YACAX;YACAO;QACF;QAEA,MAAMY,aAAab,mBAAmBc,aAAa,CAACJ;QAEpD,MAAMK,WAAW1B,+BACf;YACE2B,UAAUN;YACVX;YACAkB,aAAaX;YACbY,WAAW,IAAIC,KAAKA,KAAKC,GAAG,KAAK,IAAI,KAAK,KAAK;YAC/CC,aAAajC,mBAAmBkC,KAAK,CAAC;YACtCC,UAAU,IAAIJ;QAChB,GACAnB,mBAAmBwB,UAAU;QAG/B,OAAOC,SAASvB,IAAI,CAAC;YACnBE,WAAWO;YACXN,UAAUO;YACVc,KAAK,GAAGb,WAAWa,GAAG,CAAC,CAAC,EAAEX,SAASY,QAAQ,IAAI;QACjD;IACF;AACF,EAAC"}
package/dist/index.d.ts CHANGED
@@ -30,7 +30,13 @@ export type AzureStorageOptions = {
30
30
  */
31
31
  clientCacheKey?: string;
32
32
  /**
33
- * Do uploads directly on the client to bypass limits on Vercel. You must allow CORS PUT method to your website.
33
+ * Do uploads directly on the client to bypass limits on Vercel.
34
+ *
35
+ * Client uploads use the Azure Blob SDK, which splits large files into blocks
36
+ * (avoiding the ~5GB limit of a single upload request). The SDK sends `x-ms-*`
37
+ * headers, so the browser issues a CORS preflight: your storage account's CORS
38
+ * rules must allow the `OPTIONS` and `PUT` methods and the required headers
39
+ * (allowed headers `*`, or at minimum `x-ms-*,content-type,content-length`).
34
40
  */
35
41
  clientUploads?: ClientUploadsConfig;
36
42
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EAEnB,iBAAiB,EAClB,MAAM,wCAAwC,CAAA;AAC/C,OAAO,KAAK,EAAU,cAAc,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAO3E,OAAO,EAAE,gBAAgB,IAAI,oBAAoB,EAAE,MAAM,6BAA6B,CAAA;AAEtF,MAAM,MAAM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AAO,EAAE,MAAM,CAAA;IAEf;;;;;OAKG;IACH,cAAc,CAAC,EAAE,MAAM,CAAA;IAEvB;;;;;;;;OAQG;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;;OAEG;IACH,gBAAgB,EAAE,MAAM,CAAA;IAExB;;OAEG;IACH,aAAa,EAAE,MAAM,CAAA;IAErB;;;;OAIG;IACH,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB;;;;;;;;;;;;OAYG;IACH,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B,CAAA;AAED,KAAK,mBAAmB,GAAG,CAAC,gBAAgB,EAAE,mBAAmB,KAAK,cAAc,CAAA;AAEpF,eAAO,MAAM,YAAY,EAAE,mBA6FzB,CAAA;AAEF,OAAO,EAAE,oBAAoB,IAAI,gBAAgB,EAAE,CAAA"}
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n ClientUploadsConfig,\n PluginOptions as CloudStoragePluginOptions,\n CollectionOptions,\n} from '@payloadcms/plugin-cloud-storage/types'\nimport type { Config, StorageAdapter, UploadCollectionSlug } from 'payload'\n\nimport { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage'\nimport { initClientUploads } from '@payloadcms/plugin-cloud-storage/utilities'\n\nimport { createAzureAdapter } from './adapter.js'\nimport { getGenerateSignedURLHandler } from './generateSignedURL.js'\nimport { getStorageClient as getStorageClientFunc } from './utils/getStorageClient.js'\n\nexport type AzureStorageOptions = {\n /**\n * Whether or not to allow the container to be created if it does not exist\n *\n * @default false\n */\n allowContainerCreate: 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 * Base URL for the Azure Blob storage account\n */\n baseURL: string\n\n /**\n * Optional cache key to identify the Azure Blob storage client instance.\n * If not provided, a default key will be used.\n *\n * @default `azure:containerName`\n */\n clientCacheKey?: string\n\n /**\n * Do uploads directly on the client to bypass limits on Vercel. You must allow CORS PUT method to your website.\n */\n clientUploads?: ClientUploadsConfig\n\n /**\n * Collection options to apply the Azure Blob adapter to.\n */\n collections: Partial<Record<UploadCollectionSlug, Omit<CollectionOptions, 'adapter'> | true>>\n\n /**\n * Azure Blob storage connection string\n */\n connectionString: string\n\n /**\n * Azure Blob storage container name\n */\n containerName: string\n\n /**\n * Whether or not to enable the plugin\n *\n * Default: true\n */\n enabled?: boolean\n /**\n * When true, the collection-level prefix and document-level prefix are combined\n * (compositional). When false (default), document prefix overrides collection\n * prefix entirely.\n *\n * Example:\n * - collection prefix: `collection-prefix/`\n * - document prefix: `document-prefix/`\n * - resulting prefix with useCompositePrefixes=true: `collection-prefix/document-prefix/`\n * - resulting prefix with useCompositePrefixes=false: `document-prefix/`\n *\n * @default false\n */\n useCompositePrefixes?: boolean\n}\n\ntype AzureStorageFactory = (azureStorageArgs: AzureStorageOptions) => StorageAdapter\n\nexport const azureStorage: AzureStorageFactory = (\n azureStorageOptions: AzureStorageOptions,\n): StorageAdapter => ({\n name: 'azure',\n collections: Object.keys(azureStorageOptions.collections),\n init: (incomingConfig: Config): Config => {\n const getStorageClient = () =>\n getStorageClientFunc({\n connectionString: azureStorageOptions.connectionString,\n containerName: azureStorageOptions.containerName,\n })\n\n const isPluginDisabled = azureStorageOptions.enabled === false\n\n initClientUploads({\n clientHandler: '@payloadcms/storage-azure/client#AzureClientUploadHandler',\n collections: azureStorageOptions.collections,\n config: incomingConfig,\n enabled: !isPluginDisabled && Boolean(azureStorageOptions.clientUploads),\n serverHandler: getGenerateSignedURLHandler({\n access:\n typeof azureStorageOptions.clientUploads === 'object'\n ? azureStorageOptions.clientUploads.access\n : undefined,\n collections: azureStorageOptions.collections,\n containerName: azureStorageOptions.containerName,\n getStorageClient,\n useCompositePrefixes: azureStorageOptions.useCompositePrefixes,\n }),\n serverHandlerPath: '/storage-azure-generate-signed-url',\n })\n\n if (isPluginDisabled) {\n return incomingConfig\n }\n\n const createContainerIfNotExists = () => {\n void getStorageClientFunc({\n connectionString: azureStorageOptions.connectionString,\n containerName: azureStorageOptions.containerName,\n }).createIfNotExists({\n access: 'blob',\n })\n }\n\n const adapter = createAzureAdapter({\n allowContainerCreate: azureStorageOptions.allowContainerCreate,\n baseURL: azureStorageOptions.baseURL,\n clientUploads: azureStorageOptions.clientUploads,\n containerName: azureStorageOptions.containerName,\n createContainerIfNotExists,\n getStorageClient,\n useCompositePrefixes: azureStorageOptions.useCompositePrefixes,\n })\n\n // Add adapter to each collection option object\n const collectionsWithAdapter: CloudStoragePluginOptions['collections'] = Object.entries(\n azureStorageOptions.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: azureStorageOptions.alwaysInsertFields,\n collections: collectionsWithAdapter,\n useCompositePrefixes: azureStorageOptions.useCompositePrefixes,\n })(config)\n },\n})\n\nexport { getStorageClientFunc as getStorageClient }\n"],"names":["cloudStoragePlugin","initClientUploads","createAzureAdapter","getGenerateSignedURLHandler","getStorageClient","getStorageClientFunc","azureStorage","azureStorageOptions","name","collections","Object","keys","init","incomingConfig","connectionString","containerName","isPluginDisabled","enabled","clientHandler","config","Boolean","clientUploads","serverHandler","access","undefined","useCompositePrefixes","serverHandlerPath","createContainerIfNotExists","createIfNotExists","adapter","allowContainerCreate","baseURL","collectionsWithAdapter","entries","reduce","acc","slug","collOptions","map","collection","upload","disableLocalStorage","alwaysInsertFields"],"mappings":"AAOA,SAASA,kBAAkB,QAAQ,mCAAkC;AACrE,SAASC,iBAAiB,QAAQ,6CAA4C;AAE9E,SAASC,kBAAkB,QAAQ,eAAc;AACjD,SAASC,2BAA2B,QAAQ,yBAAwB;AACpE,SAASC,oBAAoBC,oBAAoB,QAAQ,8BAA6B;AA8EtF,OAAO,MAAMC,eAAoC,CAC/CC,sBACoB,CAAA;QACpBC,MAAM;QACNC,aAAaC,OAAOC,IAAI,CAACJ,oBAAoBE,WAAW;QACxDG,MAAM,CAACC;YACL,MAAMT,mBAAmB,IACvBC,qBAAqB;oBACnBS,kBAAkBP,oBAAoBO,gBAAgB;oBACtDC,eAAeR,oBAAoBQ,aAAa;gBAClD;YAEF,MAAMC,mBAAmBT,oBAAoBU,OAAO,KAAK;YAEzDhB,kBAAkB;gBAChBiB,eAAe;gBACfT,aAAaF,oBAAoBE,WAAW;gBAC5CU,QAAQN;gBACRI,SAAS,CAACD,oBAAoBI,QAAQb,oBAAoBc,aAAa;gBACvEC,eAAenB,4BAA4B;oBACzCoB,QACE,OAAOhB,oBAAoBc,aAAa,KAAK,WACzCd,oBAAoBc,aAAa,CAACE,MAAM,GACxCC;oBACNf,aAAaF,oBAAoBE,WAAW;oBAC5CM,eAAeR,oBAAoBQ,aAAa;oBAChDX;oBACAqB,sBAAsBlB,oBAAoBkB,oBAAoB;gBAChE;gBACAC,mBAAmB;YACrB;YAEA,IAAIV,kBAAkB;gBACpB,OAAOH;YACT;YAEA,MAAMc,6BAA6B;gBACjC,KAAKtB,qBAAqB;oBACxBS,kBAAkBP,oBAAoBO,gBAAgB;oBACtDC,eAAeR,oBAAoBQ,aAAa;gBAClD,GAAGa,iBAAiB,CAAC;oBACnBL,QAAQ;gBACV;YACF;YAEA,MAAMM,UAAU3B,mBAAmB;gBACjC4B,sBAAsBvB,oBAAoBuB,oBAAoB;gBAC9DC,SAASxB,oBAAoBwB,OAAO;gBACpCV,eAAed,oBAAoBc,aAAa;gBAChDN,eAAeR,oBAAoBQ,aAAa;gBAChDY;gBACAvB;gBACAqB,sBAAsBlB,oBAAoBkB,oBAAoB;YAChE;YAEA,+CAA+C;YAC/C,MAAMO,yBAAmEtB,OAAOuB,OAAO,CACrF1B,oBAAoBE,WAAW,EAC/ByB,MAAM,CACN,CAACC,KAAK,CAACC,MAAMC,YAAY,GAAM,CAAA;oBAC7B,GAAGF,GAAG;oBACN,CAACC,KAAK,EAAE;wBACN,GAAIC,gBAAgB,OAAO,CAAC,IAAIA,WAAW;wBAC3CR;oBACF;gBACF,CAAA,GACA,CAAC;YAGH,gFAAgF;YAChF,MAAMV,SAAS;gBACb,GAAGN,cAAc;gBACjBJ,aAAa,AAACI,CAAAA,eAAeJ,WAAW,IAAI,EAAE,AAAD,EAAG6B,GAAG,CAAC,CAACC;oBACnD,IAAI,CAACP,sBAAsB,CAACO,WAAWH,IAAI,CAAC,EAAE;wBAC5C,OAAOG;oBACT;oBAEA,OAAO;wBACL,GAAGA,UAAU;wBACbC,QAAQ;4BACN,GAAI,OAAOD,WAAWC,MAAM,KAAK,WAAWD,WAAWC,MAAM,GAAG,CAAC,CAAC;4BAClEC,qBAAqB;wBACvB;oBACF;gBACF;YACF;YAEA,OAAOzC,mBAAmB;gBACxB0C,oBAAoBnC,oBAAoBmC,kBAAkB;gBAC1DjC,aAAauB;gBACbP,sBAAsBlB,oBAAoBkB,oBAAoB;YAChE,GAAGN;QACL;IACF,CAAA,EAAE;AAEF,SAASd,wBAAwBD,gBAAgB,GAAE"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n ClientUploadsConfig,\n PluginOptions as CloudStoragePluginOptions,\n CollectionOptions,\n} from '@payloadcms/plugin-cloud-storage/types'\nimport type { Config, StorageAdapter, UploadCollectionSlug } from 'payload'\n\nimport { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage'\nimport { initClientUploads } from '@payloadcms/plugin-cloud-storage/utilities'\n\nimport { createAzureAdapter } from './adapter.js'\nimport { getGenerateSignedURLHandler } from './generateSignedURL.js'\nimport { getStorageClient as getStorageClientFunc } from './utils/getStorageClient.js'\n\nexport type AzureStorageOptions = {\n /**\n * Whether or not to allow the container to be created if it does not exist\n *\n * @default false\n */\n allowContainerCreate: 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 * Base URL for the Azure Blob storage account\n */\n baseURL: string\n\n /**\n * Optional cache key to identify the Azure Blob storage client instance.\n * If not provided, a default key will be used.\n *\n * @default `azure:containerName`\n */\n clientCacheKey?: string\n\n /**\n * Do uploads directly on the client to bypass limits on Vercel.\n *\n * Client uploads use the Azure Blob SDK, which splits large files into blocks\n * (avoiding the ~5GB limit of a single upload request). The SDK sends `x-ms-*`\n * headers, so the browser issues a CORS preflight: your storage account's CORS\n * rules must allow the `OPTIONS` and `PUT` methods and the required headers\n * (allowed headers `*`, or at minimum `x-ms-*,content-type,content-length`).\n */\n clientUploads?: ClientUploadsConfig\n\n /**\n * Collection options to apply the Azure Blob adapter to.\n */\n collections: Partial<Record<UploadCollectionSlug, Omit<CollectionOptions, 'adapter'> | true>>\n\n /**\n * Azure Blob storage connection string\n */\n connectionString: string\n\n /**\n * Azure Blob storage container name\n */\n containerName: string\n\n /**\n * Whether or not to enable the plugin\n *\n * Default: true\n */\n enabled?: boolean\n /**\n * When true, the collection-level prefix and document-level prefix are combined\n * (compositional). When false (default), document prefix overrides collection\n * prefix entirely.\n *\n * Example:\n * - collection prefix: `collection-prefix/`\n * - document prefix: `document-prefix/`\n * - resulting prefix with useCompositePrefixes=true: `collection-prefix/document-prefix/`\n * - resulting prefix with useCompositePrefixes=false: `document-prefix/`\n *\n * @default false\n */\n useCompositePrefixes?: boolean\n}\n\ntype AzureStorageFactory = (azureStorageArgs: AzureStorageOptions) => StorageAdapter\n\nexport const azureStorage: AzureStorageFactory = (\n azureStorageOptions: AzureStorageOptions,\n): StorageAdapter => ({\n name: 'azure',\n collections: Object.keys(azureStorageOptions.collections),\n init: (incomingConfig: Config): Config => {\n const getStorageClient = () =>\n getStorageClientFunc({\n connectionString: azureStorageOptions.connectionString,\n containerName: azureStorageOptions.containerName,\n })\n\n const isPluginDisabled = azureStorageOptions.enabled === false\n\n initClientUploads({\n clientHandler: '@payloadcms/storage-azure/client#AzureClientUploadHandler',\n collections: azureStorageOptions.collections,\n config: incomingConfig,\n enabled: !isPluginDisabled && Boolean(azureStorageOptions.clientUploads),\n serverHandler: getGenerateSignedURLHandler({\n access:\n typeof azureStorageOptions.clientUploads === 'object'\n ? azureStorageOptions.clientUploads.access\n : undefined,\n collections: azureStorageOptions.collections,\n containerName: azureStorageOptions.containerName,\n getStorageClient,\n useCompositePrefixes: azureStorageOptions.useCompositePrefixes,\n }),\n serverHandlerPath: '/storage-azure-generate-signed-url',\n })\n\n if (isPluginDisabled) {\n return incomingConfig\n }\n\n const createContainerIfNotExists = () => {\n void getStorageClientFunc({\n connectionString: azureStorageOptions.connectionString,\n containerName: azureStorageOptions.containerName,\n }).createIfNotExists({\n access: 'blob',\n })\n }\n\n const adapter = createAzureAdapter({\n allowContainerCreate: azureStorageOptions.allowContainerCreate,\n baseURL: azureStorageOptions.baseURL,\n clientUploads: azureStorageOptions.clientUploads,\n containerName: azureStorageOptions.containerName,\n createContainerIfNotExists,\n getStorageClient,\n useCompositePrefixes: azureStorageOptions.useCompositePrefixes,\n })\n\n // Add adapter to each collection option object\n const collectionsWithAdapter: CloudStoragePluginOptions['collections'] = Object.entries(\n azureStorageOptions.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: azureStorageOptions.alwaysInsertFields,\n collections: collectionsWithAdapter,\n useCompositePrefixes: azureStorageOptions.useCompositePrefixes,\n })(config)\n },\n})\n\nexport { getStorageClientFunc as getStorageClient }\n"],"names":["cloudStoragePlugin","initClientUploads","createAzureAdapter","getGenerateSignedURLHandler","getStorageClient","getStorageClientFunc","azureStorage","azureStorageOptions","name","collections","Object","keys","init","incomingConfig","connectionString","containerName","isPluginDisabled","enabled","clientHandler","config","Boolean","clientUploads","serverHandler","access","undefined","useCompositePrefixes","serverHandlerPath","createContainerIfNotExists","createIfNotExists","adapter","allowContainerCreate","baseURL","collectionsWithAdapter","entries","reduce","acc","slug","collOptions","map","collection","upload","disableLocalStorage","alwaysInsertFields"],"mappings":"AAOA,SAASA,kBAAkB,QAAQ,mCAAkC;AACrE,SAASC,iBAAiB,QAAQ,6CAA4C;AAE9E,SAASC,kBAAkB,QAAQ,eAAc;AACjD,SAASC,2BAA2B,QAAQ,yBAAwB;AACpE,SAASC,oBAAoBC,oBAAoB,QAAQ,8BAA6B;AAoFtF,OAAO,MAAMC,eAAoC,CAC/CC,sBACoB,CAAA;QACpBC,MAAM;QACNC,aAAaC,OAAOC,IAAI,CAACJ,oBAAoBE,WAAW;QACxDG,MAAM,CAACC;YACL,MAAMT,mBAAmB,IACvBC,qBAAqB;oBACnBS,kBAAkBP,oBAAoBO,gBAAgB;oBACtDC,eAAeR,oBAAoBQ,aAAa;gBAClD;YAEF,MAAMC,mBAAmBT,oBAAoBU,OA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CAAC,CAACC;oBACnD,IAAI,CAACP,sBAAsB,CAACO,WAAWH,IAAI,CAAC,EAAE;wBAC5C,OAAOG;oBACT;oBAEA,OAAO;wBACL,GAAGA,UAAU;wBACbC,QAAQ;4BACN,GAAI,OAAOD,WAAWC,MAAM,KAAK,WAAWD,WAAWC,MAAM,GAAG,CAAC,CAAC;4BAClEC,qBAAqB;wBACvB;oBACF;gBACF;YACF;YAEA,OAAOzC,mBAAmB;gBACxB0C,oBAAoBnC,oBAAoBmC,kBAAkB;gBAC1DjC,aAAauB;gBACbP,sBAAsBlB,oBAAoBkB,oBAAoB;YAChE,GAAGN;QACL;IACF,CAAA,EAAE;AAEF,SAASd,wBAAwBD,gBAAgB,GAAE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/storage-azure",
3
- "version": "4.0.0-internal.e387174",
3
+ "version": "4.0.0-internal.e55ccef",
4
4
  "description": "Payload storage adapter for Azure Blob Storage",
5
5
  "homepage": "https://payloadcms.com",
6
6
  "repository": {
@@ -39,13 +39,13 @@
39
39
  "dependencies": {
40
40
  "@azure/abort-controller": "^1.1.0",
41
41
  "@azure/storage-blob": "^12.11.0",
42
- "@payloadcms/plugin-cloud-storage": "4.0.0-internal.e387174"
42
+ "@payloadcms/plugin-cloud-storage": "4.0.0-internal.e55ccef"
43
43
  },
44
44
  "devDependencies": {
45
- "payload": "4.0.0-internal.e387174"
45
+ "payload": "4.0.0-internal.e55ccef"
46
46
  },
47
47
  "peerDependencies": {
48
- "payload": "4.0.0-internal.e387174"
48
+ "payload": "4.0.0-internal.e55ccef"
49
49
  },
50
50
  "engines": {
51
51
  "node": ">=24.15.0"