@humaan/payload-storage-imagekit 2.9.1 → 3.0.0-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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;IAE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"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Adapter, ClientUploadsConfig } from '@payloadcms/plugin-cloud-storage/types'\nimport type {\n CollectionConfig,\n CollectionSlug,\n Config,\n Field,\n PayloadRequest,\n StorageAdapter,\n UploadCollectionSlug,\n} from 'payload'\n\nimport ImageKit, { toFile } from '@imagekit/nodejs'\nimport { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage'\nimport { buildStoragePathData } from '@payloadcms/plugin-cloud-storage/utilities'\nimport { openAsBlob } from 'node:fs'\nimport path from 'node:path'\nimport { APIError } from 'payload'\nimport {\n assertClientUploadAllowed,\n getRangeRequestInfo,\n isXmlMimeType,\n uploadContentSecurityPolicy,\n verifyClientUploadReceipt,\n} from 'payload/internal'\n\nimport { createImageKitUploadInstructions } from './endpoints/createImageKitUploadInstructions.js'\nimport {\n getAdminThumbnailURL,\n getPrivateAdminThumbnailURL,\n isPdfMimeType,\n isVideoMimeType,\n} from './getAdminThumbnailURL.js'\nimport { getImageKitThumbnailSrc, getVideoPosterSrc } from './imageTransforms.js'\n\nexport type ImageKitCollectionOptions = { focalPoint?: boolean; private?: boolean }\nexport type PayloadStorageImageKitConfig = {\n clientUploads?: ClientUploadsConfig\n collections: Partial<Record<UploadCollectionSlug, ImageKitCollectionOptions | true>>\n disablePayloadAccessControl?: true\n enabled?: boolean\n focalPoint?: boolean\n folder: string\n privateKey: string\n publicKey: string\n signedUrlExpiresIn?: number\n urlEndpoint: string\n}\n\n/** Payload 4 storage capability. Register under config.storage, not config.plugins. */\nexport const imagekitStorage = (options: PayloadStorageImageKitConfig): StorageAdapter => ({\n name: 'imagekit',\n collections: Object.keys(options.collections),\n init: (config) => initializeStorage(config, options),\n})\n\nexport { migrateFolder } from './migrate.js'\nexport type { MigrateFolderOptions, MigrationJobResult, MigrationLocation } from './migrate.js'\nexport const payloadStorageImagekit = imagekitStorage\nexport const payloadStorageImageKit = imagekitStorage\nexport type PayloadStorageImagekitConfig = PayloadStorageImageKitConfig\n\ninterface ProviderFile {\n fileId: string\n isPrivateFile?: boolean\n mime?: string\n name: string\n size: number\n thumbnail?: string\n url: string\n}\n\ninterface FileLocation {\n _objectKey?: string\n filename?: string\n filesize?: number\n mimeType?: string\n prefix?: string\n}\n\nfunction initializeStorage(config: Config, options: PayloadStorageImageKitConfig): Config {\n for (const key of ['privateKey', 'publicKey', 'urlEndpoint', 'folder'] as const) {\n if (!options[key]?.trim()) {\n throw new Error(`imagekitStorage: \\`${key}\\` is required.`)\n }\n }\n const folder = options.folder.trim().replace(/^\\/+|\\/+$/g, '')\n if (folder.split('/').some((segment) => !segment || segment === '.' || segment === '..')) {\n throw new Error('imagekitStorage: `folder` must not contain empty or dot segments.')\n }\n const client = new ImageKit({ privateKey: options.privateKey })\n const collections: Partial<Record<string, ImageKitCollectionOptions | true>> = options.collections\n if (!Object.keys(collections).length) {\n throw new Error('imagekitStorage: `collections` must not be empty.')\n }\n const configured = new Set(Object.keys(collections))\n const apiRoute = config.routes?.api ?? '/api'\n const expiresIn = options.signedUrlExpiresIn ?? 900\n const prefixFor = (slug: string) => path.posix.join(folder, slug)\n const collectionIsPrivate = (slug: string) => {\n const value = collections[slug]\n return value !== true && value?.private === true\n }\n const sourceConfig: Config = {\n ...config,\n collections: (config.collections ?? []).map((collection) => {\n if (!configured.has(collection.slug)) {\n return collection\n }\n const isPrivate = collectionIsPrivate(collection.slug)\n if (options.disablePayloadAccessControl && (isPrivate || canStoreXml(collection))) {\n throw new Error(\n 'imagekitStorage: private and XML-capable collections require Payload access control.',\n )\n }\n const setting = collections[collection.slug]\n const focalPoint = setting !== true ? setting?.focalPoint : undefined\n const description = collection.admin?.description\n return {\n ...collection,\n admin: isPrivate\n ? {\n ...collection.admin,\n description:\n typeof description === 'string'\n ? `${description} Files in this collection are uploaded to ImageKit as private files and delivered through short-lived signed URLs.`\n : (description ??\n 'Files in this collection are uploaded to ImageKit as private files and delivered through short-lived signed URLs.'),\n }\n : collection.admin,\n hooks: {\n ...collection.hooks,\n beforeChange: [\n ...(collection.hooks?.beforeChange ?? []),\n async ({ data, operation, originalDoc, req }) => {\n if (operation === 'validate') {\n return data\n }\n const verified = req.context.imagekitVerifiedUpload as ProviderFile | undefined\n if (!verified) {\n return data\n }\n const existing = await req.payload.db.findOne({\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- Generated consumer configs narrow CollectionSlug, unlike the standalone package build.\n collection: collection.slug as CollectionSlug,\n req,\n where: { 'imagekit.fileId': { equals: verified.fileId } },\n })\n if (existing && existing.id !== originalDoc?.id) {\n throw new APIError('This ImageKit upload reference has already been used.', 400)\n }\n return applyMetadata(data, verified, isPrivate, collection.slug, apiRoute)\n },\n ],\n },\n upload: {\n focalPoint: focalPoint ?? options.focalPoint ?? false,\n ...(typeof collection.upload === 'object' ? collection.upload : {}),\n adminThumbnail: ({ doc }) =>\n isPrivateDocument(doc, isPrivate)\n ? getPrivateAdminThumbnailURL(doc, collection.slug, apiRoute)\n : getAdminThumbnailURL(doc),\n crop: false,\n },\n }\n }),\n }\n const adapter: Adapter = ({ collection, prefix = prefixFor(collection.slug) }) => {\n const isPrivate = collectionIsPrivate(collection.slug)\n const buildURL = (key: string, signed: boolean, transformation?: null | string) =>\n client.helper.buildSrc({\n expiresIn: signed ? expiresIn : undefined,\n signed,\n src: `/${key.replace(/^\\/+/, '')}`,\n transformation: transformation ? [{ raw: transformation }] : undefined,\n urlEndpoint: options.urlEndpoint,\n })\n const deleteFile = async ({ storageFilePath }: { storageFilePath: string }) => {\n const file = await findFile(client, storageFilePath)\n if (file) {\n await client.files.delete(file.fileId)\n }\n }\n return {\n name: 'imagekit',\n copyFile: async ({ from, to }) => {\n if (await findFile(client, to)) {\n throw new Error(`ImageKit destination already exists: ${to}`)\n }\n const source = await findFile(client, from)\n if (!source) {\n throw new Error(`ImageKit source not found: ${from}`)\n }\n // Upload by URL copies the exact original without buffering it in the app process.\n // overwriteFile:false protects a destination created concurrently with the lookup.\n await client.files.upload({\n customMetadata: source.customMetadata ?? undefined,\n file: buildURL(from, Boolean(source.isPrivateFile), 'orig-true'),\n fileName: path.posix.basename(to),\n folder: `/${path.posix.dirname(to)}`,\n isPrivateFile: source.isPrivateFile ?? false,\n overwriteFile: false,\n tags: source.tags ?? undefined,\n useUniqueFileName: false,\n })\n },\n deleteFile,\n fields: storageFields({ buildURL, expiresIn, isPrivate, prefix }),\n generateURL: ({ filename, prefix: docPrefix }) =>\n buildURL(\n buildStoragePathData({\n collectionPrefix: prefix,\n docPrefix,\n filename,\n }).storageFilePath,\n false,\n ),\n handleDelete: deleteFile,\n handleUpload: async ({ data, file, storageFilePath }) => {\n const uploadSource = file.tempFilePath\n ? await openAsBlob(file.tempFilePath, { type: file.mimeType })\n : file.buffer\n const uploaded = await client.files.upload({\n file: await toFile(uploadSource, file.filename, { type: file.mimeType }),\n fileName: path.posix.basename(storageFilePath),\n folder: `/${path.posix.dirname(storageFilePath)}`,\n isPrivateFile: isPrivate,\n overwriteFile: false,\n useUniqueFileName: false,\n })\n if (!uploaded.fileId || !uploaded.url) {\n throw new Error('ImageKit returned incomplete upload metadata.')\n }\n return applyMetadata(\n data,\n {\n name: path.posix.basename(storageFilePath),\n fileId: uploaded.fileId,\n isPrivateFile: isPrivate,\n mime: file.mimeType,\n size: file.filesize,\n thumbnail: uploaded.thumbnailUrl,\n url: uploaded.url,\n },\n isPrivate,\n collection.slug,\n apiRoute,\n )\n },\n staticHandler: async (req, { doc, params }) => {\n if (params.uploadReference) {\n try {\n const reference = params.uploadReference as { signedReceipt?: unknown }\n const receipt = verifyClientUploadReceipt({\n collectionSlug: collection.slug,\n req,\n signedReceipt: reference.signedReceipt,\n })\n const expectedPath = buildStoragePathData({\n collectionPrefix: prefix,\n docPrefix: path.posix.join(receipt.filePrefix, receipt._objectKey ?? ''),\n filename: params.filename,\n }).storageFilePath\n if (\n !receipt._objectKey ||\n expectedPath !== receipt.storageFilePath ||\n !expectedPath.startsWith(`${prefix.replace(/^\\/+/, '')}/`)\n ) {\n throw new APIError('Invalid ImageKit upload reference.', 400)\n }\n const uploaded = await findUploadedFile(client, expectedPath)\n if (!uploaded || !uploaded.mime || Boolean(uploaded.isPrivateFile) !== isPrivate) {\n throw new APIError('ImageKit upload did not match its authorization.', 400)\n }\n assertClientUploadAllowed({\n collection,\n filename: uploaded.name,\n mimeType: uploaded.mime,\n })\n req.context.imagekitVerifiedUpload = uploaded\n return await fetchOriginal({\n file: uploaded,\n req,\n url: buildURL(expectedPath, isPrivate, 'orig-true'),\n })\n } catch (error) {\n if (error instanceof APIError) {\n return Response.json({ message: error.message }, { status: error.status })\n }\n throw error\n }\n }\n const document =\n doc ??\n (await req.payload.db.findOne({\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- Generated consumer configs narrow CollectionSlug, unlike the standalone package build.\n collection: collection.slug as CollectionSlug,\n req,\n where: { filename: { equals: params.filename } },\n }))\n const source = getFileLocation(document, params.filename)\n const key = buildStoragePathData({\n collectionPrefix: prefix,\n docPrefix: path.posix.join(\n params.prefix ?? source.prefix ?? prefix,\n source._objectKey ?? '',\n ),\n filename: params.filename,\n }).storageFilePath\n const privateFile = isPrivateDocument(document, isPrivate)\n if (params.operation === 'transform' || isXmlMimeType(source.mimeType ?? '')) {\n const file = await findFile(client, key)\n if (!file?.mime) {\n throw new APIError('ImageKit source not found.', 404)\n }\n return fetchOriginal({ file, req, url: buildURL(key, privateFile, 'orig-true') })\n }\n const tr = new URL(req.url ?? 'http://localhost').searchParams.get('tr')\n let src = key\n if (tr && isVideoMimeType(source.mimeType)) {\n src = getVideoPosterSrc(src)\n } else if (tr && isPdfMimeType(source.mimeType)) {\n src = getImageKitThumbnailSrc(src)\n }\n // Existing v3 files may live under an earlier folder or delivery endpoint.\n const storedURL = (document as { imagekit?: { url?: string }; original?: unknown } | null)\n ?.imagekit?.url\n if (\n !privateFile &&\n !tr &&\n !(document && 'original' in document && document.original) &&\n storedURL\n ) {\n return Response.redirect(storedURL, 302)\n }\n return Response.redirect(buildURL(src, privateFile, tr), 302)\n },\n supportsTempFiles: true,\n uploadInstructions: {\n adminHandler: { path: '@humaan/payload-storage-imagekit/client#ImageKitUploadHandler' },\n enabled: options.enabled !== false && Boolean(options.clientUploads),\n generate: createImageKitUploadInstructions({\n access:\n typeof options.clientUploads === 'object' ? options.clientUploads.access : undefined,\n isPrivate,\n prefix,\n privateKey: options.privateKey,\n publicKey: options.publicKey,\n }),\n requiresUploadReceipt: true,\n useInAdmin: true,\n },\n }\n }\n const output = cloudStoragePlugin({\n collections: Object.fromEntries(\n Object.keys(collections).map((slug) => [\n slug,\n {\n adapter,\n disableLocalStorage: true,\n disablePayloadAccessControl: options.disablePayloadAccessControl,\n prefix: prefixFor(slug),\n },\n ]),\n ),\n enabled: options.enabled,\n })(sourceConfig)\n // Do not invent a prefix on reads of legacy documents. A stored prefix is retained;\n // new uploads get their normalized destination from the file-operation pipeline.\n output.collections = output.collections?.map((collection) =>\n !configured.has(collection.slug)\n ? collection\n : {\n ...collection,\n fields: collection.fields.map((field) =>\n field.type === 'text' && field.name === 'prefix'\n ? {\n ...field,\n defaultValue: ({ req }) =>\n req.file && typeof field.defaultValue === 'string' ? field.defaultValue : '',\n }\n : field,\n ),\n },\n )\n return output\n}\n\nasync function findFile(client: ImageKit, storageFilePath: string) {\n const filePath = `/${storageFilePath.replace(/^\\/+/, '')}`\n const name = path.posix.basename(filePath)\n for (let skip = 0; ; skip += 100) {\n const assets = await client.assets.list({\n type: 'file',\n limit: 100,\n path: `${path.posix.dirname(filePath)}/`,\n skip,\n })\n const found = assets.find(\n (asset) => 'fileId' in asset && asset.filePath === filePath && asset.name === name,\n )\n if (found && 'fileId' in found && found.fileId) {\n const file = await client.files.get(found.fileId)\n if (\n file.fileId !== found.fileId ||\n file.name !== name ||\n file.filePath !== filePath ||\n typeof file.size !== 'number' ||\n !Number.isSafeInteger(file.size) ||\n file.size < 0 ||\n !file.url\n ) {\n throw new Error('ImageKit returned incomplete file metadata.')\n }\n return { ...file, name: file.name, fileId: file.fileId, size: file.size, url: file.url }\n }\n if (assets.length < 100) {\n return undefined\n }\n }\n}\n\nasync function findUploadedFile(client: ImageKit, key: string) {\n // ImageKit asset listings can lag a successful upload. Only admission retries;\n // ordinary missing reads/deletes and collision lookups must stay immediate.\n let file = await findFile(client, key)\n for (const delay of [250, 500, 1000, 2000]) {\n if (file) {\n break\n }\n await new Promise((resolve) => setTimeout(resolve, delay))\n file = await findFile(client, key)\n }\n return file\n}\n\nfunction isPrivateDocument(doc: unknown, fallback: boolean): boolean {\n const value = (doc as { imagekit?: { isPrivate?: boolean } } | null)?.imagekit?.isPrivate\n return typeof value === 'boolean' ? value : fallback\n}\n\nfunction getFileLocation(doc: unknown, filename: string): FileLocation {\n const value = (doc ?? {}) as {\n original?: FileLocation\n variants?: Record<string, FileLocation>\n } & FileLocation\n return (\n [value, value.original, ...Object.values(value.variants ?? {})].find(\n (file) => file?.filename === filename,\n ) ?? value\n )\n}\n\nfunction applyMetadata(\n data: Record<string, unknown>,\n file: ProviderFile,\n isPrivate: boolean,\n slug: string,\n apiRoute: string,\n) {\n data.imagekit = {\n fileId: file.fileId,\n isPrivate,\n thumbnailUrl: file.thumbnail,\n url: file.url,\n }\n data.thumbnailURL = isPrivate\n ? getPrivateAdminThumbnailURL(data, slug, apiRoute)\n : getAdminThumbnailURL(data)\n return data\n}\n\nasync function fetchOriginal({\n file,\n req,\n url,\n}: {\n file: ProviderFile\n req: PayloadRequest\n url: string\n}): Promise<Response> {\n const range = getRangeRequestInfo({ fileSize: file.size, rangeHeader: req.headers.get('Range') })\n if (range.type === 'invalid') {\n return new Response(null, { headers: range.headers, status: range.status })\n }\n const response = await fetch(url, {\n cache: 'no-store',\n headers:\n range.type === 'partial'\n ? { Range: `bytes=${range.rangeStart}-${range.rangeEnd}` }\n : undefined,\n signal: new AbortController().signal,\n })\n if (\n response.status !== range.status ||\n response.headers.get('Content-Length') !== range.headers['Content-Length'] ||\n (range.type === 'partial' &&\n response.headers.get('Content-Range') !== range.headers['Content-Range'])\n ) {\n void response.body?.cancel().catch(() => undefined)\n throw new APIError('ImageKit returned mismatched file content metadata.', 502)\n }\n const headers = new Headers(range.headers)\n headers.set('Content-Type', file.mime ?? 'application/octet-stream')\n if (isXmlMimeType(file.mime ?? '')) {\n headers.set('Content-Security-Policy', uploadContentSecurityPolicy)\n }\n return new Response(response.body, { headers, status: range.status })\n}\n\nfunction canStoreXml(collection: CollectionConfig): boolean {\n const upload = typeof collection.upload === 'object' ? collection.upload : undefined\n return (\n Boolean(upload?.allowRestrictedFileTypes) ||\n !upload?.mimeTypes?.length ||\n upload.mimeTypes.some((mime) => mime.includes('*') || isXmlMimeType(mime))\n )\n}\n\nfunction storageFields({\n buildURL,\n expiresIn,\n isPrivate,\n prefix,\n}: {\n buildURL: (key: string, signed: boolean, transformation?: null | string) => string\n expiresIn: number\n isPrivate: boolean\n prefix: string\n}): Field[] {\n return [\n {\n type: 'collapsible',\n admin: {\n condition: (data) => Boolean(data?.imagekit?.url),\n initCollapsed: true,\n },\n fields: [\n {\n name: 'imagekit',\n type: 'group',\n admin: { disabled: { column: true, filter: true } },\n fields: [\n { name: 'fileId', type: 'text', admin: { hidden: true }, unique: true },\n { name: 'url', type: 'text', admin: { readOnly: true }, label: 'URL' },\n {\n name: 'isPrivate',\n type: 'checkbox',\n admin: { readOnly: true },\n label: 'Private file',\n },\n {\n name: 'signedUrl',\n type: 'text',\n admin: {\n condition: (_data, siblingData) =>\n isPrivateDocument({ imagekit: siblingData }, isPrivate),\n description: `Temporary signed URL. Expires ${expiresIn} seconds after load. Anyone with this URL can access the file until it expires.`,\n readOnly: true,\n },\n hooks: {\n afterRead: [\n ({ data, siblingData }) => {\n if (\n !data?.filename ||\n !isPrivateDocument({ imagekit: siblingData }, isPrivate)\n ) {\n return undefined\n }\n const key = buildStoragePathData({\n collectionPrefix: prefix,\n docPrefix: path.posix.join(data.prefix || prefix, data._objectKey || ''),\n filename: data.filename,\n }).storageFilePath\n return buildURL(key, true)\n },\n ],\n },\n label: 'Signed URL',\n virtual: true,\n },\n { name: 'thumbnailUrl', type: 'text', admin: { hidden: true } },\n ],\n interfaceName: 'imagekitFields',\n label: false,\n },\n ],\n label: 'Storage: ImageKit',\n },\n ]\n}\n"],"names":["ImageKit","toFile","cloudStoragePlugin","buildStoragePathData","openAsBlob","path","APIError","assertClientUploadAllowed","getRangeRequestInfo","isXmlMimeType","uploadContentSecurityPolicy","verifyClientUploadReceipt","createImageKitUploadInstructions","getAdminThumbnailURL","getPrivateAdminThumbnailURL","isPdfMimeType","isVideoMimeType","getImageKitThumbnailSrc","getVideoPosterSrc","imagekitStorage","options","name","collections","Object","keys","init","config","initializeStorage","migrateFolder","payloadStorageImagekit","payloadStorageImageKit","key","trim","Error","folder","replace","split","some","segment","client","privateKey","length","configured","Set","apiRoute","routes","api","expiresIn","signedUrlExpiresIn","prefixFor","slug","posix","join","collectionIsPrivate","value","private","sourceConfig","map","collection","has","isPrivate","disablePayloadAccessControl","canStoreXml","setting","focalPoint","undefined","description","admin","hooks","beforeChange","data","operation","originalDoc","req","verified","context","imagekitVerifiedUpload","existing","payload","db","findOne","where","equals","fileId","id","applyMetadata","upload","adminThumbnail","doc","isPrivateDocument","crop","adapter","prefix","buildURL","signed","transformation","helper","buildSrc","src","raw","urlEndpoint","deleteFile","storageFilePath","file","findFile","files","delete","copyFile","from","to","source","customMetadata","Boolean","isPrivateFile","fileName","basename","dirname","overwriteFile","tags","useUniqueFileName","fields","storageFields","generateURL","filename","docPrefix","collectionPrefix","handleDelete","handleUpload","uploadSource","tempFilePath","type","mimeType","buffer","uploaded","url","mime","size","filesize","thumbnail","thumbnailUrl","staticHandler","params","uploadReference","reference","receipt","collectionSlug","signedReceipt","expectedPath","filePrefix","_objectKey","startsWith","findUploadedFile","fetchOriginal","error","Response","json","message","status","document","getFileLocation","privateFile","tr","URL","searchParams","get","storedURL","imagekit","original","redirect","supportsTempFiles","uploadInstructions","adminHandler","enabled","clientUploads","generate","access","publicKey","requiresUploadReceipt","useInAdmin","output","fromEntries","disableLocalStorage","field","defaultValue","filePath","skip","assets","list","limit","found","find","asset","Number","isSafeInteger","delay","Promise","resolve","setTimeout","fallback","values","variants","thumbnailURL","range","fileSize","rangeHeader","headers","response","fetch","cache","Range","rangeStart","rangeEnd","signal","AbortController","body","cancel","catch","Headers","set","allowRestrictedFileTypes","mimeTypes","includes","condition","initCollapsed","disabled","column","filter","hidden","unique","readOnly","label","_data","siblingData","afterRead","virtual","interfaceName"],"mappings":"AAWA,OAAOA,YAAYC,MAAM,QAAQ,mBAAkB;AACnD,SAASC,kBAAkB,QAAQ,mCAAkC;AACrE,SAASC,oBAAoB,QAAQ,6CAA4C;AACjF,SAASC,UAAU,QAAQ,UAAS;AACpC,OAAOC,UAAU,YAAW;AAC5B,SAASC,QAAQ,QAAQ,UAAS;AAClC,SACEC,yBAAyB,EACzBC,mBAAmB,EACnBC,aAAa,EACbC,2BAA2B,EAC3BC,yBAAyB,QACpB,mBAAkB;AAEzB,SAASC,gCAAgC,QAAQ,kDAAiD;AAClG,SACEC,oBAAoB,EACpBC,2BAA2B,EAC3BC,aAAa,EACbC,eAAe,QACV,4BAA2B;AAClC,SAASC,uBAAuB,EAAEC,iBAAiB,QAAQ,uBAAsB;AAgBjF,qFAAqF,GACrF,OAAO,MAAMC,kBAAkB,CAACC,UAA2D,CAAA;QACzFC,MAAM;QACNC,aAAaC,OAAOC,IAAI,CAACJ,QAAQE,WAAW;QAC5CG,MAAM,CAACC,SAAWC,kBAAkBD,QAAQN;IAC9C,CAAA,EAAE;AAEF,SAASQ,aAAa,QAAQ,eAAc;AAE5C,OAAO,MAAMC,yBAAyBV,gBAAe;AACrD,OAAO,MAAMW,yBAAyBX,gBAAe;AAqBrD,SAASQ,kBAAkBD,MAAc,EAAEN,OAAqC;IAC9E,KAAK,MAAMW,OAAO;QAAC;QAAc;QAAa;QAAe;KAAS,CAAW;QAC/E,IAAI,CAACX,OAAO,CAACW,IAAI,EAAEC,QAAQ;YACzB,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AClK,MAAMqD,YACP,CAAClC,kBAAkB;4CAAE6E,UAAUkE;wCAAY,GAAG5K,YAC9C;4CACA,OAAOK;wCACT;wCACA,MAAMlC,MAAM5B,qBAAqB;4CAC/B0H,kBAAkBjC;4CAClBgC,WAAWvH,KAAK8C,KAAK,CAACC,IAAI,CAACkB,KAAKsB,MAAM,IAAIA,QAAQtB,KAAK+E,UAAU,IAAI;4CACrE1B,UAAUrD,KAAKqD,QAAQ;wCACzB,GAAGrB,eAAe;wCAClB,OAAOT,SAAS9D,KAAK;oCACvB;iCACD;4BACH;4BACAuM,OAAO;4BACPI,SAAS;wBACX;wBACA;4BAAErN,MAAM;4BAAgB6G,MAAM;4BAAQ/D,OAAO;gCAAEgK,QAAQ;4BAAK;wBAAE;qBAC/D;oBACDQ,eAAe;oBACfL,OAAO;gBACT;aACD;YACDA,OAAO;QACT;KACD;AACH"}
package/dist/migrate.js CHANGED
@@ -88,6 +88,7 @@ const transferTag = (source, filePath, documentID, isPrivate)=>{
88
88
  if (!payload) {
89
89
  throw new Error('migrateFolder: `payload` is required.');
90
90
  }
91
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- Object.keys loses the generated consumer's UploadCollectionSlug union.
91
92
  const slugs = Object.keys(collections || {});
92
93
  if (!slugs.length) {
93
94
  throw new Error('migrateFolder: `collections` must include at least one upload collection.');
@@ -132,6 +133,7 @@ const transferTag = (source, filePath, documentID, isPrivate)=>{
132
133
  collection: slug,
133
134
  depth: 0,
134
135
  limit: 100,
136
+ overrideAccess: true,
135
137
  page,
136
138
  sort: 'id'
137
139
  });
@@ -258,7 +260,8 @@ const transferTag = (source, filePath, documentID, isPrivate)=>{
258
260
  data: {
259
261
  ...data,
260
262
  _objectKey: null
261
- }
263
+ },
264
+ overrideAccess: true
262
265
  });
