@humaan/payload-storage-imagekit 2.9.0 → 2.9.2

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
@@ -24,6 +24,24 @@ pnpm add @humaan/payload-storage-imagekit
24
24
  Payload `3.90.1` or newer is required. Use matching versions of `payload` and
25
25
  `@payloadcms/plugin-cloud-storage`.
26
26
 
27
+ ### Maintainer releases
28
+
29
+ In **Actions → Start release**, set `release_branch` to the branch to release from
30
+ (default: `main`). The version/changelog PR targets that branch. Stable `2.x`
31
+ releases continue from `main`; for Payload v4, select `feat/payload-v4-beta`,
32
+ `release_type: custom`, and `custom_version: 3.0.0-canary.0` (increment the canary
33
+ number for subsequent releases). The v4 feature PR does not need to merge.
34
+
35
+ Non-main releases must be prereleases. `canary` versions publish under the npm
36
+ `canary` tag without changing `latest`, after the release commit passes push CI.
37
+ For a publication dry run or receipt-based recovery, choose the same branch in
38
+ **Publish release (automatic)**. Recovery still requires the original receipt run
39
+ ID and the `publish` confirmation.
40
+
41
+ The shared `humaan/actions@v2` update must be deployed first, and these caller
42
+ workflow changes must be present on the selected branch. The `release` environment
43
+ must permit that branch under its deployment policy.
44
+
27
45
  ## Usage
28
46
 
29
47
  ```ts
@@ -57,7 +75,7 @@ export default buildConfig({
57
75
 
58
76
  `imagekitStorage(options)` options:
59
77
 
60
- - `collections` (required): `Partial<Record<UploadCollectionSlug, true | { focalPoint?: boolean; private?: boolean }>>`. Use `true` for a normal (public) collection, `{ focalPoint: true }` to enable Payload's native focal-point picker for that collection, or `{ private: true }` to deliver the collection's files as ImageKit [private files](#private-files).
78
+ - `collections` (required): `Partial<Record<UploadCollectionSlug, true | { fileSizeLimit?: number; focalPoint?: boolean; private?: boolean }>>`. Use `true` for a normal (public) collection, `{ focalPoint: true }` to enable Payload's native focal-point picker for that collection, `{ private: true }` to deliver the collection's files as ImageKit [private files](#private-files), or `{ fileSizeLimit }` to set a [per-collection upload size limit](#file-size-limits).
61
79
  - `folder` (required): root upload folder in ImageKit, e.g. `/payload-uploads`
62
80
  - `privateKey` (required): ImageKit private API key
63
81
  - `publicKey` (required): ImageKit public key
@@ -243,6 +261,39 @@ upload: {
243
261
  The adapter streams Payload temporary files to ImageKit for server-side uploads,
244
262
  rather than loading those files into a second buffer.
245
263
 
264
+ ## File size limits
265
+
266
+ Payload's `upload.limits.fileSize` applies to every upload collection, including
267
+ client uploads: the authorization endpoint rejects a larger file before ImageKit
268
+ receives it, and the signed `"file.size"` check binds ImageKit to the authorized size.
269
+
270
+ A collection's `fileSizeLimit` (bytes) applies on top of that limit, so it can only
271
+ tighten it. Set Payload's limit to the largest size any collection allows, then lower
272
+ it for the others:
273
+
274
+ ```ts
275
+ export default buildConfig({
276
+ upload: {
277
+ limits: {
278
+ fileSize: 25 * 1024 * 1024,
279
+ },
280
+ },
281
+ plugins: [
282
+ imagekitStorage({
283
+ clientUploads: true,
284
+ collections: {
285
+ images: { fileSizeLimit: 10 * 1024 * 1024 },
286
+ videos: true,
287
+ },
288
+ // ...
289
+ }),
290
+ ],
291
+ })
292
+ ```
293
+
294
+ Client uploads that exceed a collection's limit are rejected at authorization. Server
295
+ uploads are rejected before they are sent to ImageKit.
296
+
246
297
  ## Folder and account migration
247
298
 
248
299
  Use `migrateFolder` to copy referenced originals between folders or ImageKit accounts (e.g. staging to production). It updates the supplied Payload database in place and retains source assets.
@@ -318,6 +369,12 @@ paths are flattened into the destination collection folder; collisions are repor
318
369
  history and account-specific custom metadata schemas are not transferred. Run one migration per
319
370
  destination at a time; concurrent runs may report a conflict recoverable on a subsequent run.
320
371
 
372
+ On MongoDB, migration updates use the database adapter directly so the old `_objectKey` can be
373
+ removed in the same write as the new storage reference. Writing `null` would collide with the
374
+ legacy sparse unique index. These metadata updates bypass Payload validation and change hooks,
375
+ including cache revalidation; refresh application caches after the migration. Already uploaded
376
+ files from an interrupted 2.9.0 migration can be recovered by rerunning with this fix.
377
+
321
378
  Run a migration script:
322
379
 
323
380
  ```bash
@@ -2,6 +2,7 @@ import type { ClientUploadsAccess } from '@payloadcms/plugin-cloud-storage/types
2
2
  import type { PayloadHandler, UploadCollectionSlug } from 'payload';
3
3
  import type { createImageKitClientUploadVerifier } from '../clientUploadVerification.js';
4
4
  type ImageKitUploadCollection = {
5
+ fileSizeLimit?: number;
5
6
  isPrivate: boolean;
6
7
  prefix: string;
7
8
  };
@@ -5,9 +5,9 @@ import { APIError, Forbidden } from 'payload';
5
5
  import { assertClientUploadAccess, assertClientUploadAllowed, assertClientUploadFileSize, createClientUploadReceipt, getSafeFileName, verifyClientUploadReceipt } from 'payload/internal';
6
6
  import { getSanitizedUploadFilename, validateMimeType } from 'payload/shared';
7
7
  import { isImageKitReceiptContext } from '../clientUploads.js';
8
+ import { assertWithinFileSizeLimit } from '../fileSizeLimit.js';
8
9
  import { createImageKitUploadToken } from '../imageKitUploadToken.js';
9
10
  const defaultAccess = ({ req })=>Boolean(req.user);
10
- const bytesToMB = (bytes)=>(bytes / 1024 / 1024).toFixed(2);
11
11
  const getMimeTypeEssence = (mimeType)=>(mimeType.split(';', 1)[0] || '').trim().toLowerCase();
12
12
  const getImageKitSafeFilename = (filename)=>getSanitizedUploadFilename(filename).replace(/[^\w.-]/g, '_');
13
13
  // ImageKit can't match Payload's `+xml` suffix rule, so name the XML-family types it may detect.
