payload 3.0.0-beta.34 → 3.0.0-beta.36
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/sendVerificationEmail.js +1 -1
- package/dist/auth/sendVerificationEmail.js.map +1 -1
- package/dist/collections/operations/create.d.ts.map +1 -1
- package/dist/collections/operations/create.js +1 -0
- package/dist/collections/operations/create.js.map +1 -1
- package/dist/collections/operations/update.d.ts.map +1 -1
- package/dist/collections/operations/update.js +1 -0
- package/dist/collections/operations/update.js.map +1 -1
- package/dist/collections/operations/updateByID.d.ts.map +1 -1
- package/dist/collections/operations/updateByID.js +1 -0
- package/dist/collections/operations/updateByID.js.map +1 -1
- package/dist/config/types.d.ts +1 -0
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/exports/utilities.d.ts +1 -1
- package/dist/exports/utilities.d.ts.map +1 -1
- package/dist/exports/utilities.js +1 -1
- package/dist/exports/utilities.js.map +1 -1
- package/dist/types/index.d.ts +0 -12
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/uploads/canResizeImage.d.ts +1 -1
- package/dist/uploads/canResizeImage.d.ts.map +1 -1
- package/dist/uploads/canResizeImage.js +1 -1
- package/dist/uploads/canResizeImage.js.map +1 -1
- package/dist/uploads/cropImage.d.ts +1 -1
- package/dist/uploads/cropImage.d.ts.map +1 -1
- package/dist/uploads/cropImage.js +1 -1
- package/dist/uploads/cropImage.js.map +1 -1
- package/dist/uploads/generateFileData.d.ts +3 -1
- package/dist/uploads/generateFileData.d.ts.map +1 -1
- package/dist/uploads/generateFileData.js +50 -12
- package/dist/uploads/generateFileData.js.map +1 -1
- package/dist/uploads/getBaseFields.d.ts.map +1 -1
- package/dist/uploads/getBaseFields.js +15 -0
- package/dist/uploads/getBaseFields.js.map +1 -1
- package/dist/uploads/getSafeFilename.d.ts +2 -2
- package/dist/uploads/getSafeFilename.d.ts.map +1 -1
- package/dist/uploads/getSafeFilename.js +1 -2
- package/dist/uploads/getSafeFilename.js.map +1 -1
- package/dist/uploads/imageResizer.d.ts +7 -9
- package/dist/uploads/imageResizer.d.ts.map +1 -1
- package/dist/uploads/imageResizer.js +42 -24
- package/dist/uploads/imageResizer.js.map +1 -1
- package/dist/uploads/isImage.d.ts +1 -1
- package/dist/uploads/isImage.d.ts.map +1 -1
- package/dist/uploads/isImage.js +1 -1
- package/dist/uploads/isImage.js.map +1 -1
- package/dist/uploads/types.d.ts +14 -0
- package/dist/uploads/types.d.ts.map +1 -1
- package/dist/uploads/types.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/uploads/getBaseFields.ts"],"sourcesContent":["import type { CollectionConfig } from '../collections/config/types.js'\nimport type { Config } from '../config/types.js'\nimport type { Field } from '../fields/config/types.js'\nimport type { UploadConfig } from './types.js'\n\nimport { mimeTypeValidator } from './mimeTypeValidator.js'\n\ntype GenerateURLArgs = {\n collectionSlug: string\n config: Config\n filename?: string\n}\nconst generateURL = ({ collectionSlug, config, filename }: GenerateURLArgs) => {\n if (filename) {\n return `${config.serverURL || ''}${config.routes.api || ''}/${collectionSlug}/file/${filename}`\n }\n return undefined\n}\n\ntype Options = {\n collection: CollectionConfig\n config: Config\n}\n\nexport const getBaseUploadFields = ({ collection, config }: Options): Field[] => {\n const uploadOptions: UploadConfig = typeof collection.upload === 'object' ? collection.upload : {}\n\n const mimeType: Field = {\n name: 'mimeType',\n type: 'text',\n admin: {\n hidden: true,\n readOnly: true,\n },\n label: 'MIME Type',\n }\n\n const thumbnailURL: Field = {\n name: 'thumbnailURL',\n type: 'text',\n admin: {\n hidden: true,\n readOnly: true,\n },\n hooks: {\n afterRead: [\n ({ originalDoc }) => {\n const adminThumbnail =\n typeof collection.upload !== 'boolean' ? collection.upload?.adminThumbnail : undefined\n\n if (typeof adminThumbnail === 'function') {\n return adminThumbnail({ doc: originalDoc })\n }\n\n if (\n typeof adminThumbnail === 'string' &&\n 'sizes' in originalDoc &&\n originalDoc.sizes?.[adminThumbnail]?.filename\n ) {\n return generateURL({\n collectionSlug: collection.slug,\n config,\n filename: originalDoc.sizes?.[adminThumbnail].filename as string,\n })\n }\n\n return null\n },\n ],\n },\n label: 'Thumbnail URL',\n }\n\n const width: Field = {\n name: 'width',\n type: 'number',\n admin: {\n hidden: true,\n readOnly: true,\n },\n label: ({ t }) => t('upload:width'),\n }\n\n const height: Field = {\n name: 'height',\n type: 'number',\n admin: {\n hidden: true,\n readOnly: true,\n },\n label: ({ t }) => t('upload:height'),\n }\n\n const filesize: Field = {\n name: 'filesize',\n type: 'number',\n admin: {\n hidden: true,\n readOnly: true,\n },\n label: ({ t }) => t('upload:fileSize'),\n }\n\n const filename: Field = {\n name: 'filename',\n type: 'text',\n admin: {\n disableBulkEdit: true,\n hidden: true,\n readOnly: true,\n },\n index: true,\n label: ({ t }) => t('upload:fileName'),\n unique: true,\n }\n\n const url: Field = {\n name: 'url',\n type: 'text',\n admin: {\n hidden: true,\n readOnly: true,\n },\n label: 'URL',\n }\n\n let uploadFields: Field[] = [\n {\n ...url,\n hooks: {\n afterRead: [\n ({ data, value }) => {\n if (value) return value\n\n return generateURL({\n collectionSlug: collection.slug,\n config,\n filename: data?.filename,\n })\n },\n ],\n },\n },\n thumbnailURL,\n filename,\n mimeType,\n filesize,\n width,\n height,\n ]\n\n if (uploadOptions.mimeTypes) {\n mimeType.validate = mimeTypeValidator(uploadOptions.mimeTypes)\n }\n\n if (uploadOptions.imageSizes) {\n uploadFields = uploadFields.concat([\n {\n name: 'sizes',\n type: 'group',\n admin: {\n hidden: true,\n },\n fields: uploadOptions.imageSizes.map((size) => ({\n name: size.name,\n type: 'group',\n admin: {\n hidden: true,\n },\n fields: [\n {\n ...url,\n hooks: {\n afterRead: [\n ({ data, value }) => {\n if (value) return value\n\n const sizeFilename = data?.sizes?.[size.name]?.filename\n\n if (sizeFilename) {\n return `${config.serverURL}${config.routes.api}/${collection.slug}/file/${sizeFilename}`\n }\n\n return null\n },\n ],\n },\n },\n width,\n height,\n mimeType,\n filesize,\n {\n ...filename,\n unique: false,\n },\n ],\n label: size.name,\n })),\n label: ({ t }) => t('upload:sizes'),\n },\n ])\n }\n return uploadFields\n}\n"],"names":["mimeTypeValidator","generateURL","collectionSlug","config","filename","serverURL","routes","api","undefined","getBaseUploadFields","collection","uploadOptions","upload","mimeType","name","type","admin","hidden","readOnly","label","thumbnailURL","hooks","afterRead","originalDoc","adminThumbnail","doc","sizes","slug","width","t","height","filesize","disableBulkEdit","index","unique","url","uploadFields","data","value","
|
|
1
|
+
{"version":3,"sources":["../../src/uploads/getBaseFields.ts"],"sourcesContent":["import type { CollectionConfig } from '../collections/config/types.js'\nimport type { Config } from '../config/types.js'\nimport type { Field } from '../fields/config/types.js'\nimport type { UploadConfig } from './types.js'\n\nimport { mimeTypeValidator } from './mimeTypeValidator.js'\n\ntype GenerateURLArgs = {\n collectionSlug: string\n config: Config\n filename?: string\n}\nconst generateURL = ({ collectionSlug, config, filename }: GenerateURLArgs) => {\n if (filename) {\n return `${config.serverURL || ''}${config.routes.api || ''}/${collectionSlug}/file/${filename}`\n }\n return undefined\n}\n\ntype Options = {\n collection: CollectionConfig\n config: Config\n}\n\nexport const getBaseUploadFields = ({ collection, config }: Options): Field[] => {\n const uploadOptions: UploadConfig = typeof collection.upload === 'object' ? collection.upload : {}\n\n const mimeType: Field = {\n name: 'mimeType',\n type: 'text',\n admin: {\n hidden: true,\n readOnly: true,\n },\n label: 'MIME Type',\n }\n\n const thumbnailURL: Field = {\n name: 'thumbnailURL',\n type: 'text',\n admin: {\n hidden: true,\n readOnly: true,\n },\n hooks: {\n afterRead: [\n ({ originalDoc }) => {\n const adminThumbnail =\n typeof collection.upload !== 'boolean' ? collection.upload?.adminThumbnail : undefined\n\n if (typeof adminThumbnail === 'function') {\n return adminThumbnail({ doc: originalDoc })\n }\n\n if (\n typeof adminThumbnail === 'string' &&\n 'sizes' in originalDoc &&\n originalDoc.sizes?.[adminThumbnail]?.filename\n ) {\n return generateURL({\n collectionSlug: collection.slug,\n config,\n filename: originalDoc.sizes?.[adminThumbnail].filename as string,\n })\n }\n\n return null\n },\n ],\n },\n label: 'Thumbnail URL',\n }\n\n const width: Field = {\n name: 'width',\n type: 'number',\n admin: {\n hidden: true,\n readOnly: true,\n },\n label: ({ t }) => t('upload:width'),\n }\n\n const height: Field = {\n name: 'height',\n type: 'number',\n admin: {\n hidden: true,\n readOnly: true,\n },\n label: ({ t }) => t('upload:height'),\n }\n\n const filesize: Field = {\n name: 'filesize',\n type: 'number',\n admin: {\n hidden: true,\n readOnly: true,\n },\n label: ({ t }) => t('upload:fileSize'),\n }\n\n const filename: Field = {\n name: 'filename',\n type: 'text',\n admin: {\n disableBulkEdit: true,\n hidden: true,\n readOnly: true,\n },\n index: true,\n label: ({ t }) => t('upload:fileName'),\n unique: true,\n }\n\n const url: Field = {\n name: 'url',\n type: 'text',\n admin: {\n hidden: true,\n readOnly: true,\n },\n label: 'URL',\n }\n\n let uploadFields: Field[] = [\n {\n ...url,\n hooks: {\n afterRead: [\n ({ data, value }) => {\n if (value) return value\n\n return generateURL({\n collectionSlug: collection.slug,\n config,\n filename: data?.filename,\n })\n },\n ],\n },\n },\n thumbnailURL,\n filename,\n mimeType,\n filesize,\n width,\n height,\n ]\n\n // Add focal point fields if not disabled\n if (\n uploadOptions.focalPoint !== false ||\n uploadOptions.imageSizes ||\n uploadOptions.resizeOptions\n ) {\n uploadFields = uploadFields.concat(\n ['focalX', 'focalY'].map((name) => {\n return {\n name,\n type: 'number',\n admin: {\n hidden: true,\n },\n }\n }),\n )\n }\n\n if (uploadOptions.mimeTypes) {\n mimeType.validate = mimeTypeValidator(uploadOptions.mimeTypes)\n }\n\n if (uploadOptions.imageSizes) {\n uploadFields = uploadFields.concat([\n {\n name: 'sizes',\n type: 'group',\n admin: {\n hidden: true,\n },\n fields: uploadOptions.imageSizes.map((size) => ({\n name: size.name,\n type: 'group',\n admin: {\n hidden: true,\n },\n fields: [\n {\n ...url,\n hooks: {\n afterRead: [\n ({ data, value }) => {\n if (value) return value\n\n const sizeFilename = data?.sizes?.[size.name]?.filename\n\n if (sizeFilename) {\n return `${config.serverURL}${config.routes.api}/${collection.slug}/file/${sizeFilename}`\n }\n\n return null\n },\n ],\n },\n },\n width,\n height,\n mimeType,\n filesize,\n {\n ...filename,\n unique: false,\n },\n ],\n label: size.name,\n })),\n label: ({ t }) => t('upload:sizes'),\n },\n ])\n }\n return uploadFields\n}\n"],"names":["mimeTypeValidator","generateURL","collectionSlug","config","filename","serverURL","routes","api","undefined","getBaseUploadFields","collection","uploadOptions","upload","mimeType","name","type","admin","hidden","readOnly","label","thumbnailURL","hooks","afterRead","originalDoc","adminThumbnail","doc","sizes","slug","width","t","height","filesize","disableBulkEdit","index","unique","url","uploadFields","data","value","focalPoint","imageSizes","resizeOptions","concat","map","mimeTypes","validate","fields","size","sizeFilename"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAKA,SAASA,iBAAiB,QAAQ,yBAAwB;AAO1D,MAAMC,cAAc,CAAC,EAAEC,cAAc,EAAEC,MAAM,EAAEC,QAAQ,EAAmB;IACxE,IAAIA,UAAU;QACZ,OAAO,CAAC,EAAED,OAAOE,SAAS,IAAI,GAAG,EAAEF,OAAOG,MAAM,CAACC,GAAG,IAAI,GAAG,CAAC,EAAEL,eAAe,MAAM,EAAEE,SAAS,CAAC;IACjG;IACA,OAAOI;AACT;AAOA,OAAO,MAAMC,sBAAsB,CAAC,EAAEC,UAAU,EAAEP,MAAM,EAAW;IACjE,MAAMQ,gBAA8B,OAAOD,WAAWE,MAAM,KAAK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O;oCACLC,WAAW;wCACT,CAAC,EAAEe,IAAI,EAAEC,KAAK,EAAE;4CACd,IAAIA,OAAO,OAAOA;4CAElB,MAAMU,eAAeX,MAAMX,OAAO,CAACqB,KAAKjC,IAAI,CAAC,EAAEV;4CAE/C,IAAI4C,cAAc;gDAChB,OAAO,CAAC,EAAE7C,OAAOE,SAAS,CAAC,EAAEF,OAAOG,MAAM,CAACC,GAAG,CAAC,CAAC,EAAEG,WAAWiB,IAAI,CAAC,MAAM,EAAEqB,aAAa,CAAC;4CAC1F;4CAEA,OAAO;wCACT;qCACD;gCACH;4BACF;4BACApB;4BACAE;4BACAjB;4BACAkB;4BACA;gCACE,GAAG3B,QAAQ;gCACX8B,QAAQ;4BACV;yBACD;wBACDf,OAAO4B,KAAKjC,IAAI;oBAClB,CAAA;gBACAK,OAAO,CAAC,EAAEU,CAAC,EAAE,GAAKA,EAAE;YACtB;SACD;IACH;IACA,OAAOO;AACT,EAAC"}
|
|
@@ -5,6 +5,6 @@ type Args = {
|
|
|
5
5
|
req: PayloadRequestWithData;
|
|
6
6
|
staticPath: string;
|
|
7
7
|
};
|
|
8
|
-
declare function getSafeFileName({ collectionSlug, desiredFilename, req, staticPath, }: Args): Promise<string>;
|
|
9
|
-
export
|
|
8
|
+
export declare function getSafeFileName({ collectionSlug, desiredFilename, req, staticPath, }: Args): Promise<string>;
|
|
9
|
+
export {};
|
|
10
10
|
//# sourceMappingURL=getSafeFilename.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getSafeFilename.d.ts","sourceRoot":"","sources":["../../src/uploads/getSafeFilename.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAA;AAsB/D,KAAK,IAAI,GAAG;IACV,cAAc,EAAE,MAAM,CAAA;IACtB,eAAe,EAAE,MAAM,CAAA;IACvB,GAAG,EAAE,sBAAsB,CAAA;IAC3B,UAAU,EAAE,MAAM,CAAA;CACnB,CAAA;AAED,
|
|
1
|
+
{"version":3,"file":"getSafeFilename.d.ts","sourceRoot":"","sources":["../../src/uploads/getSafeFilename.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAA;AAsB/D,KAAK,IAAI,GAAG;IACV,cAAc,EAAE,MAAM,CAAA;IACtB,eAAe,EAAE,MAAM,CAAA;IACvB,GAAG,EAAE,sBAAsB,CAAA;IAC3B,UAAU,EAAE,MAAM,CAAA;CACnB,CAAA;AAED,wBAAsB,eAAe,CAAC,EACpC,cAAc,EACd,eAAe,EACf,GAAG,EACH,UAAU,GACX,EAAE,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAgBxB"}
|
|
@@ -17,7 +17,7 @@ const incrementName = (name)=>{
|
|
|
17
17
|
}
|
|
18
18
|
return `${incrementedName}.${extension}`;
|
|
19
19
|
};
|
|
20
|
-
async function getSafeFileName({ collectionSlug, desiredFilename, req, staticPath }) {
|
|
20
|
+
export async function getSafeFileName({ collectionSlug, desiredFilename, req, staticPath }) {
|
|
21
21
|
let modifiedFilename = desiredFilename;
|
|
22
22
|
// eslint-disable-next-line no-await-in-loop
|
|
23
23
|
while(await docWithFilenameExists({
|
|
@@ -30,6 +30,5 @@ async function getSafeFileName({ collectionSlug, desiredFilename, req, staticPat
|
|
|
30
30
|
}
|
|
31
31
|
return modifiedFilename;
|
|
32
32
|
}
|
|
33
|
-
export default getSafeFileName;
|
|
34
33
|
|
|
35
34
|
//# sourceMappingURL=getSafeFilename.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/uploads/getSafeFilename.ts"],"sourcesContent":["import sanitize from 'sanitize-filename'\n\nimport type { PayloadRequestWithData } from '../types/index.js'\n\nimport docWithFilenameExists from './docWithFilenameExists.js'\nimport fileExists from './fileExists.js'\n\nconst incrementName = (name: string) => {\n const extension = name.split('.').pop()\n const baseFilename = sanitize(name.substring(0, name.lastIndexOf('.')) || name)\n let incrementedName = baseFilename\n const regex = /(.*)-(\\d+)$/\n const found = baseFilename.match(regex)\n if (found === null) {\n incrementedName += '-1'\n } else {\n const matchedName = found[1]\n const matchedNumber = found[2]\n const incremented = Number(matchedNumber) + 1\n incrementedName = `${matchedName}-${incremented}`\n }\n return `${incrementedName}.${extension}`\n}\n\ntype Args = {\n collectionSlug: string\n desiredFilename: string\n req: PayloadRequestWithData\n staticPath: string\n}\n\
|
|
1
|
+
{"version":3,"sources":["../../src/uploads/getSafeFilename.ts"],"sourcesContent":["import sanitize from 'sanitize-filename'\n\nimport type { PayloadRequestWithData } from '../types/index.js'\n\nimport docWithFilenameExists from './docWithFilenameExists.js'\nimport fileExists from './fileExists.js'\n\nconst incrementName = (name: string) => {\n const extension = name.split('.').pop()\n const baseFilename = sanitize(name.substring(0, name.lastIndexOf('.')) || name)\n let incrementedName = baseFilename\n const regex = /(.*)-(\\d+)$/\n const found = baseFilename.match(regex)\n if (found === null) {\n incrementedName += '-1'\n } else {\n const matchedName = found[1]\n const matchedNumber = found[2]\n const incremented = Number(matchedNumber) + 1\n incrementedName = `${matchedName}-${incremented}`\n }\n return `${incrementedName}.${extension}`\n}\n\ntype Args = {\n collectionSlug: string\n desiredFilename: string\n req: PayloadRequestWithData\n staticPath: string\n}\n\nexport async function getSafeFileName({\n collectionSlug,\n desiredFilename,\n req,\n staticPath,\n}: Args): Promise<string> {\n let modifiedFilename = desiredFilename\n\n // eslint-disable-next-line no-await-in-loop\n while (\n (await docWithFilenameExists({\n collectionSlug,\n filename: modifiedFilename,\n path: staticPath,\n req,\n })) ||\n (await fileExists(`${staticPath}/${modifiedFilename}`))\n ) {\n modifiedFilename = incrementName(modifiedFilename)\n }\n return modifiedFilename\n}\n"],"names":["sanitize","docWithFilenameExists","fileExists","incrementName","name","extension","split","pop","baseFilename","substring","lastIndexOf","incrementedName","regex","found","match","matchedName","matchedNumber","incremented","Number","getSafeFileName","collectionSlug","desiredFilename","req","staticPath","modifiedFilename","filename","path"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,OAAOA,cAAc,oBAAmB;AAIxC,OAAOC,2BAA2B,6BAA4B;AAC9D,OAAOC,gBAAgB,kBAAiB;AAExC,MAAMC,gBAAgB,CAACC;IACrB,MAAMC,YAAYD,KAAKE,KAAK,CAAC,KAAKC,GAAG;IACrC,MAAMC,eAAeR,SAASI,KAAKK,SAAS,CAAC,GAAGL,KAAKM,WAAW,CAAC,SAASN;IAC1E,IAAIO,kBAAkBH;IACtB,MAAMI,QAAQ;IACd,MAAMC,QAAQL,aAAaM,KAAK,CAACF;IACjC,IAAIC,UAAU,MAAM;QAClBF,mBAAmB;IACrB,OAAO;QACL,MAAMI,cAAcF,KAAK,CAAC,EAAE;QAC5B,MAAMG,gBAAgBH,KAAK,CAAC,EAAE;QAC9B,MAAMI,cAAcC,OAAOF,iBAAiB;QAC5CL,kBAAkB,CAAC,EAAEI,YAAY,CAAC,EAAEE,YAAY,CAAC;IACnD;IACA,OAAO,CAAC,EAAEN,gBAAgB,CAAC,EAAEN,UAAU,CAAC;AAC1C;AASA,OAAO,eAAec,gBAAgB,EACpCC,cAAc,EACdC,eAAe,EACfC,GAAG,EACHC,UAAU,EACL;IACL,IAAIC,mBAAmBH;IAEvB,4CAA4C;IAC5C,MACE,AAAC,MAAMpB,sBAAsB;QAC3BmB;QACAK,UAAUD;QACVE,MAAMH;QACND;IACF,MACC,MAAMpB,WAAW,CAAC,EAAEqB,WAAW,CAAC,EAAEC,iBAAiB,CAAC,EACrD;QACAA,mBAAmBrB,cAAcqB;IACnC;IACA,OAAOA;AACT"}
|
|
@@ -1,23 +1,21 @@
|
|
|
1
1
|
import type { SanitizedCollectionConfig } from '../collections/config/types.js';
|
|
2
2
|
import type { SharpDependency } from '../config/types.js';
|
|
3
|
-
import type { PayloadRequestWithData
|
|
4
|
-
import type { FileSizes, FileToSave, ProbedImageSize } from './types.js';
|
|
3
|
+
import type { PayloadRequestWithData } from '../types/index.js';
|
|
4
|
+
import type { FileSizes, FileToSave, ProbedImageSize, UploadEdits } from './types.js';
|
|
5
5
|
type ResizeArgs = {
|
|
6
6
|
config: SanitizedCollectionConfig;
|
|
7
7
|
dimensions: ProbedImageSize;
|
|
8
8
|
file: PayloadRequestWithData['file'];
|
|
9
9
|
mimeType: string;
|
|
10
|
-
req: PayloadRequestWithData
|
|
11
|
-
query?: {
|
|
12
|
-
uploadEdits?: UploadEdits;
|
|
13
|
-
};
|
|
14
|
-
};
|
|
10
|
+
req: PayloadRequestWithData;
|
|
15
11
|
savedFilename: string;
|
|
16
|
-
sharp
|
|
12
|
+
sharp?: SharpDependency;
|
|
17
13
|
staticPath: string;
|
|
14
|
+
uploadEdits?: UploadEdits;
|
|
18
15
|
};
|
|
19
16
|
/** Result from resizing and transforming the requested image sizes */
|
|
20
17
|
type ImageSizesResult = {
|
|
18
|
+
focalPoint?: UploadEdits['focalPoint'];
|
|
21
19
|
sizeData: FileSizes;
|
|
22
20
|
sizesToSave: FileToSave[];
|
|
23
21
|
};
|
|
@@ -35,6 +33,6 @@ type ImageSizesResult = {
|
|
|
35
33
|
* @param resizeConfig - the resize config
|
|
36
34
|
* @returns the result of the resize operation(s)
|
|
37
35
|
*/
|
|
38
|
-
export
|
|
36
|
+
export declare function resizeAndTransformImageSizes({ config, dimensions, file, mimeType, req, savedFilename, sharp, staticPath, uploadEdits, }: ResizeArgs): Promise<ImageSizesResult>;
|
|
39
37
|
export {};
|
|
40
38
|
//# sourceMappingURL=imageResizer.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"imageResizer.d.ts","sourceRoot":"","sources":["../../src/uploads/imageResizer.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAA;AAC/E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AACzD,OAAO,KAAK,EAAE,sBAAsB,EAAE,
|
|
1
|
+
{"version":3,"file":"imageResizer.d.ts","sourceRoot":"","sources":["../../src/uploads/imageResizer.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAA;AAC/E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AACzD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAA;AAC/D,OAAO,KAAK,EAEV,SAAS,EACT,UAAU,EAEV,eAAe,EACf,WAAW,EACZ,MAAM,YAAY,CAAA;AAKnB,KAAK,UAAU,GAAG;IAChB,MAAM,EAAE,yBAAyB,CAAA;IACjC,UAAU,EAAE,eAAe,CAAA;IAC3B,IAAI,EAAE,sBAAsB,CAAC,MAAM,CAAC,CAAA;IACpC,QAAQ,EAAE,MAAM,CAAA;IAChB,GAAG,EAAE,sBAAsB,CAAA;IAC3B,aAAa,EAAE,MAAM,CAAA;IACrB,KAAK,CAAC,EAAE,eAAe,CAAA;IACvB,UAAU,EAAE,MAAM,CAAA;IAClB,WAAW,CAAC,EAAE,WAAW,CAAA;CAC1B,CAAA;AAED,sEAAsE;AACtE,KAAK,gBAAgB,GAAG;IACtB,UAAU,CAAC,EAAE,WAAW,CAAC,YAAY,CAAC,CAAA;IACtC,QAAQ,EAAE,SAAS,CAAA;IACnB,WAAW,EAAE,UAAU,EAAE,CAAA;CAC1B,CAAA;AA6KD;;;;;;;;;;;;;GAaG;AACH,wBAAsB,4BAA4B,CAAC,EACjD,MAAM,EACN,UAAU,EACV,IAAI,EACJ,QAAQ,EACR,GAAG,EACH,aAAa,EACb,KAAK,EACL,UAAU,EACV,WAAW,GACZ,EAAE,UAAU,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAuIxC"}
|
|
@@ -43,7 +43,8 @@ import fileExists from './fileExists.js';
|
|
|
43
43
|
* @param mimeType - the mime type of the image
|
|
44
44
|
* @param sizesToSave - the sizes to save
|
|
45
45
|
* @returns the result object
|
|
46
|
-
*/ const createResult = (name, filename = null,
|
|
46
|
+
*/ const createResult = ({ name, filename = null, filesize = null, height = null, mimeType = null, sizesToSave = [], width = null })=>{
|
|
47
|
+
return {
|
|
47
48
|
sizeData: {
|
|
48
49
|
[name]: {
|
|
49
50
|
filename,
|
|
@@ -54,7 +55,8 @@ import fileExists from './fileExists.js';
|
|
|
54
55
|
}
|
|
55
56
|
},
|
|
56
57
|
sizesToSave
|
|
57
|
-
}
|
|
58
|
+
};
|
|
59
|
+
};
|
|
58
60
|
/**
|
|
59
61
|
* Check if the image needs to be resized according to the requested dimensions
|
|
60
62
|
* and the original image size. If the resize options withoutEnlargement or withoutReduction are provided,
|
|
@@ -142,13 +144,23 @@ import fileExists from './fileExists.js';
|
|
|
142
144
|
*
|
|
143
145
|
* @param resizeConfig - the resize config
|
|
144
146
|
* @returns the result of the resize operation(s)
|
|
145
|
-
*/ export
|
|
146
|
-
const { imageSizes } = config.upload;
|
|
147
|
-
//
|
|
148
|
-
|
|
147
|
+
*/ export async function resizeAndTransformImageSizes({ config, dimensions, file, mimeType, req, savedFilename, sharp, staticPath, uploadEdits }) {
|
|
148
|
+
const { focalPoint: focalPointEnabled = true, imageSizes } = config.upload;
|
|
149
|
+
// Focal point adjustments
|
|
150
|
+
const incomingFocalPoint = uploadEdits.focalPoint ? {
|
|
151
|
+
x: isNumber(uploadEdits.focalPoint.x) ? Math.round(uploadEdits.focalPoint.x) : 50,
|
|
152
|
+
y: isNumber(uploadEdits.focalPoint.y) ? Math.round(uploadEdits.focalPoint.y) : 50
|
|
153
|
+
} : undefined;
|
|
154
|
+
const defaultResult = {
|
|
155
|
+
...focalPointEnabled && incomingFocalPoint && {
|
|
156
|
+
focalPoint: incomingFocalPoint
|
|
157
|
+
},
|
|
149
158
|
sizeData: {},
|
|
150
159
|
sizesToSave: []
|
|
151
160
|
};
|
|
161
|
+
if (!imageSizes || !sharp) {
|
|
162
|
+
return defaultResult;
|
|
163
|
+
}
|
|
152
164
|
const sharpBase = sharp(file.tempFilePath || file.data).rotate() // pass rotate() to auto-rotate based on EXIF data. https://github.com/payloadcms/payload/pull/3081
|
|
153
165
|
;
|
|
154
166
|
const results = await Promise.all(imageSizes.map(async (imageResizeConfig)=>{
|
|
@@ -157,11 +169,13 @@ import fileExists from './fileExists.js';
|
|
|
157
169
|
// skipped COMPLETELY and thus will not be included in the resulting images.
|
|
158
170
|
// All further format/trim options will thus be skipped as well.
|
|
159
171
|
if (preventResize(imageResizeConfig, dimensions)) {
|
|
160
|
-
return createResult(
|
|
172
|
+
return createResult({
|
|
173
|
+
name: imageResizeConfig.name
|
|
174
|
+
});
|
|
161
175
|
}
|
|
162
176
|
const imageToResize = sharpBase.clone();
|
|
163
177
|
let resized = imageToResize;
|
|
164
|
-
if (
|
|
178
|
+
if (incomingFocalPoint && applyPayloadAdjustments(imageResizeConfig, dimensions)) {
|
|
165
179
|
const { height: resizeHeight, width: resizeWidth } = imageResizeConfig;
|
|
166
180
|
const resizeAspectRatio = resizeWidth / resizeHeight;
|
|
167
181
|
const originalAspectRatio = dimensions.width / dimensions.height;
|
|
@@ -174,18 +188,13 @@ import fileExists from './fileExists.js';
|
|
|
174
188
|
const { info: scaledImageInfo } = await scaledImage.toBuffer({
|
|
175
189
|
resolveWithObject: true
|
|
176
190
|
});
|
|
177
|
-
// Focal point adjustments
|
|
178
|
-
const focalPoint = {
|
|
179
|
-
x: isNumber(req.query.uploadEdits.focalPoint?.x) ? req.query.uploadEdits.focalPoint.x : 50,
|
|
180
|
-
y: isNumber(req.query.uploadEdits.focalPoint?.y) ? req.query.uploadEdits.focalPoint.y : 50
|
|
181
|
-
};
|
|
182
191
|
const safeResizeWidth = resizeWidth ?? scaledImageInfo.width;
|
|
183
192
|
const maxOffsetX = scaledImageInfo.width - safeResizeWidth;
|
|
184
|
-
const leftFocalEdge = Math.round(scaledImageInfo.width * (
|
|
193
|
+
const leftFocalEdge = Math.round(scaledImageInfo.width * (incomingFocalPoint.x / 100) - safeResizeWidth / 2);
|
|
185
194
|
const safeOffsetX = Math.min(Math.max(0, leftFocalEdge), maxOffsetX);
|
|
186
195
|
const safeResizeHeight = resizeHeight ?? scaledImageInfo.height;
|
|
187
196
|
const maxOffsetY = scaledImageInfo.height - safeResizeHeight;
|
|
188
|
-
const topFocalEdge = Math.round(scaledImageInfo.height * (
|
|
197
|
+
const topFocalEdge = Math.round(scaledImageInfo.height * (incomingFocalPoint.y / 100) - safeResizeHeight / 2);
|
|
189
198
|
const safeOffsetY = Math.min(Math.max(0, topFocalEdge), maxOffsetY);
|
|
190
199
|
// extract the focal area from the scaled image
|
|
191
200
|
resized = scaledImage.extract({
|
|
@@ -207,7 +216,9 @@ import fileExists from './fileExists.js';
|
|
|
207
216
|
resolveWithObject: true
|
|
208
217
|
});
|
|
209
218
|
const sanitizedImage = getSanitizedImageData(savedFilename);
|
|
210
|
-
req.payloadUploadSizes
|
|
219
|
+
if (req.payloadUploadSizes) {
|
|
220
|
+
req.payloadUploadSizes[imageResizeConfig.name] = bufferData;
|
|
221
|
+
}
|
|
211
222
|
const mimeInfo = await fromBuffer(bufferData);
|
|
212
223
|
const imageNameWithDimensions = createImageName(sanitizedImage.name, bufferInfo, mimeInfo?.ext || sanitizedImage.ext);
|
|
213
224
|
const imagePath = `${staticPath}/${imageNameWithDimensions}`;
|
|
@@ -219,20 +230,27 @@ import fileExists from './fileExists.js';
|
|
|
219
230
|
}
|
|
220
231
|
}
|
|
221
232
|
const { height, size, width } = bufferInfo;
|
|
222
|
-
return createResult(
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
233
|
+
return createResult({
|
|
234
|
+
name: imageResizeConfig.name,
|
|
235
|
+
filename: imageNameWithDimensions,
|
|
236
|
+
filesize: size,
|
|
237
|
+
height,
|
|
238
|
+
mimeType: mimeInfo?.mime || mimeType,
|
|
239
|
+
sizesToSave: [
|
|
240
|
+
{
|
|
241
|
+
buffer: bufferData,
|
|
242
|
+
path: imagePath
|
|
243
|
+
}
|
|
244
|
+
],
|
|
245
|
+
width
|
|
246
|
+
});
|
|
228
247
|
}));
|
|
229
248
|
return results.reduce((acc, result)=>{
|
|
230
249
|
Object.assign(acc.sizeData, result.sizeData);
|
|
231
250
|
acc.sizesToSave.push(...result.sizesToSave);
|
|
232
251
|
return acc;
|
|
233
252
|
}, {
|
|
234
|
-
|
|
235
|
-
sizesToSave: []
|
|
253
|
+
...defaultResult
|
|
236
254
|
});
|
|
237
255
|
}
|
|
238
256
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/uploads/imageResizer.ts"],"sourcesContent":["import type { OutputInfo } from 'sharp'\n\nimport fileType from 'file-type'\nconst { fromBuffer } = fileType\n\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 { PayloadRequestWithData, UploadEdits } from '../types/index.js'\nimport type { FileSize, FileSizes, FileToSave, ImageSize, ProbedImageSize } 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: PayloadRequestWithData['file']\n mimeType: string\n req: PayloadRequestWithData & {\n query?: {\n uploadEdits?: UploadEdits\n }\n }\n savedFilename: string\n sharp: SharpDependency\n staticPath: string\n}\n\n/** Result from resizing and transforming the requested image sizes */\ntype ImageSizesResult = {\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 */\nconst createImageName = (\n outputImageName: string,\n { height, width }: OutputInfo,\n extension: string,\n) => `${outputImageName}-${width}x${height}.${extension}`\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: string,\n filename: FileSize['filename'] = null,\n width: FileSize['width'] = null,\n height: FileSize['height'] = null,\n filesize: FileSize['filesize'] = null,\n mimeType: FileSize['mimeType'] = null,\n sizesToSave: FileToSave[] = [],\n): ImageSizesResult => ({\n sizeData: {\n [name]: {\n filename,\n filesize,\n height,\n mimeType,\n width,\n },\n },\n sizesToSave,\n})\n\n/**\n * Check if the image needs to be resized according to the requested dimensions\n * and the original image size. If the resize options withoutEnlargement or withoutReduction are provided,\n * the image will be resized regardless of the requested dimensions, given that the\n * width or height to be resized is provided.\n *\n * @param resizeConfig - object containing the requested dimensions and resize options\n * @param original - the original image size\n * @returns true if resizing is not needed, false otherwise\n */\nconst preventResize = (\n { height: desiredHeight, width: desiredWidth, withoutEnlargement, withoutReduction }: ImageSize,\n original: ProbedImageSize,\n): boolean => {\n // default is to allow reduction\n if (withoutReduction !== undefined) {\n return false // needs resize\n }\n\n // default is to prevent enlargement\n if (withoutEnlargement !== undefined) {\n return false // needs resize\n }\n\n const isWidthOrHeightNotDefined = !desiredHeight || !desiredWidth\n if (isWidthOrHeightNotDefined) {\n // If width and height are not defined, it means there is a format conversion\n // and the image needs to be \"resized\" (transformed).\n return false // needs resize\n }\n\n const hasInsufficientWidth = desiredWidth > original.width\n const hasInsufficientHeight = desiredHeight > original.height\n if (hasInsufficientWidth && hasInsufficientHeight) {\n // doesn't need resize - prevent enlargement. This should only happen if both width and height are insufficient.\n // if only one dimension is insufficient and the other is sufficient, resizing needs to happen, as the image\n // should be resized to the sufficient dimension.\n return true // do not create a new size\n }\n\n return false // needs resize\n}\n\n/**\n * Check if the image should be passed directly to sharp without payload adjusting properties.\n *\n * @param resizeConfig - object containing the requested dimensions and resize options\n * @param original - the original image size\n * @returns true if the image should passed directly to sharp\n */\nconst applyPayloadAdjustments = (\n { fit, height, width, withoutEnlargement, withoutReduction }: ImageSize,\n original: ProbedImageSize,\n) => {\n if (fit === 'contain' || fit === 'inside') return false\n if (!isNumber(height) && !isNumber(width)) return false\n\n const targetAspectRatio = width / height\n const originalAspectRatio = original.width / original.height\n if (originalAspectRatio === targetAspectRatio) return false\n\n const skipEnlargement = withoutEnlargement && (original.height < height || original.width < width)\n const skipReduction = withoutReduction && (original.height > height || original.width > width)\n if (skipEnlargement || skipReduction) return false\n\n return true\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 * 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 dos not need to be resized, an 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 default async function resizeAndTransformImageSizes({\n config,\n dimensions,\n file,\n mimeType,\n req,\n savedFilename,\n sharp,\n staticPath,\n}: ResizeArgs): Promise<ImageSizesResult> {\n const { imageSizes } = config.upload\n // Noting to resize here so return as early as possible\n if (!imageSizes) return { sizeData: {}, sizesToSave: [] }\n\n const sharpBase = sharp(file.tempFilePath || file.data).rotate() // pass rotate() to auto-rotate based on EXIF data. https://github.com/payloadcms/payload/pull/3081\n\n const results: ImageSizesResult[] = await Promise.all(\n imageSizes.map(async (imageResizeConfig): Promise<ImageSizesResult> => {\n imageResizeConfig = sanitizeResizeConfig(imageResizeConfig)\n\n // This checks if a resize should happen. If not, the resized image will be\n // skipped COMPLETELY and thus will not be included in the resulting images.\n // All further format/trim options will thus be skipped as well.\n if (preventResize(imageResizeConfig, dimensions)) {\n return createResult(imageResizeConfig.name)\n }\n\n const imageToResize = sharpBase.clone()\n let resized = imageToResize\n\n if (\n req.query?.uploadEdits?.focalPoint &&\n applyPayloadAdjustments(imageResizeConfig, dimensions)\n ) {\n const { height: resizeHeight, width: resizeWidth } = imageResizeConfig\n const resizeAspectRatio = resizeWidth / resizeHeight\n const originalAspectRatio = dimensions.width / dimensions.height\n const prioritizeHeight = resizeAspectRatio < originalAspectRatio\n\n // Scale the image up or down to fit the resize dimensions\n const scaledImage = imageToResize.resize({\n height: prioritizeHeight ? resizeHeight : null,\n width: prioritizeHeight ? null : resizeWidth,\n })\n const { info: scaledImageInfo } = await scaledImage.toBuffer({ resolveWithObject: true })\n\n // Focal point adjustments\n const focalPoint = {\n x: isNumber(req.query.uploadEdits.focalPoint?.x)\n ? req.query.uploadEdits.focalPoint.x\n : 50,\n y: isNumber(req.query.uploadEdits.focalPoint?.y)\n ? req.query.uploadEdits.focalPoint.y\n : 50,\n }\n\n const safeResizeWidth = resizeWidth ?? scaledImageInfo.width\n const maxOffsetX = scaledImageInfo.width - safeResizeWidth\n const leftFocalEdge = Math.round(\n scaledImageInfo.width * (focalPoint.x / 100) - safeResizeWidth / 2,\n )\n const safeOffsetX = Math.min(Math.max(0, leftFocalEdge), maxOffsetX)\n\n const safeResizeHeight = resizeHeight ?? scaledImageInfo.height\n const maxOffsetY = scaledImageInfo.height - safeResizeHeight\n const topFocalEdge = Math.round(\n scaledImageInfo.height * (focalPoint.y / 100) - safeResizeHeight / 2,\n )\n const safeOffsetY = Math.min(Math.max(0, topFocalEdge), maxOffsetY)\n\n // extract the focal area from the scaled image\n resized = scaledImage.extract({\n height: safeResizeHeight,\n left: safeOffsetX,\n top: safeOffsetY,\n width: safeResizeWidth,\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 req.payloadUploadSizes[imageResizeConfig.name] = bufferData\n\n const mimeInfo = await fromBuffer(bufferData)\n\n const imageNameWithDimensions = createImageName(\n sanitizedImage.name,\n bufferInfo,\n mimeInfo?.ext || sanitizedImage.ext,\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 imageResizeConfig.name,\n imageNameWithDimensions,\n width,\n height,\n size,\n mimeInfo?.mime || mimeType,\n [{ buffer: bufferData, path: imagePath }],\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 { sizeData: {}, sizesToSave: [] },\n )\n}\n"],"names":["fileType","fromBuffer","fs","sanitize","isNumber","fileExists","getSanitizedImageData","sourceImage","extension","split","pop","name","substring","lastIndexOf","ext","createImageName","outputImageName","height","width","createResult","filename","filesize","mimeType","sizesToSave","sizeData","preventResize","desiredHeight","desiredWidth","withoutEnlargement","withoutReduction","original","undefined","isWidthOrHeightNotDefined","hasInsufficientWidth","hasInsufficientHeight","applyPayloadAdjustments","fit","targetAspectRatio","originalAspectRatio","skipEnlargement","skipReduction","sanitizeResizeConfig","resizeConfig","position","resizeAndTransformImageSizes","config","dimensions","file","req","savedFilename","sharp","staticPath","imageSizes","upload","sharpBase","tempFilePath","data","rotate","results","Promise","all","map","imageResizeConfig","imageToResize","clone","resized","query","uploadEdits","focalPoint","resizeHeight","resizeWidth","resizeAspectRatio","prioritizeHeight","scaledImage","resize","info","scaledImageInfo","toBuffer","resolveWithObject","x","y","safeResizeWidth","maxOffsetX","leftFocalEdge","Math","round","safeOffsetX","min","max","safeResizeHeight","maxOffsetY","topFocalEdge","safeOffsetY","extract","left","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"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAEA,OAAOA,cAAc,YAAW;AAChC,MAAM,EAAEC,UAAU,EAAE,GAAGD;AAEvB,OAAOE,QAAQ,KAAI;AACnB,OAAOC,cAAc,oBAAmB;AAOxC,SAASC,QAAQ,QAAQ,2BAA0B;AACnD,OAAOC,gBAAgB,kBAAiB;AA4BxC;;;;;CAKC,GACD,MAAMC,wBAAw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AI,EACnB4F,YACAG,UAAU5F,OAAO0F,eAAe1F,GAAG;QAGrC,MAAM8F,YAAY,CAAC,EAAEzD,WAAW,CAAC,EAAEwD,wBAAwB,CAAC;QAE5D,IAAI,MAAMtG,WAAWuG,YAAY;YAC/B,IAAI;gBACF1G,GAAG2G,UAAU,CAACD;YAChB,EAAE,OAAM;YACN,uBAAuB;YACzB;QACF;QAEA,MAAM,EAAE3F,MAAM,EAAE6F,IAAI,EAAE5F,KAAK,EAAE,GAAGqF;QAChC,OAAOpF,aACL2C,kBAAkBnD,IAAI,EACtBgG,yBACAzF,OACAD,QACA6F,MACAJ,UAAUK,QAAQzF,UAClB;YAAC;gBAAE0F,QAAQV;gBAAYW,MAAML;YAAU;SAAE;IAE7C;IAGF,OAAOlD,QAAQwD,MAAM,CACnB,CAACC,KAAKC;QACJC,OAAOC,MAAM,CAACH,IAAI3F,QAAQ,EAAE4F,OAAO5F,QAAQ;QAC3C2F,IAAI5F,WAAW,CAACgG,IAAI,IAAIH,OAAO7F,WAAW;QAC1C,OAAO4F;IACT,GACA;QAAE3F,UAAU,CAAC;QAAGD,aAAa,EAAE;IAAC;AAEpC"}
|
|
1
|
+
{"version":3,"sources":["../../src/uploads/imageResizer.ts"],"sourcesContent":["import type { OutputInfo } from 'sharp'\n\nimport fileType from 'file-type'\nconst { fromBuffer } = fileType\n\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 { PayloadRequestWithData } 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: PayloadRequestWithData['file']\n mimeType: string\n req: PayloadRequestWithData\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 */\nconst createImageName = (\n outputImageName: string,\n { height, width }: OutputInfo,\n extension: string,\n) => `${outputImageName}-${width}x${height}.${extension}`\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 * Check if the image needs to be resized according to the requested dimensions\n * and the original image size. If the resize options withoutEnlargement or withoutReduction are provided,\n * the image will be resized regardless of the requested dimensions, given that the\n * width or height to be resized is provided.\n *\n * @param resizeConfig - object containing the requested dimensions and resize options\n * @param original - the original image size\n * @returns true if resizing is not needed, false otherwise\n */\nconst preventResize = (\n { height: desiredHeight, width: desiredWidth, withoutEnlargement, withoutReduction }: ImageSize,\n original: ProbedImageSize,\n): boolean => {\n // default is to allow reduction\n if (withoutReduction !== undefined) {\n return false // needs resize\n }\n\n // default is to prevent enlargement\n if (withoutEnlargement !== undefined) {\n return false // needs resize\n }\n\n const isWidthOrHeightNotDefined = !desiredHeight || !desiredWidth\n if (isWidthOrHeightNotDefined) {\n // If width and height are not defined, it means there is a format conversion\n // and the image needs to be \"resized\" (transformed).\n return false // needs resize\n }\n\n const hasInsufficientWidth = desiredWidth > original.width\n const hasInsufficientHeight = desiredHeight > original.height\n if (hasInsufficientWidth && hasInsufficientHeight) {\n // doesn't need resize - prevent enlargement. This should only happen if both width and height are insufficient.\n // if only one dimension is insufficient and the other is sufficient, resizing needs to happen, as the image\n // should be resized to the sufficient dimension.\n return true // do not create a new size\n }\n\n return false // needs resize\n}\n\n/**\n * Check if the image should be passed directly to sharp without payload adjusting properties.\n *\n * @param resizeConfig - object containing the requested dimensions and resize options\n * @param original - the original image size\n * @returns true if the image should passed directly to sharp\n */\nconst applyPayloadAdjustments = (\n { fit, height, width, withoutEnlargement, withoutReduction }: ImageSize,\n original: ProbedImageSize,\n) => {\n if (fit === 'contain' || fit === 'inside') return false\n if (!isNumber(height) && !isNumber(width)) return false\n\n const targetAspectRatio = width / height\n const originalAspectRatio = original.width / original.height\n if (originalAspectRatio === targetAspectRatio) return false\n\n const skipEnlargement = withoutEnlargement && (original.height < height || original.width < width)\n const skipReduction = withoutReduction && (original.height > height || original.width > width)\n if (skipEnlargement || skipReduction) return false\n\n return true\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 * 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 dos not need to be resized, an 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 const sharpBase = sharp(file.tempFilePath || file.data).rotate() // pass rotate() to auto-rotate based on EXIF data. https://github.com/payloadcms/payload/pull/3081\n\n const results: ImageSizesResult[] = await Promise.all(\n imageSizes.map(async (imageResizeConfig): Promise<ImageSizesResult> => {\n imageResizeConfig = sanitizeResizeConfig(imageResizeConfig)\n\n // This checks if a resize should happen. If not, the resized image will be\n // skipped COMPLETELY and thus will not be included in the resulting images.\n // All further format/trim options will thus be skipped as well.\n if (preventResize(imageResizeConfig, dimensions)) {\n return createResult({ name: imageResizeConfig.name })\n }\n\n const imageToResize = sharpBase.clone()\n let resized = imageToResize\n\n if (incomingFocalPoint && applyPayloadAdjustments(imageResizeConfig, dimensions)) {\n const { height: resizeHeight, width: resizeWidth } = imageResizeConfig\n const resizeAspectRatio = resizeWidth / resizeHeight\n const originalAspectRatio = dimensions.width / dimensions.height\n const prioritizeHeight = resizeAspectRatio < originalAspectRatio\n\n // Scale the image up or down to fit the resize dimensions\n const scaledImage = imageToResize.resize({\n height: prioritizeHeight ? resizeHeight : null,\n width: prioritizeHeight ? null : resizeWidth,\n })\n const { info: scaledImageInfo } = await scaledImage.toBuffer({ resolveWithObject: true })\n\n const safeResizeWidth = resizeWidth ?? scaledImageInfo.width\n const maxOffsetX = scaledImageInfo.width - safeResizeWidth\n const leftFocalEdge = Math.round(\n scaledImageInfo.width * (incomingFocalPoint.x / 100) - safeResizeWidth / 2,\n )\n const safeOffsetX = Math.min(Math.max(0, leftFocalEdge), maxOffsetX)\n\n const safeResizeHeight = resizeHeight ?? scaledImageInfo.height\n const maxOffsetY = scaledImageInfo.height - safeResizeHeight\n const topFocalEdge = Math.round(\n scaledImageInfo.height * (incomingFocalPoint.y / 100) - safeResizeHeight / 2,\n )\n const safeOffsetY = Math.min(Math.max(0, topFocalEdge), maxOffsetY)\n\n // extract the focal area from the scaled image\n resized = scaledImage.extract({\n height: safeResizeHeight,\n left: safeOffsetX,\n top: safeOffsetY,\n width: safeResizeWidth,\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 fromBuffer(bufferData)\n\n const imageNameWithDimensions = createImageName(\n sanitizedImage.name,\n bufferInfo,\n mimeInfo?.ext || sanitizedImage.ext,\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 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":["fileType","fromBuffer","fs","sanitize","isNumber","fileExists","getSanitizedImageData","sourceImage","extension","split","pop","name","substring","lastIndexOf","ext","createImageName","outputImageName","height","width","createResult","filename","filesize","mimeType","sizesToSave","sizeData","preventResize","desiredHeight","desiredWidth","withoutEnlargement","withoutReduction","original","undefined","isWidthOrHeightNotDefined","hasInsufficientWidth","hasInsufficientHeight","applyPayloadAdjustments","fit","targetAspectRatio","originalAspectRatio","skipEnlargement","skipReduction","sanitizeResizeConfig","resizeConfig","position","resizeAndTransformImageSizes","config","dimensions","file","req","savedFilename","sharp","staticPath","uploadEdits","focalPoint","focalPointEnabled","imageSizes","upload","incomingFocalPoint","x","Math","round","y","defaultResult","sharpBase","tempFilePath","data","rotate","results","Promise","all","map","imageResizeConfig","imageToResize","clone","resized","resizeHeight","resizeWidth","resizeAspectRatio","prioritizeHeight","scaledImage","resize","info","scaledImageInfo","toBuffer","resolveWithObject","safeResizeWidth","maxOffsetX","leftFocalEdge","safeOffsetX","min","max","safeResizeHeight","maxOffsetY","topFocalEdge","safeOffsetY","extract","left","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"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAEA,OAAOA,cAAc,YAAW;AAChC,MAAM,EAAEC,UAAU,EAAE,GAAGD;AAEvB,OAAOE,QAAQ,KAAI;AACnB,OAAOC,cAAc,oBAAmB;AAcxC,SAASC,QAAQ,QAAQ,2BAA0B;AACnD,OAAOC,gBAAgB,kBAAiB;AA0BxC;;;;;CAKC,GACD,MAAMC,wBAAwB,CAACC;IAC7B,MAAMC,YAAYD,YAAYE,KAAK,CAAC,KAAKC,GAAG;IAC5C,MAAMC,OAAOR,SAASI,YAAYK,SAAS,CAAC,GAAGL,YAAYM,WAAW,CAAC,SAASN;IAChF,OAAO;QAAEI;QAAMG,KAAKN;IAAU;AAChC;AAEA;;;;;;;;;;;;CAYC,GACD,MAAMO,kBAAkB,CACtBC,iBACA,EAAEC,MAAM,EAAEC,KAAK,EAAc,EAC7BV,YACG,CAAC,EAAEQ,gBAAgB,CAAC,EAAEE,MAAM,CAAC,EAAED,OAAO,CAAC,EAAET,UAAU,CAAC;AAYzD;;;;;;;;;;;;;CAaC,GACD,MAAMW,eAAe,CAAC,EACpBR,IAAI,EACJS,WAAW,IAAI,EACfC,WAAW,IAAI,EACfJ,SAAS,IAAI,EACbK,W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Aa;YAClBR,MAAM4D,kBAAkB5D,IAAI;YAC5BS,UAAUyF;YACVxF,UAAU2F;YACV/F;YACAK,UAAUsF,UAAUK,QAAQ3F;YAC5BC,aAAa;gBAAC;oBAAE2F,QAAQV;oBAAYW,MAAML;gBAAU;aAAE;YACtD5F;QACF;IACF;IAGF,OAAOiD,QAAQiD,MAAM,CACnB,CAACC,KAAKC;QACJC,OAAOC,MAAM,CAACH,IAAI7F,QAAQ,EAAE8F,OAAO9F,QAAQ;QAC3C6F,IAAI9F,WAAW,CAACkG,IAAI,IAAIH,OAAO/F,WAAW;QAC1C,OAAO8F;IACT,GACA;QAAE,GAAGvD,aAAa;IAAC;AAEvB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export
|
|
1
|
+
export declare function isImage(mimeType: string): boolean;
|
|
2
2
|
//# sourceMappingURL=isImage.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"isImage.d.ts","sourceRoot":"","sources":["../../src/uploads/isImage.ts"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"file":"isImage.d.ts","sourceRoot":"","sources":["../../src/uploads/isImage.ts"],"names":[],"mappings":"AAAA,wBAAgB,OAAO,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAMjD"}
|
package/dist/uploads/isImage.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/uploads/isImage.ts"],"sourcesContent":["export
|
|
1
|
+
{"version":3,"sources":["../../src/uploads/isImage.ts"],"sourcesContent":["export function isImage(mimeType: string): boolean {\n return (\n ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml', 'image/webp', 'image/avif'].indexOf(\n mimeType,\n ) > -1\n )\n}\n"],"names":["isImage","mimeType","indexOf"],"rangeMappings":";;;;;;;;;","mappings":"AAAA,OAAO,SAASA,QAAQC,QAAgB;IACtC,OACE;QAAC;QAAc;QAAa;QAAa;QAAiB;QAAc;KAAa,CAACC,OAAO,CAC3FD,YACE,CAAC;AAET"}
|
package/dist/uploads/types.d.ts
CHANGED
|
@@ -15,6 +15,8 @@ export type FileSizes = {
|
|
|
15
15
|
export type FileData = {
|
|
16
16
|
filename: string;
|
|
17
17
|
filesize: number;
|
|
18
|
+
focalX?: number;
|
|
19
|
+
focalY?: number;
|
|
18
20
|
height: number;
|
|
19
21
|
mimeType: string;
|
|
20
22
|
sizes: FileSizes;
|
|
@@ -110,4 +112,16 @@ export type FileToSave = {
|
|
|
110
112
|
buffer: Buffer;
|
|
111
113
|
path: string;
|
|
112
114
|
};
|
|
115
|
+
export type UploadEdits = {
|
|
116
|
+
crop?: {
|
|
117
|
+
height?: number;
|
|
118
|
+
width?: number;
|
|
119
|
+
x?: number;
|
|
120
|
+
y?: number;
|
|
121
|
+
};
|
|
122
|
+
focalPoint?: {
|
|
123
|
+
x?: number;
|
|
124
|
+
y?: number;
|
|
125
|
+
};
|
|
126
|
+
};
|
|
113
127
|
//# sourceMappingURL=types.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/uploads/types.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,KAAK,EAAE,MAAM,OAAO,CAAA;AAEjD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAA;AAChE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAA;AAE/D,MAAM,MAAM,QAAQ,GAAG;IACrB,QAAQ,EAAE,IAAI,GAAG,MAAM,CAAA;IACvB,QAAQ,EAAE,IAAI,GAAG,MAAM,CAAA;IACvB,MAAM,EAAE,IAAI,GAAG,MAAM,CAAA;IACrB,QAAQ,EAAE,IAAI,GAAG,MAAM,CAAA;IACvB,KAAK,EAAE,IAAI,GAAG,MAAM,CAAA;CACrB,CAAA;AAED,MAAM,MAAM,SAAS,GAAG;IACtB,CAAC,IAAI,EAAE,MAAM,GAAG,QAAQ,C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../../src/uploads/types.ts"],"sourcesContent":["import type { ResizeOptions, Sharp } from 'sharp'\n\nimport type { TypeWithID } from '../collections/config/types.js'\nimport type { PayloadRequestWithData } 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 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 = Omit<ResizeOptions, 'withoutEnlargement'> & {\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}\n\nexport type GetAdminThumbnail = (args: { doc: Record<string, unknown> }) => false | null | string\n\nexport type UploadConfig = {\n /**\n * The adapter to use for uploads.\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 * - If a React component, register a function that generates the thumbnail URL using the `useAdminThumbnail` hook.\n **/\n adminThumbnail?: GetAdminThumbnail | string\n crop?: boolean\n disableLocalStorage?: boolean\n /**\n * Accepts existing headers and can filter/modify them.\n *\n * Useful for adding custom headers to fetch from external providers.\n */\n externalFileHeaderFilter?: (headers: Record<string, string>) => Record<string, string>\n filesRequiredOnCreate?: boolean\n focalPoint?: boolean\n /** Options for original upload file only. For sizes, set each formatOptions individually. */\n formatOptions?: ImageUploadFormatOptions\n handlers?: ((\n req: PayloadRequestWithData,\n args: { doc: TypeWithID; params: { collection: string; filename: string } },\n ) => Promise<Response> | Response)[]\n imageSizes?: ImageSize[]\n mimeTypes?: string[]\n resizeOptions?: ResizeOptions\n staticDir?: string\n trimOptions?: ImageUploadTrimOptions\n}\n\nexport type SanitizedUploadConfig = UploadConfig & {\n staticDir: UploadConfig['staticDir']\n}\n\nexport type File = {\n data: Buffer\n mimetype: string\n name: string\n size: number\n}\n\nexport type FileToSave = {\n buffer: Buffer\n path: string\n}\n"],"names":[],"rangeMappings":"","mappings":"
|
|
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 { PayloadRequestWithData } 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 = Omit<ResizeOptions, 'withoutEnlargement'> & {\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}\n\nexport type GetAdminThumbnail = (args: { doc: Record<string, unknown> }) => false | null | string\n\nexport type UploadConfig = {\n /**\n * The adapter to use for uploads.\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 * - If a React component, register a function that generates the thumbnail URL using the `useAdminThumbnail` hook.\n **/\n adminThumbnail?: GetAdminThumbnail | string\n crop?: boolean\n disableLocalStorage?: boolean\n /**\n * Accepts existing headers and can filter/modify them.\n *\n * Useful for adding custom headers to fetch from external providers.\n */\n externalFileHeaderFilter?: (headers: Record<string, string>) => Record<string, string>\n filesRequiredOnCreate?: boolean\n focalPoint?: boolean\n /** Options for original upload file only. For sizes, set each formatOptions individually. */\n formatOptions?: ImageUploadFormatOptions\n handlers?: ((\n req: PayloadRequestWithData,\n args: { doc: TypeWithID; params: { collection: string; filename: string } },\n ) => Promise<Response> | Response)[]\n imageSizes?: ImageSize[]\n mimeTypes?: string[]\n resizeOptions?: ResizeOptions\n staticDir?: string\n trimOptions?: ImageUploadTrimOptions\n}\n\nexport type SanitizedUploadConfig = UploadConfig & {\n staticDir: UploadConfig['staticDir']\n}\n\nexport type File = {\n data: Buffer\n mimetype: string\n name: string\n size: number\n}\n\nexport type FileToSave = {\n buffer: Buffer\n path: string\n}\n\nexport type UploadEdits = {\n crop?: {\n height?: number\n width?: number\n x?: number\n y?: number\n }\n focalPoint?: {\n x?: number\n y?: number\n }\n}\n"],"names":[],"rangeMappings":"","mappings":"AA0HA,WAWC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "payload",
|
|
3
|
-
"version": "3.0.0-beta.
|
|
3
|
+
"version": "3.0.0-beta.36",
|
|
4
4
|
"description": "Node, React, Headless CMS and Application Framework built on Next.js",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"admin panel",
|
|
@@ -96,7 +96,7 @@
|
|
|
96
96
|
"scmp": "2.1.0",
|
|
97
97
|
"ts-essentials": "7.0.3",
|
|
98
98
|
"uuid": "^9.0.1",
|
|
99
|
-
"@payloadcms/translations": "3.0.0-beta.
|
|
99
|
+
"@payloadcms/translations": "3.0.0-beta.36"
|
|
100
100
|
},
|
|
101
101
|
"devDependencies": {
|
|
102
102
|
"@monaco-editor/react": "4.5.1",
|