263
266
  }
264
267
  result.migrated += 1;
@@ -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 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,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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,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"}
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 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- Object.keys loses the generated consumer's UploadCollectionSlug union.\n const slugs = Object.keys(collections || {}) as UploadCollectionSlug[]\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({\n collection: slug,\n depth: 0,\n limit: 100,\n overrideAccess: true,\n page,\n sort: 'id',\n })\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 overrideAccess: true,\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","overrideAccess","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,YAA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,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.1",
3
+ "version": "3.0.0-canary.0",
4
4
  "description": "ImageKit storage adapter plugin for Payload CMS uploads",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -37,14 +37,14 @@
37
37
  ],
38
38
  "devDependencies": {
39
39
  "@eslint/eslintrc": "^3.3.7",
40
- "@payloadcms/db-mongodb": "3.90.2",
41
- "@payloadcms/db-postgres": "3.90.2",
42
- "@payloadcms/db-sqlite": "3.90.2",
40
+ "@payloadcms/db-mongodb": "4.0.0-beta.1",
41
+ "@payloadcms/db-postgres": "4.0.0-beta.1",
42
+ "@payloadcms/db-sqlite": "4.0.0-beta.1",
43
43
  "@payloadcms/eslint-config": "3.28.0",
44
- "@payloadcms/next": "3.90.2",
45
- "@payloadcms/plugin-cloud-storage": "3.90.2",
46
- "@payloadcms/richtext-lexical": "3.90.2",
47
- "@payloadcms/ui": "3.90.2",
44
+ "@payloadcms/next": "4.0.0-beta.1",
45
+ "@payloadcms/plugin-cloud-storage": "4.0.0-beta.1",
46
+ "@payloadcms/richtext-lexical": "4.0.0-beta.1",
47
+ "@payloadcms/ui": "4.0.0-beta.1",
48
48
  "@swc-node/register": "1.12.1",
49
49
  "@swc/cli": "0.8.1",
50
50
  "@types/node": "26.6.3",
@@ -55,12 +55,12 @@
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.0",
59
59
  "graphql": "^16.14.2",
60
60
  "mongodb-memory-server": "11.3.0",
61
- "next": "16.3.8",
61
+ "next": "16.4.0",
62
62
  "open": "^11.0.4",
63
- "payload": "3.90.2",
63
+ "payload": "4.0.0-beta.1",
64
64
  "prettier": "^3.9.9",
65
65
  "qs-esm": "8.0.2",
66
66
  "react": "19.3.0",
@@ -74,8 +74,8 @@
74
74
  "vitest": "4.1.11"
75
75
  },
