payload 3.0.0-beta.68 → 3.0.0-beta.69
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/auth/baseFields/email.js +1 -1
- package/dist/auth/baseFields/email.js.map +1 -1
- package/dist/collections/config/client.d.ts.map +1 -1
- package/dist/collections/config/client.js +1 -0
- package/dist/collections/config/client.js.map +1 -1
- package/dist/collections/dataloader.js.map +1 -1
- package/dist/config/sanitize.d.ts.map +1 -1
- package/dist/config/sanitize.js +2 -0
- package/dist/config/sanitize.js.map +1 -1
- package/dist/config/types.d.ts +4 -1
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/database/migrations/getPredefinedMigration.d.ts.map +1 -1
- package/dist/database/migrations/getPredefinedMigration.js +5 -2
- package/dist/database/migrations/getPredefinedMigration.js.map +1 -1
- package/dist/exports/components/utilities.d.ts +2 -0
- package/dist/exports/components/utilities.d.ts.map +1 -0
- package/dist/exports/components/utilities.js +2 -0
- package/dist/exports/components/utilities.js.map +1 -0
- package/dist/fields/config/client.d.ts.map +1 -1
- package/dist/fields/config/types.d.ts +1 -0
- package/dist/fields/config/types.d.ts.map +1 -1
- package/dist/fields/config/types.js.map +1 -1
- package/dist/fields/validations.d.ts.map +1 -1
- package/dist/uploads/cropImage.d.ts +4 -1
- package/dist/uploads/cropImage.d.ts.map +1 -1
- package/dist/uploads/cropImage.js +8 -2
- package/dist/uploads/cropImage.js.map +1 -1
- package/dist/uploads/generateFileData.d.ts.map +1 -1
- package/dist/uploads/generateFileData.js +12 -3
- package/dist/uploads/generateFileData.js.map +1 -1
- package/dist/uploads/imageResizer.d.ts +3 -1
- package/dist/uploads/imageResizer.d.ts.map +1 -1
- package/dist/uploads/imageResizer.js +15 -4
- package/dist/uploads/imageResizer.js.map +1 -1
- package/dist/uploads/optionallyAppendMetadata.d.ts +12 -0
- package/dist/uploads/optionallyAppendMetadata.d.ts.map +1 -0
- package/dist/uploads/optionallyAppendMetadata.js +15 -0
- package/dist/uploads/optionallyAppendMetadata.js.map +1 -0
- package/dist/uploads/types.d.ts +12 -0
- package/dist/uploads/types.d.ts.map +1 -1
- package/dist/uploads/types.js.map +1 -1
- package/dist/utilities/configToJSONSchema.d.ts.map +1 -1
- package/dist/utilities/configToJSONSchema.js +105 -72
- package/dist/utilities/configToJSONSchema.js.map +1 -1
- package/dist/utilities/createLocalReq.d.ts.map +1 -1
- package/dist/utilities/createLocalReq.js +2 -1
- package/dist/utilities/createLocalReq.js.map +1 -1
- package/dist/versions/enforceMaxVersions.d.ts.map +1 -1
- package/dist/versions/enforceMaxVersions.js +2 -0
- package/dist/versions/enforceMaxVersions.js.map +1 -1
- package/dist/versions/saveVersion.d.ts.map +1 -1
- package/dist/versions/saveVersion.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/uploads/imageResizer.ts"],"sourcesContent":["import type { Sharp, Metadata as SharpMetadata, SharpOptions } from 'sharp'\n\nimport { fileTypeFromBuffer } from 'file-type'\nimport fs from 'fs'\nimport sanitize from 'sanitize-filename'\n\nimport type { SanitizedCollectionConfig } from '../collections/config/types.js'\nimport type { SharpDependency } from '../config/types.js'\nimport type { PayloadRequest } from '../types/index.js'\nimport type {\n FileSize,\n FileSizes,\n FileToSave,\n ImageSize,\n ProbedImageSize,\n UploadEdits,\n} from './types.js'\n\nimport { isNumber } from '../utilities/isNumber.js'\nimport fileExists from './fileExists.js'\n\ntype ResizeArgs = {\n config: SanitizedCollectionConfig\n dimensions: ProbedImageSize\n file: PayloadRequest['file']\n mimeType: string\n req: PayloadRequest\n savedFilename: string\n sharp?: SharpDependency\n staticPath: string\n uploadEdits?: UploadEdits\n}\n\n/** Result from resizing and transforming the requested image sizes */\ntype ImageSizesResult = {\n focalPoint?: UploadEdits['focalPoint']\n sizeData: FileSizes\n sizesToSave: FileToSave[]\n}\n\ntype SanitizedImageData = {\n ext: string\n name: string\n}\n\n/**\n * Sanitize the image name and extract the extension from the source image\n *\n * @param sourceImage - the source image\n * @returns the sanitized name and extension\n */\nconst getSanitizedImageData = (sourceImage: string): SanitizedImageData => {\n const extension = sourceImage.split('.').pop()\n const name = sanitize(sourceImage.substring(0, sourceImage.lastIndexOf('.')) || sourceImage)\n return { name, ext: extension }\n}\n\n/**\n * Create a new image name based on the output image name, the dimensions and\n * the extension.\n *\n * Ignore the fact that duplicate names could happen if the there is one\n * size with `width AND height` and one with only `height OR width`. Because\n * space is expensive, we will reuse the same image for both sizes.\n *\n * @param outputImageName - the sanitized image name\n * @param bufferInfo - the buffer info\n * @param extension - the extension to use\n * @returns the new image name that is not taken\n */\ntype CreateImageNameArgs = {\n extension: string\n height: number\n outputImageName: string\n width: number\n}\nconst createImageName = ({\n extension,\n height,\n outputImageName,\n width,\n}: CreateImageNameArgs): string => {\n return `${outputImageName}-${width}x${height}.${extension}`\n}\n\ntype CreateResultArgs = {\n filename?: FileSize['filename']\n filesize?: FileSize['filesize']\n height?: FileSize['height']\n mimeType?: FileSize['mimeType']\n name: string\n sizesToSave?: FileToSave[]\n width?: FileSize['width']\n}\n\n/**\n * Create the result object for the image resize operation based on the\n * provided parameters. If the name is not provided, an empty result object\n * is returned.\n *\n * @param name - the name of the image\n * @param filename - the filename of the image\n * @param width - the width of the image\n * @param height - the height of the image\n * @param filesize - the filesize of the image\n * @param mimeType - the mime type of the image\n * @param sizesToSave - the sizes to save\n * @returns the result object\n */\nconst createResult = ({\n name,\n filename = null,\n filesize = null,\n height = null,\n mimeType = null,\n sizesToSave = [],\n width = null,\n}: CreateResultArgs): ImageSizesResult => {\n return {\n sizeData: {\n [name]: {\n filename,\n filesize,\n height,\n mimeType,\n width,\n },\n },\n sizesToSave,\n }\n}\n\n/**\n * Determine whether or not to resize the image.\n * - resize using image config\n * - resize using image config with focal adjustments\n * - do not resize at all\n *\n * `imageResizeConfig.withoutEnlargement`:\n * - undefined [default]: uploading images with smaller width AND height than the image size will return null\n * - false: always enlarge images to the image size\n * - true: if the image is smaller than the image size, return the original image\n *\n * `imageResizeConfig.withoutReduction`:\n * - false [default]: always enlarge images to the image size\n * - true: if the image is smaller than the image size, return the original image\n *\n * @return 'omit' | 'resize' | 'resizeWithFocalPoint'\n */\nconst getImageResizeAction = ({\n dimensions: originalImage,\n hasFocalPoint,\n imageResizeConfig,\n}: {\n dimensions: ProbedImageSize\n hasFocalPoint?: boolean\n imageResizeConfig: ImageSize\n}): 'omit' | 'resize' | 'resizeWithFocalPoint' => {\n const {\n fit,\n height: targetHeight,\n width: targetWidth,\n withoutEnlargement,\n withoutReduction,\n } = imageResizeConfig\n\n // prevent upscaling by default when x and y are both smaller than target image size\n if (targetHeight && targetWidth) {\n const originalImageIsSmallerXAndY =\n originalImage.width < targetWidth && originalImage.height < targetHeight\n if (withoutEnlargement === undefined && originalImageIsSmallerXAndY) {\n return 'omit' // prevent image size from being enlarged\n }\n }\n\n const originalImageIsSmallerXOrY =\n originalImage.width < targetWidth || originalImage.height < targetHeight\n if (fit === 'contain' || fit === 'inside') return 'resize'\n if (!isNumber(targetHeight) && !isNumber(targetWidth)) return 'resize'\n\n const targetAspectRatio = targetWidth / targetHeight\n const originalAspectRatio = originalImage.width / originalImage.height\n if (originalAspectRatio === targetAspectRatio) return 'resize'\n\n if (withoutEnlargement && originalImageIsSmallerXOrY) return 'resize'\n if (withoutReduction && !originalImageIsSmallerXOrY) return 'resize'\n\n return hasFocalPoint ? 'resizeWithFocalPoint' : 'resize'\n}\n\n/**\n * Sanitize the resize config. If the resize config has the `withoutReduction`\n * property set to true, the `fit` and `position` properties will be set to `contain`\n * and `top left` respectively.\n *\n * @param resizeConfig - the resize config\n * @returns a sanitized resize config\n */\nconst sanitizeResizeConfig = (resizeConfig: ImageSize): ImageSize => {\n if (resizeConfig.withoutReduction) {\n return {\n ...resizeConfig,\n // Why fit `contain` should also be set to https://github.com/lovell/sharp/issues/3595\n fit: resizeConfig?.fit || 'contain',\n position: resizeConfig?.position || 'left top',\n }\n }\n return resizeConfig\n}\n\n/**\n * Used to extract height from images, animated or not.\n *\n * @param sharpMetadata - the sharp metadata\n * @returns the height of the image\n */\nfunction extractHeightFromImage(sharpMetadata: SharpMetadata): number {\n if (sharpMetadata?.pages) {\n return sharpMetadata.height / sharpMetadata.pages\n }\n return sharpMetadata.height\n}\n\n/**\n * For the provided image sizes, handle the resizing and the transforms\n * (format, trim, etc.) of each requested image size and return the result object.\n * This only handles the image sizes. The transforms of the original image\n * are handled in {@link ./generateFileData.ts}.\n *\n * The image will be resized according to the provided\n * resize config. If no image sizes are requested, the resolved data will be empty.\n * For every image that does not need to be resized, a result object with `null`\n * parameters will be returned.\n *\n * @param resizeConfig - the resize config\n * @returns the result of the resize operation(s)\n */\nexport async function resizeAndTransformImageSizes({\n config,\n dimensions,\n file,\n mimeType,\n req,\n savedFilename,\n sharp,\n staticPath,\n uploadEdits,\n}: ResizeArgs): Promise<ImageSizesResult> {\n const { focalPoint: focalPointEnabled = true, imageSizes } = config.upload\n\n // Focal point adjustments\n const incomingFocalPoint = uploadEdits.focalPoint\n ? {\n x: isNumber(uploadEdits.focalPoint.x) ? Math.round(uploadEdits.focalPoint.x) : 50,\n y: isNumber(uploadEdits.focalPoint.y) ? Math.round(uploadEdits.focalPoint.y) : 50,\n }\n : undefined\n\n const defaultResult: ImageSizesResult = {\n ...(focalPointEnabled && incomingFocalPoint && { focalPoint: incomingFocalPoint }),\n sizeData: {},\n sizesToSave: [],\n }\n\n if (!imageSizes || !sharp) {\n return defaultResult\n }\n\n // Determine if the file is animated\n const fileIsAnimatedType = ['image/avif', 'image/gif', 'image/webp'].includes(file.mimetype)\n const sharpOptions: SharpOptions = {}\n\n if (fileIsAnimatedType) sharpOptions.animated = true\n\n const sharpBase: Sharp | undefined = sharp(file.tempFilePath || file.data, sharpOptions).rotate() // pass rotate() to auto-rotate based on EXIF data. https://github.com/payloadcms/payload/pull/3081\n const originalImageMeta = await sharpBase.metadata()\n\n const resizeImageMeta = {\n height: extractHeightFromImage(originalImageMeta),\n width: originalImageMeta.width,\n }\n\n const results: ImageSizesResult[] = await Promise.all(\n imageSizes.map(async (imageResizeConfig): Promise<ImageSizesResult> => {\n imageResizeConfig = sanitizeResizeConfig(imageResizeConfig)\n\n const resizeAction = getImageResizeAction({\n dimensions,\n hasFocalPoint: Boolean(incomingFocalPoint),\n imageResizeConfig,\n })\n if (resizeAction === 'omit') return createResult({ name: imageResizeConfig.name })\n\n const imageToResize = sharpBase.clone()\n let resized = imageToResize\n\n if (resizeAction === 'resizeWithFocalPoint') {\n let { height: resizeHeight, width: resizeWidth } = imageResizeConfig\n\n const originalAspectRatio = dimensions.width / dimensions.height\n\n // Calculate resizeWidth based on original aspect ratio if it's undefined\n if (resizeHeight && !resizeWidth) {\n resizeWidth = Math.round(resizeHeight * originalAspectRatio)\n }\n\n // Calculate resizeHeight based on original aspect ratio if it's undefined\n if (resizeWidth && !resizeHeight) {\n resizeHeight = Math.round(resizeWidth / originalAspectRatio)\n }\n\n if (!resizeHeight) resizeHeight = resizeImageMeta.height\n if (!resizeWidth) resizeWidth = resizeImageMeta.width\n\n const resizeAspectRatio = resizeWidth / resizeHeight\n const prioritizeHeight = resizeAspectRatio < originalAspectRatio\n // Scales the image before extracting from it\n resized = imageToResize.resize({\n height: prioritizeHeight ? resizeHeight : undefined,\n width: prioritizeHeight ? undefined : resizeWidth,\n })\n\n // must read from buffer, resize.metadata will return the original image metadata\n const { info } = await resized.toBuffer({ resolveWithObject: true })\n resizeImageMeta.height = extractHeightFromImage({\n ...originalImageMeta,\n height: info.height,\n })\n resizeImageMeta.width = info.width\n\n const halfResizeX = resizeWidth / 2\n const xFocalCenter = resizeImageMeta.width * (incomingFocalPoint.x / 100)\n const calculatedRightPixelBound = xFocalCenter + halfResizeX\n let leftBound = xFocalCenter - halfResizeX\n\n // if the right bound is greater than the image width, adjust the left bound\n // keeping focus on the right\n if (calculatedRightPixelBound > resizeImageMeta.width) {\n leftBound = resizeImageMeta.width - resizeWidth\n }\n\n // if the left bound is less than 0, adjust the left bound to 0\n // keeping the focus on the left\n if (leftBound < 0) leftBound = 0\n\n const halfResizeY = resizeHeight / 2\n const yFocalCenter = resizeImageMeta.height * (incomingFocalPoint.y / 100)\n const calculatedBottomPixelBound = yFocalCenter + halfResizeY\n let topBound = yFocalCenter - halfResizeY\n\n // if the bottom bound is greater than the image height, adjust the top bound\n // keeping the image as far right as possible\n if (calculatedBottomPixelBound > resizeImageMeta.height) {\n topBound = resizeImageMeta.height - resizeHeight\n }\n\n // if the top bound is less than 0, adjust the top bound to 0\n // keeping the image focus near the top\n if (topBound < 0) topBound = 0\n\n resized = resized.extract({\n height: resizeHeight,\n left: Math.floor(leftBound),\n top: Math.floor(topBound),\n width: resizeWidth,\n })\n } else {\n resized = imageToResize.resize(imageResizeConfig)\n }\n\n if (imageResizeConfig.formatOptions) {\n resized = resized.toFormat(\n imageResizeConfig.formatOptions.format,\n imageResizeConfig.formatOptions.options,\n )\n }\n\n if (imageResizeConfig.trimOptions) {\n resized = resized.trim(imageResizeConfig.trimOptions)\n }\n\n const { data: bufferData, info: bufferInfo } = await resized.toBuffer({\n resolveWithObject: true,\n })\n\n const sanitizedImage = getSanitizedImageData(savedFilename)\n\n if (req.payloadUploadSizes) {\n req.payloadUploadSizes[imageResizeConfig.name] = bufferData\n }\n\n const mimeInfo = await fileTypeFromBuffer(bufferData)\n\n const imageNameWithDimensions = createImageName({\n extension: mimeInfo?.ext || sanitizedImage.ext,\n height: extractHeightFromImage({\n ...originalImageMeta,\n height: bufferInfo.height,\n }),\n outputImageName: sanitizedImage.name,\n width: bufferInfo.width,\n })\n\n const imagePath = `${staticPath}/${imageNameWithDimensions}`\n\n if (await fileExists(imagePath)) {\n try {\n fs.unlinkSync(imagePath)\n } catch {\n // Ignore unlink errors\n }\n }\n\n const { height, size, width } = bufferInfo\n return createResult({\n name: imageResizeConfig.name,\n filename: imageNameWithDimensions,\n filesize: size,\n height:\n fileIsAnimatedType && originalImageMeta.pages ? height / originalImageMeta.pages : height,\n mimeType: mimeInfo?.mime || mimeType,\n sizesToSave: [{ buffer: bufferData, path: imagePath }],\n width,\n })\n }),\n )\n\n return results.reduce(\n (acc, result) => {\n Object.assign(acc.sizeData, result.sizeData)\n acc.sizesToSave.push(...result.sizesToSave)\n return acc\n },\n { ...defaultResult },\n )\n}\n"],"names":["fileTypeFromBuffer","fs","sanitize","isNumber","fileExists","getSanitizedImageData","sourceImage","extension","split","pop","name","substring","lastIndexOf","ext","createImageName","height","outputImageName","width","createResult","filename","filesize","mimeType","sizesToSave","sizeData","getImageResizeAction","dimensions","originalImage","hasFocalPoint","imageResizeConfig","fit","targetHeight","targetWidth","withoutEnlargement","withoutReduction","originalImageIsSmallerXAndY","undefined","originalImageIsSmallerXOrY","targetAspectRatio","originalAspectRatio","sanitizeResizeConfig","resizeConfig","position","extractHeightFromImage","sharpMetadata","pages","resizeAndTransformImageSizes","config","file","req","savedFilename","sharp","staticPath","uploadEdits","focalPoint","focalPointEnabled","imageSizes","upload","incomingFocalPoint","x","Math","round","y","defaultResult","fileIsAnimatedType","includes","mimetype","sharpOptions","animated","sharpBase","tempFilePath","data","rotate","originalImageMeta","metadata","resizeImageMeta","results","Promise","all","map","resizeAction","Boolean","imageToResize","clone","resized","resizeHeight","resizeWidth","resizeAspectRatio","prioritizeHeight","resize","info","toBuffer","resolveWithObject","halfResizeX","xFocalCenter","calculatedRightPixelBound","leftBound","halfResizeY","yFocalCenter","calculatedBottomPixelBound","topBound","extract","left","floor","top","formatOptions","toFormat","format","options","trimOptions","trim","bufferData","bufferInfo","sanitizedImage","payloadUploadSizes","mimeInfo","imageNameWithDimensions","imagePath","unlinkSync","size","mime","buffer","path","reduce","acc","result","Object","assign","push"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,YAAW;AAC9C,OAAOC,QAAQ,KAAI;AACnB,OAAOC,cAAc,oBAAmB;AAcxC,SAASC,QAAQ,QAAQ,2BAA0B;AACnD,OAAOC,gBAAgB,kBAAiB;AA0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M;YACN,uBAAuB;YACzB;QACF;QAEA,MAAM,EAAErG,MAAM,EAAEuG,IAAI,EAAErG,KAAK,EAAE,GAAG8F;QAChC,OAAO7F,aAAa;YAClBR,MAAMkB,kBAAkBlB,IAAI;YAC5BS,UAAUgG;YACV/F,UAAUkG;YACVvG,QACEgD,sBAAsBS,kBAAkB5B,KAAK,GAAG7B,SAASyD,kBAAkB5B,KAAK,GAAG7B;YACrFM,UAAU6F,UAAUK,QAAQlG;YAC5BC,aAAa;gBAAC;oBAAEkG,QAAQV;oBAAYW,MAAML;gBAAU;aAAE;YACtDnG;QACF;IACF;IAGF,OAAO0D,QAAQ+C,MAAM,CACnB,CAACC,KAAKC;QACJC,OAAOC,MAAM,CAACH,IAAIpG,QAAQ,EAAEqG,OAAOrG,QAAQ;QAC3CoG,IAAIrG,WAAW,CAACyG,IAAI,IAAIH,OAAOtG,WAAW;QAC1C,OAAOqG;IACT,GACA;QAAE,GAAG7D,aAAa;IAAC;AAEvB"}
|
|
1
|
+
{"version":3,"sources":["../../src/uploads/imageResizer.ts"],"sourcesContent":["import type { Sharp, Metadata as SharpMetadata, SharpOptions } from 'sharp'\n\nimport { fileTypeFromBuffer } from 'file-type'\nimport fs from 'fs'\nimport sanitize from 'sanitize-filename'\n\nimport type { SanitizedCollectionConfig } from '../collections/config/types.js'\nimport type { SharpDependency } from '../config/types.js'\nimport type { PayloadRequest } from '../types/index.js'\nimport type { WithMetadata } from './optionallyAppendMetadata.js'\nimport type {\n FileSize,\n FileSizes,\n FileToSave,\n ImageSize,\n ProbedImageSize,\n UploadEdits,\n} from './types.js'\n\nimport { isNumber } from '../utilities/isNumber.js'\nimport fileExists from './fileExists.js'\nimport { optionallyAppendMetadata } from './optionallyAppendMetadata.js'\n\ntype ResizeArgs = {\n config: SanitizedCollectionConfig\n dimensions: ProbedImageSize\n file: PayloadRequest['file']\n mimeType: string\n req: PayloadRequest\n savedFilename: string\n sharp?: SharpDependency\n staticPath: string\n uploadEdits?: UploadEdits\n withMetadata?: WithMetadata\n}\n\n/** Result from resizing and transforming the requested image sizes */\ntype ImageSizesResult = {\n focalPoint?: UploadEdits['focalPoint']\n sizeData: FileSizes\n sizesToSave: FileToSave[]\n}\n\ntype SanitizedImageData = {\n ext: string\n name: string\n}\n\n/**\n * Sanitize the image name and extract the extension from the source image\n *\n * @param sourceImage - the source image\n * @returns the sanitized name and extension\n */\nconst getSanitizedImageData = (sourceImage: string): SanitizedImageData => {\n const extension = sourceImage.split('.').pop()\n const name = sanitize(sourceImage.substring(0, sourceImage.lastIndexOf('.')) || sourceImage)\n return { name, ext: extension }\n}\n\n/**\n * Create a new image name based on the output image name, the dimensions and\n * the extension.\n *\n * Ignore the fact that duplicate names could happen if the there is one\n * size with `width AND height` and one with only `height OR width`. Because\n * space is expensive, we will reuse the same image for both sizes.\n *\n * @param outputImageName - the sanitized image name\n * @param bufferInfo - the buffer info\n * @param extension - the extension to use\n * @returns the new image name that is not taken\n */\ntype CreateImageNameArgs = {\n extension: string\n height: number\n outputImageName: string\n width: number\n}\nconst createImageName = ({\n extension,\n height,\n outputImageName,\n width,\n}: CreateImageNameArgs): string => {\n return `${outputImageName}-${width}x${height}.${extension}`\n}\n\ntype CreateResultArgs = {\n filename?: FileSize['filename']\n filesize?: FileSize['filesize']\n height?: FileSize['height']\n mimeType?: FileSize['mimeType']\n name: string\n sizesToSave?: FileToSave[]\n width?: FileSize['width']\n}\n\n/**\n * Create the result object for the image resize operation based on the\n * provided parameters. If the name is not provided, an empty result object\n * is returned.\n *\n * @param name - the name of the image\n * @param filename - the filename of the image\n * @param width - the width of the image\n * @param height - the height of the image\n * @param filesize - the filesize of the image\n * @param mimeType - the mime type of the image\n * @param sizesToSave - the sizes to save\n * @returns the result object\n */\nconst createResult = ({\n name,\n filename = null,\n filesize = null,\n height = null,\n mimeType = null,\n sizesToSave = [],\n width = null,\n}: CreateResultArgs): ImageSizesResult => {\n return {\n sizeData: {\n [name]: {\n filename,\n filesize,\n height,\n mimeType,\n width,\n },\n },\n sizesToSave,\n }\n}\n\n/**\n * Determine whether or not to resize the image.\n * - resize using image config\n * - resize using image config with focal adjustments\n * - do not resize at all\n *\n * `imageResizeConfig.withoutEnlargement`:\n * - undefined [default]: uploading images with smaller width AND height than the image size will return null\n * - false: always enlarge images to the image size\n * - true: if the image is smaller than the image size, return the original image\n *\n * `imageResizeConfig.withoutReduction`:\n * - false [default]: always enlarge images to the image size\n * - true: if the image is smaller than the image size, return the original image\n *\n * @return 'omit' | 'resize' | 'resizeWithFocalPoint'\n */\nconst getImageResizeAction = ({\n dimensions: originalImage,\n hasFocalPoint,\n imageResizeConfig,\n}: {\n dimensions: ProbedImageSize\n hasFocalPoint?: boolean\n imageResizeConfig: ImageSize\n}): 'omit' | 'resize' | 'resizeWithFocalPoint' => {\n const {\n fit,\n height: targetHeight,\n width: targetWidth,\n withoutEnlargement,\n withoutReduction,\n } = imageResizeConfig\n\n // prevent upscaling by default when x and y are both smaller than target image size\n if (targetHeight && targetWidth) {\n const originalImageIsSmallerXAndY =\n originalImage.width < targetWidth && originalImage.height < targetHeight\n if (withoutEnlargement === undefined && originalImageIsSmallerXAndY) {\n return 'omit' // prevent image size from being enlarged\n }\n }\n\n const originalImageIsSmallerXOrY =\n originalImage.width < targetWidth || originalImage.height < targetHeight\n if (fit === 'contain' || fit === 'inside') return 'resize'\n if (!isNumber(targetHeight) && !isNumber(targetWidth)) return 'resize'\n\n const targetAspectRatio = targetWidth / targetHeight\n const originalAspectRatio = originalImage.width / originalImage.height\n if (originalAspectRatio === targetAspectRatio) return 'resize'\n\n if (withoutEnlargement && originalImageIsSmallerXOrY) return 'resize'\n if (withoutReduction && !originalImageIsSmallerXOrY) return 'resize'\n\n return hasFocalPoint ? 'resizeWithFocalPoint' : 'resize'\n}\n\n/**\n * Sanitize the resize config. If the resize config has the `withoutReduction`\n * property set to true, the `fit` and `position` properties will be set to `contain`\n * and `top left` respectively.\n *\n * @param resizeConfig - the resize config\n * @returns a sanitized resize config\n */\nconst sanitizeResizeConfig = (resizeConfig: ImageSize): ImageSize => {\n if (resizeConfig.withoutReduction) {\n return {\n ...resizeConfig,\n // Why fit `contain` should also be set to https://github.com/lovell/sharp/issues/3595\n fit: resizeConfig?.fit || 'contain',\n position: resizeConfig?.position || 'left top',\n }\n }\n return resizeConfig\n}\n\n/**\n * Used to extract height from images, animated or not.\n *\n * @param sharpMetadata - the sharp metadata\n * @returns the height of the image\n */\nfunction extractHeightFromImage(sharpMetadata: SharpMetadata): number {\n if (sharpMetadata?.pages) {\n return sharpMetadata.height / sharpMetadata.pages\n }\n return sharpMetadata.height\n}\n\n/**\n * For the provided image sizes, handle the resizing and the transforms\n * (format, trim, etc.) of each requested image size and return the result object.\n * This only handles the image sizes. The transforms of the original image\n * are handled in {@link ./generateFileData.ts}.\n *\n * The image will be resized according to the provided\n * resize config. If no image sizes are requested, the resolved data will be empty.\n * For every image that does not need to be resized, a result object with `null`\n * parameters will be returned.\n *\n * @param resizeConfig - the resize config\n * @returns the result of the resize operation(s)\n */\nexport async function resizeAndTransformImageSizes({\n config,\n dimensions,\n file,\n mimeType,\n req,\n savedFilename,\n sharp,\n staticPath,\n uploadEdits,\n withMetadata,\n}: ResizeArgs): Promise<ImageSizesResult> {\n const { focalPoint: focalPointEnabled = true, imageSizes } = config.upload\n\n // Focal point adjustments\n const incomingFocalPoint = uploadEdits.focalPoint\n ? {\n x: isNumber(uploadEdits.focalPoint.x) ? Math.round(uploadEdits.focalPoint.x) : 50,\n y: isNumber(uploadEdits.focalPoint.y) ? Math.round(uploadEdits.focalPoint.y) : 50,\n }\n : undefined\n\n const defaultResult: ImageSizesResult = {\n ...(focalPointEnabled && incomingFocalPoint && { focalPoint: incomingFocalPoint }),\n sizeData: {},\n sizesToSave: [],\n }\n\n if (!imageSizes || !sharp) {\n return defaultResult\n }\n\n // Determine if the file is animated\n const fileIsAnimatedType = ['image/avif', 'image/gif', 'image/webp'].includes(file.mimetype)\n const sharpOptions: SharpOptions = {}\n\n if (fileIsAnimatedType) sharpOptions.animated = true\n\n const sharpBase: Sharp | undefined = sharp(file.tempFilePath || file.data, sharpOptions).rotate() // pass rotate() to auto-rotate based on EXIF data. https://github.com/payloadcms/payload/pull/3081\n const originalImageMeta = await sharpBase.metadata()\n\n const resizeImageMeta = {\n height: extractHeightFromImage(originalImageMeta),\n width: originalImageMeta.width,\n }\n\n const results: ImageSizesResult[] = await Promise.all(\n imageSizes.map(async (imageResizeConfig): Promise<ImageSizesResult> => {\n imageResizeConfig = sanitizeResizeConfig(imageResizeConfig)\n\n const resizeAction = getImageResizeAction({\n dimensions,\n hasFocalPoint: Boolean(incomingFocalPoint),\n imageResizeConfig,\n })\n if (resizeAction === 'omit') return createResult({ name: imageResizeConfig.name })\n\n const imageToResize = sharpBase.clone()\n let resized = imageToResize\n\n if (resizeAction === 'resizeWithFocalPoint') {\n let { height: resizeHeight, width: resizeWidth } = imageResizeConfig\n\n const originalAspectRatio = dimensions.width / dimensions.height\n\n // Calculate resizeWidth based on original aspect ratio if it's undefined\n if (resizeHeight && !resizeWidth) {\n resizeWidth = Math.round(resizeHeight * originalAspectRatio)\n }\n\n // Calculate resizeHeight based on original aspect ratio if it's undefined\n if (resizeWidth && !resizeHeight) {\n resizeHeight = Math.round(resizeWidth / originalAspectRatio)\n }\n\n if (!resizeHeight) resizeHeight = resizeImageMeta.height\n if (!resizeWidth) resizeWidth = resizeImageMeta.width\n\n const resizeAspectRatio = resizeWidth / resizeHeight\n const prioritizeHeight = resizeAspectRatio < originalAspectRatio\n // Scales the image before extracting from it\n resized = imageToResize.resize({\n height: prioritizeHeight ? resizeHeight : undefined,\n width: prioritizeHeight ? undefined : resizeWidth,\n })\n\n const metadataAppendedFile = await optionallyAppendMetadata({\n req,\n sharpFile: resized,\n withMetadata,\n })\n\n // Must read from buffer, resized.metadata will return the original image metadata\n const { info } = await metadataAppendedFile.toBuffer({ resolveWithObject: true })\n\n resizeImageMeta.height = extractHeightFromImage({\n ...originalImageMeta,\n height: info.height,\n })\n resizeImageMeta.width = info.width\n\n const halfResizeX = resizeWidth / 2\n const xFocalCenter = resizeImageMeta.width * (incomingFocalPoint.x / 100)\n const calculatedRightPixelBound = xFocalCenter + halfResizeX\n let leftBound = xFocalCenter - halfResizeX\n\n // if the right bound is greater than the image width, adjust the left bound\n // keeping focus on the right\n if (calculatedRightPixelBound > resizeImageMeta.width) {\n leftBound = resizeImageMeta.width - resizeWidth\n }\n\n // if the left bound is less than 0, adjust the left bound to 0\n // keeping the focus on the left\n if (leftBound < 0) leftBound = 0\n\n const halfResizeY = resizeHeight / 2\n const yFocalCenter = resizeImageMeta.height * (incomingFocalPoint.y / 100)\n const calculatedBottomPixelBound = yFocalCenter + halfResizeY\n let topBound = yFocalCenter - halfResizeY\n\n // if the bottom bound is greater than the image height, adjust the top bound\n // keeping the image as far right as possible\n if (calculatedBottomPixelBound > resizeImageMeta.height) {\n topBound = resizeImageMeta.height - resizeHeight\n }\n\n // if the top bound is less than 0, adjust the top bound to 0\n // keeping the image focus near the top\n if (topBound < 0) topBound = 0\n\n resized = resized.extract({\n height: resizeHeight,\n left: Math.floor(leftBound),\n top: Math.floor(topBound),\n width: resizeWidth,\n })\n } else {\n resized = imageToResize.resize(imageResizeConfig)\n }\n\n if (imageResizeConfig.formatOptions) {\n resized = resized.toFormat(\n imageResizeConfig.formatOptions.format,\n imageResizeConfig.formatOptions.options,\n )\n }\n\n if (imageResizeConfig.trimOptions) {\n resized = resized.trim(imageResizeConfig.trimOptions)\n }\n\n const metadataAppendedFile = await optionallyAppendMetadata({\n req,\n sharpFile: resized,\n withMetadata,\n })\n\n const { data: bufferData, info: bufferInfo } = await metadataAppendedFile.toBuffer({\n resolveWithObject: true,\n })\n\n const sanitizedImage = getSanitizedImageData(savedFilename)\n\n if (req.payloadUploadSizes) {\n req.payloadUploadSizes[imageResizeConfig.name] = bufferData\n }\n\n const mimeInfo = await fileTypeFromBuffer(bufferData)\n\n const imageNameWithDimensions = createImageName({\n extension: mimeInfo?.ext || sanitizedImage.ext,\n height: extractHeightFromImage({\n ...originalImageMeta,\n height: bufferInfo.height,\n }),\n outputImageName: sanitizedImage.name,\n width: bufferInfo.width,\n })\n\n const imagePath = `${staticPath}/${imageNameWithDimensions}`\n\n if (await fileExists(imagePath)) {\n try {\n fs.unlinkSync(imagePath)\n } catch {\n // Ignore unlink errors\n }\n }\n\n const { height, size, width } = bufferInfo\n return createResult({\n name: imageResizeConfig.name,\n filename: imageNameWithDimensions,\n filesize: size,\n height:\n fileIsAnimatedType && originalImageMeta.pages ? height / originalImageMeta.pages : height,\n mimeType: mimeInfo?.mime || mimeType,\n sizesToSave: [{ buffer: bufferData, path: imagePath }],\n width,\n })\n }),\n )\n\n return results.reduce(\n (acc, result) => {\n Object.assign(acc.sizeData, result.sizeData)\n acc.sizesToSave.push(...result.sizesToSave)\n return acc\n },\n { ...defaultResult },\n )\n}\n"],"names":["fileTypeFromBuffer","fs","sanitize","isNumber","fileExists","optionallyAppendMetadata","getSanitizedImageData","sourceImage","extension","split","pop","name","substring","lastIndexOf","ext","createImageName","height","outputImageName","width","createResult","filename","filesize","mimeType","sizesToSave","sizeData","getImageResizeAction","dimensions","originalImage","hasFocalPoint","imageResizeConfig","fit","targetHeight","targetWidth","withoutEnlargement","withoutReduction","originalImageIsSmallerXAndY","undefined","originalImageIsSmallerXOrY","targetAspectRatio","originalAspectRatio","sanitizeResizeConfig","resizeConfig","position","extractHeightFromImage","sharpMetadata","pages","resizeAndTransformImageSizes","config","file","req","savedFilename","sharp","staticPath","uploadEdits","withMetadata","focalPoint","focalPointEnabled","imageSizes","upload","incomingFocalPoint","x","Math","round","y","defaultResult","fileIsAnimatedType","includes","mimetype","sharpOptions","animated","sharpBase","tempFilePath","data","rotate","originalImageMeta","metadata","resizeImageMeta","results","Promise","all","map","resizeAction","Boolean","imageToResize","clone","resized","resizeHeight","resizeWidth","resizeAspectRatio","prioritizeHeight","resize","metadataAppendedFile","sharpFile","info","toBuffer","resolveWithObject","halfResizeX","xFocalCenter","calculatedRightPixelBound","leftBound","halfResizeY","yFocalCenter","calculatedBottomPixelBound","topBound","extract","left","floor","top","formatOptions","toFormat","format","options","trimOptions","trim","bufferData","bufferInfo","sanitizedImage","payloadUploadSizes","mimeInfo","imageNameWithDimensions","imagePath","unlinkSync","size","mime","buffer","path","reduce","acc","result","Object","assign","push"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,YAAW;AAC9C,OAAOC,QAAQ,KAAI;AACnB,OAAOC,cAAc,oBAAmB;AAexC,SAASC,QAAQ,QAAQ,2BAA0B;AACnD,OAAOC,gBAAgB,kBAAiB;AACxC,SAASC,wBAAwB,QAAQ,gCAA+B;AA2BxE;;;;;CAKC,GACD,MAAMC,wBAAwB,CAACC;IAC7B,MAAMC,YAAYD,YAAYE,KAAK,CAAC,KAAKC,GAAG;IAC5C,MAAMC,OAAOT,SAASK,YAAYK,SAAS,CAAC,GAAGL,YAAYM,WAAW,CAAC,SAASN;IAChF,OAAO;QAAEI;QAAMG,KAAKN;IAAU;AAChC;AAqBA,MAAMO,kBAAkB,CAAC,EACvBP,SAAS,EACTQ,MAAM,EACNC,eAAe,EACfC,KAAK,EACe;IACpB,OAAO,CAAC,EAAED,gBAAgB,CAAC,EAAEC,MAAM,CAAC,EAAEF,OAAO,CAAC,EAAER,UAAU,CAAC;AAC7D;AAYA;;;;;;;;;;;;;CAaC,GACD,MAAMW,eAAe,CAAC,EACpBR,IAAI,EACJS,WAAW,IAAI,EACfC,WAAW,IAAI,EACfL,SAAS,IAAI,EACbM,WAAW,IAAI,EACfC,cAAc,EAAE,EAChBL,QAAQ,IAAI,EACK;IACjB,OAAO;QACLM,UAAU;YACR,CAACb,KAAK,EAAE;gBACNS;gBACAC;gBACAL;gBACAM;gBACAJ;YACF;QACF;QACAK;IACF;AACF;AAEA;;;;;;;;;;;;;;;;CAgBC,GACD,MAAME,uBAAuB,CAAC,EAC5BC,YAAYC,aAAa,EACzBC,aAAa,EACbC,iBAAiB,EAKlB;IACC,MAAM,EACJC,GA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harp, Metadata as SharpMetadata } from 'sharp';
|
|
2
|
+
import type { PayloadRequest } from '../types/index.js';
|
|
3
|
+
export type WithMetadata = ((options: {
|
|
4
|
+
metadata: SharpMetadata;
|
|
5
|
+
req: PayloadRequest;
|
|
6
|
+
}) => Promise<boolean>) | boolean;
|
|
7
|
+
export declare function optionallyAppendMetadata({ req, sharpFile, withMetadata, }: {
|
|
8
|
+
req: PayloadRequest;
|
|
9
|
+
sharpFile: Sharp;
|
|
10
|
+
withMetadata: WithMetadata;
|
|
11
|
+
}): Promise<Sharp>;
|
|
12
|
+
//# sourceMappingURL=optionallyAppendMetadata.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"optionallyAppendMetadata.d.ts","sourceRoot":"","sources":["../../src/uploads/optionallyAppendMetadata.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,QAAQ,IAAI,aAAa,EAAE,MAAM,OAAO,CAAA;AAE7D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAA;AAEvD,MAAM,MAAM,YAAY,GACpB,CAAC,CAAC,OAAO,EAAE;IAAE,QAAQ,EAAE,aAAa,CAAC;IAAC,GAAG,EAAE,cAAc,CAAA;CAAE,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC,GACjF,OAAO,CAAA;AAEX,wBAAsB,wBAAwB,CAAC,EAC7C,GAAG,EACH,SAAS,EACT,YAAY,GACb,EAAE;IACD,GAAG,EAAE,cAAc,CAAA;IACnB,SAAS,EAAE,KAAK,CAAA;IAChB,YAAY,EAAE,YAAY,CAAA;CAC3B,GAAG,OAAO,CAAC,KAAK,CAAC,CAYjB"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export async function optionallyAppendMetadata({ req, sharpFile, withMetadata }) {
|
|
2
|
+
const metadata = await sharpFile.metadata();
|
|
3
|
+
if (withMetadata === true) {
|
|
4
|
+
return sharpFile.withMetadata();
|
|
5
|
+
} else if (typeof withMetadata === 'function') {
|
|
6
|
+
const useMetadata = await withMetadata({
|
|
7
|
+
metadata,
|
|
8
|
+
req
|
|
9
|
+
});
|
|
10
|
+
if (useMetadata) return sharpFile.withMetadata();
|
|
11
|
+
}
|
|
12
|
+
return sharpFile;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
//# sourceMappingURL=optionallyAppendMetadata.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/uploads/optionallyAppendMetadata.ts"],"sourcesContent":["import type { Sharp, Metadata as SharpMetadata } from 'sharp'\n\nimport type { PayloadRequest } from '../types/index.js'\n\nexport type WithMetadata =\n | ((options: { metadata: SharpMetadata; req: PayloadRequest }) => Promise<boolean>)\n | boolean\n\nexport async function optionallyAppendMetadata({\n req,\n sharpFile,\n withMetadata,\n}: {\n req: PayloadRequest\n sharpFile: Sharp\n withMetadata: WithMetadata\n}): Promise<Sharp> {\n const metadata = await sharpFile.metadata()\n\n if (withMetadata === true) {\n return sharpFile.withMetadata()\n } else if (typeof withMetadata === 'function') {\n const useMetadata = await withMetadata({ metadata, req })\n\n if (useMetadata) return sharpFile.withMetadata()\n }\n\n return sharpFile\n}\n"],"names":["optionallyAppendMetadata","req","sharpFile","withMetadata","metadata","useMetadata"],"mappings":"AAQA,OAAO,eAAeA,yBAAyB,EAC7CC,GAAG,EACHC,SAAS,EACTC,YAAY,EAKb;IACC,MAAMC,WAAW,MAAMF,UAAUE,QAAQ;IAEzC,IAAID,iBAAiB,MAAM;QACzB,OAAOD,UAAUC,YAAY;IAC/B,OAAO,IAAI,OAAOA,iBAAiB,YAAY;QAC7C,MAAME,cAAc,MAAMF,aAAa;YAAEC;YAAUH;QAAI;QAEvD,IAAII,aAAa,OAAOH,UAAUC,YAAY;IAChD;IAEA,OAAOD;AACT"}
|
package/dist/uploads/types.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { ResizeOptions, Sharp } from 'sharp';
|
|
2
2
|
import type { TypeWithID } from '../collections/config/types.js';
|
|
3
3
|
import type { PayloadRequest } from '../types/index.js';
|
|
4
|
+
import type { WithMetadata } from './optionallyAppendMetadata.js';
|
|
4
5
|
export type FileSize = {
|
|
5
6
|
filename: null | string;
|
|
6
7
|
filesize: null | number;
|
|
@@ -147,6 +148,17 @@ export type UploadConfig = {
|
|
|
147
148
|
*/
|
|
148
149
|
staticDir?: string;
|
|
149
150
|
trimOptions?: ImageUploadTrimOptions;
|
|
151
|
+
/**
|
|
152
|
+
* Optionally append metadata to the image during processing.
|
|
153
|
+
*
|
|
154
|
+
* Can be a boolean or a function.
|
|
155
|
+
*
|
|
156
|
+
* If true, metadata will be appended to the image.
|
|
157
|
+
* If false, no metadata will be appended.
|
|
158
|
+
* If a function, it will receive an object containing the metadata and should return a boolean indicating whether to append the metadata.
|
|
159
|
+
* @default false
|
|
160
|
+
*/
|
|
161
|
+
withMetadata?: WithMetadata;
|
|
150
162
|
};
|
|
151
163
|
export type SanitizedUploadConfig = {
|
|
152
164
|
staticDir: UploadConfig['staticDir'];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/uploads/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,KAAK,
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/uploads/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,KAAK,EAA6B,MAAM,OAAO,CAAA;AAE5E,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAA;AAChE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAA;AACvD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAA;AAEjE,MAAM,MAAM,QAAQ,GAAG;IACrB,QAAQ,EAAE,IAAI,GAAG,MAAM,CAAA;IACvB,QAAQ,EAAE,IAAI,GAAG,MAAM,CAA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AAE,MAAM,CAAA;CACvB,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/uploads/types.ts"],"sourcesContent":["import type { ResizeOptions, Sharp } from 'sharp'\n\nimport type { TypeWithID } from '../collections/config/types.js'\nimport type { PayloadRequest } from '../types/index.js'\n\nexport type FileSize = {\n filename: null | string\n filesize: null | number\n height: null | number\n mimeType: null | string\n width: null | number\n}\n\nexport type FileSizes = {\n [size: string]: FileSize\n}\n\nexport type FileData = {\n filename: string\n filesize: number\n focalX?: number\n focalY?: number\n height: number\n mimeType: string\n sizes: FileSizes\n tempFilePath?: string\n url?: string\n width: number\n}\n\nexport type ProbedImageSize = {\n height: number\n width: number\n}\n\n/**\n * Params sent to the sharp `toFormat()` function\n * @link https://sharp.pixelplumbing.com/api-output#toformat\n */\nexport type ImageUploadFormatOptions = {\n format: Parameters<Sharp['toFormat']>[0]\n options?: Parameters<Sharp['toFormat']>[1]\n}\n\n/**\n * Params sent to the sharp trim() function\n * @link https://sharp.pixelplumbing.com/api-resize#trim\n */\nexport type ImageUploadTrimOptions = Parameters<Sharp['trim']>[0]\n\nexport type ImageSize = {\n /**\n * @deprecated prefer position\n */\n crop?: string // comes from sharp package\n formatOptions?: ImageUploadFormatOptions\n name: string\n trimOptions?: ImageUploadTrimOptions\n /**\n * When an uploaded image is smaller than the defined image size, we have 3 options:\n *\n * `undefined | false | true`\n *\n * 1. `undefined` [default]: uploading images with smaller width AND height than the image size will return null\n * 2. `false`: always enlarge images to the image size\n * 3. `true`: if the image is smaller than the image size, return the original image\n */\n withoutEnlargement?: ResizeOptions['withoutEnlargement']\n} & Omit<ResizeOptions, 'withoutEnlargement'>\n\nexport type GetAdminThumbnail = (args: { doc: Record<string, unknown> }) => false | null | string\n\nexport type UploadConfig = {\n /**\n * The adapter name to use for uploads. Used for storage adapter telemetry.\n * @default undefined\n */\n adapter?: string\n /**\n * Represents an admin thumbnail, which can be either a React component or a string.\n * - If a string, it should be one of the image size names.\n * - A function that generates a fully qualified URL for the thumbnail, receives the doc as the only argument.\n **/\n adminThumbnail?: GetAdminThumbnail | string\n /**\n * Enables cropping of images.\n * @default true\n */\n crop?: boolean\n /**\n * Disable the ability to save files to disk.\n * @default false\n */\n disableLocalStorage?: boolean\n /**\n * Ability to filter/modify Request Headers when fetching a file.\n *\n * Useful for adding custom headers to fetch from external providers.\n * @default undefined\n */\n externalFileHeaderFilter?: (headers: Record<string, string>) => Record<string, string>\n /**\n * Require files to be uploaded when creating a document.\n * @default true\n */\n filesRequiredOnCreate?: boolean\n /**\n * Enables focal point positioning for image manipulation.\n * @default false\n */\n focalPoint?: boolean\n /**\n * Format options for the uploaded file. Formatting image sizes needs to be done within each formatOptions individually.\n */\n formatOptions?: ImageUploadFormatOptions\n /**\n * Custom handlers to run when a file is fetched.\n *\n * - If a handler returns a Response, the response will be sent to the client and no further handlers will be run.\n * - If a handler returns null, the next handler will be run.\n * - If no handlers return a response the file will be returned by default.\n *\n * @default undefined\n */\n handlers?: ((\n req: PayloadRequest,\n args: {\n doc: TypeWithID\n params: { collection: string; filename: string }\n },\n ) => Promise<Response> | Promise<void> | Response | void)[]\n imageSizes?: ImageSize[]\n /**\n * Restrict mimeTypes in the file picker. Array of valid mime types or mimetype wildcards\n * @example ['image/*', 'application/pdf']\n * @default undefined\n */\n mimeTypes?: string[]\n /**\n * Ability to modify the response headers fetching a file.\n * @default undefined\n */\n modifyResponseHeaders?: ({ headers }: { headers: Headers }) => Headers\n /**\n * Sharp resize options for the original image.\n * @link https://sharp.pixelplumbing.com/api-resize#resize\n * @default undefined\n */\n resizeOptions?: ResizeOptions\n /**\n * The directory to serve static files from. Defaults to collection slug.\n * @default undefined\n */\n staticDir?: string\n trimOptions?: ImageUploadTrimOptions\n}\n\nexport type SanitizedUploadConfig = {\n staticDir: UploadConfig['staticDir']\n} & UploadConfig\n\nexport type File = {\n /**\n * The buffer of the file.\n */\n data: Buffer\n /**\n * The mimetype of the file.\n */\n mimetype: string\n /**\n * The name of the file.\n */\n name: string\n /**\n * The size of the file in bytes.\n */\n size: number\n}\n\nexport type FileToSave = {\n /**\n * The buffer of the file.\n */\n buffer: Buffer\n /**\n * The path to save the file.\n */\n path: string\n}\n\ntype Crop = {\n height: number\n unit: '%' | 'px'\n width: number\n x: number\n y: number\n}\n\ntype FocalPoint = {\n x: number\n y: number\n}\n\nexport type UploadEdits = {\n crop?: Crop\n focalPoint?: FocalPoint\n heightInPixels?: number\n widthInPixels?: number\n}\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../../src/uploads/types.ts"],"sourcesContent":["import type { ResizeOptions, Sharp, Metadata as SharpMetadata } from 'sharp'\n\nimport type { TypeWithID } from '../collections/config/types.js'\nimport type { PayloadRequest } from '../types/index.js'\nimport type { WithMetadata } from './optionallyAppendMetadata.js'\n\nexport type FileSize = {\n filename: null | string\n filesize: null | number\n height: null | number\n mimeType: null | string\n width: null | number\n}\n\nexport type FileSizes = {\n [size: string]: FileSize\n}\n\nexport type FileData = {\n filename: string\n filesize: number\n focalX?: number\n focalY?: number\n height: number\n mimeType: string\n sizes: FileSizes\n tempFilePath?: string\n url?: string\n width: number\n}\n\nexport type ProbedImageSize = {\n height: number\n width: number\n}\n\n/**\n * Params sent to the sharp `toFormat()` function\n * @link https://sharp.pixelplumbing.com/api-output#toformat\n */\nexport type ImageUploadFormatOptions = {\n format: Parameters<Sharp['toFormat']>[0]\n options?: Parameters<Sharp['toFormat']>[1]\n}\n\n/**\n * Params sent to the sharp trim() function\n * @link https://sharp.pixelplumbing.com/api-resize#trim\n */\nexport type ImageUploadTrimOptions = Parameters<Sharp['trim']>[0]\n\nexport type ImageSize = {\n /**\n * @deprecated prefer position\n */\n crop?: string // comes from sharp package\n formatOptions?: ImageUploadFormatOptions\n name: string\n trimOptions?: ImageUploadTrimOptions\n /**\n * When an uploaded image is smaller than the defined image size, we have 3 options:\n *\n * `undefined | false | true`\n *\n * 1. `undefined` [default]: uploading images with smaller width AND height than the image size will return null\n * 2. `false`: always enlarge images to the image size\n * 3. `true`: if the image is smaller than the image size, return the original image\n */\n withoutEnlargement?: ResizeOptions['withoutEnlargement']\n} & Omit<ResizeOptions, 'withoutEnlargement'>\n\nexport type GetAdminThumbnail = (args: { doc: Record<string, unknown> }) => false | null | string\n\nexport type UploadConfig = {\n /**\n * The adapter name to use for uploads. Used for storage adapter telemetry.\n * @default undefined\n */\n adapter?: string\n /**\n * Represents an admin thumbnail, which can be either a React component or a string.\n * - If a string, it should be one of the image size names.\n * - A function that generates a fully qualified URL for the thumbnail, receives the doc as the only argument.\n **/\n adminThumbnail?: GetAdminThumbnail | string\n /**\n * Enables cropping of images.\n * @default true\n */\n crop?: boolean\n /**\n * Disable the ability to save files to disk.\n * @default false\n */\n disableLocalStorage?: boolean\n /**\n * Ability to filter/modify Request Headers when fetching a file.\n *\n * Useful for adding custom headers to fetch from external providers.\n * @default undefined\n */\n externalFileHeaderFilter?: (headers: Record<string, string>) => Record<string, string>\n /**\n * Require files to be uploaded when creating a document.\n * @default true\n */\n filesRequiredOnCreate?: boolean\n /**\n * Enables focal point positioning for image manipulation.\n * @default false\n */\n focalPoint?: boolean\n /**\n * Format options for the uploaded file. Formatting image sizes needs to be done within each formatOptions individually.\n */\n formatOptions?: ImageUploadFormatOptions\n /**\n * Custom handlers to run when a file is fetched.\n *\n * - If a handler returns a Response, the response will be sent to the client and no further handlers will be run.\n * - If a handler returns null, the next handler will be run.\n * - If no handlers return a response the file will be returned by default.\n *\n * @default undefined\n */\n handlers?: ((\n req: PayloadRequest,\n args: {\n doc: TypeWithID\n params: { collection: string; filename: string }\n },\n ) => Promise<Response> | Promise<void> | Response | void)[]\n imageSizes?: ImageSize[]\n /**\n * Restrict mimeTypes in the file picker. Array of valid mime types or mimetype wildcards\n * @example ['image/*', 'application/pdf']\n * @default undefined\n */\n mimeTypes?: string[]\n /**\n * Ability to modify the response headers fetching a file.\n * @default undefined\n */\n modifyResponseHeaders?: ({ headers }: { headers: Headers }) => Headers\n /**\n * Sharp resize options for the original image.\n * @link https://sharp.pixelplumbing.com/api-resize#resize\n * @default undefined\n */\n resizeOptions?: ResizeOptions\n /**\n * The directory to serve static files from. Defaults to collection slug.\n * @default undefined\n */\n staticDir?: string\n trimOptions?: ImageUploadTrimOptions\n /**\n * Optionally append metadata to the image during processing.\n *\n * Can be a boolean or a function.\n *\n * If true, metadata will be appended to the image.\n * If false, no metadata will be appended.\n * If a function, it will receive an object containing the metadata and should return a boolean indicating whether to append the metadata.\n * @default false\n */\n withMetadata?: WithMetadata\n}\n\nexport type SanitizedUploadConfig = {\n staticDir: UploadConfig['staticDir']\n} & UploadConfig\n\nexport type File = {\n /**\n * The buffer of the file.\n */\n data: Buffer\n /**\n * The mimetype of the file.\n */\n mimetype: string\n /**\n * The name of the file.\n */\n name: string\n /**\n * The size of the file in bytes.\n */\n size: number\n}\n\nexport type FileToSave = {\n /**\n * The buffer of the file.\n */\n buffer: Buffer\n /**\n * The path to save the file.\n */\n path: string\n}\n\ntype Crop = {\n height: number\n unit: '%' | 'px'\n width: number\n x: number\n y: number\n}\n\ntype FocalPoint = {\n x: number\n y: number\n}\n\nexport type UploadEdits = {\n crop?: Crop\n focalPoint?: FocalPoint\n heightInPixels?: number\n widthInPixels?: number\n}\n"],"names":[],"mappings":"AAwNA,WAKC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"configToJSONSchema.d.ts","sourceRoot":"","sources":["../../src/utilities/configToJSONSchema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAA;AAMnE,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAA;AAC/E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AACzD,OAAO,KAAK,EAAE,KAAK,EAA8B,MAAM,2BAA2B,CAAA;AAClF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAA;AA4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,EAAE,CAK7C;AAED,wBAAgB,kBAAkB;AAChC;;;;GAIG;AACH,sBAAsB,EAAE;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,QAAQ,GAAG,QAAQ,CAAA;CAAE,EAC9D,MAAM,EAAE,KAAK,EAAE;AACf;;GAEG;AACH,wBAAwB,EAAE,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,EAClD,MAAM,CAAC,EAAE,eAAe,GACvB;IACD,UAAU,EAAE;QACV,CAAC,CAAC,EAAE,MAAM,GAAG,WAAW,CAAA;KACzB,CAAA;IACD,QAAQ,EAAE,MAAM,EAAE,CAAA;CACnB,CAsYA;AAGD,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,eAAe,EACvB,cAAc,EAAE,yBAAyB,GAAG,qBAAqB,EACjE,wBAAwB,EAAE,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,EAClD,aAAa,EAAE,QAAQ,GAAG,MAAM,GAC/B,WAAW,CA8Cb;AA4FD,wBAAgB,oCAAoC,CAClD,MAAM,EAAE,yBAAyB,GAChC,WAAW,CA0Bb;AAoBD;;GAEG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,eAAe,EACvB,aAAa,CAAC,EAAE,QAAQ,GAAG,MAAM,GAChC,WAAW,CAoDb"}
|
|
@@ -557,89 +557,122 @@ const fieldType = {
|
|
|
557
557
|
type: 'string',
|
|
558
558
|
required: false
|
|
559
559
|
};
|
|
560
|
-
const generateAuthFieldTypes = (
|
|
561
|
-
const
|
|
562
|
-
|
|
560
|
+
const generateAuthFieldTypes = ({ type, loginWithUsername })=>{
|
|
561
|
+
const emailAuthFields = {
|
|
562
|
+
additionalProperties: false,
|
|
563
|
+
properties: {
|
|
564
|
+
email: fieldType
|
|
565
|
+
},
|
|
566
|
+
required: [
|
|
567
|
+
'email'
|
|
568
|
+
]
|
|
563
569
|
};
|
|
564
|
-
|
|
565
|
-
if (loginWithUsername.allowEmailLogin) {
|
|
566
|
-
return {
|
|
567
|
-
additionalProperties: false,
|
|
568
|
-
oneOf: [
|
|
569
|
-
{
|
|
570
|
-
additionalProperties: false,
|
|
571
|
-
properties: {
|
|
572
|
-
email: fieldType,
|
|
573
|
-
...withPassword ? {
|
|
574
|
-
password: fieldType
|
|
575
|
-
} : {}
|
|
576
|
-
},
|
|
577
|
-
required: [
|
|
578
|
-
'email',
|
|
579
|
-
...withPassword ? [
|
|
580
|
-
'password'
|
|
581
|
-
] : []
|
|
582
|
-
]
|
|
583
|
-
},
|
|
584
|
-
{
|
|
585
|
-
additionalProperties: false,
|
|
586
|
-
properties: {
|
|
587
|
-
username: fieldType,
|
|
588
|
-
...withPassword ? {
|
|
589
|
-
password: fieldType
|
|
590
|
-
} : {}
|
|
591
|
-
},
|
|
592
|
-
required: [
|
|
593
|
-
'username',
|
|
594
|
-
...withPassword ? [
|
|
595
|
-
'password'
|
|
596
|
-
] : []
|
|
597
|
-
]
|
|
598
|
-
}
|
|
599
|
-
]
|
|
600
|
-
};
|
|
601
|
-
}
|
|
602
|
-
return {
|
|
603
|
-
additionalProperties: false,
|
|
604
|
-
properties: {
|
|
605
|
-
username: fieldType,
|
|
606
|
-
...withPassword ? {
|
|
607
|
-
password: fieldType
|
|
608
|
-
} : {}
|
|
609
|
-
},
|
|
610
|
-
required: [
|
|
611
|
-
'username',
|
|
612
|
-
...withPassword ? [
|
|
613
|
-
'password'
|
|
614
|
-
] : []
|
|
615
|
-
]
|
|
616
|
-
};
|
|
617
|
-
}
|
|
618
|
-
return {
|
|
570
|
+
const usernameAuthFields = {
|
|
619
571
|
additionalProperties: false,
|
|
620
572
|
properties: {
|
|
621
|
-
|
|
622
|
-
...withPassword ? {
|
|
623
|
-
password: fieldType
|
|
624
|
-
} : {}
|
|
573
|
+
username: fieldType
|
|
625
574
|
},
|
|
626
575
|
required: [
|
|
627
|
-
'
|
|
628
|
-
...withPassword ? [
|
|
629
|
-
'password'
|
|
630
|
-
] : []
|
|
576
|
+
'username'
|
|
631
577
|
]
|
|
632
578
|
};
|
|
579
|
+
if ([
|
|
580
|
+
'login',
|
|
581
|
+
'register'
|
|
582
|
+
].includes(type)) {
|
|
583
|
+
emailAuthFields.properties['password'] = fieldType;
|
|
584
|
+
emailAuthFields.required.push('password');
|
|
585
|
+
usernameAuthFields.properties['password'] = fieldType;
|
|
586
|
+
usernameAuthFields.required.push('password');
|
|
587
|
+
}
|
|
588
|
+
if (loginWithUsername) {
|
|
589
|
+
switch(type){
|
|
590
|
+
case 'login':
|
|
591
|
+
{
|
|
592
|
+
if (loginWithUsername.allowEmailLogin) {
|
|
593
|
+
// allow username or email and require password for login
|
|
594
|
+
return {
|
|
595
|
+
additionalProperties: false,
|
|
596
|
+
oneOf: [
|
|
597
|
+
emailAuthFields,
|
|
598
|
+
usernameAuthFields
|
|
599
|
+
]
|
|
600
|
+
};
|
|
601
|
+
} else {
|
|
602
|
+
// allow only username and password for login
|
|
603
|
+
return usernameAuthFields;
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
case 'register':
|
|
607
|
+
{
|
|
608
|
+
if (loginWithUsername.requireEmail) {
|
|
609
|
+
// require username, email and password for registration
|
|
610
|
+
return {
|
|
611
|
+
additionalProperties: false,
|
|
612
|
+
properties: {
|
|
613
|
+
...usernameAuthFields.properties,
|
|
614
|
+
...emailAuthFields.properties
|
|
615
|
+
},
|
|
616
|
+
required: [
|
|
617
|
+
...usernameAuthFields.required,
|
|
618
|
+
...emailAuthFields.required
|
|
619
|
+
]
|
|
620
|
+
};
|
|
621
|
+
} else if (loginWithUsername.allowEmailLogin) {
|
|
622
|
+
// allow both but only require username for registration
|
|
623
|
+
return {
|
|
624
|
+
additionalProperties: false,
|
|
625
|
+
properties: {
|
|
626
|
+
...usernameAuthFields.properties,
|
|
627
|
+
...emailAuthFields.properties
|
|
628
|
+
},
|
|
629
|
+
required: usernameAuthFields.required
|
|
630
|
+
};
|
|
631
|
+
} else {
|
|
632
|
+
// require only username and password for registration
|
|
633
|
+
return usernameAuthFields;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
case 'forgotOrUnlock':
|
|
637
|
+
{
|
|
638
|
+
if (loginWithUsername.allowEmailLogin) {
|
|
639
|
+
// allow email or username for unlock/forgot-password
|
|
640
|
+
return {
|
|
641
|
+
additionalProperties: false,
|
|
642
|
+
oneOf: [
|
|
643
|
+
emailAuthFields,
|
|
644
|
+
usernameAuthFields
|
|
645
|
+
]
|
|
646
|
+
};
|
|
647
|
+
} else {
|
|
648
|
+
// allow only username for unlock/forgot-password
|
|
649
|
+
return usernameAuthFields;
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
// default email (and password for login/register)
|
|
655
|
+
return emailAuthFields;
|
|
633
656
|
};
|
|
634
657
|
export function authCollectionToOperationsJSONSchema(config) {
|
|
635
658
|
const loginWithUsername = config.auth?.loginWithUsername;
|
|
636
|
-
const
|
|
637
|
-
|
|
659
|
+
const loginUserFields = generateAuthFieldTypes({
|
|
660
|
+
type: 'login',
|
|
661
|
+
loginWithUsername
|
|
662
|
+
});
|
|
663
|
+
const forgotOrUnlockUserFields = generateAuthFieldTypes({
|
|
664
|
+
type: 'forgotOrUnlock',
|
|
665
|
+
loginWithUsername
|
|
666
|
+
});
|
|
667
|
+
const registerUserFields = generateAuthFieldTypes({
|
|
668
|
+
type: 'register',
|
|
669
|
+
loginWithUsername
|
|
670
|
+
});
|
|
638
671
|
const properties = {
|
|
639
|
-
forgotPassword:
|
|
640
|
-
login:
|
|
641
|
-
registerFirstUser:
|
|
642
|
-
unlock:
|
|
672
|
+
forgotPassword: forgotOrUnlockUserFields,
|
|
673
|
+
login: loginUserFields,
|
|
674
|
+
registerFirstUser: registerUserFields,
|
|
675
|
+
unlock: forgotOrUnlockUserFields
|
|
643
676
|
};
|
|
644
677
|
return {
|
|
645
678
|
type: 'object',
|