@@ -148,10 +148,8 @@ export const createImageKitUploadAuthHandler = ({ access = defaultAccess, collec
148
148
  if (allowedMimeTypes.length > 0 && !validateMimeType(expectedMimeType, allowedMimeTypes)) {
149
149
  throw new APIError(`File type ${expectedMimeType} is not allowed.`, 400);
150
150
  }
151
- const filesizeLimit = req.payload.config.upload.limits?.fileSize;
152
- if (typeof filesizeLimit === 'number' && Number.isFinite(filesizeLimit) && requestedSize > filesizeLimit) {
153
- throw new APIError(`Exceeded file size limit. Limit: ${bytesToMB(filesizeLimit)}MB, got: ${bytesToMB(requestedSize)}MB`, 400);
154
- }
151
+ assertWithinFileSizeLimit(requestedSize, req.payload.config.upload.limits?.fileSize);
152
+ assertWithinFileSizeLimit(requestedSize, imageKitCollection.fileSizeLimit);
155
153
  const sanitizedFilename = await getSafeFileName({
156
154
  collectionSlug,
157
155
  desiredFilename: getImageKitSafeFilename(filename),
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/endpoints/createImageKitUploadAuthHandler.ts"],"sourcesContent":["import type { ClientUploadsAccess } from '@payloadcms/plugin-cloud-storage/types'\nimport type { PayloadHandler, UploadCollectionSlug } from 'payload'\n\nimport { buildUploadStoragePathData } from '@payloadcms/plugin-cloud-storage/utilities'\nimport { randomUUID } from 'node:crypto'\nimport { posix } from 'node:path'\nimport { APIError, Forbidden } from 'payload'\nimport {\n assertClientUploadAccess,\n assertClientUploadAllowed,\n assertClientUploadFileSize,\n createClientUploadReceipt,\n getSafeFileName,\n verifyClientUploadReceipt,\n} from 'payload/internal'\nimport { getSanitizedUploadFilename, validateMimeType } from 'payload/shared'\n\nimport type {\n ImageKitReceiptContext,\n ImageKitUploadAuthorization,\n ImageKitUploadCompletion,\n ImageKitUploadPayload,\n} from '../clientUploads.js'\nimport type { createImageKitClientUploadVerifier } from '../clientUploadVerification.js'\n\nimport { isImageKitReceiptContext } from '../clientUploads.js'\nimport { createImageKitUploadToken } from '../imageKitUploadToken.js'\n\ntype ImageKitUploadCollection = {\n isPrivate: boolean\n prefix: string\n}\n\ntype CreateImageKitUploadAuthHandlerArgs = {\n access?: ClientUploadsAccess\n collections: Partial<Record<UploadCollectionSlug, ImageKitUploadCollection>>\n privateKey: string\n publicKey: string\n verifyClientUpload: ReturnType<typeof createImageKitClientUploadVerifier>\n}\n\nconst defaultAccess: ClientUploadsAccess = ({ req }) => Boolean(req.user)\n\nconst bytesToMB = (bytes: number): string => (bytes / 1024 / 1024).toFixed(2)\n\nconst getMimeTypeEssence = (mimeType: string): string =>\n (mimeType.split(';', 1)[0] || '').trim().toLowerCase()\n\nconst getImageKitSafeFilename = (filename: string): string =>\n getSanitizedUploadFilename(filename).replace(/[^\\w.-]/g, '_')\n\n// ImageKit can't match Payload's `+xml` suffix rule, so name the XML-family types it may detect.\nconst XML_FAMILY_MIME_TYPES = [\n 'application/atom+xml',\n 'application/mathml+xml',\n 'application/rdf+xml',\n 'application/rss+xml',\n 'application/xhtml+xml',\n 'application/xml',\n 'application/xslt+xml',\n 'image/svg+xml',\n 'text/xml',\n]\n\n/**\n * ImageKit evaluates `file.mime` against its own content detection, which can differ from\n * the browser's extension-based type (e.g. `.xltm` is detected as `.xlsx`). Constrain the\n * detected type with the rules completion verification applies, not the browser's claim.\n */\nexport const getUploadChecks = ({\n allowedMimeTypes,\n allowRestrictedFileTypes,\n filesize,\n}: {\n allowedMimeTypes: string[]\n allowRestrictedFileTypes: boolean\n filesize: number\n}): string => {\n const checks = [`\"file.size\" = ${filesize}`]\n // Mirror Payload's validateMimeType, which drops the first `*` and matches by prefix.\n // Entries with quotes or backslashes can't prefix a valid MIME type, so omit them.\n const prefixes = allowedMimeTypes\n .map((mimeType) => mimeType.replace('*', ''))\n .filter((prefix) => !/[\"\\\\]/.test(prefix))\n\n if (allowedMimeTypes.length > 0 && !prefixes.includes('')) {\n checks.push(`(${prefixes.map((prefix) => `\"file.mime\" : \"${prefix}\"`).join(' OR ')})`)\n }\n\n if (!allowRestrictedFileTypes) {\n checks.push(`\"file.mime\" NOT IN [${XML_FAMILY_MIME_TYPES.map((type) => `\"${type}\"`).join(', ')}]`)\n }\n\n return checks.join(' AND ')\n}\n\n// Continue Payload's numeric suffix convention when the conflict exists only in ImageKit.\nconst nextFilename = (filename: string): string => {\n const { name, ext } = posix.parse(filename)\n const suffix = /^(.*)-(\\d+)$/.exec(name)\n return `${suffix ? `${suffix[1]}-${Number(suffix[2]) + 1}` : `${name}-1`}${ext}`\n}\n\nexport const createImageKitUploadAuthHandler = ({\n access = defaultAccess,\n collections,\n privateKey,\n publicKey,\n verifyClientUpload,\n}: CreateImageKitUploadAuthHandlerArgs): PayloadHandler => {\n return async (req) => {\n if (!req.json) {\n throw new APIError('Content-Type expected to be application/json', 400)\n }\n\n const body = (await req.json()) as {\n action?: unknown\n collectionSlug?: unknown\n fileId?: unknown\n filename?: unknown\n filesize?: unknown\n mimeType?: unknown\n signedReceipt?: unknown\n }\n const { action, collectionSlug, fileId, signedReceipt } = body\n let { filename, filesize, mimeType } = body\n\n if (typeof collectionSlug !== 'string' || !Object.hasOwn(collections, collectionSlug)) {\n throw new APIError('Invalid upload payload.', 400)\n }\n\n await assertClientUploadAccess({ collectionSlug, req })\n\n const imageKitCollection = collections[collectionSlug]\n if (!imageKitCollection) {\n throw new APIError(`Collection ${collectionSlug} was not found in ImageKit options.`, 400)\n }\n\n if (!(await access({ collectionSlug, req }))) {\n throw new Forbidden(req.t)\n }\n\n if (action === 'complete') {\n if (typeof fileId !== 'string' || !fileId.trim() || typeof signedReceipt !== 'string') {\n throw new APIError('Invalid ImageKit upload completion payload.', 400)\n }\n const receipt = verifyClientUploadReceipt({ collectionSlug, req, signedReceipt })\n if (\n !isImageKitReceiptContext(receipt.context) ||\n receipt.filename !== receipt.context.filename ||\n (receipt.context.fileId !== undefined && receipt.context.fileId !== fileId)\n ) {\n throw new APIError('Invalid ImageKit client upload context.', 400)\n }\n\n // The browser supplies a lookup ID, not proof. Check provider state against the\n // original signed authorization before including that ID in a new signed receipt.\n const context: ImageKitReceiptContext = { ...receipt.context, fileId }\n await verifyClientUpload({ collectionSlug, context })\n delete context.uploadTag\n const response: ImageKitUploadCompletion = {\n clientUploadContext: {\n _objectKey: context._objectKey,\n prefix: context.prefix,\n signedReceipt: createClientUploadReceipt({\n collectionSlug,\n context,\n filename: context.filename,\n req,\n }),\n },\n }\n return Response.json(response, { headers: { 'Cache-Control': 'no-store' } })\n }\n\n if (action === 'retry') {\n if (typeof signedReceipt !== 'string') {\n throw new APIError('Invalid ImageKit upload retry payload.', 400)\n }\n const receipt = verifyClientUploadReceipt({ collectionSlug, req, signedReceipt })\n if (\n !isImageKitReceiptContext(receipt.context) ||\n receipt.filename !== receipt.context.filename ||\n receipt.context.fileId !== undefined\n ) {\n throw new APIError('Invalid ImageKit upload retry payload.', 400)\n }\n filename = nextFilename(receipt.context.filename)\n filesize = receipt.context.expectedSize\n mimeType = receipt.context.expectedMimeType\n }\n\n if (\n (action !== undefined && action !== 'retry') ||\n typeof filename !== 'string' ||\n typeof mimeType !== 'string'\n ) {\n throw new APIError('Invalid upload payload.', 400)\n }\n\n assertClientUploadAllowed({\n collection: req.payload.collections[collectionSlug]?.config,\n filename,\n mimeType,\n })\n assertClientUploadFileSize(filesize)\n\n const requestedSize = filesize as number\n const expectedMimeType = getMimeTypeEssence(mimeType)\n if (!expectedMimeType) {\n throw new APIError('A valid MIME type is required for ImageKit client uploads.', 400)\n }\n\n const collectionConfig = req.payload.collections[collectionSlug]?.config\n const allowedMimeTypes =\n collectionConfig &&\n typeof collectionConfig.upload === 'object' &&\n Array.isArray(collectionConfig.upload.mimeTypes)\n ? collectionConfig.upload.mimeTypes\n : []\n\n if (allowedMimeTypes.length > 0 && !validateMimeType(expectedMimeType, allowedMimeTypes)) {\n throw new APIError(`File type ${expectedMimeType} is not allowed.`, 400)\n }\n\n const filesizeLimit = req.payload.config.upload.limits?.fileSize\n\n if (\n typeof filesizeLimit === 'number' &&\n Number.isFinite(filesizeLimit) &&\n requestedSize > filesizeLimit\n ) {\n throw new APIError(\n `Exceeded file size limit. Limit: ${bytesToMB(filesizeLimit)}MB, got: ${bytesToMB(requestedSize)}MB`,\n 400,\n )\n }\n\n const sanitizedFilename = await getSafeFileName({\n collectionSlug,\n desiredFilename: getImageKitSafeFilename(filename),\n req,\n })\n const resolved = buildUploadStoragePathData({\n collectionPrefix: imageKitCollection.prefix,\n docPrefix: imageKitCollection.prefix,\n filename: sanitizedFilename,\n })\n const folder = `/${resolved.storageFilePath.slice(0, -(sanitizedFilename.length + 1))}`\n const uploadTag = `payload-upload-${randomUUID()}`\n const uploadPayload: ImageKitUploadPayload = {\n checks: getUploadChecks({\n allowedMimeTypes,\n allowRestrictedFileTypes:\n typeof collectionConfig?.upload === 'object' &&\n Boolean(collectionConfig.upload.allowRestrictedFileTypes),\n filesize: requestedSize,\n }),\n fileName: sanitizedFilename,\n folder,\n isPrivateFile: imageKitCollection.isPrivate ? 'true' : 'false',\n overwriteFile: 'false',\n tags: uploadTag,\n useUniqueFileName: 'false',\n }\n const receiptContext: ImageKitReceiptContext = {\n collectionSlug,\n expectedMimeType,\n expectedSize: requestedSize,\n filename: sanitizedFilename,\n isPrivate: imageKitCollection.isPrivate,\n prefix: resolved.sanitizedDocPrefix,\n uploadTag,\n }\n const response: ImageKitUploadAuthorization = {\n clientUploadContext: {\n prefix: resolved.sanitizedDocPrefix,\n signedReceipt: createClientUploadReceipt({\n collectionSlug,\n context: receiptContext,\n filename: sanitizedFilename,\n req,\n }),\n },\n filename: sanitizedFilename,\n token: createImageKitUploadToken({ privateKey, publicKey, uploadPayload }),\n uploadPayload,\n }\n\n return Response.json(response, {\n headers: {\n 'Cache-Control': 'no-store',\n },\n })\n }\n}\n"],"names":["buildUploadStoragePathData","randomUUID","posix","APIError","Forbidden","assertClientUploadAccess","assertClientUploadAllowed","assertClientUploadFileSize","createClientUploadReceipt","getSafeFileName","verifyClientUploadReceipt","getSanitizedUploadFilename","validateMimeType","isImageKitReceiptContext","createImageKitUploadToken","defaultAccess","req","Boolean","user","bytesToMB","bytes","toFixed","getMimeTypeEssence","mimeType","split","trim","toLowerCase","getImageKitSafeFilename","filename","replace","XML_FAMILY_MIME_TYPES","getUploadChecks","allowedMimeTypes","allowRestrictedFileTypes","filesize","checks","prefixes","map","filter","prefix","test","length","includes","push","join","type","nextFilename","name","ext","parse","suffix","exec","Number","createImageKitUploadAuthHandler","access","collections","privateKey","publicKey","verifyClientUpload","json","body","action","collectionSlug","fileId","signedReceipt","Object","hasOwn","imageKitCollection","t","receipt","context","undefined","uploadTag","response","clientUploadContext","_objectKey","Response","headers","expectedSize","expectedMimeType","collection","payload","config","requestedSize","collectionConfig","upload","Array","isArray","mimeTypes","filesizeLimit","limits","fileSize","isFinite","sanitizedFilename","desiredFilename","resolved","collectionPrefix","docPrefix","folder","storageFilePath","slice","uploadPayload","fileName","isPrivateFile","isPrivate","overwriteFile","tags","useUniqueFileName","receiptContext","sanitizedDocPrefix","token"],"mappings":"AAGA,SAASA,0BAA0B,QAAQ,6CAA4C;AACvF,SAASC,UAAU,QAAQ,cAAa;AACxC,SAASC,KAAK,QAAQ,YAAW;AACjC,SAASC,QAAQ,EAAEC,SAAS,QAAQ,UAAS;AAC7C,SACEC,wBAAwB,EACxBC,yBAAyB,EACzBC,0BAA0B,EAC1BC,yBAAyB,EACzBC,eAAe,EACfC,yBAAyB,QACpB,mBAAkB;AACzB,SAASC,0BAA0B,EAAEC,gBAAgB,QAAQ,iBAAgB;AAU7E,SAASC,wBAAwB,QAAQ,sBAAqB;AAC9D,SAASC,yBAAyB,QAAQ,4BAA2B;AAerE,MAAMC,gBAAqC,CAAC,EAAEC,GAAG,EAAE,GAAKC,QAAQD,IAAIE,IAAI;AAExE,MAAMC,YAAY,CAACC,QAA0B,AAACA,CAAAA,QAAQ,OAAO,IAAG,EAAGC,OAAO,CAAC;AAE3E,MAAMC,qBAAqB,CAACC,WAC1B,AAACA,CAAAA,SAASC,KAAK,CAAC,KAAK,EAAE,CAAC,EAAE,IAAI,EAAC,EAAGC,IAAI,GAAGC,WAAW;AAEtD,MAAMC,0BAA0B,CAACC,WAC/BjB,2BAA2BiB,UAAUC,OAAO,CAAC,YAAY;AAE3D,iGAAiG;AACjG,MAAMC,wBAAwB;IAC5B;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED;;;;CAIC,GACD,OAAO,MAAMC,kBAAkB,CAAC,EAC9BC,gBAAgB,EAChBC,wBAAwB,EACxBC,QAAQ,EAKT;IACC,MAAMC,SAAS;QAAC,CAAC,cAAc,EAAED,UAAU;KAAC;IAC5C,sFAAsF;IACtF,mFAAmF;IACnF,MAAME,WAAWJ,iBACdK,GAAG,CAAC,CAACd,WAA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vCjE,QAAQwD,SAASc,kBAAkB;YACnCrC;QACF;QACA,MAAMC,WAAwC;YAC5CC,qBAAqB;gBACnBnC,QAAQwD,SAASc,kBAAkB;gBACnC7C,eAAexD,0BAA0B;oBACvCsD;oBACAQ,SAASsC;oBACThF,UAAUiE;oBACV7E;gBACF;YACF;YACAY,UAAUiE;YACViB,OAAOhG,0BAA0B;gBAAE0C;gBAAYC;gBAAW4C;YAAc;YACxEA;QACF;QAEA,OAAOzB,SAASjB,IAAI,CAACc,UAAU;YAC7BI,SAAS;gBACP,iBAAiB;YACnB;QACF;IACF;AACF,EAAC"}
1
+ {"version":3,"sources":["../../src/endpoints/createImageKitUploadAuthHandler.ts"],"sourcesContent":["import type { ClientUploadsAccess } from '@payloadcms/plugin-cloud-storage/types'\nimport type { PayloadHandler, UploadCollectionSlug } from 'payload'\n\nimport { buildUploadStoragePathData } from '@payloadcms/plugin-cloud-storage/utilities'\nimport { randomUUID } from 'node:crypto'\nimport { posix } from 'node:path'\nimport { APIError, Forbidden } from 'payload'\nimport {\n assertClientUploadAccess,\n assertClientUploadAllowed,\n assertClientUploadFileSize,\n createClientUploadReceipt,\n getSafeFileName,\n verifyClientUploadReceipt,\n} from 'payload/internal'\nimport { getSanitizedUploadFilename, validateMimeType } from 'payload/shared'\n\nimport type {\n ImageKitReceiptContext,\n ImageKitUploadAuthorization,\n ImageKitUploadCompletion,\n ImageKitUploadPayload,\n} from '../clientUploads.js'\nimport type { createImageKitClientUploadVerifier } from '../clientUploadVerification.js'\n\nimport { isImageKitReceiptContext } from '../clientUploads.js'\nimport { assertWithinFileSizeLimit } from '../fileSizeLimit.js'\nimport { createImageKitUploadToken } from '../imageKitUploadToken.js'\n\ntype ImageKitUploadCollection = {\n fileSizeLimit?: number\n isPrivate: boolean\n prefix: string\n}\n\ntype CreateImageKitUploadAuthHandlerArgs = {\n access?: ClientUploadsAccess\n collections: Partial<Record<UploadCollectionSlug, ImageKitUploadCollection>>\n privateKey: string\n publicKey: string\n verifyClientUpload: ReturnType<typeof createImageKitClientUploadVerifier>\n}\n\nconst defaultAccess: ClientUploadsAccess = ({ req }) => Boolean(req.user)\n\nconst getMimeTypeEssence = (mimeType: string): string =>\n (mimeType.split(';', 1)[0] || '').trim().toLowerCase()\n\nconst getImageKitSafeFilename = (filename: string): string =>\n getSanitizedUploadFilename(filename).replace(/[^\\w.-]/g, '_')\n\n// ImageKit can't match Payload's `+xml` suffix rule, so name the XML-family types it may detect.\nconst XML_FAMILY_MIME_TYPES = [\n 'application/atom+xml',\n 'application/mathml+xml',\n 'application/rdf+xml',\n 'application/rss+xml',\n 'application/xhtml+xml',\n 'application/xml',\n 'application/xslt+xml',\n 'image/svg+xml',\n 'text/xml',\n]\n\n/**\n * ImageKit evaluates `file.mime` against its own content detection, which can differ from\n * the browser's extension-based type (e.g. `.xltm` is detected as `.xlsx`). Constrain the\n * detected type with the rules completion verification applies, not the browser's claim.\n */\nexport const getUploadChecks = ({\n allowedMimeTypes,\n allowRestrictedFileTypes,\n filesize,\n}: {\n allowedMimeTypes: string[]\n allowRestrictedFileTypes: boolean\n filesize: number\n}): string => {\n const checks = [`\"file.size\" = ${filesize}`]\n // Mirror Payload's validateMimeType, which drops the first `*` and matches by prefix.\n // Entries with quotes or backslashes can't prefix a valid MIME type, so omit them.\n const prefixes = allowedMimeTypes\n .map((mimeType) => mimeType.replace('*', ''))\n .filter((prefix) => !/[\"\\\\]/.test(prefix))\n\n if (allowedMimeTypes.length > 0 && !prefixes.includes('')) {\n checks.push(`(${prefixes.map((prefix) => `\"file.mime\" : \"${prefix}\"`).join(' OR ')})`)\n }\n\n if (!allowRestrictedFileTypes) {\n checks.push(`\"file.mime\" NOT IN [${XML_FAMILY_MIME_TYPES.map((type) => `\"${type}\"`).join(', ')}]`)\n }\n\n return checks.join(' AND ')\n}\n\n// Continue Payload's numeric suffix convention when the conflict exists only in ImageKit.\nconst nextFilename = (filename: string): string => {\n const { name, ext } = posix.parse(filename)\n const suffix = /^(.*)-(\\d+)$/.exec(name)\n return `${suffix ? `${suffix[1]}-${Number(suffix[2]) + 1}` : `${name}-1`}${ext}`\n}\n\nexport const createImageKitUploadAuthHandler = ({\n access = defaultAccess,\n collections,\n privateKey,\n publicKey,\n verifyClientUpload,\n}: CreateImageKitUploadAuthHandlerArgs): PayloadHandler => {\n return async (req) => {\n if (!req.json) {\n throw new APIError('Content-Type expected to be application/json', 400)\n }\n\n const body = (await req.json()) as {\n action?: unknown\n collectionSlug?: unknown\n fileId?: unknown\n filename?: unknown\n filesize?: unknown\n mimeType?: unknown\n signedReceipt?: unknown\n }\n const { action, collectionSlug, fileId, signedReceipt } = body\n let { filename, filesize, mimeType } = body\n\n if (typeof collectionSlug !== 'string' || !Object.hasOwn(collections, collectionSlug)) {\n throw new APIError('Invalid upload payload.', 400)\n }\n\n await assertClientUploadAccess({ collectionSlug, req })\n\n const imageKitCollection = collections[collectionSlug]\n if (!imageKitCollection) {\n throw new APIError(`Collection ${collectionSlug} was not found in ImageKit options.`, 400)\n }\n\n if (!(await access({ collectionSlug, req }))) {\n throw new Forbidden(req.t)\n }\n\n if (action === 'complete') {\n if (typeof fileId !== 'string' || !fileId.trim() || typeof signedReceipt !== 'string') {\n throw new APIError('Invalid ImageKit upload completion payload.', 400)\n }\n const receipt = verifyClientUploadReceipt({ collectionSlug, req, signedReceipt })\n if (\n !isImageKitReceiptContext(receipt.context) ||\n receipt.filename !== receipt.context.filename ||\n (receipt.context.fileId !== undefined && receipt.context.fileId !== fileId)\n ) {\n throw new APIError('Invalid ImageKit client upload context.', 400)\n }\n\n // The browser supplies a lookup ID, not proof. Check provider state against the\n // original signed authorization before including that ID in a new signed receipt.\n const context: ImageKitReceiptContext = { ...receipt.context, fileId }\n await verifyClientUpload({ collectionSlug, context })\n delete context.uploadTag\n const response: ImageKitUploadCompletion = {\n clientUploadContext: {\n _objectKey: context._objectKey,\n prefix: context.prefix,\n signedReceipt: createClientUploadReceipt({\n collectionSlug,\n context,\n filename: context.filename,\n req,\n }),\n },\n }\n return Response.json(response, { headers: { 'Cache-Control': 'no-store' } })\n }\n\n if (action === 'retry') {\n if (typeof signedReceipt !== 'string') {\n throw new APIError('Invalid ImageKit upload retry payload.', 400)\n }\n const receipt = verifyClientUploadReceipt({ collectionSlug, req, signedReceipt })\n if (\n !isImageKitReceiptContext(receipt.context) ||\n receipt.filename !== receipt.context.filename ||\n receipt.context.fileId !== undefined\n ) {\n throw new APIError('Invalid ImageKit upload retry payload.', 400)\n }\n filename = nextFilename(receipt.context.filename)\n filesize = receipt.context.expectedSize\n mimeType = receipt.context.expectedMimeType\n }\n\n if (\n (action !== undefined && action !== 'retry') ||\n typeof filename !== 'string' ||\n typeof mimeType !== 'string'\n ) {\n throw new APIError('Invalid upload payload.', 400)\n }\n\n assertClientUploadAllowed({\n collection: req.payload.collections[collectionSlug]?.config,\n filename,\n mimeType,\n })\n assertClientUploadFileSize(filesize)\n\n const requestedSize = filesize as number\n const expectedMimeType = getMimeTypeEssence(mimeType)\n if (!expectedMimeType) {\n throw new APIError('A valid MIME type is required for ImageKit client uploads.', 400)\n }\n\n const collectionConfig = req.payload.collections[collectionSlug]?.config\n const allowedMimeTypes =\n collectionConfig &&\n typeof collectionConfig.upload === 'object' &&\n Array.isArray(collectionConfig.upload.mimeTypes)\n ? collectionConfig.upload.mimeTypes\n : []\n\n if (allowedMimeTypes.length > 0 && !validateMimeType(expectedMimeType, allowedMimeTypes)) {\n throw new APIError(`File type ${expectedMimeType} is not allowed.`, 400)\n }\n\n assertWithinFileSizeLimit(requestedSize, req.payload.config.upload.limits?.fileSize)\n assertWithinFileSizeLimit(requestedSize, imageKitCollection.fileSizeLimit)\n\n const sanitizedFilename = await getSafeFileName({\n collectionSlug,\n desiredFilename: getImageKitSafeFilename(filename),\n req,\n })\n const resolved = buildUploadStoragePathData({\n collectionPrefix: imageKitCollection.prefix,\n docPrefix: imageKitCollection.prefix,\n filename: sanitizedFilename,\n })\n const folder = `/${resolved.storageFilePath.slice(0, -(sanitizedFilename.length + 1))}`\n const uploadTag = `payload-upload-${randomUUID()}`\n const uploadPayload: ImageKitUploadPayload = {\n checks: getUploadChecks({\n allowedMimeTypes,\n allowRestrictedFileTypes:\n typeof collectionConfig?.upload === 'object' &&\n Boolean(collectionConfig.upload.allowRestrictedFileTypes),\n filesize: requestedSize,\n }),\n fileName: sanitizedFilename,\n folder,\n isPrivateFile: imageKitCollection.isPrivate ? 'true' : 'false',\n overwriteFile: 'false',\n tags: uploadTag,\n useUniqueFileName: 'false',\n }\n const receiptContext: ImageKitReceiptContext = {\n collectionSlug,\n expectedMimeType,\n expectedSize: requestedSize,\n filename: sanitizedFilename,\n isPrivate: imageKitCollection.isPrivate,\n prefix: resolved.sanitizedDocPrefix,\n uploadTag,\n }\n const response: ImageKitUploadAuthorization = {\n clientUploadContext: {\n prefix: resolved.sanitizedDocPrefix,\n signedReceipt: createClientUploadReceipt({\n collectionSlug,\n context: receiptContext,\n filename: sanitizedFilename,\n req,\n }),\n },\n filename: sanitizedFilename,\n token: createImageKitUploadToken({ privateKey, publicKey, uploadPayload }),\n uploadPayload,\n }\n\n return Response.json(response, {\n headers: {\n 'Cache-Control': 'no-store',\n },\n })\n }\n}\n"],"names":["buildUploadStoragePathData","randomUUID","posix","APIError","Forbidden","assertClientUploadAccess","assertClientUploadAllowed","assertClientUploadFileSize","createClientUploadReceipt","getSafeFileName","verifyClientUploadReceipt","getSanitizedUploadFilename","validateMimeType","isImageKitReceiptContext","assertWithinFileSizeLimit","createImageKitUploadToken","defaultAccess","req","Boolean","user","getMimeTypeEssence","mimeType","split","trim","toLowerCase","getImageKitSafeFilename","filename","replace","XML_FAMILY_MIME_TYPES","getUploadChecks","allowedMimeTypes","allowRestrictedFileTypes","filesize","checks","prefixes","map","filter","prefix","test","length","includes","push","join","type","nextFilename","name","ext","parse","suffix","exec","Number","createImageKitUploadAuthHandler","access","collections","privateKey","publicKey","verifyClientUpload","json","body","action","collectionSlug","fileId","signedReceipt","Object","hasOwn","imageKitCollection","t","receipt","context","undefined","uploadTag","response","clientUploadContext","_objectKey","Response","headers","expectedSize","expectedMimeType","collection","payload","config","requestedSize","collectionConfig","upload","Array","isArray","mimeTypes","limits","fileSize","fileSizeLimit","sanitizedFilename","desiredFilename","resolved","collectionPrefix","docPrefix","folder","storageFilePath","slice","uploadPayload","fileName","isPrivateFile","isPrivate","overwriteFile","tags","useUniqueFileName","receiptContext","sanitizedDocPrefix","token"],"mappings":"AAGA,SAASA,0BAA0B,QAAQ,6CAA4C;AACvF,SAASC,UAAU,QAAQ,cAAa;AACxC,SAASC,KAAK,QAAQ,YAAW;AACjC,SAASC,QAAQ,EAAEC,SAAS,QAAQ,UAAS;AAC7C,SACEC,wBAAwB,EACxBC,yBAAyB,EACzBC,0BAA0B,EAC1BC,yBAAyB,EACzBC,eAAe,EACfC,yBAAyB,QACpB,mBAAkB;AACzB,SAASC,0BAA0B,EAAEC,gBAAgB,QAAQ,iBAAgB;AAU7E,SAASC,wBAAwB,QAAQ,sBAAqB;AAC9D,SAASC,yBAAyB,QAAQ,sBAAqB;AAC/D,SAASC,yBAAyB,QAAQ,4BAA2B;AAgBrE,MAAMC,gBAAqC,CAAC,EAAEC,GAAG,EAAE,GAAKC,QAAQD,IAAIE,IAAI;AAExE,MAAMC,qBAAqB,CAACC,WAC1B,AAACA,CAAAA,SAASC,KAAK,CAAC,KAAK,EAAE,CAAC,EAAE,IAAI,EAAC,EAAGC,IAAI,GAAGC,WAAW;AAEtD,MAAMC,0BAA0B,CAACC,WAC/Bf,2BAA2Be,UAAUC,OAAO,CAAC,YAAY;AAE3D,iGAAiG;AACjG,MAAMC,wBAAwB;IAC5B;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED;;;;CAIC,GACD,OAAO,MAAMC,kBAAkB,CAAC,EAC9BC,gBAAgB,EAChBC,wBAAwB,EACxBC,QAAQ,EAKT;IACC,MAAMC,SAAS;QAAC,CAAC,cAAc,EAAED,UAAU;KAAC;IAC5C,sFAAsF;IACtF,mF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c,kBAAkB;gBACnC5C,eAAetD,0BAA0B;oBACvCoD;oBACAQ,SAASqC;oBACT/E,UAAUgE;oBACVzE;gBACF;YACF;YACAS,UAAUgE;YACViB,OAAO5F,0BAA0B;gBAAEuC;gBAAYC;gBAAW2C;YAAc;YACxEA;QACF;QAEA,OAAOxB,SAASjB,IAAI,CAACc,UAAU;YAC7BI,SAAS;gBACP,iBAAiB;YACnB;QACF;IACF;AACF,EAAC"}
@@ -0,0 +1,6 @@
1
+ export declare const isValidFileSizeLimit: (value: unknown) => value is number;
2
+ /**
3
+ * Rejects a file larger than `limit` bytes. An undefined or non-finite limit (Payload's
4
+ * `upload.limits.fileSize` accepts `Infinity`) means no limit.
5
+ */
6
+ export declare const assertWithinFileSizeLimit: (size: number, limit: number | undefined) => void;
@@ -0,0 +1,13 @@
1
+ import { APIError } from 'payload';
2
+ const bytesToMB = (bytes)=>(bytes / 1024 / 1024).toFixed(2);
3
+ export const isValidFileSizeLimit = (value)=>typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
4
+ /**
5
+ * Rejects a file larger than `limit` bytes. An undefined or non-finite limit (Payload's
6
+ * `upload.limits.fileSize` accepts `Infinity`) means no limit.
7
+ */ export const assertWithinFileSizeLimit = (size, limit)=>{
8
+ if (typeof limit === 'number' && Number.isFinite(limit) && size > limit) {
9
+ throw new APIError(`Exceeded file size limit. Limit: ${bytesToMB(limit)}MB, got: ${bytesToMB(size)}MB`, 400);
10
+ }
11
+ };
12
+
13
+ //# sourceMappingURL=fileSizeLimit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/fileSizeLimit.ts"],"sourcesContent":["import { APIError } from 'payload'\n\nconst bytesToMB = (bytes: number): string => (bytes / 1024 / 1024).toFixed(2)\n\nexport const isValidFileSizeLimit = (value: unknown): value is number =>\n typeof value === 'number' && Number.isSafeInteger(value) && value > 0\n\n/**\n * Rejects a file larger than `limit` bytes. An undefined or non-finite limit (Payload's\n * `upload.limits.fileSize` accepts `Infinity`) means no limit.\n */\nexport const assertWithinFileSizeLimit = (size: number, limit: number | undefined): void => {\n if (typeof limit === 'number' && Number.isFinite(limit) && size > limit) {\n throw new APIError(\n `Exceeded file size limit. Limit: ${bytesToMB(limit)}MB, got: ${bytesToMB(size)}MB`,\n 400,\n )\n }\n}\n"],"names":["APIError","bytesToMB","bytes","toFixed","isValidFileSizeLimit","value","Number","isSafeInteger","assertWithinFileSizeLimit","size","limit","isFinite"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,UAAS;AAElC,MAAMC,YAAY,CAACC,QAA0B,AAACA,CAAAA,QAAQ,OAAO,IAAG,EAAGC,OAAO,CAAC;AAE3E,OAAO,MAAMC,uBAAuB,CAACC,QACnC,OAAOA,UAAU,YAAYC,OAAOC,aAAa,CAACF,UAAUA,QAAQ,EAAC;AAEvE;;;CAGC,GACD,OAAO,MAAMG,4BAA4B,CAACC,MAAcC;IACtD,IAAI,OAAOA,UAAU,YAAYJ,OAAOK,QAAQ,CAACD,UAAUD,OAAOC,OAAO;QACvE,MAAM,IAAIV,SACR,CAAC,iCAAiC,EAAEC,UAAUS,OAAO,SAAS,EAAET,UAAUQ,MAAM,EAAE,CAAC,EACnF;IAEJ;AACF,EAAC"}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,12 @@
1
1
  import type { ClientUploadsConfig } from '@payloadcms/plugin-cloud-storage/types';
2
2
  import type { Config, UploadCollectionSlug } from 'payload';
3
3
  export type ImageKitCollectionOptions = {
4
+ /**
5
+ * Maximum upload size in bytes for this collection. Applies on top of Payload's
6
+ * `upload.limits.fileSize`, so it can only tighten that limit. Client uploads are
7
+ * rejected before ImageKit authorization; server uploads before they reach ImageKit.
8
+ */
9
+ fileSizeLimit?: number;
4
10
  /**
5
11
  * Override Payload's native focal-point picker (`upload.focalPoint`) for this
6
12
  * collection.
package/dist/index.js CHANGED
@@ -9,6 +9,7 @@ import { validateMimeType } from 'payload/shared';
9
9
  import { imageKitUploadAuthPath, isImageKitReceiptContext } from './clientUploads.js';
10
10
  import { createImageKitClientUploadVerifier, getClientUploadStorageFilePath } from './clientUploadVerification.js';
11
11
  import { createImageKitUploadAuthHandler } from './endpoints/createImageKitUploadAuthHandler.js';
12
+ import { assertWithinFileSizeLimit, isValidFileSizeLimit } from './fileSizeLimit.js';
12
13
  import { getAdminThumbnailURL, getPrivateAdminThumbnailURL, isPdfMimeType, isVideoMimeType } from './getAdminThumbnailURL.js';
13
14
  import { getImageKitThumbnailSrc, getVideoPosterSrc } from './imageTransforms.js';
14
15
  const DEFAULT_SIGNED_URL_EXPIRES_IN = 900;
@@ -22,6 +23,7 @@ const DEFAULT_SIGNED_URL_EXPIRES_IN = 900;
22
23
  */ const ORIGINAL_FILE_TRANSFORMATION = 'orig-true';
23
24
  const PRIVATE_COLLECTION_DESCRIPTION = 'Files in this collection are uploaded to ImageKit as private files and delivered through short-lived signed URLs.';
24
25
  const isPrivateCollectionConfig = (value)=>value !== true && typeof value === 'object' && value?.private === true;
26
+ const getCollectionFileSizeLimit = (value)=>value !== true && typeof value === 'object' ? value?.fileSizeLimit : undefined;
25
27
  const XML_FAMILY_MIME_TYPES = [
26
28
  'application/xml',
27
29
  'image/svg+xml',
@@ -468,6 +470,13 @@ export const imagekitStorage = (pluginOptions)=>(config)=>{
468
470
  if (!collections || Object.keys(collections).length === 0) {
469
471
  throw new Error('imagekitStorage: `collections` must include at least one upload collection.');
470
472
  }
473
+ const invalidFileSizeLimitSlugs = Object.entries(collections).filter(([, value])=>{
474
+ const fileSizeLimit = getCollectionFileSizeLimit(value);
475
+ return fileSizeLimit !== undefined && !isValidFileSizeLimit(fileSizeLimit);
476
+ }).map(([slug])=>slug);
477
+ if (invalidFileSizeLimitSlugs.length > 0) {
478
+ throw new Error(`imagekitStorage: \`fileSizeLimit\` must be a positive integer number of bytes (${invalidFileSizeLimitSlugs.join(', ')}).`);
479
+ }
471
480
  const privateSlugs = new Set(Object.entries(collections).filter(([, value])=>isPrivateCollectionConfig(value)).map(([slug])=>slug));
472
481
  const configuredSlugs = new Set(Object.keys(collections));
473
482
  if (disablePayloadAccessControl && privateSlugs.size > 0) {
@@ -516,6 +525,7 @@ export const imagekitStorage = (pluginOptions)=>(config)=>{
516
525
  const isCollectionPrivate = privateSlugs.has(collection.slug);
517
526
  const buildThumbnailURL = (doc)=>isDocumentPrivate(doc, isCollectionPrivate) ? getPrivateAdminThumbnailURL(doc, collection.slug, apiRoute) : getAdminThumbnailURL(doc);
518
527
  const collectionOptions = collections[collection.slug];
528
+ const collectionFileSizeLimit = getCollectionFileSizeLimit(collectionOptions);
519
529
  const collectionFocalPoint = collectionOptions !== true && typeof collectionOptions === 'object' && typeof collectionOptions.focalPoint === 'boolean' ? collectionOptions.focalPoint : undefined;
520
530
  // Surface a "this is a private collection" note in the list and edit views.
521
531
  // Preserve an existing string description by appending; leave custom
@@ -574,6 +584,14 @@ export const imagekitStorage = (pluginOptions)=>(config)=>{
574
584
  ],
575
585
  beforeOperation: [
576
586
  ...collection.hooks?.beforeOperation || [],
587
+ ({ args, operation, req })=>{
588
+ // Client uploads are checked when ImageKit authorization is requested, and
589
+ // their verified size is bound to that authorization.
590
+ if ((operation === 'create' || operation === 'update') && req.file && !req.file.clientUploadContext) {
591
+ assertWithinFileSizeLimit(req.file.size, collectionFileSizeLimit);
592
+ }
593
+ return args;
594
+ },
577
595
  ({ args, operation, req })=>{
578
596
  if (operation !== 'create' && operation !== 'update' || req.context?.skipCloudStorage || !req.file || req.file.clientUploadContext || !('data' in args) || !isRecord(args.data) || typeof args.data.prefix !== 'string') {
579
597
  return args;
@@ -611,6 +629,7 @@ export const imagekitStorage = (pluginOptions)=>(config)=>{
611
629
  const uploadCollections = Object.fromEntries(Object.keys(collections).map((collectionSlug)=>[
612
630
  collectionSlug,
613
631
  {
632
+ fileSizeLimit: getCollectionFileSizeLimit(collections[collectionSlug]),
614
633
  isPrivate: privateSlugs.has(collectionSlug),
615
634
  prefix: getCollectionFolder(rootFolder, collectionSlug)
616
635
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n Adapter,\n ClientUploadsConfig,\n CollectionOptions,\n} from '@payloadcms/plugin-cloud-storage/types'\nimport type {\n CollectionConfig,\n CollectionSlug,\n Config,\n Field,\n PayloadRequest,\n TypeWithID,\n UploadCollectionSlug,\n Where,\n} from 'payload'\n\nimport ImageKit, { toFile } from '@imagekit/nodejs'\nimport { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage'\nimport {\n buildStoragePathData,\n buildUploadStoragePathData,\n getStorageFilePath,\n initClientUploads,\n} from '@payloadcms/plugin-cloud-storage/utilities'\nimport { openAsBlob } from 'node:fs'\nimport path from 'node:path'\nimport { APIError } from 'payload'\nimport {\n getRangeRequestInfo,\n isXmlMimeType,\n UPLOAD_CONTENT_SECURITY_POLICY,\n} from 'payload/internal'\nimport { validateMimeType } from 'payload/shared'\n\nimport type { VerifiedImageKitUpload } from './clientUploadVerification.js'\n\nimport { imageKitUploadAuthPath, isImageKitReceiptContext } from './clientUploads.js'\nimport {\n createImageKitClientUploadVerifier,\n getClientUploadStorageFilePath,\n} from './clientUploadVerification.js'\nimport { createImageKitUploadAuthHandler } from './endpoints/createImageKitUploadAuthHandler.js'\nimport {\n getAdminThumbnailURL,\n getPrivateAdminThumbnailURL,\n isPdfMimeType,\n isVideoMimeType,\n} from './getAdminThumbnailURL.js'\nimport { getImageKitThumbnailSrc, getVideoPosterSrc } from './imageTransforms.js'\n\nexport type ImageKitCollectionOptions = {\n /**\n * Override Payload's native focal-point picker (`upload.focalPoint`) for this\n * collection.\n */\n focalPoint?: boolean\n /**\n * Upload files in this collection as ImageKit private files (`isPrivateFile: true`)\n * and deliver them only through short-lived signed URLs, behind Payload access control.\n */\n private?: boolean\n}\ntype ImageKitCollectionConfig = ImageKitCollectionOptions | true\ntype ImageKitCollectionMap = Partial<Record<UploadCollectionSlug, ImageKitCollectionConfig>>\n\nconst DEFAULT_SIGNED_URL_EXPIRES_IN = 900\n/**\n * ImageKit re-encodes some uploads and serves the smaller derivative from the plain\n * delivery URL — a 1.9 MB MP4 can come back as 868 KB. That is exactly what we want\n * for visitors, but not when reading the file back to verify a client upload: the\n * bytes and the byte count would both belong to a file ImageKit's API never reported.\n * `orig-true` asks for the untouched original and does not disable optimisation for\n * anyone else.\n */\nconst ORIGINAL_FILE_TRANSFORMATION = 'orig-true'\n\nconst PRIVATE_COLLECTION_DESCRIPTION =\n 'Files in this collection are uploaded to ImageKit as private files and delivered through short-lived signed URLs.'\n\nconst isPrivateCollectionConfig = (value: ImageKitCollectionConfig | undefined): boolean =>\n value !== true && typeof value === 'object' && value?.private === true\n\nconst XML_FAMILY_MIME_TYPES = ['application/xml', 'image/svg+xml', 'text/xml']\n\nconst collectionCanStoreXml = (collection: CollectionConfig): boolean => {\n const upload = collection.upload\n\n if (!upload || upload === true) {\n return Boolean(upload)\n }\n\n // Payload skips MIME and content restrictions when this escape hatch is enabled.\n if (upload.allowRestrictedFileTypes) {\n return true\n }\n\n const allowedMimeTypes = upload.mimeTypes\n\n return (\n !allowedMimeTypes?.length ||\n allowedMimeTypes.some((mimeType) => mimeType.includes('*') || isXmlMimeType(mimeType)) ||\n XML_FAMILY_MIME_TYPES.some((mimeType) => validateMimeType(mimeType, allowedMimeTypes))\n )\n}\n\n/**\n * Whether a specific document is private. The flag stored on the document at upload time\n * (`imagekit.isPrivate`) is the source of truth — a file's privacy on ImageKit is fixed\n * when it is uploaded and does not change if the collection's `private` setting changes\n * later. Falls back to the collection setting for documents uploaded before this flag existed.\n */\nconst isDocumentPrivate = (doc: unknown, collectionIsPrivate: boolean): boolean => {\n const stored = (doc as { imagekit?: { isPrivate?: boolean } } | undefined)?.imagekit?.isPrivate\n\n return typeof stored === 'boolean' ? stored : collectionIsPrivate\n}\ntype ImageKitReference = {\n imagekit?: {\n fileId?: string\n isPrivate?: boolean\n thumbnailUrl?: string\n url?: string\n }\n}\n\ntype UploadDocumentData = {\n thumbnailURL?: string\n} & ImageKitReference\n\nexport type PayloadStorageImageKitConfig = {\n alwaysInsertFields?: boolean\n clientUploads?: ClientUploadsConfig\n collections: ImageKitCollectionMap\n disablePayloadAccessControl?: true\n enabled?: boolean\n /**\n * Broad default for Payload's native focal-point picker (`upload.focalPoint`)\n * on every configured collection. Focal points are disabled by default for\n * configured collections, so prefer collection-level `focalPoint: true` for\n * image collections. A collection's own `upload.focalPoint` still takes\n * precedence.\n */\n focalPoint?: boolean\n folder: string\n privateKey: string\n publicKey: string\n /**\n * Expiry (in seconds) applied to signed URLs generated for private collections.\n * Defaults to 900 (15 minutes). URLs are signed fresh on every request, so a short\n * window is safe.\n */\n signedUrlExpiresIn?: number\n urlEndpoint: string\n}\n\nconst normalizeFolder = (folder: string): string => {\n const normalized = folder.trim().replace(/^\\/+|\\/+$/g, '')\n\n if (!normalized) {\n throw new Error('imagekitStorage: `folder` is required.')\n }\n\n return `/${normalized}`\n}\n\nconst getCollectionFolder = (rootFolder: string, collectionSlug: string): string =>\n path.posix.join(rootFolder, collectionSlug)\n\nconst findImageKitFileId = async (\n imagekit: ImageKit,\n filePath: string,\n): Promise<string | undefined> => {\n const parentPath = path.posix.dirname(filePath)\n const name = path.posix.basename(filePath)\n\n const limit = 100\n\n for (let skip = 0; ; skip += limit) {\n const assets = await imagekit.assets.list({\n type: 'file',\n limit,\n path: parentPath === '/' ? '/' : `${parentPath}/`,\n skip,\n })\n\n const found = assets.find(\n (asset) => 'fileId' in asset && asset.filePath === filePath && asset.name === name,\n )\n\n if (found && 'fileId' in found) {\n return found.fileId\n }\n\n if (assets.length < limit) {\n break\n }\n }\n\n return undefined\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === 'object'\n\nconst getStoredImageKitURL = (doc: unknown): string | undefined => {\n const storedURL = (doc as ImageKitReference | undefined)?.imagekit?.url\n\n return typeof storedURL === 'string' && storedURL.trim().length > 0 ? storedURL : undefined\n}\n\nconst hasStoredImageKitURL = (doc: unknown): boolean => !!getStoredImageKitURL(doc)\n\nconst findUploadDocumentByFilename = async ({\n collection,\n filename,\n prefix,\n req,\n}: {\n collection: string\n filename: string\n prefix?: string\n req: PayloadRequest\n}): Promise<null | TypeWithID> => {\n const constraints: Where[] = [\n {\n filename: {\n equals: filename,\n },\n },\n ]\n\n if (typeof prefix === 'string') {\n constraints.push({\n prefix: {\n equals: prefix,\n },\n })\n }\n\n return req.payload.db.findOne({\n collection,\n req,\n where: {\n and: constraints,\n },\n })\n}\n\nconst applyVerifiedClientUploadToData = <T extends UploadDocumentData>(\n data: T,\n uploaded: VerifiedImageKitUpload,\n buildThumbnailURL: (data: T) => string = getAdminThumbnailURL,\n isPrivate: boolean,\n): T => {\n data.imagekit = {\n fileId: uploaded.fileId,\n isPrivate,\n thumbnailUrl: uploaded.thumbnailUrl,\n url: uploaded.url,\n }\n\n // Preserve the admin preview when the original file was already uploaded client-side.\n data.thumbnailURL = buildThumbnailURL(data)\n\n return data\n}\n\nconst imagekitAdapter = ({\n apiRoute,\n client,\n clientUploads,\n privateSlugs,\n rootFolder,\n signedUrlExpiresIn,\n urlEndpoint,\n verifyClientUpload,\n}: {\n apiRoute: string\n client: ImageKit\n clientUploads?: ClientUploadsConfig\n privateSlugs: Set<string>\n rootFolder: string\n signedUrlExpiresIn: number\n urlEndpoint: string\n verifyClientUpload: ReturnType<typeof createImageKitClientUploadVerifier>\n}): Adapter => {\n const fetchUploadedFile = async ({\n fileSize,\n fileURL,\n mimeType,\n range,\n }: {\n fileSize: number\n fileURL: string\n mimeType: string\n range?: null | string\n }): Promise<Response> => {\n const rangeResult = getRangeRequestInfo({ fileSize, rangeHeader: range ?? null })\n\n if (rangeResult.type === 'invalid') {\n return new Response(null, {\n headers: new Headers(rangeResult.headers),\n status: rangeResult.status,\n })\n }\n\n const normalizedRange =\n rangeResult.type === 'partial'\n ? `bytes=${rangeResult.rangeStart}-${rangeResult.rangeEnd}`\n : undefined\n // Payload cancels image probes after reading a bounded prefix. Next.js memoizes\n // GET responses by teeing their streams; cancelling one branch can then wait\n // forever for its unread cached sibling. An explicit signal opts out of that\n // memoization, while no-store also excludes these reads from the data cache.\n const response = await fetch(fileURL, {\n cache: 'no-store',\n ...(normalizedRange ? { headers: { Range: normalizedRange } } : {}),\n signal: new AbortController().signal,\n })\n\n if (!response.ok || response.status !== rangeResult.status) {\n void response.body?.cancel().catch(() => undefined)\n throw new Error(\n `imagekitStorage: ImageKit returned an unexpected file response (${response.status}).`,\n )\n }\n\n const upstreamLength = response.headers.get('Content-Length')\n const expectedLength = rangeResult.headers['Content-Length']\n const upstreamRange = response.headers.get('Content-Range')\n const expectedRange =\n rangeResult.type === 'partial' ? rangeResult.headers['Content-Range'] : undefined\n\n if (\n (upstreamLength !== null && upstreamLength !== expectedLength) ||\n (expectedRange && upstreamRange !== expectedRange)\n ) {\n void response.body?.cancel().catch(() => undefined)\n throw new Error('imagekitStorage: ImageKit returned mismatched file content metadata.')\n }\n\n const headers = new Headers(rangeResult.headers)\n headers.set('Content-Type', mimeType)\n if (isXmlMimeType(mimeType)) {\n headers.set('Content-Security-Policy', UPLOAD_CONTENT_SECURITY_POLICY)\n }\n\n return new Response(response.body, {\n headers,\n status: response.status,\n })\n }\n\n return ({ collection, prefix = getCollectionFolder(rootFolder, collection.slug) }) => {\n const isPrivate = privateSlugs.has(collection.slug)\n\n // Sign a relative ImageKit path against the configured urlEndpoint. We always sign\n // a computed path (never a stored absolute URL) because ImageKit's signature is\n // derived from the path after stripping urlEndpoint, so the host must match.\n const buildSignedURL = (src: string, tr?: null | string): string =>\n client.helper.buildSrc({\n expiresIn: signedUrlExpiresIn,\n signed: true,\n src,\n transformation: tr ? [{ raw: tr }] : undefined,\n urlEndpoint,\n })\n\n const buildThumbnailURL = (doc: UploadDocumentData): string =>\n isDocumentPrivate(doc, isPrivate)\n ? getPrivateAdminThumbnailURL(doc, collection.slug, apiRoute)\n : getAdminThumbnailURL(doc)\n\n return {\n name: 'imagekit',\n clientUploads,\n fields: [\n {\n // Presentational wrapper: tucks the ImageKit details into a closed panel without\n // changing the `imagekit.*` data paths.\n type: 'collapsible',\n admin: {\n condition: (data) => hasStoredImageKitURL(data),\n initCollapsed: true,\n },\n fields: [\n {\n name: 'imagekit',\n type: 'group',\n admin: {\n disableListColumn: true,\n disableListFilter: true,\n },\n fields: [\n {\n name: 'fileId',\n type: 'text',\n admin: {\n hidden: true,\n },\n },\n {\n name: 'url',\n type: 'text',\n admin: {\n readOnly: true,\n },\n label: 'URL',\n },\n {\n name: 'isPrivate',\n type: 'checkbox',\n admin: {\n condition: (_data, siblingData) =>\n isDocumentPrivate({ imagekit: siblingData }, isPrivate),\n description:\n \"Indicates whether this file was uploaded to ImageKit as private. Private files are delivered through signed URLs. Changes to this collection's private option in payload.config only affect future uploads.\",\n readOnly: true,\n },\n label: 'Private file',\n },\n {\n name: 'signedUrl',\n type: 'text',\n admin: {\n // Only relevant for private files; the plain `url` works directly for public ones.\n condition: (_data, siblingData) =>\n isDocumentPrivate({ imagekit: siblingData }, isPrivate),\n description: `Temporary signed URL for reaching this private file directly on ImageKit. Expires ${signedUrlExpiresIn} seconds after load and is regenerated on every read. Note: anyone with this URL can access the file until it expires — it is not gated by Payload access control.`,\n readOnly: true,\n },\n hooks: {\n // Computed server-side on read so it is always freshly signed and never persisted.\n afterRead: [\n ({ data, siblingData }) => {\n if (!isDocumentPrivate({ imagekit: siblingData }, isPrivate)) {\n return undefined\n }\n\n const filename = (data as { filename?: string } | undefined)?.filename\n\n if (!filename) {\n return undefined\n }\n\n const source = (data || {}) as { _objectKey?: string; prefix?: string }\n const documentPrefix = path.posix.join(\n source.prefix || prefix,\n source._objectKey || '',\n )\n const storageFilePath = buildStoragePathData({\n collectionPrefix: prefix,\n docPrefix: documentPrefix,\n filename,\n }).storageFilePath\n\n return buildSignedURL(`/${storageFilePath}`)\n },\n ],\n },\n label: 'Signed URL',\n virtual: true,\n },\n {\n name: 'thumbnailUrl',\n type: 'text',\n admin: {\n hidden: true,\n },\n },\n ],\n interfaceName: 'imagekitFields',\n label: false,\n },\n ],\n label: 'Storage: ImageKit',\n },\n ],\n generateURL: ({ filename, prefix: documentPrefix = '' }) =>\n client.helper.buildSrc({\n src: `/${buildStoragePathData({\n collectionPrefix: prefix,\n docPrefix: documentPrefix,\n filename,\n }).storageFilePath}`,\n urlEndpoint,\n }),\n handleDelete: async ({ doc, storageFilePath }) => {\n const storedFileId = (doc as ImageKitReference & typeof doc).imagekit?.fileId\n const fileId =\n storedFileId || (await findImageKitFileId(client, `/${storageFilePath.replace(/^\\/+/, '')}`))\n\n if (!fileId) {\n return\n }\n\n await client.files.delete(fileId)\n },\n handleUpload: async ({ clientUploadContext, data, file, storageFilePath }) => {\n if (clientUploadContext) {\n const uploaded = await verifyClientUpload({\n collectionSlug: collection.slug,\n context: clientUploadContext,\n })\n\n return applyVerifiedClientUploadToData(data, uploaded, buildThumbnailURL, isPrivate)\n }\n\n // ImageKit's `toFile()` consumes async iterables before starting the request. A file-backed\n // Blob keeps temporary-file uploads lazy so FormData can stream them from disk instead.\n const uploadSource = file.tempFilePath\n ? await openAsBlob(file.tempFilePath, { type: file.mimeType })\n : file.buffer\n const uploadFile = await toFile(uploadSource, file.filename, { type: file.mimeType })\n const uploadFolder = path.posix.dirname(`/${storageFilePath.replace(/^\\/+/, '')}`)\n const uploadFilename = path.posix.basename(storageFilePath)\n\n const uploaded = await client.files.upload({\n file: uploadFile,\n fileName: uploadFilename,\n folder: uploadFolder,\n useUniqueFileName: false,\n ...(isPrivate ? { isPrivateFile: true } : {}),\n })\n\n data.imagekit = {\n fileId: uploaded.fileId,\n isPrivate,\n thumbnailUrl: uploaded.thumbnailUrl,\n url: uploaded.url,\n }\n\n // Set the root-level thumbnailURL that Payload's admin interface expects.\n // `buildThumbnailURL` needs the filename, which Payload may not have copied onto\n // `data` yet at this point, so fall back to the uploaded file's name.\n data.thumbnailURL = buildThumbnailURL({\n ...data,\n filename: (data as { filename?: string }).filename || uploadFilename,\n })\n\n return data\n },\n requiresClientUploadReceipt: true,\n staticHandler: async (req, args) => {\n const requestURL = new URL(req.url || 'http://localhost')\n const tr = requestURL.searchParams.get('tr')\n const hasClientUploadContext = 'clientUploadContext' in args.params\n\n if (hasClientUploadContext) {\n const clientUploadContext = args.params.clientUploadContext\n\n if (!isImageKitReceiptContext(clientUploadContext)) {\n throw new APIError('Invalid ImageKit client upload context.', 400)\n }\n\n const uploadedFile = await verifyClientUpload({\n collectionSlug: collection.slug,\n context: clientUploadContext,\n })\n const expectedFilePath = getClientUploadStorageFilePath({\n collectionPrefix: prefix,\n context: clientUploadContext,\n })\n const verifiedFileURL = isPrivate\n ? buildSignedURL(`/${expectedFilePath}`, ORIGINAL_FILE_TRANSFORMATION)\n : client.helper.buildSrc({\n src: `/${expectedFilePath}`,\n transformation: [{ raw: ORIGINAL_FILE_TRANSFORMATION }],\n urlEndpoint,\n })\n\n return fetchUploadedFile({\n fileSize: uploadedFile.size,\n fileURL: verifiedFileURL,\n mimeType: uploadedFile.mimeType,\n range: req.headers.get('Range'),\n })\n }\n\n const doc =\n args.doc ||\n (await findUploadDocumentByFilename({\n collection: args.params.collection,\n filename: args.params.filename,\n prefix: args.params.prefix,\n req,\n }))\n\n const storageFilePath = await getStorageFilePath({\n collection,\n collectionPrefix: prefix,\n doc: doc || undefined,\n filename: args.params.filename,\n prefixQueryParam: args.params.prefix,\n req,\n })\n const imageKitPath = `/${storageFilePath.replace(/^\\/+/, '')}`\n const mimeType = (doc as { mimeType?: string } | null)?.mimeType\n\n // XML-family uploads (including SVG) must pass through Payload so its CSP is\n // present even when ImageKit uses a custom, same-origin delivery domain.\n if (typeof mimeType === 'string' && isXmlMimeType(mimeType)) {\n const filesize = (doc as { filesize?: number } | null)?.filesize\n\n if (typeof filesize !== 'number' || !Number.isSafeInteger(filesize) || filesize < 0) {\n throw new APIError('Stored ImageKit file metadata is incomplete.', 500)\n }\n\n const fileURL = isDocumentPrivate(doc, isPrivate)\n ? buildSignedURL(imageKitPath, ORIGINAL_FILE_TRANSFORMATION)\n : client.helper.buildSrc({\n src: imageKitPath,\n transformation: [{ raw: ORIGINAL_FILE_TRANSFORMATION }],\n urlEndpoint,\n })\n\n return fetchUploadedFile({\n fileSize: filesize,\n fileURL,\n mimeType,\n range: req.headers.get('Range'),\n })\n }\n\n // Sign based on the document's stored status, not the collection's current\n // setting, so files keep working if the collection's privacy is changed later.\n if (isDocumentPrivate(doc, isPrivate)) {\n let signSrc = imageKitPath\n\n // A `tr` request for a video/PDF is a thumbnail request (the plain transform\n // can't render a preview); serve ImageKit's generated thumbnail instead.\n if (tr && isVideoMimeType(mimeType)) {\n signSrc = getVideoPosterSrc(signSrc)\n } else if (tr && isPdfMimeType(mimeType)) {\n signSrc = getImageKitThumbnailSrc(signSrc)\n }\n\n return Response.redirect(buildSignedURL(signSrc, tr), 302)\n }\n\n const imageKitURL = client.helper.buildSrc({\n src:\n getStoredImageKitURL(doc) ||\n imageKitPath,\n transformation: tr ? [{ raw: tr }] : undefined,\n urlEndpoint,\n })\n\n return Response.redirect(imageKitURL, 302)\n },\n }\n }\n}\n\nconst toCloudStorageCollections = (\n collections: ImageKitCollectionMap,\n adapter: Adapter,\n privateSlugs: Set<string>,\n rootFolder: string,\n disablePayloadAccessControl?: true,\n): Partial<Record<CollectionSlug, CollectionOptions>> => {\n const mappedCollections: Partial<Record<CollectionSlug, CollectionOptions>> = {}\n\n for (const collectionSlug of Object.keys(collections)) {\n mappedCollections[collectionSlug] = {\n adapter,\n disableLocalStorage: true,\n // Private files require Payload access control so URLs can be signed at serve time.\n disablePayloadAccessControl: privateSlugs.has(collectionSlug)\n ? undefined\n : disablePayloadAccessControl,\n prefix: getCollectionFolder(rootFolder, collectionSlug),\n }\n }\n\n return mappedCollections\n}\n\nexport const imagekitStorage =\n (pluginOptions: PayloadStorageImageKitConfig) =>\n (config: Config): Config => {\n const {\n alwaysInsertFields,\n clientUploads,\n collections,\n disablePayloadAccessControl,\n enabled,\n focalPoint,\n folder,\n privateKey,\n publicKey,\n signedUrlExpiresIn: signedUrlExpiresInOption,\n urlEndpoint,\n } = pluginOptions\n\n if (!privateKey?.trim()) {\n throw new Error('imagekitStorage: `privateKey` is required.')\n }\n\n if (!publicKey?.trim()) {\n throw new Error('imagekitStorage: `publicKey` is required.')\n }\n\n if (!urlEndpoint?.trim()) {\n throw new Error('imagekitStorage: `urlEndpoint` is required.')\n }\n\n if (!collections || Object.keys(collections).length === 0) {\n throw new Error('imagekitStorage: `collections` must include at least one upload collection.')\n }\n\n const privateSlugs = new Set(\n Object.entries(collections)\n .filter(([, value]) => isPrivateCollectionConfig(value))\n .map(([slug]) => slug),\n )\n const configuredSlugs = new Set(Object.keys(collections))\n\n if (disablePayloadAccessControl && privateSlugs.size > 0) {\n throw new Error(\n 'imagekitStorage: `disablePayloadAccessControl` cannot be used with private collections. Private files require Payload access control to remain enabled so URLs can be signed at serve time.',\n )\n }\n\n if (disablePayloadAccessControl) {\n const xmlCollectionSlugs = (config.collections || [])\n .filter(\n (collection) =>\n configuredSlugs.has(collection.slug) && collectionCanStoreXml(collection),\n )\n .map((collection) => collection.slug)\n\n if (xmlCollectionSlugs.length > 0) {\n throw new Error(\n `imagekitStorage: \\`disablePayloadAccessControl\\` cannot be used with collections that can store XML-family files (${xmlCollectionSlugs.join(', ')}). XML-family files require Payload's file route so its Content Security Policy is applied. Configure a MIME allow list that excludes SVG/XML, or keep Payload access control enabled.`,\n )\n }\n }\n\n const signedUrlExpiresIn =\n typeof signedUrlExpiresInOption === 'number' && signedUrlExpiresInOption > 0\n ? signedUrlExpiresInOption\n : DEFAULT_SIGNED_URL_EXPIRES_IN\n const apiRoute = config.routes?.api ?? '/api'\n\n const rootFolder = normalizeFolder(folder)\n\n const imageKitClient = new ImageKit({ privateKey })\n const collectionSecurity = Object.fromEntries(\n (config.collections || [])\n .filter((collection) => configuredSlugs.has(collection.slug))\n .map((collection) => [\n collection.slug,\n {\n collection,\n isPrivate: privateSlugs.has(collection.slug),\n prefix: getCollectionFolder(rootFolder, collection.slug),\n },\n ]),\n )\n const verifyClientUpload = createImageKitClientUploadVerifier({\n client: imageKitClient,\n collections: collectionSecurity,\n })\n const adapter = imagekitAdapter({\n apiRoute,\n client: imageKitClient,\n clientUploads,\n privateSlugs,\n rootFolder,\n signedUrlExpiresIn,\n urlEndpoint,\n verifyClientUpload,\n })\n\n const configWithCropDisabled: Config = {\n ...config,\n collections: (config.collections || []).map((collection) => {\n if (!configuredSlugs.has(collection.slug)) {\n return collection\n }\n\n const isCollectionPrivate = privateSlugs.has(collection.slug)\n const buildThumbnailURL = (doc: unknown): string =>\n isDocumentPrivate(doc, isCollectionPrivate)\n ? getPrivateAdminThumbnailURL(doc, collection.slug, apiRoute)\n : getAdminThumbnailURL(doc)\n\n const collectionOptions = collections[collection.slug]\n const collectionFocalPoint =\n collectionOptions !== true &&\n typeof collectionOptions === 'object' &&\n typeof collectionOptions.focalPoint === 'boolean'\n ? collectionOptions.focalPoint\n : undefined\n\n // Surface a \"this is a private collection\" note in the list and edit views.\n // Preserve an existing string description by appending; leave custom\n // component descriptions untouched.\n const existingDescription = collection.admin?.description\n const baseAdmin = isCollectionPrivate\n ? {\n ...(collection.admin || {}),\n description:\n typeof existingDescription === 'string' && existingDescription.trim().length > 0\n ? `${existingDescription} ${PRIVATE_COLLECTION_DESCRIPTION}`\n : (existingDescription ?? PRIVATE_COLLECTION_DESCRIPTION),\n }\n : collection.admin\n\n return {\n ...collection,\n admin: baseAdmin,\n hooks: {\n ...(collection.hooks || {}),\n beforeChange: [\n ...(collection.hooks?.beforeChange || []),\n async ({ data, req }) => {\n if (!isRecord(data) || !req.file?.clientUploadContext) {\n return data\n }\n\n const context = req.file.clientUploadContext\n const requestMimeType = req.file.mimetype.split(';', 1)[0]?.trim().toLowerCase()\n if (\n !isImageKitReceiptContext(context) ||\n context.filename !== data.filename ||\n context.filename !== req.file.name ||\n // Payload can clear req.file.size when preparing an in-memory image.\n // generateFileData preserves the original size on the document.\n context.expectedSize !== data.filesize\n ) {\n throw new APIError('ImageKit client upload reference does not match this request.', 400)\n }\n\n const uploaded = await verifyClientUpload({\n collectionSlug: collection.slug,\n context,\n })\n // Payload keeps the browser's MIME unless it fetched the file content, in which\n // case it uses the verified ImageKit-detected type the static handler served.\n if (\n requestMimeType !== context.expectedMimeType &&\n requestMimeType !== uploaded.mimeType\n ) {\n throw new APIError('ImageKit client upload reference does not match this request.', 400)\n }\n // A provider file can only be claimed once, including through legacy receipts.\n // The unique file ID index also rejects concurrent claims.\n const existing = await req.payload.db.findOne({\n collection: collection.slug,\n req,\n where: {\n 'imagekit.fileId': {\n equals: uploaded.fileId,\n },\n },\n })\n if (existing) {\n throw new APIError('This ImageKit client upload receipt has already been used.', 400)\n }\n\n data.filename = uploaded.name\n data.filesize = uploaded.size\n data.mimeType = uploaded.mimeType\n\n return applyVerifiedClientUploadToData(\n data,\n uploaded,\n buildThumbnailURL,\n isCollectionPrivate,\n )\n },\n ],\n beforeOperation: [\n ...(collection.hooks?.beforeOperation || []),\n ({ args, operation, req }) => {\n if (\n (operation !== 'create' && operation !== 'update') ||\n req.context?.skipCloudStorage ||\n !req.file ||\n req.file.clientUploadContext ||\n !('data' in args) ||\n !isRecord(args.data) ||\n typeof args.data.prefix !== 'string'\n ) {\n return args\n }\n\n // Payload checks filename uniqueness before cloud storage's beforeChange\n // normalizes the prefix. Use the persisted form during that lookup too.\n args.data.prefix = buildUploadStoragePathData({\n collectionPrefix: getCollectionFolder(rootFolder, collection.slug),\n docPrefix: args.data.prefix,\n filename: req.file.name,\n }).sanitizedDocPrefix\n return args\n },\n ],\n },\n upload: {\n // Focal points are opt-in for configured collections. Plugin-level\n // and collection-level options can override this default; a\n // collection's own `upload.focalPoint` still wins because it is\n // spread in afterwards.\n focalPoint: false,\n ...(typeof focalPoint === 'boolean' ? { focalPoint } : {}),\n ...(typeof collectionFocalPoint === 'boolean'\n ? { focalPoint: collectionFocalPoint }\n : {}),\n ...(typeof collection.upload === 'object' ? collection.upload : {}),\n adminThumbnail: ({ doc }) => buildThumbnailURL(doc),\n crop: false,\n },\n }\n }),\n }\n\n const uploadCollections = Object.fromEntries(\n Object.keys(collections).map((collectionSlug) => [\n collectionSlug,\n {\n isPrivate: privateSlugs.has(collectionSlug),\n prefix: getCollectionFolder(rootFolder, collectionSlug),\n },\n ]),\n ) as Partial<\n Record<UploadCollectionSlug, { isPrivate: boolean; prefix: string }>\n >\n\n initClientUploads({\n clientHandler: '@humaan/payload-storage-imagekit/client#ImageKitUploadHandler',\n collections: uploadCollections,\n config: configWithCropDisabled,\n enabled: enabled !== false && Boolean(clientUploads),\n serverHandler: createImageKitUploadAuthHandler({\n access: typeof clientUploads === 'object' ? clientUploads.access : undefined,\n collections: uploadCollections,\n privateKey,\n publicKey,\n verifyClientUpload,\n }),\n serverHandlerPath: imageKitUploadAuthPath,\n })\n\n const output = cloudStoragePlugin({\n alwaysInsertFields,\n collections: toCloudStorageCollections(\n collections,\n adapter,\n privateSlugs,\n rootFolder,\n disablePayloadAccessControl,\n ),\n enabled,\n })(configWithCropDisabled)\n\n // Make the provider identity unique at persistence time to reject concurrent receipt replays.\n // Keep the legacy object key index for existing uploads.\n output.collections = (output.collections || []).map((collection) => {\n if (!configuredSlugs.has(collection.slug)) {\n return collection\n }\n\n const originalPrefixField = (config.collections || [])\n .find((original) => original.slug === collection.slug)\n ?.fields.find((field) => 'name' in field && field.name === 'prefix')\n\n const withUniqueIdentity = (field: Field): Field => {\n if (\n field.type === 'text' &&\n 'name' in field &&\n field.name === 'prefix' &&\n (!originalPrefixField ||\n !('defaultValue' in originalPrefixField) ||\n originalPrefixField.defaultValue == null)\n ) {\n // Cloud storage's collection-prefix default is applied on reads of old\n // documents that have no stored prefix. Its URL hook then appends that\n // prefix, but Payload's file access check cannot find it in the DB.\n // Upload hooks still persist the collection prefix for new files.\n return {\n ...field,\n defaultValue: ({ req }) =>\n req.file && typeof field.defaultValue === 'string' ? field.defaultValue : '',\n }\n }\n if ('name' in field && field.name === '_objectKey') {\n return { ...field, unique: true } as Field\n }\n if (field.type === 'group' && 'name' in field && field.name === 'imagekit') {\n return {\n ...field,\n fields: field.fields.map((metadataField) =>\n 'name' in metadataField && metadataField.name === 'fileId'\n ? { ...metadataField, unique: true }\n : metadataField,\n ),\n }\n }\n // The imagekit group sits inside the adapter's presentational \"Storage: ImageKit\" panel.\n if (field.type === 'collapsible') {\n return { ...field, fields: field.fields.map(withUniqueIdentity) }\n }\n return field\n }\n\n return {\n ...collection,\n fields: collection.fields.map(withUniqueIdentity),\n }\n })\n\n return output\n }\n\nexport { migrateFolder } from './migrate.js'\nexport type { MigrateFolderOptions, MigrationJobResult, MigrationLocation } from './migrate.js'\n\n// Backward-compatible alias\nexport const payloadStorageImagekit = imagekitStorage\nexport const payloadStorageImageKit = imagekitStorage\n\nexport type PayloadStorageImagekitConfig = PayloadStorageImageKitConfig\n"],"names":["ImageKit","toFile","cloudStoragePlugin","buildStoragePathData","buildUploadStoragePathData","getStorageFilePath","initClientUploads","openAsBlob","path","APIError","getRangeRequestInfo","isXmlMimeType","UPLOAD_CONTENT_SECURITY_POLICY","validateMimeType","imageKitUploadAuthPath","isImageKitReceiptContext","createImageKitClientUploadVerifier","getClientUploadStorageFilePath","createImageKitUploadAuthHandler","getAdminThumbnailURL","getPrivateAdminThumbnailURL","isPdfMimeType","isVideoMimeType","getImageKitThumbnailSrc","getVideoPosterSrc","DEFAULT_SIGNED_URL_EXPIRES_IN","ORIGINAL_FILE_TRANSFORMATION","PRIVATE_COLLECTION_DESCRIPTION","isPrivateCollectionConfig","value","private","XML_FAMILY_MIME_TYPES","collectionCanStoreXml","collection","upload","Boolean","allowRestrictedFileTypes","allowedMimeTypes","mimeTypes","length","some","mimeType","includes","isDocumentPrivate","doc","collectionIsPrivate","stored","imagekit","isPrivate","normalizeFolder","folder","normalized","trim","replace","Error","getCollectionFolder","rootFolder","collectionSlug","posix","join","findImageKitFileId","filePath","parentPath","dirname","name","basename","limit","skip","assets","list","type","found","find","asset","fileId","undefined","isRecord","getStoredImageKitURL","storedURL","url","hasStoredImageKitURL","findUploadDocumentByFilename","filename","prefix","req","constraints","equals","push","payload","db","findOne","where","and","applyVerifiedClientUploadToData","data","uploaded","buildThumbnailURL","thumbnailUrl","thumbnailURL","imagekitAdapter","apiRoute","client","clientUploads","privateSlugs","signedUrlExpiresIn","urlEndpoint","verifyClientUpload","fetchUploadedFile","fileSize","fileURL","range","rangeResult","rangeHeader","Response","headers","Headers","status","normalizedRange","rangeStart","rangeEnd","response","fetch","cache","Range","signal","AbortController","ok","body","cancel","catch","upstreamLength","get","expectedLength","upstreamRange","expectedRange","set","slug","has","buildSignedURL","src","tr","helper","buildSrc","expiresIn","signed","transformation","raw","fields","admin","condition","initCollapsed","disableListColumn","disableListFilter","hidden","readOnly","label","_data","siblingData","description","hooks","afterRead","source","documentPrefix","_objectKey","storageFilePath","collectionPrefix","docPrefix","virtual","interfaceName","generateURL","handleDelete","storedFileId","files","delete","handleUpload","clientUploadContext","file","context","uploadSource","tempFilePath","buffer","uploadFile","uploadFolder","uploadFilename","fileName","useUniqueFileName","isPrivateFile","requiresClientUploadReceipt","staticHandler","args","requestURL","URL","searchParams","hasClientUploadContext","params","uploadedFile","expectedFilePath","verifiedFileURL","size","prefixQueryParam","imageKitPath","filesize","Number","isSafeInteger","signSrc","redirect","imageKitURL","toCloudStorageCollections","collections","adapter","disablePayloadAccessControl","mappedCollections","Object","keys","disableLocalStorage","imagekitStorage","pluginOptions","config","alwaysInsertFields","enabled","focalPoint","privateKey","publicKey","signedUrlExpiresInOption","Set","entries","filter","map","configuredSlugs","xmlCollectionSlugs","routes","api","imageKitClient","collectionSecurity","fromEntries","configWithCropDisabled","isCollectionPrivate","collectionOptions","collectionFocalPoint","existingDescription","baseAdmin","beforeChange","requestMimeType","mimetype","split","toLowerCase","expectedSize","expectedMimeType","existing","beforeOperation","operation","skipCloudStorage","sanitizedDocPrefix","adminThumbnail","crop","uploadCollections","clientHandler","serverHandler","access","serverHandlerPath","output","originalPrefixField","original","field","withUniqueIdentity","defaultValue","unique","metadataField","migrateFolder","payloadStorageImagekit","payloadStorageImageKit"],"mappings":"AAgBA,OAAOA,YAAYC,MAAM,QAAQ,mBAAkB;AACnD,SAASC,kBAAkB,QAAQ,mCAAkC;AACrE,SACEC,oBAAoB,EACpBC,0BAA0B,EAC1BC,kBAAkB,EAClBC,iBAAiB,QACZ,6CAA4C;AACnD,SAASC,UAAU,QAAQ,UAAS;AACpC,OAAOC,UAAU,YAAW;AAC5B,SAASC,QAAQ,QAAQ,UAAS;AAClC,SACEC,mBAAmB,EACnBC,aAAa,EACbC,8BAA8B,QACzB,mBAAkB;AACzB,SAASC,gBAAgB,QAAQ,iBAAgB;AAIjD,SAASC,sBAAsB,EAAEC,wBAAwB,QAAQ,qBAAoB;AACrF,SACEC,kCAAkC,EAClCC,8BAA8B,QACzB,gCAA+B;AACtC,SAASC,+BAA+B,QAAQ,iDAAgD;AAChG,SACEC,oBAAoB,EACpBC,2BAA2B,EAC3BC,aAAa,EACbC,eAAe,QACV,4BAA2B;AAClC,SAASC,uBAAuB,EAAEC,iBAAiB,QAAQ,uBAAsB;AAiBjF,MAAMC,gCAAgC;AACtC;;;;;;;CAOC,GACD,MAAMC,+BAA+B;AAErC,MAAMC,iCACJ;AAEF,MAAMC,4BAA4B,CAACC,QACjCA,UAAU,QAAQ,OAAOA,UAAU,YAAYA,OAAOC,YAAY;AAEpE,MAAMC,wBAAwB;IAAC;IAAmB;IAAiB;CAAW;AAE9E,MAAMC,wBAAwB,CAACC;IAC7B,MAAMC,SAASD,WAAWC,MAAM;IAEhC,IAAI,CAACA,UAAUA,WAAW,MAAM;QAC9B,OAAOC,QAAQD;IACjB;IAEA,iFAAiF;IACjF,IAAIA,OAAOE,wBAAwB,EAAE;QACnC,OAAO;IACT;IAEA,MAAMC,mBAAmBH,OAAOI,SAAS;IAEzC,OACE,CAACD,kBAAkBE,UACnBF,iBAAiBG,IAAI,CAAC,CAACC,WAAaA,SAASC,QAAQ,CAAC,QAAQ/B,cAAc8B,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ACtCA,oBAAoBI,YAAY,IAAI,IAAG,GACzC;oBACA,uEAAuE;oBACvE,uEAAuE;oBACvE,oEAAoE;oBACpE,kEAAkE;oBAClE,OAAO;wBACL,GAAGF,KAAK;wBACRE,cAAc,CAAC,EAAErL,GAAG,EAAE,GACpBA,IAAI4F,IAAI,IAAI,OAAOuF,MAAME,YAAY,KAAK,WAAWF,MAAME,YAAY,GAAG;oBAC9E;gBACF;gBACA,IAAI,UAAUF,SAASA,MAAMvM,IAAI,KAAK,cAAc;oBAClD,OAAO;wBAAE,GAAGuM,KAAK;wBAAEG,QAAQ;oBAAK;gBAClC;gBACA,IAAIH,MAAMjM,IAAI,KAAK,WAAW,UAAUiM,SAASA,MAAMvM,IAAI,KAAK,YAAY;oBAC1E,OAAO;wBACL,GAAGuM,KAAK;wBACRpH,QAAQoH,MAAMpH,MAAM,CAACgF,GAAG,CAAC,CAACwC,gBACxB,UAAUA,iBAAiBA,cAAc3M,IAAI,KAAK,WAC9C;gCAAE,GAAG2M,aAAa;gCAAED,QAAQ;4BAAK,IACjCC;oBAER;gBACF;gBACA,yFAAyF;gBACzF,IAAIJ,MAAMjM,IAAI,KAAK,eAAe;oBAChC,OAAO;wBAAE,GAAGiM,KAAK;wBAAEpH,QAAQoH,MAAMpH,MAAM,CAACgF,GAAG,CAACqC;oBAAoB;gBAClE;gBACA,OAAOD;YACT;YAEA,OAAO;gBACL,GAAGtO,UAAU;gBACbkH,QAAQlH,WAAWkH,MAAM,CAACgF,GAAG,CAACqC;YAChC;QACF;QAEA,OAAOJ;IACT,EAAC;AAEH,SAASQ,aAAa,QAAQ,eAAc;AAG5C,4BAA4B;AAC5B,OAAO,MAAMC,yBAAyBtD,gBAAe;AACrD,OAAO,MAAMuD,yBAAyBvD,gBAAe"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n Adapter,\n ClientUploadsConfig,\n CollectionOptions,\n} from '@payloadcms/plugin-cloud-storage/types'\nimport type {\n CollectionConfig,\n CollectionSlug,\n Config,\n Field,\n PayloadRequest,\n TypeWithID,\n UploadCollectionSlug,\n Where,\n} from 'payload'\n\nimport ImageKit, { toFile } from '@imagekit/nodejs'\nimport { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage'\nimport {\n buildStoragePathData,\n buildUploadStoragePathData,\n getStorageFilePath,\n initClientUploads,\n} from '@payloadcms/plugin-cloud-storage/utilities'\nimport { openAsBlob } from 'node:fs'\nimport path from 'node:path'\nimport { APIError } from 'payload'\nimport {\n getRangeRequestInfo,\n isXmlMimeType,\n UPLOAD_CONTENT_SECURITY_POLICY,\n} from 'payload/internal'\nimport { validateMimeType } from 'payload/shared'\n\nimport type { VerifiedImageKitUpload } from './clientUploadVerification.js'\n\nimport { imageKitUploadAuthPath, isImageKitReceiptContext } from './clientUploads.js'\nimport {\n createImageKitClientUploadVerifier,\n getClientUploadStorageFilePath,\n} from './clientUploadVerification.js'\nimport { createImageKitUploadAuthHandler } from './endpoints/createImageKitUploadAuthHandler.js'\nimport { assertWithinFileSizeLimit, isValidFileSizeLimit } from './fileSizeLimit.js'\nimport {\n getAdminThumbnailURL,\n getPrivateAdminThumbnailURL,\n isPdfMimeType,\n isVideoMimeType,\n} from './getAdminThumbnailURL.js'\nimport { getImageKitThumbnailSrc, getVideoPosterSrc } from './imageTransforms.js'\n\nexport type ImageKitCollectionOptions = {\n /**\n * Maximum upload size in bytes for this collection. Applies on top of Payload's\n * `upload.limits.fileSize`, so it can only tighten that limit. Client uploads are\n * rejected before ImageKit authorization; server uploads before they reach ImageKit.\n */\n fileSizeLimit?: number\n /**\n * Override Payload's native focal-point picker (`upload.focalPoint`) for this\n * collection.\n */\n focalPoint?: boolean\n /**\n * Upload files in this collection as ImageKit private files (`isPrivateFile: true`)\n * and deliver them only through short-lived signed URLs, behind Payload access control.\n */\n private?: boolean\n}\ntype ImageKitCollectionConfig = ImageKitCollectionOptions | true\ntype ImageKitCollectionMap = Partial<Record<UploadCollectionSlug, ImageKitCollectionConfig>>\n\nconst DEFAULT_SIGNED_URL_EXPIRES_IN = 900\n/**\n * ImageKit re-encodes some uploads and serves the smaller derivative from the plain\n * delivery URL — a 1.9 MB MP4 can come back as 868 KB. That is exactly what we want\n * for visitors, but not when reading the file back to verify a client upload: the\n * bytes and the byte count would both belong to a file ImageKit's API never reported.\n * `orig-true` asks for the untouched original and does not disable optimisation for\n * anyone else.\n */\nconst ORIGINAL_FILE_TRANSFORMATION = 'orig-true'\n\nconst PRIVATE_COLLECTION_DESCRIPTION =\n 'Files in this collection are uploaded to ImageKit as private files and delivered through short-lived signed URLs.'\n\nconst isPrivateCollectionConfig = (value: ImageKitCollectionConfig | undefined): boolean =>\n value !== true && typeof value === 'object' && value?.private === true\n\nconst getCollectionFileSizeLimit = (\n value: ImageKitCollectionConfig | undefined,\n): number | undefined =>\n value !== true && typeof value === 'object' ? value?.fileSizeLimit : undefined\n\nconst XML_FAMILY_MIME_TYPES = ['application/xml', 'image/svg+xml', 'text/xml']\n\nconst collectionCanStoreXml = (collection: CollectionConfig): boolean => {\n const upload = collection.upload\n\n if (!upload || upload === true) {\n return Boolean(upload)\n }\n\n // Payload skips MIME and content restrictions when this escape hatch is enabled.\n if (upload.allowRestrictedFileTypes) {\n return true\n }\n\n const allowedMimeTypes = upload.mimeTypes\n\n return (\n !allowedMimeTypes?.length ||\n allowedMimeTypes.some((mimeType) => mimeType.includes('*') || isXmlMimeType(mimeType)) ||\n XML_FAMILY_MIME_TYPES.some((mimeType) => validateMimeType(mimeType, allowedMimeTypes))\n )\n}\n\n/**\n * Whether a specific document is private. The flag stored on the document at upload time\n * (`imagekit.isPrivate`) is the source of truth — a file's privacy on ImageKit is fixed\n * when it is uploaded and does not change if the collection's `private` setting changes\n * later. Falls back to the collection setting for documents uploaded before this flag existed.\n */\nconst isDocumentPrivate = (doc: unknown, collectionIsPrivate: boolean): boolean => {\n const stored = (doc as { imagekit?: { isPrivate?: boolean } } | undefined)?.imagekit?.isPrivate\n\n return typeof stored === 'boolean' ? stored : collectionIsPrivate\n}\ntype ImageKitReference = {\n imagekit?: {\n fileId?: string\n isPrivate?: boolean\n thumbnailUrl?: string\n url?: string\n }\n}\n\ntype UploadDocumentData = {\n thumbnailURL?: string\n} & ImageKitReference\n\nexport type PayloadStorageImageKitConfig = {\n alwaysInsertFields?: boolean\n clientUploads?: ClientUploadsConfig\n collections: ImageKitCollectionMap\n disablePayloadAccessControl?: true\n enabled?: boolean\n /**\n * Broad default for Payload's native focal-point picker (`upload.focalPoint`)\n * on every configured collection. Focal points are disabled by default for\n * configured collections, so prefer collection-level `focalPoint: true` for\n * image collections. A collection's own `upload.focalPoint` still takes\n * precedence.\n */\n focalPoint?: boolean\n folder: string\n privateKey: string\n publicKey: string\n /**\n * Expiry (in seconds) applied to signed URLs generated for private collections.\n * Defaults to 900 (15 minutes). URLs are signed fresh on every request, so a short\n * window is safe.\n */\n signedUrlExpiresIn?: number\n urlEndpoint: string\n}\n\nconst normalizeFolder = (folder: string): string => {\n const normalized = folder.trim().replace(/^\\/+|\\/+$/g, '')\n\n if (!normalized) {\n throw new Error('imagekitStorage: `folder` is required.')\n }\n\n return `/${normalized}`\n}\n\nconst getCollectionFolder = (rootFolder: string, collectionSlug: string): string =>\n path.posix.join(rootFolder, collectionSlug)\n\nconst findImageKitFileId = async (\n imagekit: ImageKit,\n filePath: string,\n): Promise<string | undefined> => {\n const parentPath = path.posix.dirname(filePath)\n const name = path.posix.basename(filePath)\n\n const limit = 100\n\n for (let skip = 0; ; skip += limit) {\n const assets = await imagekit.assets.list({\n type: 'file',\n limit,\n path: parentPath === '/' ? '/' : `${parentPath}/`,\n skip,\n })\n\n const found = assets.find(\n (asset) => 'fileId' in asset && asset.filePath === filePath && asset.name === name,\n )\n\n if (found && 'fileId' in found) {\n return found.fileId\n }\n\n if (assets.length < limit) {\n break\n }\n }\n\n return undefined\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === 'object'\n\nconst getStoredImageKitURL = (doc: unknown): string | undefined => {\n const storedURL = (doc as ImageKitReference | undefined)?.imagekit?.url\n\n return typeof storedURL === 'string' && storedURL.trim().length > 0 ? storedURL : undefined\n}\n\nconst hasStoredImageKitURL = (doc: unknown): boolean => !!getStoredImageKitURL(doc)\n\nconst findUploadDocumentByFilename = async ({\n collection,\n filename,\n prefix,\n req,\n}: {\n collection: string\n filename: string\n prefix?: string\n req: PayloadRequest\n}): Promise<null | TypeWithID> => {\n const constraints: Where[] = [\n {\n filename: {\n equals: filename,\n },\n },\n ]\n\n if (typeof prefix === 'string') {\n constraints.push({\n prefix: {\n equals: prefix,\n },\n })\n }\n\n return req.payload.db.findOne({\n collection,\n req,\n where: {\n and: constraints,\n },\n })\n}\n\nconst applyVerifiedClientUploadToData = <T extends UploadDocumentData>(\n data: T,\n uploaded: VerifiedImageKitUpload,\n buildThumbnailURL: (data: T) => string = getAdminThumbnailURL,\n isPrivate: boolean,\n): T => {\n data.imagekit = {\n fileId: uploaded.fileId,\n isPrivate,\n thumbnailUrl: uploaded.thumbnailUrl,\n url: uploaded.url,\n }\n\n // Preserve the admin preview when the original file was already uploaded client-side.\n data.thumbnailURL = buildThumbnailURL(data)\n\n return data\n}\n\nconst imagekitAdapter = ({\n apiRoute,\n client,\n clientUploads,\n privateSlugs,\n rootFolder,\n signedUrlExpiresIn,\n urlEndpoint,\n verifyClientUpload,\n}: {\n apiRoute: string\n client: ImageKit\n clientUploads?: ClientUploadsConfig\n privateSlugs: Set<string>\n rootFolder: string\n signedUrlExpiresIn: number\n urlEndpoint: string\n verifyClientUpload: ReturnType<typeof createImageKitClientUploadVerifier>\n}): Adapter => {\n const fetchUploadedFile = async ({\n fileSize,\n fileURL,\n mimeType,\n range,\n }: {\n fileSize: number\n fileURL: string\n mimeType: string\n range?: null | string\n }): Promise<Response> => {\n const rangeResult = getRangeRequestInfo({ fileSize, rangeHeader: range ?? null })\n\n if (rangeResult.type === 'invalid') {\n return new Response(null, {\n headers: new Headers(rangeResult.headers),\n status: rangeResult.status,\n })\n }\n\n const normalizedRange =\n rangeResult.type === 'partial'\n ? `bytes=${rangeResult.rangeStart}-${rangeResult.rangeEnd}`\n : undefined\n // Payload cancels image probes after reading a bounded prefix. Next.js memoizes\n // GET responses by teeing their streams; cancelling one branch can then wait\n // forever for its unread cached sibling. An explicit signal opts out of that\n // memoization, while no-store also excludes these reads from the data cache.\n const response = await fetch(fileURL, {\n cache: 'no-store',\n ...(normalizedRange ? { headers: { Range: normalizedRange } } : {}),\n signal: new AbortController().signal,\n })\n\n if (!response.ok || response.status !== rangeResult.status) {\n void response.body?.cancel().catch(() => undefined)\n throw new Error(\n `imagekitStorage: ImageKit returned an unexpected file response (${response.status}).`,\n )\n }\n\n const upstreamLength = response.headers.get('Content-Length')\n const expectedLength = rangeResult.headers['Content-Length']\n const upstreamRange = response.headers.get('Content-Range')\n const expectedRange =\n rangeResult.type === 'partial' ? rangeResult.headers['Content-Range'] : undefined\n\n if (\n (upstreamLength !== null && upstreamLength !== expectedLength) ||\n (expectedRange && upstreamRange !== expectedRange)\n ) {\n void response.body?.cancel().catch(() => undefined)\n throw new Error('imagekitStorage: ImageKit returned mismatched file content metadata.')\n }\n\n const headers = new Headers(rangeResult.headers)\n headers.set('Content-Type', mimeType)\n if (isXmlMimeType(mimeType)) {\n headers.set('Content-Security-Policy', UPLOAD_CONTENT_SECURITY_POLICY)\n }\n\n return new Response(response.body, {\n headers,\n status: response.status,\n })\n }\n\n return ({ collection, prefix = getCollectionFolder(rootFolder, collection.slug) }) => {\n const isPrivate = privateSlugs.has(collection.slug)\n\n // Sign a relative ImageKit path against the configured urlEndpoint. We always sign\n // a computed path (never a stored absolute URL) because ImageKit's signature is\n // derived from the path after stripping urlEndpoint, so the host must match.\n const buildSignedURL = (src: string, tr?: null | string): string =>\n client.helper.buildSrc({\n expiresIn: signedUrlExpiresIn,\n signed: true,\n src,\n transformation: tr ? [{ raw: tr }] : undefined,\n urlEndpoint,\n })\n\n const buildThumbnailURL = (doc: UploadDocumentData): string =>\n isDocumentPrivate(doc, isPrivate)\n ? getPrivateAdminThumbnailURL(doc, collection.slug, apiRoute)\n : getAdminThumbnailURL(doc)\n\n return {\n name: 'imagekit',\n clientUploads,\n fields: [\n {\n // Presentational wrapper: tucks the ImageKit details into a closed panel without\n // changing the `imagekit.*` data paths.\n type: 'collapsible',\n admin: {\n condition: (data) => hasStoredImageKitURL(data),\n initCollapsed: true,\n },\n fields: [\n {\n name: 'imagekit',\n type: 'group',\n admin: {\n disableListColumn: true,\n disableListFilter: true,\n },\n fields: [\n {\n name: 'fileId',\n type: 'text',\n admin: {\n hidden: true,\n },\n },\n {\n name: 'url',\n type: 'text',\n admin: {\n readOnly: true,\n },\n label: 'URL',\n },\n {\n name: 'isPrivate',\n type: 'checkbox',\n admin: {\n condition: (_data, siblingData) =>\n isDocumentPrivate({ imagekit: siblingData }, isPrivate),\n description:\n \"Indicates whether this file was uploaded to ImageKit as private. Private files are delivered through signed URLs. Changes to this collection's private option in payload.config only affect future uploads.\",\n readOnly: true,\n },\n label: 'Private file',\n },\n {\n name: 'signedUrl',\n type: 'text',\n admin: {\n // Only relevant for private files; the plain `url` works directly for public ones.\n condition: (_data, siblingData) =>\n isDocumentPrivate({ imagekit: siblingData }, isPrivate),\n description: `Temporary signed URL for reaching this private file directly on ImageKit. Expires ${signedUrlExpiresIn} seconds after load and is regenerated on every read. Note: anyone with this URL can access the file until it expires — it is not gated by Payload access control.`,\n readOnly: true,\n },\n hooks: {\n // Computed server-side on read so it is always freshly signed and never persisted.\n afterRead: [\n ({ data, siblingData }) => {\n if (!isDocumentPrivate({ imagekit: siblingData }, isPrivate)) {\n return undefined\n }\n\n const filename = (data as { filename?: string } | undefined)?.filename\n\n if (!filename) {\n return undefined\n }\n\n const source = (data || {}) as { _objectKey?: string; prefix?: string }\n const documentPrefix = path.posix.join(\n source.prefix || prefix,\n source._objectKey || '',\n )\n const storageFilePath = buildStoragePathData({\n collectionPrefix: prefix,\n docPrefix: documentPrefix,\n filename,\n }).storageFilePath\n\n return buildSignedURL(`/${storageFilePath}`)\n },\n ],\n },\n label: 'Signed URL',\n virtual: true,\n },\n {\n name: 'thumbnailUrl',\n type: 'text',\n admin: {\n hidden: true,\n },\n },\n ],\n interfaceName: 'imagekitFields',\n label: false,\n },\n ],\n label: 'Storage: ImageKit',\n },\n ],\n generateURL: ({ filename, prefix: documentPrefix = '' }) =>\n client.helper.buildSrc({\n src: `/${buildStoragePathData({\n collectionPrefix: prefix,\n docPrefix: documentPrefix,\n filename,\n }).storageFilePath}`,\n urlEndpoint,\n }),\n handleDelete: async ({ doc, storageFilePath }) => {\n const storedFileId = (doc as ImageKitReference & typeof doc).imagekit?.fileId\n const fileId =\n storedFileId || (await findImageKitFileId(client, `/${storageFilePath.replace(/^\\/+/, '')}`))\n\n if (!fileId) {\n return\n }\n\n await client.files.delete(fileId)\n },\n handleUpload: async ({ clientUploadContext, data, file, storageFilePath }) => {\n if (clientUploadContext) {\n const uploaded = await verifyClientUpload({\n collectionSlug: collection.slug,\n context: clientUploadContext,\n })\n\n return applyVerifiedClientUploadToData(data, uploaded, buildThumbnailURL, isPrivate)\n }\n\n // ImageKit's `toFile()` consumes async iterables before starting the request. A file-backed\n // Blob keeps temporary-file uploads lazy so FormData can stream them from disk instead.\n const uploadSource = file.tempFilePath\n ? await openAsBlob(file.tempFilePath, { type: file.mimeType })\n : file.buffer\n const uploadFile = await toFile(uploadSource, file.filename, { type: file.mimeType })\n const uploadFolder = path.posix.dirname(`/${storageFilePath.replace(/^\\/+/, '')}`)\n const uploadFilename = path.posix.basename(storageFilePath)\n\n const uploaded = await client.files.upload({\n file: uploadFile,\n fileName: uploadFilename,\n folder: uploadFolder,\n useUniqueFileName: false,\n ...(isPrivate ? { isPrivateFile: true } : {}),\n })\n\n data.imagekit = {\n fileId: uploaded.fileId,\n isPrivate,\n thumbnailUrl: uploaded.thumbnailUrl,\n url: uploaded.url,\n }\n\n // Set the root-level thumbnailURL that Payload's admin interface expects.\n // `buildThumbnailURL` needs the filename, which Payload may not have copied onto\n // `data` yet at this point, so fall back to the uploaded file's name.\n data.thumbnailURL = buildThumbnailURL({\n ...data,\n filename: (data as { filename?: string }).filename || uploadFilename,\n })\n\n return data\n },\n requiresClientUploadReceipt: true,\n staticHandler: async (req, args) => {\n const requestURL = new URL(req.url || 'http://localhost')\n const tr = requestURL.searchParams.get('tr')\n const hasClientUploadContext = 'clientUploadContext' in args.params\n\n if (hasClientUploadContext) {\n const clientUploadContext = args.params.clientUploadContext\n\n if (!isImageKitReceiptContext(clientUploadContext)) {\n throw new APIError('Invalid ImageKit client upload context.', 400)\n }\n\n const uploadedFile = await verifyClientUpload({\n collectionSlug: collection.slug,\n context: clientUploadContext,\n })\n const expectedFilePath = getClientUploadStorageFilePath({\n collectionPrefix: prefix,\n context: clientUploadContext,\n })\n const verifiedFileURL = isPrivate\n ? buildSignedURL(`/${expectedFilePath}`, ORIGINAL_FILE_TRANSFORMATION)\n : client.helper.buildSrc({\n src: `/${expectedFilePath}`,\n transformation: [{ raw: ORIGINAL_FILE_TRANSFORMATION }],\n urlEndpoint,\n })\n\n return fetchUploadedFile({\n fileSize: uploadedFile.size,\n fileURL: verifiedFileURL,\n mimeType: uploadedFile.mimeType,\n range: req.headers.get('Range'),\n })\n }\n\n const doc =\n args.doc ||\n (await findUploadDocumentByFilename({\n collection: args.params.collection,\n filename: args.params.filename,\n prefix: args.params.prefix,\n req,\n }))\n\n const storageFilePath = await getStorageFilePath({\n collection,\n collectionPrefix: prefix,\n doc: doc || undefined,\n filename: args.params.filename,\n prefixQueryParam: args.params.prefix,\n req,\n })\n const imageKitPath = `/${storageFilePath.replace(/^\\/+/, '')}`\n const mimeType = (doc as { mimeType?: string } | null)?.mimeType\n\n // XML-family uploads (including SVG) must pass through Payload so its CSP is\n // present even when ImageKit uses a custom, same-origin delivery domain.\n if (typeof mimeType === 'string' && isXmlMimeType(mimeType)) {\n const filesize = (doc as { filesize?: number } | null)?.filesize\n\n if (typeof filesize !== 'number' || !Number.isSafeInteger(filesize) || filesize < 0) {\n throw new APIError('Stored ImageKit file metadata is incomplete.', 500)\n }\n\n const fileURL = isDocumentPrivate(doc, isPrivate)\n ? buildSignedURL(imageKitPath, ORIGINAL_FILE_TRANSFORMATION)\n : client.helper.buildSrc({\n src: imageKitPath,\n transformation: [{ raw: ORIGINAL_FILE_TRANSFORMATION }],\n urlEndpoint,\n })\n\n return fetchUploadedFile({\n fileSize: filesize,\n fileURL,\n mimeType,\n range: req.headers.get('Range'),\n })\n }\n\n // Sign based on the document's stored status, not the collection's current\n // setting, so files keep working if the collection's privacy is changed later.\n if (isDocumentPrivate(doc, isPrivate)) {\n let signSrc = imageKitPath\n\n // A `tr` request for a video/PDF is a thumbnail request (the plain transform\n // can't render a preview); serve ImageKit's generated thumbnail instead.\n if (tr && isVideoMimeType(mimeType)) {\n signSrc = getVideoPosterSrc(signSrc)\n } else if (tr && isPdfMimeType(mimeType)) {\n signSrc = getImageKitThumbnailSrc(signSrc)\n }\n\n return Response.redirect(buildSignedURL(signSrc, tr), 302)\n }\n\n const imageKitURL = client.helper.buildSrc({\n src:\n getStoredImageKitURL(doc) ||\n imageKitPath,\n transformation: tr ? [{ raw: tr }] : undefined,\n urlEndpoint,\n })\n\n return Response.redirect(imageKitURL, 302)\n },\n }\n }\n}\n\nconst toCloudStorageCollections = (\n collections: ImageKitCollectionMap,\n adapter: Adapter,\n privateSlugs: Set<string>,\n rootFolder: string,\n disablePayloadAccessControl?: true,\n): Partial<Record<CollectionSlug, CollectionOptions>> => {\n const mappedCollections: Partial<Record<CollectionSlug, CollectionOptions>> = {}\n\n for (const collectionSlug of Object.keys(collections)) {\n mappedCollections[collectionSlug] = {\n adapter,\n disableLocalStorage: true,\n // Private files require Payload access control so URLs can be signed at serve time.\n disablePayloadAccessControl: privateSlugs.has(collectionSlug)\n ? undefined\n : disablePayloadAccessControl,\n prefix: getCollectionFolder(rootFolder, collectionSlug),\n }\n }\n\n return mappedCollections\n}\n\nexport const imagekitStorage =\n (pluginOptions: PayloadStorageImageKitConfig) =>\n (config: Config): Config => {\n const {\n alwaysInsertFields,\n clientUploads,\n collections,\n disablePayloadAccessControl,\n enabled,\n focalPoint,\n folder,\n privateKey,\n publicKey,\n signedUrlExpiresIn: signedUrlExpiresInOption,\n urlEndpoint,\n } = pluginOptions\n\n if (!privateKey?.trim()) {\n throw new Error('imagekitStorage: `privateKey` is required.')\n }\n\n if (!publicKey?.trim()) {\n throw new Error('imagekitStorage: `publicKey` is required.')\n }\n\n if (!urlEndpoint?.trim()) {\n throw new Error('imagekitStorage: `urlEndpoint` is required.')\n }\n\n if (!collections || Object.keys(collections).length === 0) {\n throw new Error('imagekitStorage: `collections` must include at least one upload collection.')\n }\n\n const invalidFileSizeLimitSlugs = Object.entries(collections)\n .filter(([, value]) => {\n const fileSizeLimit = getCollectionFileSizeLimit(value)\n return fileSizeLimit !== undefined && !isValidFileSizeLimit(fileSizeLimit)\n })\n .map(([slug]) => slug)\n\n if (invalidFileSizeLimitSlugs.length > 0) {\n throw new Error(\n `imagekitStorage: \\`fileSizeLimit\\` must be a positive integer number of bytes (${invalidFileSizeLimitSlugs.join(', ')}).`,\n )\n }\n\n const privateSlugs = new Set(\n Object.entries(collections)\n .filter(([, value]) => isPrivateCollectionConfig(value))\n .map(([slug]) => slug),\n )\n const configuredSlugs = new Set(Object.keys(collections))\n\n if (disablePayloadAccessControl && privateSlugs.size > 0) {\n throw new Error(\n 'imagekitStorage: `disablePayloadAccessControl` cannot be used with private collections. Private files require Payload access control to remain enabled so URLs can be signed at serve time.',\n )\n }\n\n if (disablePayloadAccessControl) {\n const xmlCollectionSlugs = (config.collections || [])\n .filter(\n (collection) =>\n configuredSlugs.has(collection.slug) && collectionCanStoreXml(collection),\n )\n .map((collection) => collection.slug)\n\n if (xmlCollectionSlugs.length > 0) {\n throw new Error(\n `imagekitStorage: \\`disablePayloadAccessControl\\` cannot be used with collections that can store XML-family files (${xmlCollectionSlugs.join(', ')}). XML-family files require Payload's file route so its Content Security Policy is applied. Configure a MIME allow list that excludes SVG/XML, or keep Payload access control enabled.`,\n )\n }\n }\n\n const signedUrlExpiresIn =\n typeof signedUrlExpiresInOption === 'number' && signedUrlExpiresInOption > 0\n ? signedUrlExpiresInOption\n : DEFAULT_SIGNED_URL_EXPIRES_IN\n const apiRoute = config.routes?.api ?? '/api'\n\n const rootFolder = normalizeFolder(folder)\n\n const imageKitClient = new ImageKit({ privateKey })\n const collectionSecurity = Object.fromEntries(\n (config.collections || [])\n .filter((collection) => configuredSlugs.has(collection.slug))\n .map((collection) => [\n collection.slug,\n {\n collection,\n isPrivate: privateSlugs.has(collection.slug),\n prefix: getCollectionFolder(rootFolder, collection.slug),\n },\n ]),\n )\n const verifyClientUpload = createImageKitClientUploadVerifier({\n client: imageKitClient,\n collections: collectionSecurity,\n })\n const adapter = imagekitAdapter({\n apiRoute,\n client: imageKitClient,\n clientUploads,\n privateSlugs,\n rootFolder,\n signedUrlExpiresIn,\n urlEndpoint,\n verifyClientUpload,\n })\n\n const configWithCropDisabled: Config = {\n ...config,\n collections: (config.collections || []).map((collection) => {\n if (!configuredSlugs.has(collection.slug)) {\n return collection\n }\n\n const isCollectionPrivate = privateSlugs.has(collection.slug)\n const buildThumbnailURL = (doc: unknown): string =>\n isDocumentPrivate(doc, isCollectionPrivate)\n ? getPrivateAdminThumbnailURL(doc, collection.slug, apiRoute)\n : getAdminThumbnailURL(doc)\n\n const collectionOptions = collections[collection.slug]\n const collectionFileSizeLimit = getCollectionFileSizeLimit(collectionOptions)\n const collectionFocalPoint =\n collectionOptions !== true &&\n typeof collectionOptions === 'object' &&\n typeof collectionOptions.focalPoint === 'boolean'\n ? collectionOptions.focalPoint\n : undefined\n\n // Surface a \"this is a private collection\" note in the list and edit views.\n // Preserve an existing string description by appending; leave custom\n // component descriptions untouched.\n const existingDescription = collection.admin?.description\n const baseAdmin = isCollectionPrivate\n ? {\n ...(collection.admin || {}),\n description:\n typeof existingDescription === 'string' && existingDescription.trim().length > 0\n ? `${existingDescription} ${PRIVATE_COLLECTION_DESCRIPTION}`\n : (existingDescription ?? PRIVATE_COLLECTION_DESCRIPTION),\n }\n : collection.admin\n\n return {\n ...collection,\n admin: baseAdmin,\n hooks: {\n ...(collection.hooks || {}),\n beforeChange: [\n ...(collection.hooks?.beforeChange || []),\n async ({ data, req }) => {\n if (!isRecord(data) || !req.file?.clientUploadContext) {\n return data\n }\n\n const context = req.file.clientUploadContext\n const requestMimeType = req.file.mimetype.split(';', 1)[0]?.trim().toLowerCase()\n if (\n !isImageKitReceiptContext(context) ||\n context.filename !== data.filename ||\n context.filename !== req.file.name ||\n // Payload can clear req.file.size when preparing an in-memory image.\n // generateFileData preserves the original size on the document.\n context.expectedSize !== data.filesize\n ) {\n throw new APIError('ImageKit client upload reference does not match this request.', 400)\n }\n\n const uploaded = await verifyClientUpload({\n collectionSlug: collection.slug,\n context,\n })\n // Payload keeps the browser's MIME unless it fetched the file content, in which\n // case it uses the verified ImageKit-detected type the static handler served.\n if (\n requestMimeType !== context.expectedMimeType &&\n requestMimeType !== uploaded.mimeType\n ) {\n throw new APIError('ImageKit client upload reference does not match this request.', 400)\n }\n // A provider file can only be claimed once, including through legacy receipts.\n // The unique file ID index also rejects concurrent claims.\n const existing = await req.payload.db.findOne({\n collection: collection.slug,\n req,\n where: {\n 'imagekit.fileId': {\n equals: uploaded.fileId,\n },\n },\n })\n if (existing) {\n throw new APIError('This ImageKit client upload receipt has already been used.', 400)\n }\n\n data.filename = uploaded.name\n data.filesize = uploaded.size\n data.mimeType = uploaded.mimeType\n\n return applyVerifiedClientUploadToData(\n data,\n uploaded,\n buildThumbnailURL,\n isCollectionPrivate,\n )\n },\n ],\n beforeOperation: [\n ...(collection.hooks?.beforeOperation || []),\n ({ args, operation, req }) => {\n // Client uploads are checked when ImageKit authorization is requested, and\n // their verified size is bound to that authorization.\n if (\n (operation === 'create' || operation === 'update') &&\n req.file &&\n !req.file.clientUploadContext\n ) {\n assertWithinFileSizeLimit(req.file.size, collectionFileSizeLimit)\n }\n return args\n },\n ({ args, operation, req }) => {\n if (\n (operation !== 'create' && operation !== 'update') ||\n req.context?.skipCloudStorage ||\n !req.file ||\n req.file.clientUploadContext ||\n !('data' in args) ||\n !isRecord(args.data) ||\n typeof args.data.prefix !== 'string'\n ) {\n return args\n }\n\n // Payload checks filename uniqueness before cloud storage's beforeChange\n // normalizes the prefix. Use the persisted form during that lookup too.\n args.data.prefix = buildUploadStoragePathData({\n collectionPrefix: getCollectionFolder(rootFolder, collection.slug),\n docPrefix: args.data.prefix,\n filename: req.file.name,\n }).sanitizedDocPrefix\n return args\n },\n ],\n },\n upload: {\n // Focal points are opt-in for configured collections. Plugin-level\n // and collection-level options can override this default; a\n // collection's own `upload.focalPoint` still wins because it is\n // spread in afterwards.\n focalPoint: false,\n ...(typeof focalPoint === 'boolean' ? { focalPoint } : {}),\n ...(typeof collectionFocalPoint === 'boolean'\n ? { focalPoint: collectionFocalPoint }\n : {}),\n ...(typeof collection.upload === 'object' ? collection.upload : {}),\n adminThumbnail: ({ doc }) => buildThumbnailURL(doc),\n crop: false,\n },\n }\n }),\n }\n\n const uploadCollections = Object.fromEntries(\n Object.keys(collections).map((collectionSlug) => [\n collectionSlug,\n {\n fileSizeLimit: getCollectionFileSizeLimit(collections[collectionSlug]),\n isPrivate: privateSlugs.has(collectionSlug),\n prefix: getCollectionFolder(rootFolder, collectionSlug),\n },\n ]),\n ) as Partial<\n Record<UploadCollectionSlug, { fileSizeLimit?: number; isPrivate: boolean; prefix: string }>\n >\n\n initClientUploads({\n clientHandler: '@humaan/payload-storage-imagekit/client#ImageKitUploadHandler',\n collections: uploadCollections,\n config: configWithCropDisabled,\n enabled: enabled !== false && Boolean(clientUploads),\n serverHandler: createImageKitUploadAuthHandler({\n access: typeof clientUploads === 'object' ? clientUploads.access : undefined,\n collections: uploadCollections,\n privateKey,\n publicKey,\n verifyClientUpload,\n }),\n serverHandlerPath: imageKitUploadAuthPath,\n })\n\n const output = cloudStoragePlugin({\n alwaysInsertFields,\n collections: toCloudStorageCollections(\n collections,\n adapter,\n privateSlugs,\n rootFolder,\n disablePayloadAccessControl,\n ),\n enabled,\n })(configWithCropDisabled)\n\n // Make the provider identity unique at persistence time to reject concurrent receipt replays.\n // Keep the legacy object key index for existing uploads.\n output.collections = (output.collections || []).map((collection) => {\n if (!configuredSlugs.has(collection.slug)) {\n return collection\n }\n\n const originalPrefixField = (config.collections || [])\n .find((original) => original.slug === collection.slug)\n ?.fields.find((field) => 'name' in field && field.name === 'prefix')\n\n const withUniqueIdentity = (field: Field): Field => {\n if (\n field.type === 'text' &&\n 'name' in field &&\n field.name === 'prefix' &&\n (!originalPrefixField ||\n !('defaultValue' in originalPrefixField) ||\n originalPrefixField.defaultValue == null)\n ) {\n // Cloud storage's collection-prefix default is applied on reads of old\n // documents that have no stored prefix. Its URL hook then appends that\n // prefix, but Payload's file access check cannot find it in the DB.\n // Upload hooks still persist the collection prefix for new files.\n return {\n ...field,\n defaultValue: ({ req }) =>\n req.file && typeof field.defaultValue === 'string' ? field.defaultValue : '',\n }\n }\n if ('name' in field && field.name === '_objectKey') {\n return { ...field, unique: true } as Field\n }\n if (field.type === 'group' && 'name' in field && field.name === 'imagekit') {\n return {\n ...field,\n fields: field.fields.map((metadataField) =>\n 'name' in metadataField && metadataField.name === 'fileId'\n ? { ...metadataField, unique: true }\n : metadataField,\n ),\n }\n }\n // The imagekit group sits inside the adapter's presentational \"Storage: ImageKit\" panel.\n if (field.type === 'collapsible') {\n return { ...field, fields: field.fields.map(withUniqueIdentity) }\n }\n return field\n }\n\n return {\n ...collection,\n fields: collection.fields.map(withUniqueIdentity),\n }\n })\n\n return output\n }\n\nexport { migrateFolder } from './migrate.js'\nexport type { MigrateFolderOptions, MigrationJobResult, MigrationLocation } from './migrate.js'\n\n// Backward-compatible alias\nexport const payloadStorageImagekit = imagekitStorage\nexport const payloadStorageImageKit = imagekitStorage\n\nexport type PayloadStorageImagekitConfig = PayloadStorageImageKitConfig\n"],"names":["ImageKit","toFile","cloudStoragePlugin","buildStoragePathData","buildUploadStoragePathData","getStorageFilePath","initClientUploads","openAsBlob","path","APIError","getRangeRequestInfo","isXmlMimeType","UPLOAD_CONTENT_SECURITY_POLICY","validateMimeType","imageKitUploadAuthPath","isImageKitReceiptContext","createImageKitClientUploadVerifier","getClientUploadStorageFilePath","createImageKitUploadAuthHandler","assertWithinFileSizeLimit","isValidFileSizeLimit","getAdminThumbnailURL","getPrivateAdminThumbnailURL","isPdfMimeType","isVideoMimeType","getImageKitThumbnailSrc","getVideoPosterSrc","DEFAULT_SIGNED_URL_EXPIRES_IN","ORIGINAL_FILE_TRANSFORMATION","PRIVATE_COLLECTION_DESCRIPTION","isPrivateCollectionConfig","value","private","getCollectionFileSizeLimit","fileSizeLimit","undefined","XML_FAMILY_MIME_TYPES","collectionCanStoreXml","collection","upload","Boolean","allowRestrictedFileTypes","allowedMimeTypes","mimeTypes","length","some","mimeType","includes","isDocumentPrivate","doc","collectionIsPrivate","stored","imagekit","isPrivate","normalizeFolder","folder","normalized","trim","replace","Error","getCollectionFolder","rootFolder","collectionSlug","posix","join","findImageKitFileId","filePath","parentPath","dirname","name","basename","limit","skip","assets","list","type","found","find","asset","fileId","isRecord","getStoredImageKitURL","storedURL","url","hasStoredImageKitURL","findUploadDocumentByFilename","filename","prefix","req","constraints","equals","push","payload","db","findOne","where","and","applyVerifiedClientUploadToData","data","uploaded","buildThumbnailURL","thumbnailUrl","thumbnailURL","imagekitAdapter","apiRoute","client","clientUploads","privateSlugs","signedUrlExpiresIn","urlEndpoint","verifyClientUpload","fetchUploadedFile","fileSize","fileURL","range","rangeResult","rangeHeader","Response","headers","Headers","status","normalizedRange","rangeStart","rangeEnd","response","fetch","cache","Range","signal","AbortController","ok","body","cancel","catch","upstreamLength","get","expectedLength","upstreamRange","expectedRange","set","slug","has","buildSignedURL","src","tr","helper","buildSrc","expiresIn","signed","transformation","raw","fields","admin","condition","initCollapsed","disableListColumn","disableListFilter","hidden","readOnly","label","_data","siblingData","description","hooks","afterRead","source","documentPrefix","_objectKey","storageFilePath","collectionPrefix","docPrefix","virtual","interfaceName","generateURL","handleDelete","storedFileId","files","delete","handleUpload","clientUploadContext","file","context","uploadSource","tempFilePath","buffer","uploadFile","uploadFolder","uploadFilename","fileName","useUniqueFileName","isPrivateFile","requiresClientUploadReceipt","staticHandler","args","requestURL","URL","searchParams","hasClientUploadContext","params","uploadedFile","expectedFilePath","verifiedFileURL","size","prefixQueryParam","imageKitPath","filesize","Number","isSafeInteger","signSrc","redirect","imageKitURL","toCloudStorageCollections","collections","adapter","disablePayloadAccessControl","mappedCollections","Object","keys","disableLocalStorage","imagekitStorage","pluginOptions","config","alwaysInsertFields","enabled","focalPoint","privateKey","publicKey","signedUrlExpiresInOption","invalidFileSizeLimitSlugs","entries","filter","map","Set","configuredSlugs","xmlCollectionSlugs","routes","api","imageKitClient","collectionSecurity","fromEntries","configWithCropDisabled","isCollectionPrivate","collectionOptions","collectionFileSizeLimit","collectionFocalPoint","existingDescription","baseAdmin","beforeChange","requestMimeType","mimetype","split","toLowerCase","expectedSize","expectedMimeType","existing","beforeOperation","operation","skipCloudStorage","sanitizedDocPrefix","adminThumbnail","crop","uploadCollections","clientHandler","serverHandler","access","serverHandlerPath","output","originalPrefixField","original","field","withUniqueIdentity","defaultValue","unique","metadataField","migrateFolder","payloadStorageImagekit","payloadStorageImageKit"],"mappings":"AAgBA,OAAOA,YAAYC,MAAM,QAAQ,mBAAkB;AACnD,SAASC,kBAAkB,QAAQ,mCAAkC;AACrE,SACEC,oBAAoB,EACpBC,0BAA0B,EAC1BC,kBAAkB,EAClBC,iBAAiB,QACZ,6CAA4C;AACnD,SAASC,UAAU,QAAQ,UAAS;AACpC,OAAOC,UAAU,YAAW;AAC5B,SAASC,QAAQ,QAAQ,UAAS;AAClC,SACEC,mBAAmB,EACnBC,aAAa,EACbC,8BAA8B,QACzB,mBAAkB;AACzB,SAASC,gBAAgB,QAAQ,iBAAgB;AAIjD,SAASC,sBAAsB,EAAEC,w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CAACgF,GAAG,CAACuC;oBAAoB;gBAClE;gBACA,OAAOD;YACT;YAEA,OAAO;gBACL,GAAGvO,UAAU;gBACbiH,QAAQjH,WAAWiH,MAAM,CAACgF,GAAG,CAACuC;YAChC;QACF;QAEA,OAAOJ;IACT,EAAC;AAEH,SAASQ,aAAa,QAAQ,eAAc;AAG5C,4BAA4B;AAC5B,OAAO,MAAMC,yBAAyBxD,gBAAe;AACrD,OAAO,MAAMyD,yBAAyBzD,gBAAe"}
package/dist/migrate.js CHANGED
@@ -227,20 +227,40 @@ const transferTag = (source, filePath, documentID, isPrivate)=>{
227
227
  filename: destination.name,
228
228
  imagekit
229
229
  };
230
- await payload.update({
231
- id: doc.id,
232
- collection: slug,
233
- context: {
234
- skipCloudStorage: true
235
- },
236
- data: {
237
- _objectKey: null,
238
- filename: destination.name,
239
- imagekit,
240
- prefix: destinationFolder.replace(/^\//, ''),
241
- thumbnailURL: isPrivate ? getPrivateAdminThumbnailURL(updated, slug, payload.config.routes.api) : getAdminThumbnailURL(updated)
242
- }
243
- });
230
+ const data = {
231
+ filename: destination.name,
232
+ imagekit,
233
+ prefix: destinationFolder.replace(/^\//, ''),
234
+ thumbnailURL: isPrivate ? getPrivateAdminThumbnailURL(updated, slug, payload.config.routes.api) : getAdminThumbnailURL(updated)
235
+ };
236
+ if (payload.db.name === 'mongoose') {
237
+ // A sparse unique MongoDB index permits missing keys, but only one null.
238
+ // Use the adapter directly: Local API merges the old key back into the
239
+ // update, which conflicts with $unset. Remove it and save the reference
240
+ // in one database write, so failed updates leave the source intact.
241
+ await payload.db.updateOne({
242
+ id: doc.id,
243
+ collection: slug,
244
+ data: {
245
+ ...data,
246
+ $unset: {
247
+ _objectKey: 1
248
+ }
249
+ }
250
+ });
251
+ } else {
252
+ await payload.update({
253
+ id: doc.id,
254
+ collection: slug,
255
+ context: {
256
+ skipCloudStorage: true
257
+ },
258
+ data: {
259
+ ...data,
260
+ _objectKey: null
261
+ }
262
+ });
263
+ }
244
264
  result.migrated += 1;
245
265
  console.log(`[migrateFolder] Migrated ${slug}/${doc.id} to ${destinationPath}.`);
246
266
  } catch (error) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/migrate.ts"],"sourcesContent":["/* eslint-disable no-console -- Migration progress is intentionally reported to the invoking process. */\n\nimport type { Payload, UploadCollectionSlug } from 'payload'\n\nimport ImageKit from '@imagekit/nodejs'\nimport { createHash } from 'node:crypto'\nimport path from 'node:path'\n\nimport { getAdminThumbnailURL, getPrivateAdminThumbnailURL } from './getAdminThumbnailURL.js'\n\nexport type MigrationLocation = {\n /** Root folder, with collection subfolders beneath it. */\n folder: string\n privateKey: string\n urlEndpoint: string\n}\n\nexport type MigrateFolderOptions = {\n /** `true` preserves source privacy; an explicit `private` value sets destination privacy. */\n collections: Partial<Record<UploadCollectionSlug, { private?: boolean } | true>>\n /** Reads and reports the same plan without uploading or updating documents. Defaults to true. */\n dryRun?: boolean\n from: MigrationLocation\n /** The database containing the records to update, including any already at the destination. */\n payload: Payload\n signedUrlExpiresIn?: number\n to: MigrationLocation\n}\n\nexport type MigrationJobResult = {\n collectionSlug: string\n errors: { documentID: number | string; message: string }[]\n failed: number\n migrated: number\n planned: number\n /** Existing tagged transfers recovered after an interrupted run. Included in migrated when live. */\n reused: number\n skipped: number\n}\n\ntype Asset = {\n fileId: string\n filePath: string\n isPrivateFile?: boolean\n name: string\n tags?: null | string[]\n thumbnail?: string\n updatedAt?: string\n url: string\n versionInfo?: { id?: string }\n}\n\nconst normalizeLocation = (location: MigrationLocation, label: string): MigrationLocation => {\n if (!location?.privateKey?.trim()) {\n throw new Error(`migrateFolder: \\`${label}.privateKey\\` is required.`)\n }\n if (!location.urlEndpoint?.trim()) {\n throw new Error(`migrateFolder: \\`${label}.urlEndpoint\\` is required.`)\n }\n const endpoint = new URL(location.urlEndpoint)\n if (!['http:', 'https:'].includes(endpoint.protocol) || endpoint.search || endpoint.hash) {\n throw new Error(\n `migrateFolder: \\`${label}.urlEndpoint\\` must be an HTTP(S) URL without a query or fragment.`,\n )\n }\n const folder = location.folder?.trim().replace(/^\\/+|\\/+$/g, '')\n if (\n !folder ||\n folder.split('/').some((segment) => !segment || segment === '.' || segment === '..')\n ) {\n throw new Error(\n `migrateFolder: \\`${label}.folder\\` must be a non-empty folder without dot segments.`,\n )\n }\n return { ...location, folder: `/${folder}`, urlEndpoint: endpoint.href.replace(/\\/$/, '') }\n}\n\nconst isInFolder = (filePath: string, folder: string): boolean => filePath.startsWith(`${folder}/`)\n\nconst getAsset = async (client: ImageKit, fileId: string): Promise<Asset | undefined> => {\n try {\n const file = await client.files.get(fileId)\n if (!file.fileId || !file.filePath || !file.url) {\n throw new Error(`ImageKit returned incomplete file details for \"${fileId}\".`)\n }\n return {\n ...file,\n name: file.name || path.posix.basename(file.filePath),\n fileId: file.fileId,\n filePath: file.filePath,\n url: file.url,\n }\n } catch (error) {\n // Authentication errors, rate limits and outages are not evidence of a missing file.\n if (error instanceof ImageKit.NotFoundError) {\n return undefined\n }\n throw error\n }\n}\n\nconst findDestination = async (client: ImageKit, filePath: string): Promise<Asset | undefined> => {\n const limit = 100\n for (let skip = 0; ; skip += limit) {\n const assets = await client.assets.list({\n type: 'file',\n limit,\n path: `${path.posix.dirname(filePath)}/`,\n skip,\n })\n const match = assets.find((asset) => 'fileId' in asset && asset.filePath === filePath)\n if (match && 'fileId' in match && match.fileId) {\n return getAsset(client, match.fileId)\n }\n if (assets.length < limit) {\n return undefined\n }\n }\n}\n\nconst transferTag = (\n source: Asset,\n filePath: string,\n documentID: number | string,\n isPrivate: boolean,\n): string => {\n const identity = JSON.stringify([\n source.fileId,\n source.versionInfo?.id || source.updatedAt,\n source.url,\n filePath,\n documentID,\n isPrivate,\n ])\n return `payload-migration-${createHash('sha256').update(identity).digest('hex')}`\n}\n\n/**\n * Copy referenced originals between ImageKit folders/accounts and update Payload in place.\n * Transfers are tagged at upload time and never overwrite an existing destination file.\n * Reruns recover the upload/database-update gap without relying on filename equality.\n */\nexport const migrateFolder = async (\n options: MigrateFolderOptions,\n): Promise<MigrationJobResult[]> => {\n const { collections, dryRun = true, payload, signedUrlExpiresIn = 900 } = options\n const from = normalizeLocation(options.from, 'from')\n const to = normalizeLocation(options.to, 'to')\n if (!payload) {\n throw new Error('migrateFolder: `payload` is required.')\n }\n const slugs = Object.keys(collections || {})\n if (!slugs.length) {\n throw new Error('migrateFolder: `collections` must include at least one upload collection.')\n }\n for (const slug of slugs) {\n if (!payload.collections[slug]?.config.upload) {\n throw new Error(`migrateFolder: \"${slug}\" is not an upload collection.`)\n }\n }\n if (!Number.isFinite(signedUrlExpiresIn) || signedUrlExpiresIn <= 0) {\n throw new Error('migrateFolder: `signedUrlExpiresIn` must be positive.')\n }\n\n // A single transfer path for both cases gives uploads atomic provenance tags, including\n // when an upload succeeds remotely but its response is lost. Native copy cannot add a tag.\n const sourceClient = new ImageKit({ maxRetries: 0, privateKey: from.privateKey })\n const destinationClient = new ImageKit({ maxRetries: 0, privateKey: to.privateKey })\n const results: MigrationJobResult[] = []\n\n for (const slug of slugs) {\n const result: MigrationJobResult = {\n collectionSlug: slug,\n errors: [],\n failed: 0,\n migrated: 0,\n planned: 0,\n reused: 0,\n skipped: 0,\n }\n const sourceFolder = path.posix.join(from.folder, slug)\n const destinationFolder = path.posix.join(to.folder, slug)\n const collectionOptions = collections[slug]\n const plannedPaths = new Map<string, string>()\n let page = 1\n let hasNextPage: boolean\n\n do {\n const found = await payload.find({ collection: slug, depth: 0, limit: 100, page, sort: 'id' })\n hasNextPage = found.hasNextPage\n page += 1\n for (const doc of found.docs) {\n const reference = (doc as { imagekit?: { fileId?: string } }).imagekit\n if (!reference?.fileId) {\n result.skipped += 1\n console.log(`[migrateFolder] Skipping ${slug}/${doc.id}: no ImageKit file ID.`)\n continue\n }\n try {\n const atDestination = await getAsset(destinationClient, reference.fileId)\n if (atDestination && isInFolder(atDestination.filePath, destinationFolder)) {\n result.skipped += 1\n console.log(`[migrateFolder] Skipping ${slug}/${doc.id}: already at destination.`)\n continue\n }\n const source = await getAsset(sourceClient, reference.fileId)\n if (!source) {\n throw new Error(`File \"${reference.fileId}\" was not found in the source account.`)\n }\n if (!isInFolder(source.filePath, sourceFolder)) {\n result.skipped += 1\n console.log(`[migrateFolder] Skipping ${slug}/${doc.id}: outside ${sourceFolder}.`)\n continue\n }\n\n const isPrivate =\n collectionOptions !== true && typeof collectionOptions?.private === 'boolean'\n ? collectionOptions.private\n : source.isPrivateFile === true\n const destinationPath = path.posix.join(destinationFolder, source.name)\n const tag = transferTag(source, destinationPath, doc.id, isPrivate)\n const previousTransfer = plannedPaths.get(destinationPath)\n if (previousTransfer && previousTransfer !== tag) {\n throw new Error(\n `Destination conflict at \"${destinationPath}\": multiple source records target this path.`,\n )\n }\n plannedPaths.set(destinationPath, tag)\n let destination = await findDestination(destinationClient, destinationPath)\n if (\n destination &&\n (!destination.tags?.includes(tag) || (destination.isPrivateFile === true) !== isPrivate)\n ) {\n throw new Error(\n `Destination conflict at \"${destinationPath}\": existing asset is not this transfer.`,\n )\n }\n if (destination) {\n result.reused += 1\n }\n if (dryRun) {\n result.planned += 1\n console.log(\n `[migrateFolder] [dry-run] Would ${destination ? 'reuse' : 'upload'} ${slug}/${doc.id}: ${source.filePath} -> ${destinationPath}`,\n )\n continue\n }\n\n if (!destination) {\n const sourceURL = sourceClient.helper.buildSrc({\n ...(source.isPrivateFile ? { expiresIn: signedUrlExpiresIn, signed: true } : {}),\n src: source.filePath,\n transformation: [{ raw: 'orig-true' }],\n urlEndpoint: from.urlEndpoint,\n })\n const uploaded = await destinationClient.files.upload({\n file: sourceURL,\n fileName: source.name,\n folder: destinationFolder,\n isPrivateFile: isPrivate,\n overwriteFile: false,\n tags: [tag],\n useUniqueFileName: false,\n })\n if (!uploaded.fileId) {\n throw new Error(`Upload of \"${source.fileId}\" did not return a file ID.`)\n }\n destination = await getAsset(destinationClient, uploaded.fileId)\n if (\n !destination ||\n destination.filePath !== destinationPath ||\n !destination.tags?.includes(tag) ||\n (destination.isPrivateFile === true) !== isPrivate\n ) {\n throw new Error(\n `Upload of \"${source.fileId}\" returned unexpected destination details.`,\n )\n }\n }\n\n const imagekit = {\n fileId: destination.fileId,\n isPrivate,\n thumbnailUrl: destination.thumbnail || null,\n url: destinationClient.helper.buildSrc({\n src: destination.filePath,\n urlEndpoint: to.urlEndpoint,\n }),\n }\n const updated = { ...doc, filename: destination.name, imagekit }\n await payload.update({\n id: doc.id,\n collection: slug,\n context: { skipCloudStorage: true },\n data: {\n _objectKey: null,\n filename: destination.name,\n imagekit,\n prefix: destinationFolder.replace(/^\\//, ''),\n thumbnailURL: isPrivate\n ? getPrivateAdminThumbnailURL(updated, slug, payload.config.routes.api)\n : getAdminThumbnailURL(updated),\n },\n })\n result.migrated += 1\n console.log(`[migrateFolder] Migrated ${slug}/${doc.id} to ${destinationPath}.`)\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown migration error'\n result.failed += 1\n result.errors.push({ documentID: doc.id, message })\n console.error(`[migrateFolder] Failed ${slug}/${doc.id}: ${message}`)\n }\n }\n } while (hasNextPage)\n\n results.push(result)\n console.log(\n `[migrateFolder] ${slug}: planned=${result.planned}, migrated=${result.migrated}, reused=${result.reused}, skipped=${result.skipped}, failed=${result.failed}.`,\n )\n }\n return results\n}\n"],"names":["ImageKit","createHash","path","getAdminThumbnailURL","getPrivateAdminThumbnailURL","normalizeLocation","location","label","privateKey","trim","Error","urlEndpoint","endpoint","URL","includes","protocol","search","hash","folder","replace","split","some","segment","href","isInFolder","filePath","startsWith","getAsset","client","fileId","file","files","get","url","name","posix","basename","error","NotFoundError","undefined","findDestination","limit","skip","assets","list","type","dirname","match","find","asset","length","transferTag","source","documentID","isPrivate","identity","JSON","stringify","versionInfo","id","updatedAt","update","digest","migrateFolder","options","collections","dryRun","payload","signedUrlExpiresIn","from","to","slugs","Object","keys","slug","config","upload","Number","isFinite","sourceClient","maxRetries","destinationClient","results","result","collectionSlug","errors","failed","migrated","planned","reused","skipped","sourceFolder","join","destinationFolder","collectionOptions","plannedPaths","Map","page","hasNextPage","found","collection","depth","sort","doc","docs","reference","imagekit","console","log","atDestination","private","isPrivateFile","destinationPath","tag","previousTransfer","set","destination","tags","sourceURL","helper","buildSrc","expiresIn","signed","src","transformation","raw","uploaded","fileName","overwriteFile","useUniqueFileName","thumbnailUrl","thumbnail","updated","filename","context","skipCloudStorage","data","_objectKey","prefix","thumbnailURL","routes","api","message","push"],"mappings":"AAAA,sGAAsG,GAItG,OAAOA,cAAc,mBAAkB;AACvC,SAASC,UAAU,QAAQ,cAAa;AACxC,OAAOC,UAAU,YAAW;AAE5B,SAASC,oBAAoB,EAAEC,2BAA2B,QAAQ,4BAA2B;AA4C7F,MAAMC,oBAAoB,CAACC,UAA6BC;IACtD,IAAI,CAACD,UAAUE,YAAYC,QAAQ;QACjC,MAAM,IAAIC,MAAM,CAAC,iBAAiB,EAAEH,MAAM,0BAA0B,CAAC;IACvE;IACA,IAAI,CAACD,SAASK,WAAW,EAAEF,QAAQ;QACjC,MAAM,IAAIC,MAAM,CAAC,iBAAiB,EAAEH,MAAM,2BAA2B,CAAC;IACxE;IACA,MAAMK,WAAW,IAAIC,IAAIP,SAASK,WAAW;IAC7C,IAAI,CAAC;QAAC;QAAS;KAAS,CAACG,QAAQ,CAACF,SAASG,QAAQ,KAAKH,SAASI,MAAM,IAAIJ,SAASK,IAAI,EAAE;QACxF,MAAM,IAAIP,MACR,CAAC,iBAAiB,EAAEH,MAAM,kEAAkE,CAAC;IAEjG;IACA,MAAMW,SAASZ,SAASY,MAAM,EAAET,OAAOU,QAAQ,cAAc;IAC7D,IACE,CAACD,UACDA,OAAOE,KAAK,CAAC,KAAKC,IAAI,CAAC,CAACC,UAAY,CAACA,WAAWA,YAAY,OAAOA,YAAY,OAC/E;QACA,MAAM,IAAIZ,MACR,CAAC,iBAAiB,EAAEH,MAAM,0DAA0D,CAAC;IAEzF;IACA,OAAO;QAAE,GAAGD,QAAQ;QAAEY,QAAQ,CAAC,CAAC,EAAEA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AC,SAAS,EAAEJ,OAAOM,MAAM,CAAC,UAAU,EAAEN,OAAOO,OAAO,CAAC,SAAS,EAAEP,OAAOG,MAAM,CAAC,CAAC,CAAC;IAEnK;IACA,OAAOJ;AACT,EAAC"}
1
+ {"version":3,"sources":["../src/migrate.ts"],"sourcesContent":["/* eslint-disable no-console -- Migration progress is intentionally reported to the invoking process. */\n\nimport type { Payload, UploadCollectionSlug } from 'payload'\n\nimport ImageKit from '@imagekit/nodejs'\nimport { createHash } from 'node:crypto'\nimport path from 'node:path'\n\nimport { getAdminThumbnailURL, getPrivateAdminThumbnailURL } from './getAdminThumbnailURL.js'\n\nexport type MigrationLocation = {\n /** Root folder, with collection subfolders beneath it. */\n folder: string\n privateKey: string\n urlEndpoint: string\n}\n\nexport type MigrateFolderOptions = {\n /** `true` preserves source privacy; an explicit `private` value sets destination privacy. */\n collections: Partial<Record<UploadCollectionSlug, { private?: boolean } | true>>\n /** Reads and reports the same plan without uploading or updating documents. Defaults to true. */\n dryRun?: boolean\n from: MigrationLocation\n /** The database containing the records to update, including any already at the destination. */\n payload: Payload\n signedUrlExpiresIn?: number\n to: MigrationLocation\n}\n\nexport type MigrationJobResult = {\n collectionSlug: string\n errors: { documentID: number | string; message: string }[]\n failed: number\n migrated: number\n planned: number\n /** Existing tagged transfers recovered after an interrupted run. Included in migrated when live. */\n reused: number\n skipped: number\n}\n\ntype Asset = {\n fileId: string\n filePath: string\n isPrivateFile?: boolean\n name: string\n tags?: null | string[]\n thumbnail?: string\n updatedAt?: string\n url: string\n versionInfo?: { id?: string }\n}\n\nconst normalizeLocation = (location: MigrationLocation, label: string): MigrationLocation => {\n if (!location?.privateKey?.trim()) {\n throw new Error(`migrateFolder: \\`${label}.privateKey\\` is required.`)\n }\n if (!location.urlEndpoint?.trim()) {\n throw new Error(`migrateFolder: \\`${label}.urlEndpoint\\` is required.`)\n }\n const endpoint = new URL(location.urlEndpoint)\n if (!['http:', 'https:'].includes(endpoint.protocol) || endpoint.search || endpoint.hash) {\n throw new Error(\n `migrateFolder: \\`${label}.urlEndpoint\\` must be an HTTP(S) URL without a query or fragment.`,\n )\n }\n const folder = location.folder?.trim().replace(/^\\/+|\\/+$/g, '')\n if (\n !folder ||\n folder.split('/').some((segment) => !segment || segment === '.' || segment === '..')\n ) {\n throw new Error(\n `migrateFolder: \\`${label}.folder\\` must be a non-empty folder without dot segments.`,\n )\n }\n return { ...location, folder: `/${folder}`, urlEndpoint: endpoint.href.replace(/\\/$/, '') }\n}\n\nconst isInFolder = (filePath: string, folder: string): boolean => filePath.startsWith(`${folder}/`)\n\nconst getAsset = async (client: ImageKit, fileId: string): Promise<Asset | undefined> => {\n try {\n const file = await client.files.get(fileId)\n if (!file.fileId || !file.filePath || !file.url) {\n throw new Error(`ImageKit returned incomplete file details for \"${fileId}\".`)\n }\n return {\n ...file,\n name: file.name || path.posix.basename(file.filePath),\n fileId: file.fileId,\n filePath: file.filePath,\n url: file.url,\n }\n } catch (error) {\n // Authentication errors, rate limits and outages are not evidence of a missing file.\n if (error instanceof ImageKit.NotFoundError) {\n return undefined\n }\n throw error\n }\n}\n\nconst findDestination = async (client: ImageKit, filePath: string): Promise<Asset | undefined> => {\n const limit = 100\n for (let skip = 0; ; skip += limit) {\n const assets = await client.assets.list({\n type: 'file',\n limit,\n path: `${path.posix.dirname(filePath)}/`,\n skip,\n })\n const match = assets.find((asset) => 'fileId' in asset && asset.filePath === filePath)\n if (match && 'fileId' in match && match.fileId) {\n return getAsset(client, match.fileId)\n }\n if (assets.length < limit) {\n return undefined\n }\n }\n}\n\nconst transferTag = (\n source: Asset,\n filePath: string,\n documentID: number | string,\n isPrivate: boolean,\n): string => {\n const identity = JSON.stringify([\n source.fileId,\n source.versionInfo?.id || source.updatedAt,\n source.url,\n filePath,\n documentID,\n isPrivate,\n ])\n return `payload-migration-${createHash('sha256').update(identity).digest('hex')}`\n}\n\n/**\n * Copy referenced originals between ImageKit folders/accounts and update Payload in place.\n * Transfers are tagged at upload time and never overwrite an existing destination file.\n * Reruns recover the upload/database-update gap without relying on filename equality.\n */\nexport const migrateFolder = async (\n options: MigrateFolderOptions,\n): Promise<MigrationJobResult[]> => {\n const { collections, dryRun = true, payload, signedUrlExpiresIn = 900 } = options\n const from = normalizeLocation(options.from, 'from')\n const to = normalizeLocation(options.to, 'to')\n if (!payload) {\n throw new Error('migrateFolder: `payload` is required.')\n }\n const slugs = Object.keys(collections || {})\n if (!slugs.length) {\n throw new Error('migrateFolder: `collections` must include at least one upload collection.')\n }\n for (const slug of slugs) {\n if (!payload.collections[slug]?.config.upload) {\n throw new Error(`migrateFolder: \"${slug}\" is not an upload collection.`)\n }\n }\n if (!Number.isFinite(signedUrlExpiresIn) || signedUrlExpiresIn <= 0) {\n throw new Error('migrateFolder: `signedUrlExpiresIn` must be positive.')\n }\n\n // A single transfer path for both cases gives uploads atomic provenance tags, including\n // when an upload succeeds remotely but its response is lost. Native copy cannot add a tag.\n const sourceClient = new ImageKit({ maxRetries: 0, privateKey: from.privateKey })\n const destinationClient = new ImageKit({ maxRetries: 0, privateKey: to.privateKey })\n const results: MigrationJobResult[] = []\n\n for (const slug of slugs) {\n const result: MigrationJobResult = {\n collectionSlug: slug,\n errors: [],\n failed: 0,\n migrated: 0,\n planned: 0,\n reused: 0,\n skipped: 0,\n }\n const sourceFolder = path.posix.join(from.folder, slug)\n const destinationFolder = path.posix.join(to.folder, slug)\n const collectionOptions = collections[slug]\n const plannedPaths = new Map<string, string>()\n let page = 1\n let hasNextPage: boolean\n\n do {\n const found = await payload.find({ collection: slug, depth: 0, limit: 100, page, sort: 'id' })\n hasNextPage = found.hasNextPage\n page += 1\n for (const doc of found.docs) {\n const reference = (doc as { imagekit?: { fileId?: string } }).imagekit\n if (!reference?.fileId) {\n result.skipped += 1\n console.log(`[migrateFolder] Skipping ${slug}/${doc.id}: no ImageKit file ID.`)\n continue\n }\n try {\n const atDestination = await getAsset(destinationClient, reference.fileId)\n if (atDestination && isInFolder(atDestination.filePath, destinationFolder)) {\n result.skipped += 1\n console.log(`[migrateFolder] Skipping ${slug}/${doc.id}: already at destination.`)\n continue\n }\n const source = await getAsset(sourceClient, reference.fileId)\n if (!source) {\n throw new Error(`File \"${reference.fileId}\" was not found in the source account.`)\n }\n if (!isInFolder(source.filePath, sourceFolder)) {\n result.skipped += 1\n console.log(`[migrateFolder] Skipping ${slug}/${doc.id}: outside ${sourceFolder}.`)\n continue\n }\n\n const isPrivate =\n collectionOptions !== true && typeof collectionOptions?.private === 'boolean'\n ? collectionOptions.private\n : source.isPrivateFile === true\n const destinationPath = path.posix.join(destinationFolder, source.name)\n const tag = transferTag(source, destinationPath, doc.id, isPrivate)\n const previousTransfer = plannedPaths.get(destinationPath)\n if (previousTransfer && previousTransfer !== tag) {\n throw new Error(\n `Destination conflict at \"${destinationPath}\": multiple source records target this path.`,\n )\n }\n plannedPaths.set(destinationPath, tag)\n let destination = await findDestination(destinationClient, destinationPath)\n if (\n destination &&\n (!destination.tags?.includes(tag) || (destination.isPrivateFile === true) !== isPrivate)\n ) {\n throw new Error(\n `Destination conflict at \"${destinationPath}\": existing asset is not this transfer.`,\n )\n }\n if (destination) {\n result.reused += 1\n }\n if (dryRun) {\n result.planned += 1\n console.log(\n `[migrateFolder] [dry-run] Would ${destination ? 'reuse' : 'upload'} ${slug}/${doc.id}: ${source.filePath} -> ${destinationPath}`,\n )\n continue\n }\n\n if (!destination) {\n const sourceURL = sourceClient.helper.buildSrc({\n ...(source.isPrivateFile ? { expiresIn: signedUrlExpiresIn, signed: true } : {}),\n src: source.filePath,\n transformation: [{ raw: 'orig-true' }],\n urlEndpoint: from.urlEndpoint,\n })\n const uploaded = await destinationClient.files.upload({\n file: sourceURL,\n fileName: source.name,\n folder: destinationFolder,\n isPrivateFile: isPrivate,\n overwriteFile: false,\n tags: [tag],\n useUniqueFileName: false,\n })\n if (!uploaded.fileId) {\n throw new Error(`Upload of \"${source.fileId}\" did not return a file ID.`)\n }\n destination = await getAsset(destinationClient, uploaded.fileId)\n if (\n !destination ||\n destination.filePath !== destinationPath ||\n !destination.tags?.includes(tag) ||\n (destination.isPrivateFile === true) !== isPrivate\n ) {\n throw new Error(\n `Upload of \"${source.fileId}\" returned unexpected destination details.`,\n )\n }\n }\n\n const imagekit = {\n fileId: destination.fileId,\n isPrivate,\n thumbnailUrl: destination.thumbnail || null,\n url: destinationClient.helper.buildSrc({\n src: destination.filePath,\n urlEndpoint: to.urlEndpoint,\n }),\n }\n const updated = { ...doc, filename: destination.name, imagekit }\n const data = {\n filename: destination.name,\n imagekit,\n prefix: destinationFolder.replace(/^\\//, ''),\n thumbnailURL: isPrivate\n ? getPrivateAdminThumbnailURL(updated, slug, payload.config.routes.api)\n : getAdminThumbnailURL(updated),\n }\n if (payload.db.name === 'mongoose') {\n // A sparse unique MongoDB index permits missing keys, but only one null.\n // Use the adapter directly: Local API merges the old key back into the\n // update, which conflicts with $unset. Remove it and save the reference\n // in one database write, so failed updates leave the source intact.\n await payload.db.updateOne({\n id: doc.id,\n collection: slug,\n data: { ...data, $unset: { _objectKey: 1 } },\n })\n } else {\n await payload.update({\n id: doc.id,\n collection: slug,\n context: { skipCloudStorage: true },\n data: { ...data, _objectKey: null },\n })\n }\n result.migrated += 1\n console.log(`[migrateFolder] Migrated ${slug}/${doc.id} to ${destinationPath}.`)\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown migration error'\n result.failed += 1\n result.errors.push({ documentID: doc.id, message })\n console.error(`[migrateFolder] Failed ${slug}/${doc.id}: ${message}`)\n }\n }\n } while (hasNextPage)\n\n results.push(result)\n console.log(\n `[migrateFolder] ${slug}: planned=${result.planned}, migrated=${result.migrated}, reused=${result.reused}, skipped=${result.skipped}, failed=${result.failed}.`,\n )\n }\n return results\n}\n"],"names":["ImageKit","createHash","path","getAdminThumbnailURL","getPrivateAdminThumbnailURL","normalizeLocation","location","label","privateKey","trim","Error","urlEndpoint","endpoint","URL","includes","protocol","search","hash","folder","replace","split","some","segment","href","isInFolder","filePath","startsWith","getAsset","client","fileId","file","files","get","url","name","posix","basename","error","NotFoundError","undefined","findDestination","limit","skip","assets","list","type","dirname","match","find","asset","length","transferTag","source","documentID","isPrivate","identity","JSON","stringify","versionInfo","id","updatedAt","update","digest","migrateFolder","options","collections","dryRun","payload","signedUrlExpiresIn","from","to","slugs","Object","keys","slug","config","upload","Number","isFinite","sourceClient","maxRetries","destinationClient","results","result","collectionSlug","errors","failed","migrated","planned","reused","skipped","sourceFolder","join","destinationFolder","collectionOptions","plannedPaths","Map","page","hasNextPage","found","collection","depth","sort","doc","docs","reference","imagekit","console","log","atDestination","private","isPrivateFile","destinationPath","tag","previousTransfer","set","destination","tags","sourceURL","helper","buildSrc","expiresIn","signed","src","transformation","raw","uploaded","fileName","overwriteFile","useUniqueFileName","thumbnailUrl","thumbnail","updated","filename","data","prefix","thumbnailURL","routes","api","db","updateOne","$unset","_objectKey","context","skipCloudStorage","message","push"],"mappings":"AAAA,sGAAsG,GAItG,OAAOA,cAAc,mBAAkB;AACvC,SAASC,UAAU,QAAQ,cAAa;AACxC,OAAOC,UAAU,YAAW;AAE5B,SAASC,oBAAoB,EAAEC,2BAA2B,QAAQ,4BAA2B;AA4C7F,MAAMC,oBAAoB,CAACC,UAA6BC;IACtD,IAAI,CAACD,UAAUE,YAAYC,QAAQ;QACjC,MAAM,IAAIC,MAAM,CAAC,iBAAiB,EAAEH,MAAM,0BAA0B,CAAC;IACvE;IACA,IAAI,CAACD,SAASK,WAAW,EAAEF,QAAQ;QACjC,MAAM,IAAIC,MAAM,CAAC,iBAAiB,EAAEH,MAAM,2BAA2B,CAAC;IACxE;IACA,MAAMK,WAAW,IAAIC,IAAIP,SAASK,WAAW;IAC7C,IAAI,CAAC;QAAC;QAAS;KAAS,CAACG,QAAQ,CAACF,SAASG,QAAQ,KAAKH,SAASI,MAAM,IAAIJ,SAASK,IAAI,EAAE;QACxF,MAAM,IAAIP,MACR,CAAC,iBAAiB,EAAEH,MAAM,kEAAkE,CAAC;IAEjG;IACA,MAAMW,SAASZ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;oBACA3D,OAAOI,QAAQ,IAAI;oBACnBoB,QAAQC,GAAG,CAAC,CAAC,yBAAyB,EAAElC,KAAK,CAAC,EAAE6B,IAAI5C,EAAE,CAAC,IAAI,EAAEqD,gBAAgB,CAAC,CAAC;gBACjF,EAAE,OAAO3E,OAAO;oBACd,MAAM4G,UAAU5G,iBAAiB3B,QAAQ2B,MAAM4G,OAAO,GAAG;oBACzD9D,OAAOG,MAAM,IAAI;oBACjBH,OAAOE,MAAM,CAAC6D,IAAI,CAAC;wBAAE7F,YAAYkD,IAAI5C,EAAE;wBAAEsF;oBAAQ;oBACjDtC,QAAQtE,KAAK,CAAC,CAAC,uBAAuB,EAAEqC,KAAK,CAAC,EAAE6B,IAAI5C,EAAE,CAAC,EAAE,EAAEsF,SAAS;gBACtE;YACF;QACF,QAAS/C,YAAY;QAErBhB,QAAQgE,IAAI,CAAC/D;QACbwB,QAAQC,GAAG,CACT,CAAC,gBAAgB,EAAElC,KAAK,UAAU,EAAES,OAAOK,OAAO,CAAC,WAAW,EAAEL,OAAOI,QAAQ,CAAC,SAAS,EAAEJ,OAAOM,MAAM,CAAC,UAAU,EAAEN,OAAOO,OAAO,CAAC,SAAS,EAAEP,OAAOG,MAAM,CAAC,CAAC,CAAC;IAEnK;IACA,OAAOJ;AACT,EAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@humaan/payload-storage-imagekit",
3
- "version": "2.9.0",
3
+ "version": "2.9.2",
4
4
  "description": "ImageKit storage adapter plugin for Payload CMS uploads",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -47,21 +47,21 @@
47
47
  "@payloadcms/ui": "3.90.2",
48
48
  "@swc-node/register": "1.12.1",
49
49
  "@swc/cli": "0.8.1",
50
- "@types/node": "26.6.3",
50
+ "@types/node": "26.6.5",
51
51
  "@types/react": "19.3.0",
52
52
  "@types/react-dom": "19.3.0",
53
53
  "conventional-changelog": "8.1.3",
54
- "conventional-changelog-conventionalcommits": "10.4.0",
54
+ "conventional-changelog-conventionalcommits": "10.4.1",
55
55
  "copyfiles": "2.4.1",
56
56
  "cross-env": "10.1.0",
57
57
  "eslint": "^9.39.5",
58
- "eslint-config-next": "16.3.8",
58
+ "eslint-config-next": "16.4.1",
59
59
  "graphql": "^16.14.2",
60
60
  "mongodb-memory-server": "11.3.0",
61
- "next": "16.3.8",
61
+ "next": "16.4.1",
62
62
  "open": "^11.0.4",
63
63
  "payload": "3.90.2",
64
- "prettier": "^3.9.9",
64
+ "prettier": "^3.9.10",
65
65
  "qs-esm": "8.0.2",
66
66
  "react": "19.3.0",
67
67
  "react-dom": "19.3.0",
@@ -69,7 +69,7 @@
69
69
  "sharp": "0.35.5",
70
70
  "sort-package-json": "^4.0.0",
71
71
  "typescript": "6.0.3",
72
- "vite": "8.3.1",
72
+ "vite": "8.3.4",
73
73
  "vite-tsconfig-paths": "6.1.1",
74
74
  "vitest": "4.1.11"
75
75
  },
@@ -78,7 +78,7 @@
78
78
  "payload": ">=3.90.1 <4.0.0"
79
79
  },
80
80
  "engines": {
81
- "node": ">=24.15.0 <25"
81
+ "node": ">=24.22.0 <25"
82
82
  },
83
83
  "publishConfig": {
84
84
  "access": "public",