76
76
  "peerDependencies": {
77
- "@payloadcms/plugin-cloud-storage": ">=3.90.1 <4.0.0",
78
- "payload": ">=3.90.1 <4.0.0"
77
+ "@payloadcms/plugin-cloud-storage": "4.0.0-beta.1",
78
+ "payload": "4.0.0-beta.1"
79
79
  },
80
80
  "engines": {
81
81
  "node": ">=24.15.0 <25"
@@ -1,30 +0,0 @@
1
- import type ImageKit from '@imagekit/nodejs';
2
- import type { CollectionConfig } from 'payload';
3
- import type { ImageKitReceiptContext } from './clientUploads.js';
4
- export type VerifiedImageKitUpload = {
5
- fileId: string;
6
- filePath: string;
7
- fileType?: string;
8
- mimeType: string;
9
- name: string;
10
- size: number;
11
- thumbnailUrl?: string;
12
- url: string;
13
- };
14
- type CollectionSecurityConfig = {
15
- collection: CollectionConfig;
16
- isPrivate: boolean;
17
- prefix: string;
18
- };
19
- export declare const getClientUploadStorageFilePath: ({ collectionPrefix, context, }: {
20
- collectionPrefix: string;
21
- context: ImageKitReceiptContext;
22
- }) => string;
23
- export declare const createImageKitClientUploadVerifier: ({ client, collections, }: {
24
- client: ImageKit;
25
- collections: Record<string, CollectionSecurityConfig>;
26
- }) => ({ collectionSlug, context, }: {
27
- collectionSlug: string;
28
- context: unknown;
29
- }) => Promise<VerifiedImageKitUpload>;
30
- export {};
@@ -1,106 +0,0 @@
1
- import { buildStoragePathData } from '@payloadcms/plugin-cloud-storage/utilities';
2
- import { APIError } from 'payload';
3
- import { assertClientUploadAllowed } from 'payload/internal';
4
- import { validateMimeType } from 'payload/shared';
5
- import { isImageKitReceiptContext } from './clientUploads.js';
6
- const getMimeTypeEssence = (mimeType)=>(mimeType.split(';', 1)[0] || '').trim().toLowerCase();
7
- const toImageKitPath = (storageFilePath)=>`/${storageFilePath.replace(/^\/+/, '')}`;
8
- const assetLookupRetryDelays = [
9
- 250,
10
- 500,
11
- 1000,
12
- 2000
13
- ];
14
- const findFileIDByPath = async (client, filePath)=>{
15
- const parentPath = `${filePath.slice(0, filePath.lastIndexOf('/') + 1)}`;
16
- const name = filePath.slice(filePath.lastIndexOf('/') + 1);
17
- const limit = 100;
18
- for(let skip = 0;; skip += limit){
19
- const assets = await client.assets.list({
20
- type: 'file',
21
- limit,
22
- path: parentPath,
23
- skip
24
- });
25
- const found = assets.find((asset)=>'fileId' in asset && asset.filePath === filePath && asset.name === name);
26
- if (found && 'fileId' in found) {
27
- return found.fileId;
28
- }
29
- if (assets.length < limit) {
30
- return undefined;
31
- }
32
- }
33
- };
34
- export const getClientUploadStorageFilePath = ({ collectionPrefix, context })=>buildStoragePathData({
35
- collectionPrefix,
36
- docPrefix: [
37
- context.prefix,
38
- context._objectKey
39
- ].filter(Boolean).join('/'),
40
- filename: context.filename
41
- }).storageFilePath;
42
- export const createImageKitClientUploadVerifier = ({ client, collections })=>{
43
- const verifiedContexts = new WeakMap();
44
- return async ({ collectionSlug, context })=>{
45
- if (!isImageKitReceiptContext(context)) {
46
- throw new APIError('Invalid ImageKit client upload context.', 400);
47
- }
48
- const collectionSecurity = collections[collectionSlug];
49
- if (!collectionSecurity || context.collectionSlug !== collectionSlug || context.isPrivate !== collectionSecurity.isPrivate) {
50
- throw new APIError('ImageKit client upload reference does not match this collection.', 400);
51
- }
52
- const cached = verifiedContexts.get(context);
53
- if (cached) {
54
- return cached;
55
- }
56
- const storageFilePath = getClientUploadStorageFilePath({
57
- collectionPrefix: collectionSecurity.prefix,
58
- context
59
- });
60
- const expectedFilePath = toImageKitPath(storageFilePath);
61
- let fileId = context.fileId;
62
- // Receipts without a file ID can still be verified by their signed path and binding.
63
- // The completion handshake avoids depending on asset listing visibility.
64
- if (!fileId) {
65
- fileId = await findFileIDByPath(client, expectedFilePath);
66
- for (const delay of assetLookupRetryDelays){
67
- if (fileId) {
68
- break;
69
- }
70
- await new Promise((resolve)=>setTimeout(resolve, delay));
71
- fileId = await findFileIDByPath(client, expectedFilePath);
72
- }
73
- }
74
- if (!fileId) {
75
- throw new APIError('ImageKit client upload was not found at its authorized path.', 400);
76
- }
77
- const uploadedFile = await client.files.get(fileId);
78
- const uploadedMime = typeof uploadedFile.mime === 'string' ? getMimeTypeEssence(uploadedFile.mime) : '';
79
- const uploadedSize = uploadedFile.size;
80
- // ImageKit's detected type is authoritative. It may differ from the browser's
81
- // extension-based type, so validate it against the collection, not the claim.
82
- assertClientUploadAllowed({
83
- collection: collectionSecurity.collection,
84
- filename: context.filename,
85
- mimeType: uploadedMime
86
- });
87
- const allowedMimeTypes = typeof collectionSecurity.collection.upload === 'object' && Array.isArray(collectionSecurity.collection.upload.mimeTypes) ? collectionSecurity.collection.upload.mimeTypes : [];
88
- if (uploadedFile.fileId !== fileId || uploadedFile.filePath !== expectedFilePath || uploadedFile.name !== context.filename || context.uploadTag !== undefined && !uploadedFile.tags?.includes(context.uploadTag) || !uploadedMime || typeof uploadedSize !== 'number' || !Number.isSafeInteger(uploadedSize) || uploadedSize !== context.expectedSize || allowedMimeTypes.length > 0 && !validateMimeType(uploadedMime, allowedMimeTypes) || Boolean(uploadedFile.isPrivateFile) !== collectionSecurity.isPrivate || typeof uploadedFile.url !== 'string' || uploadedFile.url.length === 0) {
89
- throw new APIError('ImageKit client upload metadata did not match its authorization.', 400);
90
- }
91
- const verified = {
92
- name: uploadedFile.name,
93
- fileId,
94
- filePath: expectedFilePath,
95
- fileType: uploadedFile.fileType,
96
- mimeType: uploadedMime,
97
- size: uploadedSize,
98
- thumbnailUrl: typeof uploadedFile.thumbnail === 'string' ? uploadedFile.thumbnail : undefined,
99
- url: uploadedFile.url
100
- };
101
- verifiedContexts.set(context, verified);
102
- return verified;
103
- };
104
- };
105
-
106
- //# sourceMappingURL=clientUploadVerification.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/clientUploadVerification.ts"],"sourcesContent":["import type ImageKit from '@imagekit/nodejs'\nimport type { CollectionConfig } from 'payload'\n\nimport { buildStoragePathData } from '@payloadcms/plugin-cloud-storage/utilities'\nimport { APIError } from 'payload'\nimport { assertClientUploadAllowed } from 'payload/internal'\nimport { validateMimeType } from 'payload/shared'\n\nimport type { ImageKitReceiptContext } from './clientUploads.js'\n\nimport { isImageKitReceiptContext } from './clientUploads.js'\n\nexport type VerifiedImageKitUpload = {\n fileId: string\n filePath: string\n fileType?: string\n mimeType: string\n name: string\n size: number\n thumbnailUrl?: string\n url: string\n}\n\ntype CollectionSecurityConfig = {\n collection: CollectionConfig\n isPrivate: boolean\n prefix: string\n}\n\nconst getMimeTypeEssence = (mimeType: string): string =>\n (mimeType.split(';', 1)[0] || '').trim().toLowerCase()\n\nconst toImageKitPath = (storageFilePath: string): string =>\n `/${storageFilePath.replace(/^\\/+/, '')}`\n\nconst assetLookupRetryDelays = [250, 500, 1000, 2000]\n\nconst findFileIDByPath = async (\n client: ImageKit,\n filePath: string,\n): Promise<string | undefined> => {\n const parentPath = `${filePath.slice(0, filePath.lastIndexOf('/') + 1)}`\n const name = filePath.slice(filePath.lastIndexOf('/') + 1)\n const limit = 100\n\n for (let skip = 0; ; skip += limit) {\n const assets = await client.assets.list({\n type: 'file',\n limit,\n path: parentPath,\n skip,\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 return undefined\n }\n }\n}\n\nexport const getClientUploadStorageFilePath = ({\n collectionPrefix,\n context,\n}: {\n collectionPrefix: string\n context: ImageKitReceiptContext\n}): string =>\n buildStoragePathData({\n collectionPrefix,\n docPrefix: [context.prefix, context._objectKey].filter(Boolean).join('/'),\n filename: context.filename,\n }).storageFilePath\n\nexport const createImageKitClientUploadVerifier = ({\n client,\n collections,\n}: {\n client: ImageKit\n collections: Record<string, CollectionSecurityConfig>\n}) => {\n const verifiedContexts = new WeakMap<object, VerifiedImageKitUpload>()\n\n return async ({\n collectionSlug,\n context,\n }: {\n collectionSlug: string\n context: unknown\n }): Promise<VerifiedImageKitUpload> => {\n if (!isImageKitReceiptContext(context)) {\n throw new APIError('Invalid ImageKit client upload context.', 400)\n }\n\n const collectionSecurity = collections[collectionSlug]\n if (\n !collectionSecurity ||\n context.collectionSlug !== collectionSlug ||\n context.isPrivate !== collectionSecurity.isPrivate\n ) {\n throw new APIError('ImageKit client upload reference does not match this collection.', 400)\n }\n\n const cached = verifiedContexts.get(context)\n if (cached) {\n return cached\n }\n\n const storageFilePath = getClientUploadStorageFilePath({\n collectionPrefix: collectionSecurity.prefix,\n context,\n })\n const expectedFilePath = toImageKitPath(storageFilePath)\n let fileId = context.fileId\n\n // Receipts without a file ID can still be verified by their signed path and binding.\n // The completion handshake avoids depending on asset listing visibility.\n if (!fileId) {\n fileId = await findFileIDByPath(client, expectedFilePath)\n for (const delay of assetLookupRetryDelays) {\n if (fileId) {\n break\n }\n await new Promise((resolve) => setTimeout(resolve, delay))\n fileId = await findFileIDByPath(client, expectedFilePath)\n }\n }\n\n if (!fileId) {\n throw new APIError('ImageKit client upload was not found at its authorized path.', 400)\n }\n\n const uploadedFile = await client.files.get(fileId)\n const uploadedMime =\n typeof uploadedFile.mime === 'string' ? getMimeTypeEssence(uploadedFile.mime) : ''\n const uploadedSize = uploadedFile.size\n\n // ImageKit's detected type is authoritative. It may differ from the browser's\n // extension-based type, so validate it against the collection, not the claim.\n assertClientUploadAllowed({\n collection: collectionSecurity.collection,\n filename: context.filename,\n mimeType: uploadedMime,\n })\n const allowedMimeTypes =\n typeof collectionSecurity.collection.upload === 'object' &&\n Array.isArray(collectionSecurity.collection.upload.mimeTypes)\n ? collectionSecurity.collection.upload.mimeTypes\n : []\n\n if (\n uploadedFile.fileId !== fileId ||\n uploadedFile.filePath !== expectedFilePath ||\n uploadedFile.name !== context.filename ||\n (context.uploadTag !== undefined && !uploadedFile.tags?.includes(context.uploadTag)) ||\n !uploadedMime ||\n typeof uploadedSize !== 'number' ||\n !Number.isSafeInteger(uploadedSize) ||\n uploadedSize !== context.expectedSize ||\n (allowedMimeTypes.length > 0 && !validateMimeType(uploadedMime, allowedMimeTypes)) ||\n Boolean(uploadedFile.isPrivateFile) !== collectionSecurity.isPrivate ||\n typeof uploadedFile.url !== 'string' ||\n uploadedFile.url.length === 0\n ) {\n throw new APIError('ImageKit client upload metadata did not match its authorization.', 400)\n }\n\n const verified: VerifiedImageKitUpload = {\n name: uploadedFile.name,\n fileId,\n filePath: expectedFilePath,\n fileType: uploadedFile.fileType,\n mimeType: uploadedMime,\n size: uploadedSize,\n thumbnailUrl: typeof uploadedFile.thumbnail === 'string' ? uploadedFile.thumbnail : undefined,\n url: uploadedFile.url,\n }\n\n verifiedContexts.set(context, verified)\n return verified\n }\n}\n"],"names":["buildStoragePathData","APIError","assertClientUploadAllowed","validateMimeType","isImageKitReceiptContext","getMimeTypeEssence","mimeType","split","trim","toLowerCase","toImageKitPath","storageFilePath","replace","assetLookupRetryDelays","findFileIDByPath","client","filePath","parentPath","slice","lastIndexOf","name","limit","skip","assets","list","type","path","found","find","asset","fileId","length","undefined","getClientUploadStorageFilePath","collectionPrefix","context","docPrefix","prefix","_objectKey","filter","Boolean","join","filename","createImageKitClientUploadVerifier","collections","verifiedContexts","WeakMap","collectionSlug","collectionSecurity","isPrivate","cached","get","expectedFilePath","delay","Promise","resolve","setTimeout","uploadedFile","files","uploadedMime","mime","uploadedSize","size","collection","allowedMimeTypes","upload","Array","isArray","mimeTypes","uploadTag","tags","includes","Number","isSafeInteger","expectedSize","isPrivateFile","url","verified","fileType","thumbnailUrl","thumbnail","set"],"mappings":"AAGA,SAASA,oBAAoB,QAAQ,6CAA4C;AACjF,SAASC,QAAQ,QAAQ,UAAS;AAClC,SAASC,yBAAyB,QAAQ,mBAAkB;AAC5D,SAASC,gBAAgB,QAAQ,iBA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