@payloadcms/transformer-sharp 4.0.0-beta.8 → 4.0.0-canary.20261117

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.
@@ -0,0 +1,14 @@
1
+ import type { UploadTransformerInternal } from 'payload/internal';
2
+ import type { SharpCollectionConfig, SharpDependency } from './types.js';
3
+ /**
4
+ * Creates the Sharp bridge's `transformUpload`. When core calls it, it plans the upload tasks (the
5
+ * main file, optionally cropped, and every configured image size), runs each one through the
6
+ * injected `transform` callback exactly once, and reads the size of each result. Reads the
7
+ * Sharp-owned config from `sharpTransformer({ collections })` at factory-construction time — not
8
+ * from the sanitized collection, which only gets the narrowed projection `init()` writes back.
9
+ */
10
+ export declare function createTransformUpload({ collections, sharpDependency, }: {
11
+ collections: Partial<Record<string, SharpCollectionConfig>>;
12
+ sharpDependency: SharpDependency;
13
+ }): NonNullable<UploadTransformerInternal['transformUpload']>;
14
+ //# sourceMappingURL=createTransformUpload.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createTransformUpload.d.ts","sourceRoot":"","sources":["../src/createTransformUpload.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAwB,yBAAyB,EAAE,MAAM,kBAAkB,CAAA;AAEvF,OAAO,KAAK,EAAE,qBAAqB,EAAE,eAAe,EAA0B,MAAM,YAAY,CAAA;AAsBhG;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,EACpC,WAAW,EACX,eAAe,GAChB,EAAE;IACD,WAAW,EAAE,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,qBAAqB,CAAC,CAAC,CAAA;IAC3D,eAAe,EAAE,eAAe,CAAA;CACjC,GAAG,WAAW,CAAC,yBAAyB,CAAC,iBAAiB,CAAC,CAAC,CAqF5D"}
@@ -1,4 +1,3 @@
1
- import { isNumber } from 'payload/shared';
2
1
  import { canResizeImage } from './canResizeImage.js';
3
2
  import { createSharpFromFile } from './createSharpFromFile.js';
4
3
  import { getImageResizeAction } from './getImageResizeAction.js';
@@ -20,16 +19,15 @@ import { sanitizeResizeConfig } from './sanitizeResizeConfig.js';
20
19
  }
21
20
  }
22
21
  /**
23
- * Computes the legacy upload tasks (the main file, optionally cropped, and every
24
- * configured legacy image size) and hands each to the injected `transform` callback
25
- * exactly once. Reads the Sharp-owned config from `sharpTransformer({ collections })`
26
- * at factory-construction time — not from the sanitized collection, which only gets
27
- * the narrowed projection `init()` writes back.
28
- */ export function createPrepareLegacyUpload({ collections, sharpDependency }) {
29
- return async ({ collectionSlug, file, req, transform, uploadEdits })=>{
22
+ * Creates the Sharp bridge's `transformUpload`. When core calls it, it plans the upload tasks (the
23
+ * main file, optionally cropped, and every configured image size), runs each one through the
24
+ * injected `transform` callback exactly once, and reads the size of each result. Reads the
25
+ * Sharp-owned config from `sharpTransformer({ collections })` at factory-construction time — not
26
+ * from the sanitized collection, which only gets the narrowed projection `init()` writes back.
27
+ */ export function createTransformUpload({ collections, sharpDependency }) {
28
+ return async function transformUpload({ collectionSlug, cropSize, file, req, transform }) {
30
29
  const collectionUpload = collections[collectionSlug] ?? {};
31
30
  const fileSupportsResize = canResizeImage(file.type);
32
- const cropData = uploadEdits && typeof uploadEdits === 'object' && 'crop' in uploadEdits ? uploadEdits.crop : undefined;
33
31
  let originalDimensions;
34
32
  if (fileSupportsResize) {
35
33
  const originalMeta = await tryProbe(file, sharpDependency);
@@ -42,18 +40,14 @@ import { sanitizeResizeConfig } from './sanitizeResizeConfig.js';
42
40
  }
43
41
  // Unreadable dimensions can't be cropped/resized — treat as non-resizable rather than failing the upload.
44
42
  const canProcessAsImage = fileSupportsResize && originalDimensions !== undefined;
45
- const crop = cropData && originalDimensions ? {
46
- cropData,
47
- heightInPixels: uploadEdits.heightInPixels,
48
- originalDimensions,
49
- widthInPixels: uploadEdits.widthInPixels
50
- } : undefined;
43
+ // `transformFile` reads the crop from `doc._transforms`. It needs the original's size for it.
51
44
  const mainResultFile = await transform({
52
45
  fieldPath: 'filename',
53
46
  options: {
54
47
  collectionUpload,
55
- crop,
56
- kind: 'main'
48
+ cropSize,
49
+ kind: 'main',
50
+ originalDimensions
57
51
  }
58
52
  });
59
53
  const mainResult = await describeResult({
@@ -70,16 +64,13 @@ import { sanitizeResizeConfig } from './sanitizeResizeConfig.js';
70
64
  const focalPointEnabled = effectiveFocalPoint !== false;
71
65
  const variants = collectionUpload.variants;
72
66
  if (canProcessAsImage && Array.isArray(variants) && originalDimensions) {
73
- const focalPoint = focalPointEnabled && uploadEdits?.focalPoint ? {
74
- x: isNumber(uploadEdits.focalPoint.x) ? Math.round(uploadEdits.focalPoint.x) : 50,
75
- y: isNumber(uploadEdits.focalPoint.y) ? Math.round(uploadEdits.focalPoint.y) : 50
76
- } : undefined;
77
67
  const sizeResults = await mapWithBoundedConcurrency(variants, async (rawConfig)=>{
78
68
  const imageResizeConfig = sanitizeResizeConfig(rawConfig);
79
69
  const fieldPath = `variants.${imageResizeConfig.name}`;
80
70
  const resizeAction = getImageResizeAction({
81
71
  dimensions: originalDimensions,
82
- hasFocalPoint: Boolean(focalPoint),
72
+ // Whether a size may use a focal point. `transformFile` uses one only when it is saved.
73
+ hasFocalPoint: focalPointEnabled,
83
74
  imageResizeConfig
84
75
  });
85
76
  if (resizeAction === 'omit') {
@@ -90,8 +81,8 @@ import { sanitizeResizeConfig } from './sanitizeResizeConfig.js';
90
81
  const sizeResultFile = await transform({
91
82
  fieldPath,
92
83
  options: {
84
+ canUseFocalPoint: resizeAction === 'resizeWithFocalPoint',
93
85
  collectionUpload,
94
- focalPoint: resizeAction === 'resizeWithFocalPoint' ? focalPoint : undefined,
95
86
  imageResizeConfig,
96
87
  kind: 'size',
97
88
  originalDimensions
@@ -136,4 +127,4 @@ async function describeResult({ fieldPath, fileSupportsResize, resultFile, sharp
136
127
  };
137
128
  }
138
129
 
139
- //# sourceMappingURL=prepareLegacyUpload.js.map
130
+ //# sourceMappingURL=createTransformUpload.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/createTransformUpload.ts"],"sourcesContent":["import type { ProbedImageSize } from 'payload'\nimport type { UploadTransformation, UploadTransformerInternal } from 'payload/internal'\n\nimport type { SharpCollectionConfig, SharpDependency, SharpUploadTaskOptions } from './types.js'\n\nimport { canResizeImage } from './canResizeImage.js'\nimport { createSharpFromFile } from './createSharpFromFile.js'\nimport { getImageResizeAction } from './getImageResizeAction.js'\nimport { mapWithBoundedConcurrency } from './mapWithBoundedConcurrency.js'\nimport { sanitizeResizeConfig } from './sanitizeResizeConfig.js'\n\n/**\n * Sharp throws on truncated/header-only files. Returns `undefined` instead —\n * matching core's dependency-free probe — since unreadable dimensions shouldn't fail the upload.\n */\nasync function tryProbe(file: File, sharpDependency: SharpDependency) {\n try {\n const sharpFile = await createSharpFromFile({ file, sharpDependency })\n const metadata = await sharpFile.metadata()\n return metadata.width && metadata.height ? metadata : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Creates the Sharp bridge's `transformUpload`. When core calls it, it plans the upload tasks (the\n * main file, optionally cropped, and every configured image size), runs each one through the\n * injected `transform` callback exactly once, and reads the size of each result. Reads the\n * Sharp-owned config from `sharpTransformer({ collections })` at factory-construction time — not\n * from the sanitized collection, which only gets the narrowed projection `init()` writes back.\n */\nexport function createTransformUpload({\n collections,\n sharpDependency,\n}: {\n collections: Partial<Record<string, SharpCollectionConfig>>\n sharpDependency: SharpDependency\n}): NonNullable<UploadTransformerInternal['transformUpload']> {\n return async function transformUpload({ collectionSlug, cropSize, file, req, transform }) {\n const collectionUpload = collections[collectionSlug] ?? {}\n\n const fileSupportsResize = canResizeImage(file.type)\n\n let originalDimensions: ProbedImageSize | undefined\n\n if (fileSupportsResize) {\n const originalMeta = await tryProbe(file, sharpDependency)\n if (originalMeta) {\n originalDimensions = { height: originalMeta.height, width: originalMeta.width }\n }\n }\n\n // Unreadable dimensions can't be cropped/resized — treat as non-resizable rather than failing the upload.\n const canProcessAsImage = fileSupportsResize && originalDimensions !== undefined\n\n // `transformFile` reads the crop from `doc._transforms`. It needs the original's size for it.\n const mainResultFile = await transform({\n fieldPath: 'filename',\n options: {\n collectionUpload,\n cropSize,\n kind: 'main',\n originalDimensions,\n } satisfies SharpUploadTaskOptions,\n })\n\n const mainResult = await describeResult({\n fieldPath: 'filename',\n fileSupportsResize: canProcessAsImage,\n resultFile: mainResultFile,\n sharpDependency,\n })\n\n const results: UploadTransformation[] = [mainResult]\n\n // Same precedence `init()` applies: Sharp's setting, else the collection's own `focalPoint`.\n const effectiveFocalPoint =\n collectionUpload.focalPoint ??\n req.payload.collections[collectionSlug]?.config.upload?.focalPoint\n const focalPointEnabled = effectiveFocalPoint !== false\n const variants = collectionUpload.variants\n\n if (canProcessAsImage && Array.isArray(variants) && originalDimensions) {\n const sizeResults = await mapWithBoundedConcurrency(variants, async (rawConfig) => {\n const imageResizeConfig = sanitizeResizeConfig(rawConfig)\n const fieldPath = `variants.${imageResizeConfig.name}` as const\n\n const resizeAction = getImageResizeAction({\n dimensions: originalDimensions,\n // Whether a size may use a focal point. `transformFile` uses one only when it is saved.\n hasFocalPoint: focalPointEnabled,\n imageResizeConfig,\n })\n\n if (resizeAction === 'omit') {\n return { fieldPath } satisfies UploadTransformation\n }\n\n const sizeResultFile = await transform({\n fieldPath,\n options: {\n canUseFocalPoint: resizeAction === 'resizeWithFocalPoint',\n collectionUpload,\n imageResizeConfig,\n kind: 'size',\n originalDimensions,\n } satisfies SharpUploadTaskOptions,\n })\n\n return describeResult({\n fieldPath,\n fileSupportsResize: true,\n resultFile: sizeResultFile,\n sharpDependency,\n })\n })\n\n results.push(...sizeResults)\n }\n\n return results\n }\n}\n\nasync function describeResult({\n fieldPath,\n fileSupportsResize,\n resultFile,\n sharpDependency,\n}: {\n fieldPath: UploadTransformation['fieldPath']\n fileSupportsResize: boolean\n resultFile: File\n sharpDependency: SharpDependency\n}): Promise<UploadTransformation> {\n if (!fileSupportsResize) {\n return { fieldPath, file: resultFile, mimeType: resultFile.type }\n }\n\n const meta = await tryProbe(resultFile, sharpDependency)\n\n if (!meta) {\n return { fieldPath, file: resultFile, mimeType: resultFile.type }\n }\n\n // `tryProbe` never sets `animated: true`, so `meta.height` is already the\n // single-frame height — do not divide by page count here.\n return {\n fieldPath,\n file: resultFile,\n height: meta.height,\n mimeType: resultFile.type,\n width: meta.width,\n }\n}\n"],"names":["canResizeImage","createSharpFromFile","getImageResizeAction","mapWithBoundedConcurrency","sanitizeResizeConfig","tryProbe","file","sharpDependency","sharpFile","metadata","width","height","undefined","createTransformUpload","collections","transformUpload","collectionSlug","cropSize","req","transform","collectionUpload","fileSupportsResize","type","originalDimensions","originalMeta","canProcessAsImage","mainResultFile","fieldPath","options","kind","mainResult","describeResult","resultFile","results","effectiveFocalPoint","focalPoint","payload","config","upload","focalPointEnabled","variants","Array","isArray","sizeResults","rawConfig","imageResizeConfig","name","resizeAction","dimensions","hasFocalPoint","sizeResultFile","canUseFocalPoint","push","mimeType","meta"],"mappings":"AAKA,SAASA,cAAc,QAAQ,sBAAqB;AACpD,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,oBAAoB,QAAQ,4BAA2B;AAChE,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,oBAAoB,QAAQ,4BAA2B;AAEhE;;;CAGC,GACD,eAAeC,SAASC,IAAU,EAAEC,eAAgC;IAClE,IAAI;QACF,MAAMC,YAAY,MAAMP,oBAAoB;YAAEK;YAAMC;QAAgB;QACpE,MAAME,WAAW,MAAMD,UAAUC,QAAQ;QACzC,OAAOA,SAASC,KAAK,IAAID,SAASE,MAAM,GAAGF,WAAWG;IACxD,EAAE,OAAM;QACN,OAAOA;IACT;AACF;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,sBAAsB,EACpCC,WAAW,EACXP,eAAe,EAIhB;IACC,OAAO,eAAeQ,gBAAgB,EAAEC,cAAc,EAAEC,QAAQ,EAAEX,IAAI,EAAEY,GAAG,EAAEC,SAAS,EAAE;QACtF,MAAMC,mBAAmBN,WAAW,CAACE,e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;wBACAyB;wBACAhB,MAAM;wBACNN;oBACF;gBACF;gBAEA,OAAOQ,eAAe;oBACpBJ;oBACAN,oBAAoB;oBACpBW,YAAYkB;oBACZ3C;gBACF;YACF;YAEA0B,QAAQmB,IAAI,IAAIT;QAClB;QAEA,OAAOV;IACT;AACF;AAEA,eAAeF,eAAe,EAC5BJ,SAAS,EACTN,kBAAkB,EAClBW,UAAU,EACVzB,eAAe,EAMhB;IACC,IAAI,CAACc,oBAAoB;QACvB,OAAO;YAAEM;YAAWrB,MAAM0B;YAAYqB,UAAUrB,WAAWV,IAAI;QAAC;IAClE;IAEA,MAAMgC,OAAO,MAAMjD,SAAS2B,YAAYzB;IAExC,IAAI,CAAC+C,MAAM;QACT,OAAO;YAAE3B;YAAWrB,MAAM0B;YAAYqB,UAAUrB,WAAWV,IAAI;QAAC;IAClE;IAEA,0EAA0E;IAC1E,0DAA0D;IAC1D,OAAO;QACLK;QACArB,MAAM0B;QACNrB,QAAQ2C,KAAK3C,MAAM;QACnB0C,UAAUrB,WAAWV,IAAI;QACzBZ,OAAO4C,KAAK5C,KAAK;IACnB;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it, vi } from 'vitest';
2
- import { createPrepareLegacyUpload } from './prepareLegacyUpload.js';
2
+ import { createTransformUpload } from './createTransformUpload.js';
3
3
  const sharpDependency = ()=>({
4
4
  metadata: async ()=>({
5
5
  height: 1000,
@@ -19,13 +19,13 @@ const makeReq = ({ focalPoint })=>({
19
19
  }
20
20
  }
21
21
  });
22
- const runPrepareUpload = async ({ collectionFocalPoint, sharpConfig })=>{
22
+ const runTransformUpload = async ({ collectionFocalPoint, sharpConfig })=>{
23
23
  const transform = vi.fn(async (_task)=>new File([
24
24
  'x'
25
25
  ], 'image.png', {
26
26
  type: 'image/png'
27
27
  }));
28
- await createPrepareLegacyUpload({
28
+ await createTransformUpload({
29
29
  collections: {
30
30
  media: sharpConfig
31
31
  },
@@ -40,16 +40,10 @@ const runPrepareUpload = async ({ collectionFocalPoint, sharpConfig })=>{
40
40
  req: makeReq({
41
41
  focalPoint: collectionFocalPoint
42
42
  }),
43
- transform,
44
- uploadEdits: {
45
- focalPoint: {
46
- x: 10,
47
- y: 90
48
- }
49
- }
43
+ transform
50
44
  });
51
45
  const sizeTask = transform.mock.calls.map(([task])=>task.options).find((options)=>options.kind === 'size');
52
- return sizeTask?.kind === 'size' ? sizeTask.focalPoint : undefined;
46
+ return sizeTask?.kind === 'size' ? sizeTask.canUseFocalPoint : undefined;
53
47
  };
54
48
  const variants = [
55
49
  {
@@ -58,31 +52,25 @@ const variants = [
58
52
  width: 400
59
53
  }
60
54
  ];
61
- describe('createPrepareLegacyUpload', ()=>{
55
+ describe('createTransformUpload', ()=>{
62
56
  it.each([
63
57
  {
64
58
  collectionFocalPoint: false,
65
- expected: undefined,
59
+ expected: false,
66
60
  sharpFocalPoint: undefined
67
61
  },
68
62
  {
69
63
  collectionFocalPoint: false,
70
- expected: {
71
- x: 10,
72
- y: 90
73
- },
64
+ expected: true,
74
65
  sharpFocalPoint: true
75
66
  },
76
67
  {
77
68
  collectionFocalPoint: undefined,
78
- expected: {
79
- x: 10,
80
- y: 90
81
- },
69
+ expected: true,
82
70
  sharpFocalPoint: undefined
83
71
  }
84
- ])('should resolve the size focal point from Sharp ($sharpFocalPoint) over the collection ($collectionFocalPoint)', async ({ collectionFocalPoint, expected, sharpFocalPoint })=>{
85
- expect(await runPrepareUpload({
72
+ ])('should let sizes use a saved focal point when Sharp ($sharpFocalPoint) or else the collection ($collectionFocalPoint) enables it', async ({ collectionFocalPoint, expected, sharpFocalPoint })=>{
73
+ expect(await runTransformUpload({
86
74
  collectionFocalPoint,
87
75
  sharpConfig: {
88
76
  focalPoint: sharpFocalPoint,
@@ -92,4 +80,4 @@ describe('createPrepareLegacyUpload', ()=>{
92
80
  });
93
81
  });
94
82
 
95
- //# sourceMappingURL=prepareLegacyUpload.spec.js.map
83
+ //# sourceMappingURL=createTransformUpload.spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/createTransformUpload.spec.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport type { UploadTransformTask } from 'payload/internal'\n\nimport { describe, expect, it, vi } from 'vitest'\n\nimport type { SharpCollectionConfig, SharpDependency, SharpUploadTaskOptions } from './types.js'\n\nimport { createTransformUpload } from './createTransformUpload.js'\n\nconst sharpDependency = (() => ({\n metadata: async () => ({ height: 1000, width: 1000 }),\n})) as unknown as SharpDependency\n\nconst makeReq = ({ focalPoint }: { focalPoint?: boolean }): PayloadRequest =>\n ({\n payload: { collections: { media: { config: { upload: { focalPoint } } } } },\n }) as unknown as PayloadRequest\n\nconst runTransformUpload = async ({\n collectionFocalPoint,\n sharpConfig,\n}: {\n collectionFocalPoint?: boolean\n sharpConfig: SharpCollectionConfig\n}) => {\n const transform = vi.fn(\n async (_task: UploadTransformTask) => new File(['x'], 'image.png', { type: 'image/png' }),\n )\n\n await createTransformUpload({ collections: { media: sharpConfig }, sharpDependency })({\n collectionSlug: 'media',\n file: new File(['x'], 'image.png', { type: 'image/png' }),\n req: makeReq({ focalPoint: collectionFocalPoint }),\n transform,\n })\n\n const sizeTask = transform.mock.calls\n .map(([task]) => task.options as SharpUploadTaskOptions)\n .find((options) => options.kind === 'size')\n\n return sizeTask?.kind === 'size' ? sizeTask.canUseFocalPoint : undefined\n}\n\nconst variants = [{ name: 'card', height: 200, width: 400 }]\n\ndescribe('createTransformUpload', () => {\n it.each([\n { collectionFocalPoint: false, expected: false, sharpFocalPoint: undefined },\n { collectionFocalPoint: false, expected: true, sharpFocalPoint: true },\n { collectionFocalPoint: undefined, expected: true, sharpFocalPoint: undefined },\n ])(\n 'should let sizes use a saved focal point when Sharp ($sharpFocalPoint) or else the collection ($collectionFocalPoint) enables it',\n async ({ collectionFocalPoint, expected, sharpFocalPoint }) => {\n expect(\n await runTransformUpload({\n collectionFocalPoint,\n sharpConfig: { focalPoint: sharpFocalPoint, variants },\n }),\n ).toEqual(expected)\n },\n )\n})\n"],"names":["describe","expect","it","vi","createTransformUpload","sharpDependency","metadata","height","width","makeReq","focalPoint","payload","collections","media","config","upload","runTransformUpload","collectionFocalPoint","sharpConfig","transform","fn","_task","File","type","collectionSlug","file","req","sizeTask","mock","calls","map","task","options","find","kind","canUseFocalPoint","undefined","variants","name","each","expected","sharpFocalPoint","toEqual"],"mappings":"AAGA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,EAAEC,EAAE,QAAQ,SAAQ;AAIjD,SAASC,qBAAqB,QAAQ,6BAA4B;AAElE,MAAMC,kBAAmB,IAAO,CAAA;QAC9BC,UAAU,UAAa,CAAA;gBAAEC,QAAQ;gBAAMC,OAAO;YAAK,CAAA;IACrD,CAAA;AAEA,MAAMC,UAAU,CAAC,EAAEC,UAAU,EAA4B,GACtD,CAAA;QACCC,SAAS;YAAEC,aAAa;gBAAEC,OAAO;oBAAEC,QAAQ;wBAAEC,QAAQ;4BAAEL;wBAAW;oBAAE;gBAAE;YAAE;QAAE;IAC5E,CAAA;AAEF,MAAMM,qBAAqB,OAAO,EAChCC,oBAAoB,EACpBC,WAAW,EAIZ;IACC,MAAMC,YAAYhB,GAAGiB,EAAE,CACrB,OAAOC,QAA+B,IAAIC,KAAK;YAAC;SAAI,EAAE,aAAa;YAAEC,MAAM;QAAY;IAGzF,MAAMnB,sBAAsB;QAAEQ,aAAa;YAAEC,OAAOK;QAAY;QAAGb;IAAgB,GAAG;QACpFmB,gBAAgB;QAChBC,MAAM,IAAIH,KAAK;YAAC;SAAI,EAAE,aAAa;YAAEC,MAAM;QAAY;QACvDG,KAAKjB,QAAQ;YAAEC,YAAYO;QAAqB;QAChDE;IACF;IAEA,MAAMQ,WAAWR,UAAUS,IAAI,CAACC,KAAK,CAClCC,GAAG,CAAC,CAAC,CAACC,KAAK,GAAKA,KAAKC,OAAO,EAC5BC,IAAI,CAAC,CAACD,UAAYA,QAAQE,IAAI,KAAK;IAEtC,OAAOP,UAAUO,SAAS,SAASP,SAASQ,gBAAgB,GAAGC;AACjE;AAEA,MAAMC,WAAW;IAAC;QAAEC,MAAM;QAAQ/B,QAAQ;QAAKC,OAAO;IAAI;CAAE;AAE5DR,SAAS,yBAAyB;IAChCE,GAAGqC,IAAI,CAAC;QACN;YAAEtB,sBAAsB;YAAOuB,UAAU;YAAOC,iBAAiBL;QAAU;QAC3E;YAAEnB,sBAAsB;YAAOuB,UAAU;YAAMC,iBAAiB;QAAK;QACrE;YAAExB,sBAAsBmB;YAAWI,UAAU;YAAMC,iBAAiBL;QAAU;KAC/E,EACC,oIACA,OAAO,EAAEnB,oBAAoB,EAAEuB,QAAQ,EAAEC,eAAe,EAAE;QACxDxC,OACE,MAAMe,mBAAmB;YACvBC;YACAC,aAAa;gBAAER,YAAY+B;gBAAiBJ;YAAS;QACvD,IACAK,OAAO,CAACF;IACZ;AAEJ"}
@@ -0,0 +1,14 @@
1
+ import type { Crop, Document, FocalPoint } from 'payload';
2
+ /** The crop saved in `doc._transforms`, or `undefined` when there is none. */
3
+ export declare function getSavedCrop({ doc }: {
4
+ doc?: Document;
5
+ }): Omit<Crop, 'unit'> | undefined;
6
+ /**
7
+ * The focal point saved in `doc._transforms`, rounded to whole percent as `focalX`/`focalY` are.
8
+ * A document saved before `_transforms` existed has only `focalX`/`focalY`. Payload does not save
9
+ * a focal point at the center, so `focalX`/`focalY` at the center also mean "no focal point".
10
+ */
11
+ export declare function getSavedFocalPoint({ doc }: {
12
+ doc?: Document;
13
+ }): FocalPoint | undefined;
14
+ //# sourceMappingURL=readSavedTransforms.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"readSavedTransforms.d.ts","sourceRoot":"","sources":["../src/readSavedTransforms.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAIzD,8EAA8E;AAC9E,wBAAgB,YAAY,CAAC,EAAE,GAAG,EAAE,EAAE;IAAE,GAAG,CAAC,EAAE,QAAQ,CAAA;CAAE,GAAG,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,GAAG,SAAS,CAYxF;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,EAAE,GAAG,EAAE,EAAE;IAAE,GAAG,CAAC,EAAE,QAAQ,CAAA;CAAE,GAAG,UAAU,GAAG,SAAS,CAYtF"}
@@ -0,0 +1,42 @@
1
+ import { isNumber } from 'payload/shared';
2
+ /** The crop saved in `doc._transforms`, or `undefined` when there is none. */ export function getSavedCrop({ doc }) {
3
+ const crop = getTransforms({
4
+ doc
5
+ })?.crop;
6
+ if (crop && isNumber(crop.height) && isNumber(crop.width) && isNumber(crop.x) && isNumber(crop.y)) {
7
+ return {
8
+ height: crop.height,
9
+ width: crop.width,
10
+ x: crop.x,
11
+ y: crop.y
12
+ };
13
+ }
14
+ }
15
+ /**
16
+ * The focal point saved in `doc._transforms`, rounded to whole percent as `focalX`/`focalY` are.
17
+ * A document saved before `_transforms` existed has only `focalX`/`focalY`. Payload does not save
18
+ * a focal point at the center, so `focalX`/`focalY` at the center also mean "no focal point".
19
+ */ export function getSavedFocalPoint({ doc }) {
20
+ const focalPoint = getTransforms({
21
+ doc
22
+ })?.focalPoint;
23
+ if (focalPoint && isNumber(focalPoint.x) && isNumber(focalPoint.y)) {
24
+ return {
25
+ x: Math.round(focalPoint.x),
26
+ y: Math.round(focalPoint.y)
27
+ };
28
+ }
29
+ if (isNumber(doc?.focalX) && isNumber(doc?.focalY)) {
30
+ const legacyFocalPoint = {
31
+ x: Math.round(doc.focalX),
32
+ y: Math.round(doc.focalY)
33
+ };
34
+ return legacyFocalPoint.x === 50 && legacyFocalPoint.y === 50 ? undefined : legacyFocalPoint;
35
+ }
36
+ }
37
+ function getTransforms({ doc }) {
38
+ const transforms = doc?._transforms;
39
+ return transforms && typeof transforms === 'object' && !Array.isArray(transforms) ? transforms : undefined;
40
+ }
41
+
42
+ //# sourceMappingURL=readSavedTransforms.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/readSavedTransforms.ts"],"sourcesContent":["import type { Crop, Document, FocalPoint } from 'payload'\n\nimport { isNumber } from 'payload/shared'\n\n/** The crop saved in `doc._transforms`, or `undefined` when there is none. */\nexport function getSavedCrop({ doc }: { doc?: Document }): Omit<Crop, 'unit'> | undefined {\n const crop = getTransforms({ doc })?.crop\n\n if (\n crop &&\n isNumber(crop.height) &&\n isNumber(crop.width) &&\n isNumber(crop.x) &&\n isNumber(crop.y)\n ) {\n return { height: crop.height, width: crop.width, x: crop.x, y: crop.y }\n }\n}\n\n/**\n * The focal point saved in `doc._transforms`, rounded to whole percent as `focalX`/`focalY` are.\n * A document saved before `_transforms` existed has only `focalX`/`focalY`. Payload does not save\n * a focal point at the center, so `focalX`/`focalY` at the center also mean \"no focal point\".\n */\nexport function getSavedFocalPoint({ doc }: { doc?: Document }): FocalPoint | undefined {\n const focalPoint = getTransforms({ doc })?.focalPoint\n\n if (focalPoint && isNumber(focalPoint.x) && isNumber(focalPoint.y)) {\n return { x: Math.round(focalPoint.x), y: Math.round(focalPoint.y) }\n }\n\n if (isNumber(doc?.focalX) && isNumber(doc?.focalY)) {\n const legacyFocalPoint = { x: Math.round(doc.focalX), y: Math.round(doc.focalY) }\n\n return legacyFocalPoint.x === 50 && legacyFocalPoint.y === 50 ? undefined : legacyFocalPoint\n }\n}\n\nfunction getTransforms({ doc }: { doc?: Document }):\n | {\n crop?: Partial<Record<keyof Omit<Crop, 'unit'>, unknown>>\n focalPoint?: { x?: unknown; y?: unknown }\n }\n | undefined {\n const transforms = doc?._transforms\n\n return transforms && typeof transforms === 'object' && !Array.isArray(transforms)\n ? transforms\n : undefined\n}\n"],"names":["isNumber","getSavedCrop","doc","crop","getTransforms","height","width","x","y","getSavedFocalPoint","focalPoint","Math","round","focalX","focalY","legacyFocalPoint","undefined","transforms","_transforms","Array","isArray"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,iBAAgB;AAEzC,4EAA4E,GAC5E,OAAO,SAASC,aAAa,EAAEC,GAAG,EAAsB;IACtD,MAAMC,OAAOC,cAAc;QAAEF;IAAI,IAAIC;IAErC,IACEA,QACAH,SAASG,KAAKE,MAAM,KACpBL,SAASG,KAAKG,KAAK,KACnBN,SAASG,KAAKI,CAAC,KACfP,SAASG,KAAKK,CAAC,GACf;QACA,OAAO;YAAEH,QAAQF,KAAKE,MAAM;YAAEC,OAAOH,KAAKG,KAAK;YAAEC,GAAGJ,KAAKI,CAAC;YAAEC,GAAGL,KAAKK,CAAC;QAAC;IACxE;AACF;AAEA;;;;CAIC,GACD,OAAO,SAASC,mBAAmB,EAAEP,GAAG,EAAsB;IAC5D,MAAMQ,aAAaN,cAAc;QAAEF;IAAI,IAAIQ;IAE3C,IAAIA,cAAcV,SAASU,WAAWH,CAAC,KAAKP,SAASU,WAAWF,CAAC,GAAG;QAClE,OAAO;YAAED,GAAGI,KAAKC,KAAK,CAACF,WAAWH,CAAC;YAAGC,GAAGG,KAAKC,KAAK,CAACF,WAAWF,CAAC;QAAE;IACpE;IAEA,IAAIR,SAASE,KAAKW,WAAWb,SAASE,KAAKY,SAAS;QAClD,MAAMC,mBAAmB;YAAER,GAAGI,KAAKC,KAAK,CAACV,IAAIW,MAAM;YAAGL,GAAGG,KAAKC,KAAK,CAACV,IAAIY,MAAM;QAAE;QAEhF,OAAOC,iBAAiBR,CAAC,KAAK,MAAMQ,iBAAiBP,CAAC,KAAK,KAAKQ,YAAYD;IAC9E;AACF;AAEA,SAASX,cAAc,EAAEF,GAAG,EAAsB;IAMhD,MAAMe,aAAaf,KAAKgB;IAExB,OAAOD,cAAc,OAAOA,eAAe,YAAY,CAACE,MAAMC,OAAO,CAACH,cAClEA,aACAD;AACN"}
@@ -1,9 +1,9 @@
1
1
  import { getUploadTransformerInternal, uploadTransformerInternal } from 'payload/internal';
2
2
  import bundledSharp from 'sharp';
3
+ import { createTransformUpload } from './createTransformUpload.js';
3
4
  import { createHandleRequest } from './handleRequest.js';
4
5
  import { initSharpCollections } from './initSharpCollections.js';
5
6
  import { parseDynamicResize } from './parseDynamicResize.js';
6
- import { createPrepareLegacyUpload } from './prepareLegacyUpload.js';
7
7
  import { createTransformFile } from './transformFile.js';
8
8
  const DEFAULT_MIME_TYPES = [
9
9
  'image/jpeg',
@@ -88,12 +88,12 @@ export function resolveSharpDynamicDefaults(overrides) {
88
88
  mimeTypes: DEFAULT_MIME_TYPES,
89
89
  [uploadTransformerInternal]: {
90
90
  handlesCollection,
91
- prepareUpload: createPrepareLegacyUpload({
91
+ transformUpload: createTransformUpload({
92
92
  collections,
93
93
  sharpDependency
94
94
  })
95
95
  },
96
- // `options` here is always what this transformer computed via `prepareUpload`'s
96
+ // `options` here is always what this transformer computed via `transformUpload`'s
97
97
  // `transform` callback; the public contract's `unknown` just reflects that core never inspects it.
98
98
  transformFile: createTransformFile({
99
99
  sharpDependency
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sharpTransformer.ts"],"sourcesContent":["import type { Config, TransformFileArgs, TransformFileResult, UploadTransformer } from 'payload'\nimport type { TransformerWithInternalBridge } from 'payload/internal'\n\nimport { getUploadTransformerInternal, uploadTransformerInternal } from 'payload/internal'\nimport bundledSharp from 'sharp'\n\nimport type { SharpDynamicDefaults, SharpDynamicOptions, SharpTransformerOptions } from './types.js'\n\nimport { createHandleRequest } from './handleRequest.js'\nimport { initSharpCollections } from './initSharpCollections.js'\nimport { parseDynamicResize } from './parseDynamicResize.js'\nimport { createPrepareLegacyUpload } from './prepareLegacyUpload.js'\nimport { createTransformFile } from './transformFile.js'\n\nconst DEFAULT_MIME_TYPES = [\n 'image/jpeg',\n 'image/png',\n 'image/gif',\n 'image/webp',\n 'image/tiff',\n 'image/avif',\n]\n\nexport function resolveSharpDynamicDefaults(\n overrides?: SharpDynamicDefaults,\n): Required<SharpDynamicDefaults> {\n return {\n fit: overrides?.fit ?? 'cover',\n maxHeight: overrides?.maxHeight ?? 4096,\n maxPixels: overrides?.maxPixels ?? 16_777_216,\n maxWidth: overrides?.maxWidth ?? 4096,\n position: overrides?.position ?? 'center',\n withoutEnlargement: overrides?.withoutEnlargement ?? false,\n }\n}\n\n/**\n * Normalizes the `dynamic` option: `false`/omitted disables request-time\n * resizing, `true` enables it with defaults for every upload collection.\n */\nfunction resolveSharpDynamicOptions(\n dynamic: SharpTransformerOptions['dynamic'],\n): false | SharpDynamicOptions {\n if (!dynamic) {\n return false\n }\n\n return dynamic === true ? {} : dynamic\n}\n\n/**\n * Payload's official Sharp-based file transformer: upload-time image processing,\n * plus opt-in (`dynamic`) request-time width/height/`withoutEnlargement` resizing.\n */\nexport function sharpTransformer(\n options: SharpTransformerOptions = {},\n): TransformerWithInternalBridge & UploadTransformer {\n const dynamicOptions = resolveSharpDynamicOptions(options.dynamic)\n const dynamicDefaults = resolveSharpDynamicDefaults(dynamicOptions || undefined)\n const sharpDependency = options.sharp ?? bundledSharp\n const collections = options.collections ?? {}\n const handlesCollection = ({ collectionSlug }: { collectionSlug: string }) =>\n Boolean(collections[collectionSlug])\n\n const transformer: TransformerWithInternalBridge & UploadTransformer = {\n slug: options.slug ?? 'sharp',\n canTransform: (args) => {\n // Upload-time eligibility is already decided by the MIME match that ran\n // before `canTransform`; only dynamic request routing needs the query.\n if (args.operation === 'upload') {\n return { canTransform: true, handledTransformKeys: ['crop', 'focalPoint'] }\n }\n\n // Sharp applies saved transforms at upload time, so it resizes only for the request phase.\n if (\n !dynamicOptions ||\n args.purpose === 'persisted-default' ||\n (dynamicOptions.collections && !dynamicOptions.collections.includes(args.collectionSlug))\n ) {\n return false\n }\n\n const result = parseDynamicResize({\n limits: dynamicDefaults,\n searchParams: args.req.searchParams ?? new URLSearchParams(),\n })\n\n return result.isRouted\n },\n handleRequest: createHandleRequest({ dynamicDefaults, sharpDependency }),\n init: (config) => {\n assertDynamicCollectionsExist({ config, dynamicOptions })\n assertCollectionsOwnedOnce({ collections, config, transformer })\n\n return initSharpCollections({ collections, config, transformerSlug: transformer.slug })\n },\n mimeTypes: DEFAULT_MIME_TYPES,\n [uploadTransformerInternal]: {\n handlesCollection,\n prepareUpload: createPrepareLegacyUpload({ collections, sharpDependency }),\n },\n // `options` here is always what this transformer computed via `prepareUpload`'s\n // `transform` callback; the public contract's `unknown` just reflects that core never inspects it.\n transformFile: createTransformFile({ sharpDependency }) as (\n args: TransformFileArgs,\n ) => Promise<TransformFileResult>,\n }\n\n return transformer\n}\n\n/**\n * Core drives each upload through a single Sharp instance, so a collection's upload settings\n * split across instances would silently lose all but one of them.\n */\nfunction assertCollectionsOwnedOnce({\n collections,\n config,\n transformer,\n}: {\n collections: NonNullable<SharpTransformerOptions['collections']>\n config: Config\n transformer: UploadTransformer\n}): void {\n for (const [collectionSlug, collectionConfig] of Object.entries(collections)) {\n if (!collectionConfig) {\n continue\n }\n\n const owners = (config.upload?.transformers ?? []).filter(\n (candidate) =>\n candidate === transformer ||\n getUploadTransformerInternal(candidate)?.handlesCollection?.({ collectionSlug }),\n )\n\n if (owners.length > 1) {\n throw new Error(\n `Invalid \\`sharpTransformer({ collections })\\` configuration: collection \"${collectionSlug}\" has upload settings on more than one Sharp transformer: ${owners.map((owner) => `\"${owner.slug}\"`).join(', ')}. Configure each collection on exactly one instance.`,\n )\n }\n }\n}\n\nfunction assertDynamicCollectionsExist({\n config,\n dynamicOptions,\n}: {\n config: Config\n dynamicOptions: false | SharpDynamicOptions\n}): void {\n if (!dynamicOptions || !dynamicOptions.collections) {\n return\n }\n\n const invalidSlugs = dynamicOptions.collections.filter(\n (slug) =>\n !config.collections?.some((collection) => collection.slug === slug && collection.upload),\n )\n\n if (invalidSlugs.length > 0) {\n throw new Error(\n `Invalid \\`sharpTransformer({ dynamic: { collections } })\\` configuration: not an upload-enabled collection: ${invalidSlugs.map((slug) => `\"${slug}\"`).join(', ')}.`,\n )\n }\n}\n"],"names":["getUploadTransformerInternal","uploadTransformerInternal","bundledSharp","createHandleRequest","initSharpCollections","parseDynamicResize","createPrepareLegacyUpload","createTransformFile","DEFAULT_MIME_TYPES","resolveSharpDynamicDefaults","overrides","fit","maxHeight","maxPixels","maxWidth","position","withoutEnlargement","resolveSharpDynamicOptions","dynamic","sharpTransformer","options","dynamicOptions","dynamicDefaults","undefined","sharpDependency","sharp","collections","handlesCollection","collectionSlug","Boolean","transformer","slug","canTransform","args","operation","handledTransformKeys","purpose","includes","result","limits","searchParams","req","URLSearchParams","isRouted","handleRequest","init","config","assertDynamicCollectionsExist","assertCollectionsOwnedOnce","transformerSlug","mimeTypes","prepareUpload","transformFile","collectionConfig","Object","entries","owners","upload","transformers","filter","candidate","length","Error","map","owner","join","invalidSlugs","some","collection"],"mappings":"AAGA,SAASA,4BAA4B,EAAEC,yBAAyB,QAAQ,mBAAkB;AAC1F,OAAOC,kBAAkB,QAAO;AAIhC,SAASC,mBAAmB,QAAQ,qBAAoB;AACxD,SAASC,oBAAoB,QAAQ,4BAA2B;AAChE,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,yBAAyB,QAAQ,2BAA0B;AACpE,SAASC,mBAAmB,QAAQ,qBAAoB;AAExD,MAAMC,qBAAqB;IACzB;IACA;IACA;IACA;IACA;IACA;CACD;AAED,OAAO,SAASC,4BACdC,SAAgC;IAEhC,OAAO;QACLC,KAAKD,WAAWC,OAAO;QACvBC,WAAWF,WAAWE,aAAa;QACnCC,WAAWH,WAAWG,aAAa;QACnCC,UAAUJ,WAAWI,YAAY;QACjCC,UAAUL,WAAWK,YAAY;QACjCC,oBAAoBN,WAAWM,sBAAsB;IACvD;AACF;AAEA;;;CAGC,GACD,SAASC,2BACPC,OAA2C;IAE3C,IAAI,CAACA,SAAS;QACZ,OAAO;IACT;IAEA,OAAOA,YAAY,OAAO,CAAC,IAAIA;AACjC;AAEA;;;CAGC,GACD,OAAO,SAASC,iBACdC,UAAmC,CAAC,CAAC;IAErC,MAAMC,iBAAiBJ,2BAA2BG,QAAQF,OAAO;IACjE,MAAMI,kBAAkBb,4BAA4BY,kBAAkBE;IACtE,MAAMC,kBAAkBJ,QAAQK,KAAK,IAAIv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C,OAAOC,OAAO,CAAC7B,aAAc;QAC5E,IAAI,CAAC2B,kBAAkB;YACrB;QACF;QAEA,MAAMG,SAAS,AAACV,CAAAA,OAAOW,MAAM,EAAEC,gBAAgB,EAAE,AAAD,EAAGC,MAAM,CACvD,CAACC,YACCA,cAAc9B,eACd9B,6BAA6B4D,YAAYjC,oBAAoB;gBAAEC;YAAe;QAGlF,IAAI4B,OAAOK,MAAM,GAAG,GAAG;YACrB,MAAM,IAAIC,MACR,CAAC,yEAAyE,EAAElC,eAAe,0DAA0D,EAAE4B,OAAOO,GAAG,CAAC,CAACC,QAAU,CAAC,CAAC,EAAEA,MAAMjC,IAAI,CAAC,CAAC,CAAC,EAAEkC,IAAI,CAAC,MAAM,oDAAoD,CAAC;QAEpQ;IACF;AACF;AAEA,SAASlB,8BAA8B,EACrCD,MAAM,EACNzB,cAAc,EAIf;IACC,IAAI,CAACA,kBAAkB,CAACA,eAAeK,WAAW,EAAE;QAClD;IACF;IAEA,MAAMwC,eAAe7C,eAAeK,WAAW,CAACiC,MAAM,CACpD,CAAC5B,OACC,CAACe,OAAOpB,WAAW,EAAEyC,KAAK,CAACC,aAAeA,WAAWrC,IAAI,KAAKA,QAAQqC,WAAWX,MAAM;IAG3F,IAAIS,aAAaL,MAAM,GAAG,GAAG;QAC3B,MAAM,IAAIC,MACR,CAAC,4GAA4G,EAAEI,aAAaH,GAAG,CAAC,CAAChC,OAAS,CAAC,CAAC,EAAEA,KAAK,CAAC,CAAC,EAAEkC,IAAI,CAAC,MAAM,CAAC,CAAC;IAExK;AACF"}
1
+ {"version":3,"sources":["../src/sharpTransformer.ts"],"sourcesContent":["import type { Config, TransformFileArgs, TransformFileResult, UploadTransformer } from 'payload'\nimport type { TransformerWithInternalBridge } from 'payload/internal'\n\nimport { getUploadTransformerInternal, uploadTransformerInternal } from 'payload/internal'\nimport bundledSharp from 'sharp'\n\nimport type { SharpDynamicDefaults, SharpDynamicOptions, SharpTransformerOptions } from './types.js'\n\nimport { createTransformUpload } from './createTransformUpload.js'\nimport { createHandleRequest } from './handleRequest.js'\nimport { initSharpCollections } from './initSharpCollections.js'\nimport { parseDynamicResize } from './parseDynamicResize.js'\nimport { createTransformFile } from './transformFile.js'\n\nconst DEFAULT_MIME_TYPES = [\n 'image/jpeg',\n 'image/png',\n 'image/gif',\n 'image/webp',\n 'image/tiff',\n 'image/avif',\n]\n\nexport function resolveSharpDynamicDefaults(\n overrides?: SharpDynamicDefaults,\n): Required<SharpDynamicDefaults> {\n return {\n fit: overrides?.fit ?? 'cover',\n maxHeight: overrides?.maxHeight ?? 4096,\n maxPixels: overrides?.maxPixels ?? 16_777_216,\n maxWidth: overrides?.maxWidth ?? 4096,\n position: overrides?.position ?? 'center',\n withoutEnlargement: overrides?.withoutEnlargement ?? false,\n }\n}\n\n/**\n * Normalizes the `dynamic` option: `false`/omitted disables request-time\n * resizing, `true` enables it with defaults for every upload collection.\n */\nfunction resolveSharpDynamicOptions(\n dynamic: SharpTransformerOptions['dynamic'],\n): false | SharpDynamicOptions {\n if (!dynamic) {\n return false\n }\n\n return dynamic === true ? {} : dynamic\n}\n\n/**\n * Payload's official Sharp-based file transformer: upload-time image processing,\n * plus opt-in (`dynamic`) request-time width/height/`withoutEnlargement` resizing.\n */\nexport function sharpTransformer(\n options: SharpTransformerOptions = {},\n): TransformerWithInternalBridge & UploadTransformer {\n const dynamicOptions = resolveSharpDynamicOptions(options.dynamic)\n const dynamicDefaults = resolveSharpDynamicDefaults(dynamicOptions || undefined)\n const sharpDependency = options.sharp ?? bundledSharp\n const collections = options.collections ?? {}\n const handlesCollection = ({ collectionSlug }: { collectionSlug: string }) =>\n Boolean(collections[collectionSlug])\n\n const transformer: TransformerWithInternalBridge & UploadTransformer = {\n slug: options.slug ?? 'sharp',\n canTransform: (args) => {\n // Upload-time eligibility is already decided by the MIME match that ran\n // before `canTransform`; only dynamic request routing needs the query.\n if (args.operation === 'upload') {\n return { canTransform: true, handledTransformKeys: ['crop', 'focalPoint'] }\n }\n\n // Sharp applies saved transforms at upload time, so it resizes only for the request phase.\n if (\n !dynamicOptions ||\n args.purpose === 'persisted-default' ||\n (dynamicOptions.collections && !dynamicOptions.collections.includes(args.collectionSlug))\n ) {\n return false\n }\n\n const result = parseDynamicResize({\n limits: dynamicDefaults,\n searchParams: args.req.searchParams ?? new URLSearchParams(),\n })\n\n return result.isRouted\n },\n handleRequest: createHandleRequest({ dynamicDefaults, sharpDependency }),\n init: (config) => {\n assertDynamicCollectionsExist({ config, dynamicOptions })\n assertCollectionsOwnedOnce({ collections, config, transformer })\n\n return initSharpCollections({ collections, config, transformerSlug: transformer.slug })\n },\n mimeTypes: DEFAULT_MIME_TYPES,\n [uploadTransformerInternal]: {\n handlesCollection,\n transformUpload: createTransformUpload({ collections, sharpDependency }),\n },\n // `options` here is always what this transformer computed via `transformUpload`'s\n // `transform` callback; the public contract's `unknown` just reflects that core never inspects it.\n transformFile: createTransformFile({ sharpDependency }) as (\n args: TransformFileArgs,\n ) => Promise<TransformFileResult>,\n }\n\n return transformer\n}\n\n/**\n * Core drives each upload through a single Sharp instance, so a collection's upload settings\n * split across instances would silently lose all but one of them.\n */\nfunction assertCollectionsOwnedOnce({\n collections,\n config,\n transformer,\n}: {\n collections: NonNullable<SharpTransformerOptions['collections']>\n config: Config\n transformer: UploadTransformer\n}): void {\n for (const [collectionSlug, collectionConfig] of Object.entries(collections)) {\n if (!collectionConfig) {\n continue\n }\n\n const owners = (config.upload?.transformers ?? []).filter(\n (candidate) =>\n candidate === transformer ||\n getUploadTransformerInternal(candidate)?.handlesCollection?.({ collectionSlug }),\n )\n\n if (owners.length > 1) {\n throw new Error(\n `Invalid \\`sharpTransformer({ collections })\\` configuration: collection \"${collectionSlug}\" has upload settings on more than one Sharp transformer: ${owners.map((owner) => `\"${owner.slug}\"`).join(', ')}. Configure each collection on exactly one instance.`,\n )\n }\n }\n}\n\nfunction assertDynamicCollectionsExist({\n config,\n dynamicOptions,\n}: {\n config: Config\n dynamicOptions: false | SharpDynamicOptions\n}): void {\n if (!dynamicOptions || !dynamicOptions.collections) {\n return\n }\n\n const invalidSlugs = dynamicOptions.collections.filter(\n (slug) =>\n !config.collections?.some((collection) => collection.slug === slug && collection.upload),\n )\n\n if (invalidSlugs.length > 0) {\n throw new Error(\n `Invalid \\`sharpTransformer({ dynamic: { collections } })\\` configuration: not an upload-enabled collection: ${invalidSlugs.map((slug) => `\"${slug}\"`).join(', ')}.`,\n )\n }\n}\n"],"names":["getUploadTransformerInternal","uploadTransformerInternal","bundledSharp","createTransformUpload","createHandleRequest","initSharpCollections","parseDynamicResize","createTransformFile","DEFAULT_MIME_TYPES","resolveSharpDynamicDefaults","overrides","fit","maxHeight","maxPixels","maxWidth","position","withoutEnlargement","resolveSharpDynamicOptions","dynamic","sharpTransformer","options","dynamicOptions","dynamicDefaults","undefined","sharpDependency","sharp","collections","handlesCollection","collectionSlug","Boolean","transformer","slug","canTransform","args","operation","handledTransformKeys","purpose","includes","result","limits","searchParams","req","URLSearchParams","isRouted","handleRequest","init","config","assertDynamicCollectionsExist","assertCollectionsOwnedOnce","transformerSlug","mimeTypes","transformUpload","transformFile","collectionConfig","Object","entries","owners","upload","transformers","filter","candidate","length","Error","map","owner","join","invalidSlugs","some","collection"],"mappings":"AAGA,SAASA,4BAA4B,EAAEC,yBAAyB,QAAQ,mBAAkB;AAC1F,OAAOC,kBAAkB,QAAO;AAIhC,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,mBAAmB,QAAQ,qBAAoB;AACxD,SAASC,oBAAoB,QAAQ,4BAA2B;AAChE,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,mBAAmB,QAAQ,qBAAoB;AAExD,MAAMC,qBAAqB;IACzB;IACA;IACA;IACA;IACA;IACA;CACD;AAED,OAAO,SAASC,4BACdC,SAAgC;IAEhC,OAAO;QACLC,KAAKD,WAAWC,OAAO;QACvBC,WAAWF,WAAWE,aAAa;QACnCC,WAAWH,WAAWG,aAAa;QACnCC,UAAU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AAC,4GAA4G,EAAEI,aAAaH,GAAG,CAAC,CAAChC,OAAS,CAAC,CAAC,EAAEA,KAAK,CAAC,CAAC,EAAEkC,IAAI,CAAC,MAAM,CAAC,CAAC;IAExK;AACF"}
@@ -2,11 +2,11 @@ import type { TransformFileArgs, TransformFileResult } from 'payload';
2
2
  import type { SharpDependency, SharpUploadTaskOptions } from './types.js';
3
3
  /**
4
4
  * The Sharp package's public one-file-in/one-file-out upload primitive.
5
- * `options.kind` selects which legacy task to run: the main file (optionally
6
- * cropped, with `resizeOptions` re-applied to the crop output), or one named
7
- * legacy image size. Never writes to storage.
5
+ * `options.kind` selects which legacy task to run: the main file (cropped by the
6
+ * crop saved in `doc._transforms`, with `resizeOptions` re-applied to the crop
7
+ * output), or one named legacy image size. Never writes to storage.
8
8
  */
9
9
  export declare function createTransformFile({ sharpDependency }: {
10
10
  sharpDependency: SharpDependency;
11
- }): ({ file, options, req, }: TransformFileArgs<SharpUploadTaskOptions>) => Promise<TransformFileResult>;
11
+ }): ({ doc, file, options, req, }: TransformFileArgs<SharpUploadTaskOptions>) => Promise<TransformFileResult>;
12
12
  //# sourceMappingURL=transformFile.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"transformFile.d.ts","sourceRoot":"","sources":["../src/transformFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAkB,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAA;AAGrF,OAAO,KAAK,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAA;AAUzE;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,EAAE,eAAe,EAAE,EAAE;IAAE,eAAe,EAAE,eAAe,CAAA;CAAE,6BAKxF,iBAAiB,CAAC,sBAAsB,CAAC,KAAG,OAAO,CAAC,mBAAmB,CAAC,CAO5E"}
1
+ {"version":3,"file":"transformFile.d.ts","sourceRoot":"","sources":["../src/transformFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAIV,iBAAiB,EACjB,mBAAmB,EACpB,MAAM,SAAS,CAAA;AAGhB,OAAO,KAAK,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAA;AAQzE;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,EAAE,eAAe,EAAE,EAAE;IAAE,eAAe,EAAE,eAAe,CAAA;CAAE,kCAMxF,iBAAiB,CAAC,sBAAsB,CAAC,KAAG,OAAO,CAAC,mBAAmB,CAAC,CAO5E"}
@@ -1,21 +1,21 @@
1
1
  import { createSharpFromFile } from './createSharpFromFile.js';
2
2
  import { optionallyAppendMetadata } from './optionallyAppendMetadata.js';
3
+ import { getSavedCrop, getSavedFocalPoint } from './readSavedTransforms.js';
3
4
  const ANIMATED_MIME_TYPES = [
4
5
  'image/avif',
5
6
  'image/gif',
6
7
  'image/webp'
7
8
  ];
8
- // Rounds, as core does when it saves the crop in pixels. Flooring loses 1px to float error.
9
- const percentToPixel = (value, dimension)=>Math.round(value / 100 * dimension);
10
9
  /**
11
10
  * The Sharp package's public one-file-in/one-file-out upload primitive.
12
- * `options.kind` selects which legacy task to run: the main file (optionally
13
- * cropped, with `resizeOptions` re-applied to the crop output), or one named
14
- * legacy image size. Never writes to storage.
11
+ * `options.kind` selects which legacy task to run: the main file (cropped by the
12
+ * crop saved in `doc._transforms`, with `resizeOptions` re-applied to the crop
13
+ * output), or one named legacy image size. Never writes to storage.
15
14
  */ export function createTransformFile({ sharpDependency }) {
16
- return async function transformFile({ file, options, req }) {
15
+ return async function transformFile({ doc, file, options, req }) {
17
16
  if (options.kind === 'main') {
18
17
  return transformMain({
18
+ doc,
19
19
  file,
20
20
  options,
21
21
  req,
@@ -23,6 +23,7 @@ const percentToPixel = (value, dimension)=>Math.round(value / 100 * dimension);
23
23
  });
24
24
  }
25
25
  return transformSize({
26
+ doc,
26
27
  file,
27
28
  options,
28
29
  req,
@@ -30,16 +31,26 @@ const percentToPixel = (value, dimension)=>Math.round(value / 100 * dimension);
30
31
  });
31
32
  };
32
33
  }
33
- async function transformMain({ file, options, req, sharpDependency }) {
34
- const { collectionUpload, crop } = options;
34
+ async function transformMain({ doc, file, options, req, sharpDependency }) {
35
+ const { collectionUpload, cropSize, originalDimensions } = options;
36
+ // A full-image selection saves no crop, but a request crop size still extracts from the corner.
37
+ const crop = getSavedCrop({
38
+ doc
39
+ }) ?? (cropSize ? {
40
+ ...cropSize,
41
+ x: 0,
42
+ y: 0
43
+ } : undefined);
35
44
  const { constructorOptions, formatOptions, resizeOptions, trimOptions, withMetadata } = collectionUpload;
36
45
  const fileIsAnimatedType = ANIMATED_MIME_TYPES.includes(file.type);
37
46
  const fileHasAdjustments = Boolean(resizeOptions || formatOptions || trimOptions || constructorOptions);
38
- if (crop) {
47
+ if (crop && originalDimensions) {
39
48
  return transformCrop({
40
49
  crop,
50
+ cropSize,
41
51
  file,
42
52
  fileIsAnimatedType,
53
+ originalDimensions,
43
54
  req,
44
55
  resizeOptions,
45
56
  sharpDependency,
@@ -89,21 +100,20 @@ async function transformMain({ file, options, req, sharpDependency }) {
89
100
  status: 'continue'
90
101
  };
91
102
  }
92
- async function transformCrop({ crop, file, fileIsAnimatedType, req, resizeOptions, sharpDependency, withMetadata }) {
93
- const { cropData, heightInPixels, originalDimensions, widthInPixels } = crop;
103
+ async function transformCrop({ crop, cropSize, file, fileIsAnimatedType, originalDimensions, req, resizeOptions, sharpDependency, withMetadata }) {
94
104
  const sharpOptions = fileIsAnimatedType ? {
95
105
  animated: true
96
106
  } : {};
97
- const newWidth = Number(widthInPixels);
98
- const newHeight = Number(heightInPixels);
107
+ const newWidth = Number(cropSize?.width ?? crop.width);
108
+ const newHeight = Number(cropSize?.height ?? crop.height);
99
109
  const dimensionsChanged = originalDimensions.width !== newWidth || originalDimensions.height !== newHeight;
100
110
  let croppedFile = file;
101
111
  if (dimensionsChanged) {
102
112
  const formattedCropData = {
103
113
  height: newHeight,
104
- // Rounding up can push the crop 1px past the far edge.
105
- left: Math.min(percentToPixel(cropData.x, originalDimensions.width), originalDimensions.width - newWidth),
106
- top: Math.min(percentToPixel(cropData.y, originalDimensions.height), originalDimensions.height - newHeight),
114
+ // A request crop size larger than the saved crop could pass the far edge.
115
+ left: Math.min(crop.x, originalDimensions.width - newWidth),
116
+ top: Math.min(crop.y, originalDimensions.height - newHeight),
107
117
  width: newWidth
108
118
  };
109
119
  let cropped = (await createSharpFromFile({
@@ -152,8 +162,11 @@ async function transformCrop({ crop, file, fileIsAnimatedType, req, resizeOption
152
162
  status: 'continue'
153
163
  };
154
164
  }
155
- async function transformSize({ file, options, req, sharpDependency }) {
156
- const { collectionUpload, focalPoint, imageResizeConfig, originalDimensions } = options;
165
+ async function transformSize({ doc, file, options, req, sharpDependency }) {
166
+ const { canUseFocalPoint, collectionUpload, imageResizeConfig, originalDimensions } = options;
167
+ const focalPoint = canUseFocalPoint ? getSavedFocalPoint({
168
+ doc
169
+ }) : undefined;
157
170
  const { withMetadata } = collectionUpload;
158
171
  const fileIsAnimatedType = ANIMATED_MIME_TYPES.includes(file.type);
159
172
  const sharpOptions = fileIsAnimatedType ? {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/transformFile.ts"],"sourcesContent":["import type { PayloadRequest, TransformFileArgs, TransformFileResult } from 'payload'\nimport type { ResizeOptions, SharpOptions } from 'sharp'\n\nimport type { SharpDependency, SharpUploadTaskOptions } from './types.js'\n\nimport { createSharpFromFile } from './createSharpFromFile.js'\nimport { optionallyAppendMetadata } from './optionallyAppendMetadata.js'\n\nconst ANIMATED_MIME_TYPES = ['image/avif', 'image/gif', 'image/webp']\n\n// Rounds, as core does when it saves the crop in pixels. Flooring loses 1px to float error.\nconst percentToPixel = (value: number, dimension: number) => Math.round((value / 100) * dimension)\n\n/**\n * The Sharp package's public one-file-in/one-file-out upload primitive.\n * `options.kind` selects which legacy task to run: the main file (optionally\n * cropped, with `resizeOptions` re-applied to the crop output), or one named\n * legacy image size. Never writes to storage.\n */\nexport function createTransformFile({ sharpDependency }: { sharpDependency: SharpDependency }) {\n return async function transformFile({\n file,\n options,\n req,\n }: TransformFileArgs<SharpUploadTaskOptions>): Promise<TransformFileResult> {\n if (options.kind === 'main') {\n return transformMain({ file, options, req, sharpDependency })\n }\n\n return transformSize({ file, options, req, sharpDependency })\n }\n}\n\nasync function transformMain({\n file,\n options,\n req,\n sharpDependency,\n}: {\n file: File\n options: Extract<SharpUploadTaskOptions, { kind: 'main' }>\n req: PayloadRequest\n sharpDependency: SharpDependency\n}): Promise<TransformFileResult> {\n const { collectionUpload, crop } = options\n const { constructorOptions, formatOptions, resizeOptions, trimOptions, withMetadata } =\n collectionUpload\n\n const fileIsAnimatedType = ANIMATED_MIME_TYPES.includes(file.type)\n const fileHasAdjustments = Boolean(\n resizeOptions || formatOptions || trimOptions || constructorOptions,\n )\n\n if (crop) {\n return transformCrop({\n crop,\n file,\n fileIsAnimatedType,\n req,\n resizeOptions,\n sharpDependency,\n withMetadata,\n })\n }\n\n if (!fileIsAnimatedType && !fileHasAdjustments) {\n return { status: 'continue' }\n }\n\n const sharpOptions: SharpOptions = { ...constructorOptions }\n\n if (fileIsAnimatedType) {\n sharpOptions.animated = true\n }\n\n // pass rotate() to auto-rotate based on EXIF data. https://github.com/payloadcms/payload/pull/3081\n let sharpFile = (\n await createSharpFromFile({ file, options: sharpOptions, sharpDependency })\n ).rotate()\n\n if (resizeOptions) {\n sharpFile = sharpFile.resize(resizeOptions)\n }\n if (formatOptions) {\n sharpFile = sharpFile.toFormat(formatOptions.format, formatOptions.options)\n }\n if (trimOptions) {\n sharpFile = sharpFile.trim(trimOptions)\n }\n\n sharpFile = await optionallyAppendMetadata({ req, sharpFile, withMetadata })\n const { data: outputData } = await sharpFile.toBuffer({ resolveWithObject: true })\n\n return {\n file: new File([outputData], file.name, { type: file.type }),\n status: 'continue',\n }\n}\n\nasync function transformCrop({\n crop,\n file,\n fileIsAnimatedType,\n req,\n resizeOptions,\n sharpDependency,\n withMetadata,\n}: {\n crop: NonNullable<Extract<SharpUploadTaskOptions, { kind: 'main' }>['crop']>\n file: File\n fileIsAnimatedType: boolean\n req: PayloadRequest\n resizeOptions: ResizeOptions | undefined\n sharpDependency: SharpDependency\n withMetadata: SharpUploadTaskOptions['collectionUpload']['withMetadata']\n}): Promise<TransformFileResult> {\n const { cropData, heightInPixels, originalDimensions, widthInPixels } = crop\n\n const sharpOptions: SharpOptions = fileIsAnimatedType ? { animated: true } : {}\n\n const newWidth = Number(widthInPixels)\n const newHeight = Number(heightInPixels)\n const dimensionsChanged =\n originalDimensions.width !== newWidth || originalDimensions.height !== newHeight\n\n let croppedFile = file\n\n if (dimensionsChanged) {\n const formattedCropData = {\n height: newHeight,\n // Rounding up can push the crop 1px past the far edge.\n left: Math.min(\n percentToPixel(cropData.x, originalDimensions.width),\n originalDimensions.width - newWidth,\n ),\n top: Math.min(\n percentToPixel(cropData.y, originalDimensions.height),\n originalDimensions.height - newHeight,\n ),\n width: newWidth,\n }\n\n let cropped = (\n await createSharpFromFile({ file, options: sharpOptions, sharpDependency })\n ).extract(formattedCropData)\n cropped = await optionallyAppendMetadata({ req, sharpFile: cropped, withMetadata })\n const { data } = await cropped.toBuffer({ resolveWithObject: true })\n croppedFile = new File([data], file.name, { type: file.type })\n }\n\n if (resizeOptions && !resizeOptions.withoutEnlargement) {\n const sharpFile = await createSharpFromFile({ file: croppedFile, sharpDependency })\n const { data: resizedBuffer } = await sharpFile\n .resize({\n fit: resizeOptions.fit || 'cover',\n height: resizeOptions.height,\n position: resizeOptions.position || 'center',\n width: resizeOptions.width,\n })\n .toBuffer({ resolveWithObject: true })\n\n return {\n file: new File([resizedBuffer], file.name, { type: file.type }),\n status: 'continue',\n }\n }\n\n return {\n file: croppedFile,\n status: 'continue',\n }\n}\n\nasync function transformSize({\n file,\n options,\n req,\n sharpDependency,\n}: {\n file: File\n options: Extract<SharpUploadTaskOptions, { kind: 'size' }>\n req: PayloadRequest\n sharpDependency: SharpDependency\n}): Promise<TransformFileResult> {\n const { collectionUpload, focalPoint, imageResizeConfig, originalDimensions } = options\n const { withMetadata } = collectionUpload\n\n const fileIsAnimatedType = ANIMATED_MIME_TYPES.includes(file.type)\n const sharpOptions: SharpOptions = fileIsAnimatedType ? { animated: true } : {}\n\n const sharpBase = (\n await createSharpFromFile({ file, options: sharpOptions, sharpDependency })\n ).rotate()\n const originalImageMeta = await sharpBase.metadata()\n\n let adjustedDimensions = { ...originalDimensions }\n\n if ([5, 6, 7, 8].includes(originalImageMeta.orientation!)) {\n adjustedDimensions = {\n height: originalDimensions.width,\n width: originalDimensions.height,\n }\n }\n\n let resized = sharpBase.clone()\n\n if (focalPoint) {\n let { height: resizeHeight, width: resizeWidth } = imageResizeConfig\n\n const originalAspectRatio = adjustedDimensions.width / adjustedDimensions.height\n\n if (resizeHeight && !resizeWidth) {\n resizeWidth = Math.round(resizeHeight * originalAspectRatio)\n }\n if (resizeWidth && !resizeHeight) {\n resizeHeight = Math.round(resizeWidth / originalAspectRatio)\n }\n if (!resizeHeight) {\n resizeHeight = originalImageMeta.height\n }\n if (!resizeWidth) {\n resizeWidth = originalImageMeta.width\n }\n\n const resizeAspectRatio = resizeWidth / resizeHeight\n const prioritizeHeight = resizeAspectRatio < originalAspectRatio\n\n resized = resized.resize({\n fastShrinkOnLoad: false,\n height: prioritizeHeight ? resizeHeight : undefined,\n width: prioritizeHeight ? undefined : resizeWidth,\n })\n\n const metadataAppended = await optionallyAppendMetadata({\n req,\n sharpFile: resized,\n withMetadata,\n })\n const { info } = await metadataAppended.toBuffer({ resolveWithObject: true })\n\n const resizedHeight = originalImageMeta.pages\n ? info.height / originalImageMeta.pages\n : info.height\n const resizedWidth = info.width\n\n const halfResizeX = resizeWidth / 2\n const xFocalCenter = resizedWidth * (focalPoint.x / 100)\n let leftBound = xFocalCenter - halfResizeX\n if (xFocalCenter + halfResizeX > resizedWidth) {\n leftBound = resizedWidth - resizeWidth\n }\n if (leftBound < 0) {\n leftBound = 0\n }\n\n const halfResizeY = resizeHeight / 2\n const yFocalCenter = resizedHeight * (focalPoint.y / 100)\n let topBound = yFocalCenter - halfResizeY\n if (yFocalCenter + halfResizeY > resizedHeight) {\n topBound = resizedHeight - resizeHeight\n }\n if (topBound < 0) {\n topBound = 0\n }\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 = resized.resize(imageResizeConfig)\n }\n\n if (imageResizeConfig.formatOptions) {\n resized = resized.toFormat(\n imageResizeConfig.formatOptions.format,\n imageResizeConfig.formatOptions.options,\n )\n }\n if (imageResizeConfig.trimOptions) {\n resized = resized.trim(imageResizeConfig.trimOptions)\n }\n\n resized = await optionallyAppendMetadata({ req, sharpFile: resized, withMetadata })\n const { data: outputData } = await resized.toBuffer({ resolveWithObject: true })\n\n return {\n file: new File([outputData], file.name, { type: file.type }),\n status: 'continue',\n }\n}\n"],"names":["createSharpFromFile","optionallyAppendMetadata","ANIMATED_MIME_TYPES","percentToPixel","value","dimension","Math","round","createTransformFile","sharpDependency","transformFile","file","options","req","kind","transformMain","transformSize","collectionUpload","crop","constructorOptions","formatOptions","resizeOptions","trimOptions","withMetadata","fileIsAnimatedType","includes","type","fileHasAdjustments","Boolean","transformCrop","status","sharpOptions","animated","sharpFile","rotate","resize","toFormat","format","trim","data","outputData","toBuffer","resolveWithObject","File","name","cropData","heightInPixels","originalDimensions","widthInPixels","newWidth","Number","newHeight","dimensionsChanged","width","height","croppedFile","formattedCropData","left","min","x","top","y","cropped","extract","withoutEnlargement","resizedBuffer","fit","position","focalPoint","imageResizeConfig","sharpBase","originalImageMeta","metadata","adjustedDimensions","orientation","resized","clone","resizeHeight","resizeWidth","originalAspectRatio","resizeAspectRatio","prioritizeHeight","fastShrinkOnLoad","undefined","metadataAppended","info","resizedHeight","pages","resizedWidth","halfResizeX","xFocalCenter","leftBound","halfResizeY","yFocalCenter","topBound","floor"],"mappings":"AAKA,SAASA,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,wBAAwB,QAAQ,gC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AAK;IAE9E,OAAO;QACL/B,MAAM,IAAIgC,KAAK;YAACH;SAAW,EAAE7B,KAAKiC,IAAI,EAAE;YAAElB,MAAMf,KAAKe,IAAI;QAAC;QAC1DI,QAAQ;IACV;AACF"}
1
+ {"version":3,"sources":["../src/transformFile.ts"],"sourcesContent":["import type {\n Crop,\n Document,\n PayloadRequest,\n TransformFileArgs,\n TransformFileResult,\n} from 'payload'\nimport type { ResizeOptions, SharpOptions } from 'sharp'\n\nimport type { SharpDependency, SharpUploadTaskOptions } from './types.js'\n\nimport { createSharpFromFile } from './createSharpFromFile.js'\nimport { optionallyAppendMetadata } from './optionallyAppendMetadata.js'\nimport { getSavedCrop, getSavedFocalPoint } from './readSavedTransforms.js'\n\nconst ANIMATED_MIME_TYPES = ['image/avif', 'image/gif', 'image/webp']\n\n/**\n * The Sharp package's public one-file-in/one-file-out upload primitive.\n * `options.kind` selects which legacy task to run: the main file (cropped by the\n * crop saved in `doc._transforms`, with `resizeOptions` re-applied to the crop\n * output), or one named legacy image size. Never writes to storage.\n */\nexport function createTransformFile({ sharpDependency }: { sharpDependency: SharpDependency }) {\n return async function transformFile({\n doc,\n file,\n options,\n req,\n }: TransformFileArgs<SharpUploadTaskOptions>): Promise<TransformFileResult> {\n if (options.kind === 'main') {\n return transformMain({ doc, file, options, req, sharpDependency })\n }\n\n return transformSize({ doc, file, options, req, sharpDependency })\n }\n}\n\nasync function transformMain({\n doc,\n file,\n options,\n req,\n sharpDependency,\n}: {\n doc: Document\n file: File\n options: Extract<SharpUploadTaskOptions, { kind: 'main' }>\n req: PayloadRequest\n sharpDependency: SharpDependency\n}): Promise<TransformFileResult> {\n const { collectionUpload, cropSize, originalDimensions } = options\n // A full-image selection saves no crop, but a request crop size still extracts from the corner.\n const crop = getSavedCrop({ doc }) ?? (cropSize ? { ...cropSize, x: 0, y: 0 } : undefined)\n const { constructorOptions, formatOptions, resizeOptions, trimOptions, withMetadata } =\n collectionUpload\n\n const fileIsAnimatedType = ANIMATED_MIME_TYPES.includes(file.type)\n const fileHasAdjustments = Boolean(\n resizeOptions || formatOptions || trimOptions || constructorOptions,\n )\n\n if (crop && originalDimensions) {\n return transformCrop({\n crop,\n cropSize,\n file,\n fileIsAnimatedType,\n originalDimensions,\n req,\n resizeOptions,\n sharpDependency,\n withMetadata,\n })\n }\n\n if (!fileIsAnimatedType && !fileHasAdjustments) {\n return { status: 'continue' }\n }\n\n const sharpOptions: SharpOptions = { ...constructorOptions }\n\n if (fileIsAnimatedType) {\n sharpOptions.animated = true\n }\n\n // pass rotate() to auto-rotate based on EXIF data. https://github.com/payloadcms/payload/pull/3081\n let sharpFile = (\n await createSharpFromFile({ file, options: sharpOptions, sharpDependency })\n ).rotate()\n\n if (resizeOptions) {\n sharpFile = sharpFile.resize(resizeOptions)\n }\n if (formatOptions) {\n sharpFile = sharpFile.toFormat(formatOptions.format, formatOptions.options)\n }\n if (trimOptions) {\n sharpFile = sharpFile.trim(trimOptions)\n }\n\n sharpFile = await optionallyAppendMetadata({ req, sharpFile, withMetadata })\n const { data: outputData } = await sharpFile.toBuffer({ resolveWithObject: true })\n\n return {\n file: new File([outputData], file.name, { type: file.type }),\n status: 'continue',\n }\n}\n\nasync function transformCrop({\n crop,\n cropSize,\n file,\n fileIsAnimatedType,\n originalDimensions,\n req,\n resizeOptions,\n sharpDependency,\n withMetadata,\n}: {\n crop: Omit<Crop, 'unit'>\n cropSize: Extract<SharpUploadTaskOptions, { kind: 'main' }>['cropSize']\n file: File\n fileIsAnimatedType: boolean\n originalDimensions: { height: number; width: number }\n req: PayloadRequest\n resizeOptions: ResizeOptions | undefined\n sharpDependency: SharpDependency\n withMetadata: SharpUploadTaskOptions['collectionUpload']['withMetadata']\n}): Promise<TransformFileResult> {\n const sharpOptions: SharpOptions = fileIsAnimatedType ? { animated: true } : {}\n\n const newWidth = Number(cropSize?.width ?? crop.width)\n const newHeight = Number(cropSize?.height ?? crop.height)\n const dimensionsChanged =\n originalDimensions.width !== newWidth || originalDimensions.height !== newHeight\n\n let croppedFile = file\n\n if (dimensionsChanged) {\n const formattedCropData = {\n height: newHeight,\n // A request crop size larger than the saved crop could pass the far edge.\n left: Math.min(crop.x, originalDimensions.width - newWidth),\n top: Math.min(crop.y, originalDimensions.height - newHeight),\n width: newWidth,\n }\n\n let cropped = (\n await createSharpFromFile({ file, options: sharpOptions, sharpDependency })\n ).extract(formattedCropData)\n cropped = await optionallyAppendMetadata({ req, sharpFile: cropped, withMetadata })\n const { data } = await cropped.toBuffer({ resolveWithObject: true })\n croppedFile = new File([data], file.name, { type: file.type })\n }\n\n if (resizeOptions && !resizeOptions.withoutEnlargement) {\n const sharpFile = await createSharpFromFile({ file: croppedFile, sharpDependency })\n const { data: resizedBuffer } = await sharpFile\n .resize({\n fit: resizeOptions.fit || 'cover',\n height: resizeOptions.height,\n position: resizeOptions.position || 'center',\n width: resizeOptions.width,\n })\n .toBuffer({ resolveWithObject: true })\n\n return {\n file: new File([resizedBuffer], file.name, { type: file.type }),\n status: 'continue',\n }\n }\n\n return {\n file: croppedFile,\n status: 'continue',\n }\n}\n\nasync function transformSize({\n doc,\n file,\n options,\n req,\n sharpDependency,\n}: {\n doc: Document\n file: File\n options: Extract<SharpUploadTaskOptions, { kind: 'size' }>\n req: PayloadRequest\n sharpDependency: SharpDependency\n}): Promise<TransformFileResult> {\n const { canUseFocalPoint, collectionUpload, imageResizeConfig, originalDimensions } = options\n const focalPoint = canUseFocalPoint ? getSavedFocalPoint({ doc }) : undefined\n const { withMetadata } = collectionUpload\n\n const fileIsAnimatedType = ANIMATED_MIME_TYPES.includes(file.type)\n const sharpOptions: SharpOptions = fileIsAnimatedType ? { animated: true } : {}\n\n const sharpBase = (\n await createSharpFromFile({ file, options: sharpOptions, sharpDependency })\n ).rotate()\n const originalImageMeta = await sharpBase.metadata()\n\n let adjustedDimensions = { ...originalDimensions }\n\n if ([5, 6, 7, 8].includes(originalImageMeta.orientation!)) {\n adjustedDimensions = {\n height: originalDimensions.width,\n width: originalDimensions.height,\n }\n }\n\n let resized = sharpBase.clone()\n\n if (focalPoint) {\n let { height: resizeHeight, width: resizeWidth } = imageResizeConfig\n\n const originalAspectRatio = adjustedDimensions.width / adjustedDimensions.height\n\n if (resizeHeight && !resizeWidth) {\n resizeWidth = Math.round(resizeHeight * originalAspectRatio)\n }\n if (resizeWidth && !resizeHeight) {\n resizeHeight = Math.round(resizeWidth / originalAspectRatio)\n }\n if (!resizeHeight) {\n resizeHeight = originalImageMeta.height\n }\n if (!resizeWidth) {\n resizeWidth = originalImageMeta.width\n }\n\n const resizeAspectRatio = resizeWidth / resizeHeight\n const prioritizeHeight = resizeAspectRatio < originalAspectRatio\n\n resized = resized.resize({\n fastShrinkOnLoad: false,\n height: prioritizeHeight ? resizeHeight : undefined,\n width: prioritizeHeight ? undefined : resizeWidth,\n })\n\n const metadataAppended = await optionallyAppendMetadata({\n req,\n sharpFile: resized,\n withMetadata,\n })\n const { info } = await metadataAppended.toBuffer({ resolveWithObject: true })\n\n const resizedHeight = originalImageMeta.pages\n ? info.height / originalImageMeta.pages\n : info.height\n const resizedWidth = info.width\n\n const halfResizeX = resizeWidth / 2\n const xFocalCenter = resizedWidth * (focalPoint.x / 100)\n let leftBound = xFocalCenter - halfResizeX\n if (xFocalCenter + halfResizeX > resizedWidth) {\n leftBound = resizedWidth - resizeWidth\n }\n if (leftBound < 0) {\n leftBound = 0\n }\n\n const halfResizeY = resizeHeight / 2\n const yFocalCenter = resizedHeight * (focalPoint.y / 100)\n let topBound = yFocalCenter - halfResizeY\n if (yFocalCenter + halfResizeY > resizedHeight) {\n topBound = resizedHeight - resizeHeight\n }\n if (topBound < 0) {\n topBound = 0\n }\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 = resized.resize(imageResizeConfig)\n }\n\n if (imageResizeConfig.formatOptions) {\n resized = resized.toFormat(\n imageResizeConfig.formatOptions.format,\n imageResizeConfig.formatOptions.options,\n )\n }\n if (imageResizeConfig.trimOptions) {\n resized = resized.trim(imageResizeConfig.trimOptions)\n }\n\n resized = await optionallyAppendMetadata({ req, sharpFile: resized, withMetadata })\n const { data: outputData } = await resized.toBuffer({ resolveWithObject: true })\n\n return {\n file: new File([outputData], file.name, { type: file.type }),\n status: 'continue',\n }\n}\n"],"names":["createSharpFromFile","optionallyAppendMetadata","getSavedCrop","getSavedFocalPoint","ANIMATED_MIME_TYPES","createTransformFile","sharpDependency","transformFile","doc","file","options","req","kind","transformMain","transformSize","collectionUpload","cropSize","originalDimensions","crop","x","y","undefined","constructorOptions","formatOptions","resizeOptions","trimOptions","withMetadata","fileIsAnimatedType","includes","type","fileHasAdjustments","Boolean","transformCrop","status","sharpOptions","animated","sharpFile","rotate","resize","toFormat","format","trim","data","outputData","toBuffer","resolveWithObject","File","name","newWidth","Number","width","newHeight","height","dimensionsChanged","croppedFile","formattedCropData","left","Math","min","top","cropped","extract","withoutEnlargement","resizedBuffer","fit","position","canUseFocalPoint","imageResizeConfig","focalPoint","sharpBase","originalImageMeta","metadata","adjustedDimensions","orientation","resized","clone","resizeHeight","resizeWidth","originalAspectRatio","round","resizeAspectRatio","prioritizeHeight","fastShrinkOnLoad","metadataAppended","info","resizedHeight","pages","resizedWidth","halfResizeX","xFocalCenter","leftBound","halfResizeY","yFocalCenter","topBound","floor"],"mappings":"AAWA,SAASA,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,YAAY,EAAEC,kBAAkB,QAAQ,2BAA0B;AAE3E,MAAMC,sBAAsB;IAAC;IAAc;IAAa;CAAa;AAErE;;;;;CAKC,GACD,OAAO,SAASC,oBAAoB,EAAEC,eAAe,EAAwC;IAC3F,OAAO,eAAeC,cAAc,EAClCC,GAAG,EACHC,IAAI,EACJC,OAAO,EACPC,GAAG,EACuC;QAC1C,IAAID,QAAQE,IAAI,KAAK,QAAQ;YAC3B,OAAOC,cAAc;gBAAEL;gBAAKC;g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AI;QAAC;QAC1DI,QAAQ;IACV;AACF"}
@@ -132,27 +132,26 @@ describe('createTransformFile', ()=>{
132
132
  sharpDependency: sharp
133
133
  });
134
134
  const result = await transformFile({
135
- file,
136
- options: {
137
- collectionUpload: {
138
- resizeOptions
139
- },
140
- crop: {
141
- cropData: {
135
+ doc: {
136
+ _transforms: {
137
+ crop: {
142
138
  height: 40,
143
- unit: '%',
144
139
  width: 40,
145
140
  x: 25,
146
141
  y: 25
147
- },
148
- heightInPixels: 40,
149
- originalDimensions: {
150
- height: 100,
151
- width: 100
152
- },
153
- widthInPixels: 40
142
+ }
143
+ }
144
+ },
145
+ file,
146
+ options: {
147
+ collectionUpload: {
148
+ resizeOptions
154
149
  },
155
- kind: 'main'
150
+ kind: 'main',
151
+ originalDimensions: {
152
+ height: 100,
153
+ width: 100
154
+ }
156
155
  },
157
156
  req: makeReq()
158
157
  });
@@ -162,11 +161,16 @@ describe('createTransformFile', ()=>{
162
161
  });
163
162
  });
164
163
  describe('main crop', ()=>{
165
- const cropMain = async ({ cropData, image })=>{
164
+ const cropMain = async ({ crop, cropSize, image })=>{
166
165
  const transformFile = createTransformFile({
167
166
  sharpDependency: sharp
168
167
  });
169
168
  const result = await transformFile({
169
+ doc: crop ? {
170
+ _transforms: {
171
+ crop
172
+ }
173
+ } : {},
170
174
  file: new File([
171
175
  image
172
176
  ], 'photo.png', {
@@ -174,24 +178,20 @@ describe('createTransformFile', ()=>{
174
178
  }),
175
179
  options: {
176
180
  collectionUpload: {},
177
- crop: {
178
- cropData,
179
- heightInPixels: 10,
180
- originalDimensions: {
181
- height: 10,
182
- width: 100
183
- },
184
- widthInPixels: cropData.width
185
- },
186
- kind: 'main'
181
+ cropSize,
182
+ kind: 'main',
183
+ originalDimensions: {
184
+ height: 10,
185
+ width: 100
186
+ }
187
187
  },
188
188
  req: makeReq()
189
189
  });
190
190
  return sharp(await toBuffer(result.file));
191
191
  };
192
192
  it('should start the crop at the saved pixel, not 1px before it', async ()=>{
193
- // Red columns 0-28, blue from column 29. Core saves x = 29px and sends it as 29 / 100 * 100,
194
- // which is 28.999…%, so flooring it starts the crop on the last red column.
193
+ // Red columns 0-28, blue from column 29. The crop is read from `doc._transforms` in pixels,
194
+ // so it starts on the first blue column.
195
195
  const blue = await makeImageBuffer({
196
196
  background: {
197
197
  b: 255,
@@ -220,11 +220,10 @@ describe('createTransformFile', ()=>{
220
220
  }
221
221
  ]).png().toBuffer();
222
222
  const cropped = await cropMain({
223
- cropData: {
224
- height: 100,
225
- unit: '%',
223
+ crop: {
224
+ height: 10,
226
225
  width: 10,
227
- x: 29 / 100 * 100,
226
+ x: 29,
228
227
  y: 0
229
228
  },
230
229
  image
@@ -242,16 +241,19 @@ describe('createTransformFile', ()=>{
242
241
  r: 0
243
242
  });
244
243
  });
245
- it('should keep a rounded crop inside the image', async ()=>{
246
- // 30.5% rounds up to 31px, and 31 + 70 would pass the right edge of a 100px image.
244
+ it('should keep a crop inside the image when the request crop size is larger than the saved crop', async ()=>{
245
+ // The request's `widthInPixels` is 70, and 31 + 70 would pass the right edge of a 100px image.
247
246
  const cropped = await cropMain({
248
- cropData: {
249
- height: 100,
250
- unit: '%',
251
- width: 70,
252
- x: 30.5,
247
+ crop: {
248
+ height: 10,
249
+ width: 69,
250
+ x: 31,
253
251
  y: 0
254
252
  },
253
+ cropSize: {
254
+ height: 10,
255
+ width: 70
256
+ },
255
257
  image: await makeImageBuffer({
256
258
  height: 10,
257
259
  width: 100
@@ -259,15 +261,37 @@ describe('createTransformFile', ()=>{
259
261
  });
260
262
  expect((await cropped.metadata()).width).toBe(70);
261
263
  });
264
+ it('should extract the request crop size from the top-left corner when no crop is saved', async ()=>{
265
+ // A full-image selection saves no crop, but the request can still send a smaller
266
+ // `widthInPixels`/`heightInPixels` to extract.
267
+ const cropped = await cropMain({
268
+ cropSize: {
269
+ height: 5,
270
+ width: 20
271
+ },
272
+ image: await makeImageBuffer({
273
+ height: 10,
274
+ width: 100
275
+ })
276
+ });
277
+ expect(await cropped.metadata()).toMatchObject({
278
+ height: 5,
279
+ width: 20
280
+ });
281
+ });
262
282
  });
263
283
  describe('size (transformSize)', ()=>{
264
284
  // Each original forces one resize-priority branch, and a focal point at 80% pushes the
265
285
  // 50px extract window against the clamped far edge, so a correct crop is entirely blue.
266
286
  it.each([
267
287
  {
268
- focalPoint: {
269
- x: 80,
270
- y: 50
288
+ doc: {
289
+ _transforms: {
290
+ focalPoint: {
291
+ x: 79.6,
292
+ y: 50
293
+ }
294
+ }
271
295
  },
272
296
  original: {
273
297
  height: 100,
@@ -285,10 +309,11 @@ describe('createTransformFile', ()=>{
285
309
  }
286
310
  ]
287
311
  },
312
+ // A document saved before `_transforms` existed has only `focalX`/`focalY`.
288
313
  {
289
- focalPoint: {
290
- x: 50,
291
- y: 80
314
+ doc: {
315
+ focalX: 50,
316
+ focalY: 80
292
317
  },
293
318
  original: {
294
319
  height: 200,
@@ -306,7 +331,7 @@ describe('createTransformFile', ()=>{
306
331
  }
307
332
  ]
308
333
  }
309
- ])('should extract the focal-point region along the $original.splitAxis axis', async ({ focalPoint, original, samples })=>{
334
+ ])('should extract the saved focal-point region along the $original.splitAxis axis', async ({ doc, original, samples })=>{
310
335
  const buffer = await makeTwoColorImage(original);
311
336
  const file = new File([
312
337
  buffer
@@ -317,16 +342,17 @@ describe('createTransformFile', ()=>{
317
342
  sharpDependency: sharp
318
343
  });
319
344
  const result = await transformFile({
345
+ doc,
320
346
  file,
321
347
  options: {
322
348
  collectionUpload: {},
323
- focalPoint,
324
349
  imageResizeConfig: {
325
350
  name: 'thumb',
326
351
  height: 50,
327
352
  width: 50
328
353
  },
329
354
  kind: 'size',
355
+ canUseFocalPoint: true,
330
356
  originalDimensions: {
331
357
  height: original.height,
332
358
  width: original.width
@@ -352,6 +378,67 @@ describe('createTransformFile', ()=>{
352
378
  });
353
379
  }
354
380
  });
381
+ // A focal point at the center is not saved, so it means "no focal point". The size then uses
382
+ // its own `position`: a left-aligned 50px cut of the 100px resize is red. A cut around the
383
+ // center would end on blue.
384
+ it.each([
385
+ {
386
+ name: 'no saved focal point',
387
+ doc: {}
388
+ },
389
+ {
390
+ name: 'a legacy focal point at the center',
391
+ doc: {
392
+ focalX: 50,
393
+ focalY: 50
394
+ }
395
+ }
396
+ ])('should resize with the size config when there is $name', async ({ doc })=>{
397
+ const buffer = await makeTwoColorImage({
398
+ height: 100,
399
+ splitAxis: 'x',
400
+ width: 200
401
+ });
402
+ const transformFile = createTransformFile({
403
+ sharpDependency: sharp
404
+ });
405
+ const result = await transformFile({
406
+ doc,
407
+ file: new File([
408
+ buffer
409
+ ], 'photo.png', {
410
+ type: 'image/png'
411
+ }),
412
+ options: {
413
+ canUseFocalPoint: true,
414
+ collectionUpload: {},
415
+ imageResizeConfig: {
416
+ name: 'thumb',
417
+ height: 50,
418
+ position: 'left',
419
+ width: 50
420
+ },
421
+ kind: 'size',
422
+ originalDimensions: {
423
+ height: 100,
424
+ width: 200
425
+ }
426
+ },
427
+ req: makeReq()
428
+ });
429
+ const raw = await sharp(await toBuffer(result.file)).raw().toBuffer({
430
+ resolveWithObject: true
431
+ });
432
+ expect(sampleRawPixel({
433
+ ...raw,
434
+ x: 40,
435
+ y: 25
436
+ })).toEqual({
437
+ b: 0,
438
+ g: 0,
439
+ r: 255
440
+ });
441
+ });
355
442
  });
356
443
  });
357
444
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/transformFile.spec.ts"],"sourcesContent":["import type { PayloadRequest, UploadEdits } from 'payload'\n\nimport sharp from 'sharp'\nimport { describe, expect, it } from 'vitest'\n\nimport type { SharpUploadTaskOptions } from './types.js'\n\nimport { createTransformFile } from './transformFile.js'\n\nconst makeReq = (): PayloadRequest => ({}) as PayloadRequest\n\nconst toBuffer = async (file: File): Promise<Buffer> => Buffer.from(await file.arrayBuffer())\n\nconst makeImageBuffer = async ({\n background = { b: 0, g: 128, r: 255 },\n height,\n width,\n}: {\n background?: { b: number; g: number; r: number }\n height: number\n width: number\n}): Promise<Buffer> =>\n sharp({ create: { background, channels: 3, height, width } })\n .png()\n .toBuffer()\n\n/**\n * A two-colour image split along `splitAxis` (red/blue halves) — proves the\n * focal-point extract region in `transformSize` lands where the math says,\n * not just that the output dimensions are right.\n */\nconst makeTwoColorImage = async ({\n height,\n splitAxis,\n width,\n}: {\n height: number\n splitAxis: 'x' | 'y'\n width: number\n}): Promise<Buffer> => {\n const raw = Buffer.alloc(width * height * 3)\n\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const idx = (y * width + x) * 3\n const isFirstHalf = splitAxis === 'x' ? x < width / 2 : y < height / 2\n\n if (isFirstHalf) {\n raw[idx] = 255 // red\n } else {\n raw[idx + 2] = 255 // blue\n }\n }\n }\n\n return sharp(raw, { raw: { channels: 3, height, width } })\n .png()\n .toBuffer()\n}\n\nconst sampleRawPixel = ({\n data,\n info,\n x,\n y,\n}: {\n data: Buffer\n info: { channels: number; width: number }\n x: number\n y: number\n}): { b: number; g: number; r: number } => {\n const idx = (y * info.width + x) * info.channels\n return { b: data[idx + 2]!, g: data[idx + 1]!, r: data[idx]! }\n}\n\ndescribe('createTransformFile', () => {\n describe('main (transformMain)', () => {\n it('should trim uniform-colour padding from the main file', async () => {\n const square = await makeImageBuffer({\n background: { b: 0, g: 0, r: 0 },\n height: 20,\n width: 20,\n })\n const framed = await sharp({\n create: { background: { b: 255, g: 255, r: 255 }, channels: 3, height: 60, width: 60 },\n })\n .composite([{ input: square, left: 20, top: 20 }])\n .png()\n .toBuffer()\n const file = new File([framed], 'photo.png', { type: 'image/png' })\n const transformFile = createTransformFile({ sharpDependency: sharp })\n\n const result = await transformFile({\n file,\n options: {\n collectionUpload: { trimOptions: {} },\n kind: 'main',\n } satisfies SharpUploadTaskOptions,\n req: makeReq(),\n })\n\n const metadata = await sharp(await toBuffer(result.file!)).metadata()\n expect(metadata.width).toBe(20)\n expect(metadata.height).toBe(20)\n })\n\n it.each([\n // Re-applied by default, so the 40x40 crop is resized down to 20x20.\n { expectedSize: 20, resizeOptions: { fit: 'cover' as const, height: 20, width: 20 } },\n { expectedSize: 40, resizeOptions: { height: 20, width: 20, withoutEnlargement: true } },\n ])(\n 'should re-apply resizeOptions to the crop output unless withoutEnlargement is set (%#)',\n async ({ expectedSize, resizeOptions }) => {\n const buffer = await makeImageBuffer({ height: 100, width: 100 })\n const file = new File([buffer], 'photo.png', { type: 'image/png' })\n const transformFile = createTransformFile({ sharpDependency: sharp })\n\n const result = await transformFile({\n file,\n options: {\n collectionUpload: { resizeOptions },\n crop: {\n cropData: { height: 40, unit: '%', width: 40, x: 25, y: 25 },\n heightInPixels: 40,\n originalDimensions: { height: 100, width: 100 },\n widthInPixels: 40,\n },\n kind: 'main',\n } satisfies SharpUploadTaskOptions,\n req: makeReq(),\n })\n\n const metadata = await sharp(await toBuffer(result.file!)).metadata()\n expect(metadata.width).toBe(expectedSize)\n expect(metadata.height).toBe(expectedSize)\n },\n )\n })\n\n describe('main crop', () => {\n const cropMain = async ({\n cropData,\n image,\n }: {\n cropData: NonNullable<UploadEdits['crop']>\n image: Buffer\n }) => {\n const transformFile = createTransformFile({ sharpDependency: sharp })\n\n const result = await transformFile({\n file: new File([image], 'photo.png', { type: 'image/png' }),\n options: {\n collectionUpload: {},\n crop: {\n cropData,\n heightInPixels: 10,\n originalDimensions: { height: 10, width: 100 },\n widthInPixels: cropData.width,\n },\n kind: 'main',\n } satisfies SharpUploadTaskOptions,\n req: makeReq(),\n })\n\n return sharp(await toBuffer(result.file!))\n }\n\n it('should start the crop at the saved pixel, not 1px before it', async () => {\n // Red columns 0-28, blue from column 29. Core saves x = 29px and sends it as 29 / 100 * 100,\n // which is 28.999…%, so flooring it starts the crop on the last red column.\n const blue = await makeImageBuffer({\n background: { b: 255, g: 0, r: 0 },\n height: 10,\n width: 71,\n })\n const image = await sharp({\n create: { background: { b: 0, g: 0, r: 255 }, channels: 3, height: 10, width: 100 },\n })\n .composite([{ input: blue, left: 29, top: 0 }])\n .png()\n .toBuffer()\n\n const cropped = await cropMain({\n cropData: { height: 100, unit: '%', width: 10, x: (29 / 100) * 100, y: 0 },\n image,\n })\n\n const raw = await cropped.raw().toBuffer({ resolveWithObject: true })\n expect(sampleRawPixel({ ...raw, x: 0, y: 0 })).toEqual({ b: 255, g: 0, r: 0 })\n })\n\n it('should keep a rounded crop inside the image', async () => {\n // 30.5% rounds up to 31px, and 31 + 70 would pass the right edge of a 100px image.\n const cropped = await cropMain({\n cropData: { height: 100, unit: '%', width: 70, x: 30.5, y: 0 },\n image: await makeImageBuffer({ height: 10, width: 100 }),\n })\n\n expect((await cropped.metadata()).width).toBe(70)\n })\n })\n\n describe('size (transformSize)', () => {\n // Each original forces one resize-priority branch, and a focal point at 80% pushes the\n // 50px extract window against the clamped far edge, so a correct crop is entirely blue.\n it.each([\n {\n focalPoint: { x: 80, y: 50 },\n original: { height: 100, splitAxis: 'x' as const, width: 200 },\n samples: [\n { x: 10, y: 25 },\n { x: 40, y: 25 },\n ],\n },\n {\n focalPoint: { x: 50, y: 80 },\n original: { height: 200, splitAxis: 'y' as const, width: 100 },\n samples: [\n { x: 25, y: 10 },\n { x: 25, y: 40 },\n ],\n },\n ])(\n 'should extract the focal-point region along the $original.splitAxis axis',\n async ({ focalPoint, original, samples }) => {\n const buffer = await makeTwoColorImage(original)\n const file = new File([buffer], 'photo.png', { type: 'image/png' })\n const transformFile = createTransformFile({ sharpDependency: sharp })\n\n const result = await transformFile({\n file,\n options: {\n collectionUpload: {},\n focalPoint,\n imageResizeConfig: { name: 'thumb', height: 50, width: 50 },\n kind: 'size',\n originalDimensions: { height: original.height, width: original.width },\n } satisfies SharpUploadTaskOptions,\n req: makeReq(),\n })\n\n const { data, info } = await sharp(await toBuffer(result.file!))\n .raw()\n .toBuffer({ resolveWithObject: true })\n expect(info.width).toBe(50)\n expect(info.height).toBe(50)\n for (const { x, y } of samples) {\n expect(sampleRawPixel({ data, info, x, y })).toEqual({ b: 255, g: 0, r: 0 })\n }\n },\n )\n })\n})\n"],"names":["sharp","describe","expect","it","createTransformFile","makeReq","toBuffer","file","Buffer","from","arrayBuffer","makeImageBuffer","background","b","g","r","height","width","create","channels","png","makeTwoColorImage","splitAxis","raw","alloc","y","x","idx","isFirstHalf","sampleRawPixel","data","info","square","framed","composite","input","left","top","File","type","transformFile","sharpDependency","result","options","collectionUpload","trimOptions","kind","req","metadata","toBe","each","expectedSize","resizeOptions","fit","withoutEnlargement","buffer","crop","cropData","unit","heightInPixels","originalDimensions","widthInPixels","cropMain","image","blue","cropped","resolveWithObject","toEqual","focalPoint","original","samples","imageResizeConfig","name"],"mappings":"AAEA,OAAOA,WAAW,QAAO;AACzB,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAQ;AAI7C,SAASC,mBAAmB,QAAQ,qBAAoB;AAExD,MAAMC,UAAU,IAAuB,CAAA,CAAC,CAAA;AAExC,MAAMC,WAAW,OAAOC,OAAgCC,OAAOC,IAAI,CAAC,MAAMF,KAAKG,WAAW;AAE1F,MAAMC,kBAAkB,OAAO,EAC7BC,aAAa;IAAEC,GAAG;IAAGC,GAAG;IAAKC,GAAG;AAAI,CAAC,EACrCC,MAAM,EACNC,KAAK,EAKN,GACCjB,MAAM;QAAEkB,QAAQ;YAAEN;YAAYO,UAAU;YAAGH;YAAQC;QAAM;IAAE,GACxDG,GAAG,GACHd,QAAQ;AAEb;;;;CAIC,GACD,MAAMe,oBAAoB,OAAO,EAC/BL,MAAM,EACNM,SAAS,EACTL,KAAK,EAKN;IACC,MAAMM,MAAMf,OAAOgB,KAAK,CAACP,QAAQD,SAAS;IAE1C,IAAK,IAAIS,IAAI,GAAGA,IAAIT,QAAQS,IAAK;QAC/B,IAAK,IAAIC,IAAI,GAAGA,IAAIT,OAAOS,IAAK;YAC9B,MAAMC,MAAM,AAACF,CAAAA,IAAIR,QAAQS,CAAAA,IAAK;YAC9B,MAAME,cAAcN,cAAc,MAAMI,IAAIT,QAAQ,IAAIQ,IAAIT,SAAS;YAErE,IAAIY,aAAa;gBACfL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YACtC,MAAMf,SAAS,MAAMlC,kBAAkBgD;YACvC,MAAM9D,OAAO,IAAI+B,KAAK;gBAACiB;aAAO,EAAE,aAAa;gBAAEhB,MAAM;YAAY;YACjE,MAAMC,gBAAgBpC,oBAAoB;gBAAEqC,iBAAiBzC;YAAM;YAEnE,MAAM0C,SAAS,MAAMF,cAAc;gBACjCjC;gBACAoC,SAAS;oBACPC,kBAAkB,CAAC;oBACnBwB;oBACAG,mBAAmB;wBAAEC,MAAM;wBAASxD,QAAQ;wBAAIC,OAAO;oBAAG;oBAC1D6B,MAAM;oBACNc,oBAAoB;wBAAE5C,QAAQqD,SAASrD,MAAM;wBAAEC,OAAOoD,SAASpD,KAAK;oBAAC;gBACvE;gBACA8B,KAAK1C;YACP;YAEA,MAAM,EAAEyB,IAAI,EAAEC,IAAI,EAAE,GAAG,MAAM/B,MAAM,MAAMM,SAASoC,OAAOnC,IAAI,GAC1DgB,GAAG,GACHjB,QAAQ,CAAC;gBAAE4D,mBAAmB;YAAK;YACtChE,OAAO6B,KAAKd,KAAK,EAAEgC,IAAI,CAAC;YACxB/C,OAAO6B,KAAKf,MAAM,EAAEiC,IAAI,CAAC;YACzB,KAAK,MAAM,EAAEvB,CAAC,EAAED,CAAC,EAAE,IAAI6C,QAAS;gBAC9BpE,OAAO2B,eAAe;oBAAEC;oBAAMC;oBAAML;oBAAGD;gBAAE,IAAI0C,OAAO,CAAC;oBAAEtD,GAAG;oBAAKC,GAAG;oBAAGC,GAAG;gBAAE;YAC5E;QACF;IAEJ;AACF"}
1
+ {"version":3,"sources":["../src/transformFile.spec.ts"],"sourcesContent":["import type { Document, PayloadRequest } from 'payload'\n\nimport sharp from 'sharp'\nimport { describe, expect, it } from 'vitest'\n\nimport type { SharpUploadTaskOptions } from './types.js'\n\nimport { createTransformFile } from './transformFile.js'\n\nconst makeReq = (): PayloadRequest => ({}) as PayloadRequest\n\nconst toBuffer = async (file: File): Promise<Buffer> => Buffer.from(await file.arrayBuffer())\n\nconst makeImageBuffer = async ({\n background = { b: 0, g: 128, r: 255 },\n height,\n width,\n}: {\n background?: { b: number; g: number; r: number }\n height: number\n width: number\n}): Promise<Buffer> =>\n sharp({ create: { background, channels: 3, height, width } })\n .png()\n .toBuffer()\n\n/**\n * A two-colour image split along `splitAxis` (red/blue halves) — proves the\n * focal-point extract region in `transformSize` lands where the math says,\n * not just that the output dimensions are right.\n */\nconst makeTwoColorImage = async ({\n height,\n splitAxis,\n width,\n}: {\n height: number\n splitAxis: 'x' | 'y'\n width: number\n}): Promise<Buffer> => {\n const raw = Buffer.alloc(width * height * 3)\n\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const idx = (y * width + x) * 3\n const isFirstHalf = splitAxis === 'x' ? x < width / 2 : y < height / 2\n\n if (isFirstHalf) {\n raw[idx] = 255 // red\n } else {\n raw[idx + 2] = 255 // blue\n }\n }\n }\n\n return sharp(raw, { raw: { channels: 3, height, width } })\n .png()\n .toBuffer()\n}\n\nconst sampleRawPixel = ({\n data,\n info,\n x,\n y,\n}: {\n data: Buffer\n info: { channels: number; width: number }\n x: number\n y: number\n}): { b: number; g: number; r: number } => {\n const idx = (y * info.width + x) * info.channels\n return { b: data[idx + 2]!, g: data[idx + 1]!, r: data[idx]! }\n}\n\ndescribe('createTransformFile', () => {\n describe('main (transformMain)', () => {\n it('should trim uniform-colour padding from the main file', async () => {\n const square = await makeImageBuffer({\n background: { b: 0, g: 0, r: 0 },\n height: 20,\n width: 20,\n })\n const framed = await sharp({\n create: { background: { b: 255, g: 255, r: 255 }, channels: 3, height: 60, width: 60 },\n })\n .composite([{ input: square, left: 20, top: 20 }])\n .png()\n .toBuffer()\n const file = new File([framed], 'photo.png', { type: 'image/png' })\n const transformFile = createTransformFile({ sharpDependency: sharp })\n\n const result = await transformFile({\n file,\n options: {\n collectionUpload: { trimOptions: {} },\n kind: 'main',\n } satisfies SharpUploadTaskOptions,\n req: makeReq(),\n })\n\n const metadata = await sharp(await toBuffer(result.file!)).metadata()\n expect(metadata.width).toBe(20)\n expect(metadata.height).toBe(20)\n })\n\n it.each([\n // Re-applied by default, so the 40x40 crop is resized down to 20x20.\n { expectedSize: 20, resizeOptions: { fit: 'cover' as const, height: 20, width: 20 } },\n { expectedSize: 40, resizeOptions: { height: 20, width: 20, withoutEnlargement: true } },\n ])(\n 'should re-apply resizeOptions to the crop output unless withoutEnlargement is set (%#)',\n async ({ expectedSize, resizeOptions }) => {\n const buffer = await makeImageBuffer({ height: 100, width: 100 })\n const file = new File([buffer], 'photo.png', { type: 'image/png' })\n const transformFile = createTransformFile({ sharpDependency: sharp })\n\n const result = await transformFile({\n doc: { _transforms: { crop: { height: 40, width: 40, x: 25, y: 25 } } },\n file,\n options: {\n collectionUpload: { resizeOptions },\n kind: 'main',\n originalDimensions: { height: 100, width: 100 },\n } satisfies SharpUploadTaskOptions,\n req: makeReq(),\n })\n\n const metadata = await sharp(await toBuffer(result.file!)).metadata()\n expect(metadata.width).toBe(expectedSize)\n expect(metadata.height).toBe(expectedSize)\n },\n )\n })\n\n describe('main crop', () => {\n const cropMain = async ({\n crop,\n cropSize,\n image,\n }: {\n crop?: { height: number; width: number; x: number; y: number }\n cropSize?: { height: number; width: number }\n image: Buffer\n }) => {\n const transformFile = createTransformFile({ sharpDependency: sharp })\n\n const result = await transformFile({\n doc: crop ? { _transforms: { crop } } : {},\n file: new File([image], 'photo.png', { type: 'image/png' }),\n options: {\n collectionUpload: {},\n cropSize,\n kind: 'main',\n originalDimensions: { height: 10, width: 100 },\n } satisfies SharpUploadTaskOptions,\n req: makeReq(),\n })\n\n return sharp(await toBuffer(result.file!))\n }\n\n it('should start the crop at the saved pixel, not 1px before it', async () => {\n // Red columns 0-28, blue from column 29. The crop is read from `doc._transforms` in pixels,\n // so it starts on the first blue column.\n const blue = await makeImageBuffer({\n background: { b: 255, g: 0, r: 0 },\n height: 10,\n width: 71,\n })\n const image = await sharp({\n create: { background: { b: 0, g: 0, r: 255 }, channels: 3, height: 10, width: 100 },\n })\n .composite([{ input: blue, left: 29, top: 0 }])\n .png()\n .toBuffer()\n\n const cropped = await cropMain({ crop: { height: 10, width: 10, x: 29, y: 0 }, image })\n\n const raw = await cropped.raw().toBuffer({ resolveWithObject: true })\n expect(sampleRawPixel({ ...raw, x: 0, y: 0 })).toEqual({ b: 255, g: 0, r: 0 })\n })\n\n it('should keep a crop inside the image when the request crop size is larger than the saved crop', async () => {\n // The request's `widthInPixels` is 70, and 31 + 70 would pass the right edge of a 100px image.\n const cropped = await cropMain({\n crop: { height: 10, width: 69, x: 31, y: 0 },\n cropSize: { height: 10, width: 70 },\n image: await makeImageBuffer({ height: 10, width: 100 }),\n })\n\n expect((await cropped.metadata()).width).toBe(70)\n })\n\n it('should extract the request crop size from the top-left corner when no crop is saved', async () => {\n // A full-image selection saves no crop, but the request can still send a smaller\n // `widthInPixels`/`heightInPixels` to extract.\n const cropped = await cropMain({\n cropSize: { height: 5, width: 20 },\n image: await makeImageBuffer({ height: 10, width: 100 }),\n })\n\n expect(await cropped.metadata()).toMatchObject({ height: 5, width: 20 })\n })\n })\n\n describe('size (transformSize)', () => {\n // Each original forces one resize-priority branch, and a focal point at 80% pushes the\n // 50px extract window against the clamped far edge, so a correct crop is entirely blue.\n it.each<{\n doc: Document\n original: { height: number; splitAxis: 'x' | 'y'; width: number }\n samples: { x: number; y: number }[]\n }>([\n {\n doc: { _transforms: { focalPoint: { x: 79.6, y: 50 } } },\n original: { height: 100, splitAxis: 'x', width: 200 },\n samples: [\n { x: 10, y: 25 },\n { x: 40, y: 25 },\n ],\n },\n // A document saved before `_transforms` existed has only `focalX`/`focalY`.\n {\n doc: { focalX: 50, focalY: 80 },\n original: { height: 200, splitAxis: 'y', width: 100 },\n samples: [\n { x: 25, y: 10 },\n { x: 25, y: 40 },\n ],\n },\n ])(\n 'should extract the saved focal-point region along the $original.splitAxis axis',\n async ({ doc, original, samples }) => {\n const buffer = await makeTwoColorImage(original)\n const file = new File([buffer], 'photo.png', { type: 'image/png' })\n const transformFile = createTransformFile({ sharpDependency: sharp })\n\n const result = await transformFile({\n doc,\n file,\n options: {\n collectionUpload: {},\n imageResizeConfig: { name: 'thumb', height: 50, width: 50 },\n kind: 'size',\n canUseFocalPoint: true,\n originalDimensions: { height: original.height, width: original.width },\n } satisfies SharpUploadTaskOptions,\n req: makeReq(),\n })\n\n const { data, info } = await sharp(await toBuffer(result.file!))\n .raw()\n .toBuffer({ resolveWithObject: true })\n expect(info.width).toBe(50)\n expect(info.height).toBe(50)\n for (const { x, y } of samples) {\n expect(sampleRawPixel({ data, info, x, y })).toEqual({ b: 255, g: 0, r: 0 })\n }\n },\n )\n\n // A focal point at the center is not saved, so it means \"no focal point\". The size then uses\n // its own `position`: a left-aligned 50px cut of the 100px resize is red. A cut around the\n // center would end on blue.\n it.each<{ doc: Document; name: string }>([\n { name: 'no saved focal point', doc: {} },\n { name: 'a legacy focal point at the center', doc: { focalX: 50, focalY: 50 } },\n ])('should resize with the size config when there is $name', async ({ doc }) => {\n const buffer = await makeTwoColorImage({ height: 100, splitAxis: 'x', width: 200 })\n const transformFile = createTransformFile({ sharpDependency: sharp })\n\n const result = await transformFile({\n doc,\n file: new File([buffer], 'photo.png', { type: 'image/png' }),\n options: {\n canUseFocalPoint: true,\n collectionUpload: {},\n imageResizeConfig: { name: 'thumb', height: 50, position: 'left', width: 50 },\n kind: 'size',\n originalDimensions: { height: 100, width: 200 },\n } satisfies SharpUploadTaskOptions,\n req: makeReq(),\n })\n\n const raw = await sharp(await toBuffer(result.file!))\n .raw()\n .toBuffer({ resolveWithObject: true })\n expect(sampleRawPixel({ ...raw, x: 40, y: 25 })).toEqual({ b: 0, g: 0, r: 255 })\n })\n })\n})\n"],"names":["sharp","describe","expect","it","createTransformFile","makeReq","toBuffer","file","Buffer","from","arrayBuffer","makeImageBuffer","background","b","g","r","height","width","create","channels","png","makeTwoColorImage","splitAxis","raw","alloc","y","x","idx","isFirstHalf","sampleRawPixel","data","info","square","framed","composite","input","left","top","File","type","transformFile","sharpDependency","result","options","collectionUpload","trimOptions","kind","req","metadata","toBe","each","expectedSize","resizeOptions","fit","withoutEnlargement","buffer","doc","_transforms","crop","originalDimensions","cropMain","cropSize","image","blue","cropped","resolveWithObject","toEqual","toMatchObject","focalPoint","original","samples","focalX","focalY","imageResizeConfig","name","canUseFocalPoint","position"],"mappings":"AAEA,OAAOA,WAAW,QAAO;AACzB,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAQ;AAI7C,SAASC,mBAAmB,QAAQ,qBAAoB;AAExD,MAAMC,UAAU,IAAuB,CAAA,CAAC,CAAA;AAExC,MAAMC,WAAW,OAAOC,OAAgCC,OAAOC,IAAI,CAAC,MAAMF,KAAKG,WAAW;AAE1F,MAAMC,kBAAkB,OAAO,EAC7BC,aAAa;IAAEC,GAAG;IAAGC,GAAG;IAAKC,GAAG;AAAI,CAAC,EACrCC,MAAM,EACNC,KAAK,EAKN,GACCjB,MAAM;QAAEkB,QAAQ;YAAEN;YAAYO,UAAU;YAAGH;YAAQC;QAAM;IAAE,GACxDG,GAAG,GACHd,QAAQ;AAEb;;;;CAIC,GACD,MAAMe,oBAAoB,OAAO,EAC/BL,MAAM,EACNM,SAAS,EACTL,KAAK,EAKN;IACC,MAAMM,MAAMf,OAAOgB,KAAK,CAACP,QAAQD,SAAS;IAE1C,IAAK,IAAIS,IAAI,GAAGA,IAAIT,QAAQS,IAAK;QAC/B,IAAK,IAAIC,IAAI,GAAGA,IAAIT,OAAOS,IAAK;YAC9B,MAAMC,MAAM,AAACF,CAAAA,IAAIR,QAAQS,CAAAA,IAAK;YAC9B,MAAME,cAAcN,cAAc,MAAMI,IAAIT,QAAQ,IAAIQ,IAAIT,SAAS;YAErE,IAAIY,aAAa;gBACfL,GAAG,CAACI,IAAI,GAAG,KAAI,MAAM;YACvB,OAAO;gBACLJ,GAAG,CAACI,MAAM,EAAE,GAAG,KAAI,OAAO;YAC5B;QACF;IACF;IAEA,OAAO3B,MAAMuB,KAAK;QAAEA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G+C,IAAI,CAAkC;YACvC;gBAAEwB,MAAM;gBAAwBlB,KAAK,CAAC;YAAE;YACxC;gBAAEkB,MAAM;gBAAsClB,KAAK;oBAAEe,QAAQ;oBAAIC,QAAQ;gBAAG;YAAE;SAC/E,EAAE,0DAA0D,OAAO,EAAEhB,GAAG,EAAE;YACzE,MAAMD,SAAS,MAAMlC,kBAAkB;gBAAEL,QAAQ;gBAAKM,WAAW;gBAAKL,OAAO;YAAI;YACjF,MAAMuB,gBAAgBpC,oBAAoB;gBAAEqC,iBAAiBzC;YAAM;YAEnE,MAAM0C,SAAS,MAAMF,cAAc;gBACjCgB;gBACAjD,MAAM,IAAI+B,KAAK;oBAACiB;iBAAO,EAAE,aAAa;oBAAEhB,MAAM;gBAAY;gBAC1DI,SAAS;oBACPgC,kBAAkB;oBAClB/B,kBAAkB,CAAC;oBACnB6B,mBAAmB;wBAAEC,MAAM;wBAAS1D,QAAQ;wBAAI4D,UAAU;wBAAQ3D,OAAO;oBAAG;oBAC5E6B,MAAM;oBACNa,oBAAoB;wBAAE3C,QAAQ;wBAAKC,OAAO;oBAAI;gBAChD;gBACA8B,KAAK1C;YACP;YAEA,MAAMkB,MAAM,MAAMvB,MAAM,MAAMM,SAASoC,OAAOnC,IAAI,GAC/CgB,GAAG,GACHjB,QAAQ,CAAC;gBAAE2D,mBAAmB;YAAK;YACtC/D,OAAO2B,eAAe;gBAAE,GAAGN,GAAG;gBAAEG,GAAG;gBAAID,GAAG;YAAG,IAAIyC,OAAO,CAAC;gBAAErD,GAAG;gBAAGC,GAAG;gBAAGC,GAAG;YAAI;QAChF;IACF;AACF"}
package/dist/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { FocalPoint, ImageSize, PayloadRequest, ProbedImageSize, UploadCollectionSlug, UploadEdits } from 'payload';
1
+ import type { ImageSize, PayloadRequest, ProbedImageSize, UploadCollectionSlug } from 'payload';
2
2
  import type { FitEnum, ResizeOptions, Sharp, Metadata as SharpMetadata, SharpOptions } from 'sharp';
3
3
  /**
4
4
  * Params sent to the sharp `toFormat()` function
@@ -128,23 +128,33 @@ export type SharpTransformerOptions = {
128
128
  };
129
129
  /**
130
130
  * `options` for the one-file-in/one-file-out `transformFile` primitive, computed
131
- * by `prepareLegacyUpload` for each task it hands to the injected `transform`
132
- * callback: the main file (optionally a crop), or one named legacy image size.
131
+ * by `createTransformUpload` for each task it hands to the injected `transform`
132
+ * callback: the main file, or one named legacy image size. The crop and focal point
133
+ * are not options: `transformFile` reads them from `doc._transforms`.
133
134
  */
134
135
  export type SharpUploadTaskOptions = {
136
+ /**
137
+ * Whether this size may be cut around a focal point: the focal point is enabled, and the
138
+ * size's `fit` allows a cut. `transformFile` cuts around it only when one is saved, and
139
+ * otherwise resizes with the size's own config.
140
+ */
141
+ canUseFocalPoint?: boolean;
135
142
  collectionUpload: SharpCollectionConfig;
136
- crop?: {
137
- cropData: NonNullable<UploadEdits['crop']>;
138
- heightInPixels: number;
139
- originalDimensions: ProbedImageSize;
140
- widthInPixels: number;
141
- };
142
- kind: 'main';
143
- } | {
144
- collectionUpload: SharpCollectionConfig;
145
- focalPoint?: FocalPoint;
146
143
  imageResizeConfig: ImageSize;
147
144
  kind: 'size';
148
145
  originalDimensions: ProbedImageSize;
146
+ } | {
147
+ collectionUpload: SharpCollectionConfig;
148
+ /**
149
+ * The pixel size of a crop sent in the request (`uploadEdits.widthInPixels` and
150
+ * `heightInPixels`). It replaces the saved crop's size for this upload only.
151
+ */
152
+ cropSize?: {
153
+ height: number;
154
+ width: number;
155
+ };
156
+ kind: 'main';
157
+ /** The original's size. Without it, the saved crop cannot be applied. */
158
+ originalDimensions?: ProbedImageSize;
149
159
  };
150
160
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,UAAU,EACV,SAAS,EACT,cAAc,EACd,eAAe,EACf,oBAAoB,EACpB,WAAW,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,MAAM,uBAAuB,GAAG;IACpC,4DAA4D;IAC5D,WAAW,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,oBAAoB,EAAE,qBAAqB,CAAC,CAAC,CAAA;IAC1E;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,OAAO,GAAG,mBAAmB,CAAA;IACvC,6FAA6F;IAC7F,KAAK,CAAC,EAAE,eAAe,CAAA;IACvB,uBAAuB;IACvB,IAAI,CAAC,EAAE,MAAM,CAAA;CACd,CAAA;AAED;;;;;GAKG;AACH,MAAM,MAAM,sBAAsB,GAC9B;IACE;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAA;IAC1B,gBAAgB,EAAE,qBAAqB,CAAA;IACvC,iBAAiB,EAAE,SAAS,CAAA;IAC5B,IAAI,EAAE,MAAM,CAAA;IACZ,kBAAkB,EAAE,eAAe,CAAA;CACpC,GACD;IACE,gBAAgB,EAAE,qBAAqB,CAAA;IACvC;;;OAGG;IACH,QAAQ,CAAC,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAA;IAC5C,IAAI,EAAE,MAAM,CAAA;IACZ,yEAAyE;IACzE,kBAAkB,CAAC,EAAE,eAAe,CAAA;CACrC,CAAA"}
package/dist/types.js CHANGED
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * `options` for the one-file-in/one-file-out `transformFile` primitive, computed
3
- * by `prepareLegacyUpload` for each task it hands to the injected `transform`
4
- * callback: the main file (optionally a crop), or one named legacy image size.
3
+ * by `createTransformUpload` for each task it hands to the injected `transform`
4
+ * callback: the main file, or one named legacy image size. The crop and focal point
5
+ * are not options: `transformFile` reads them from `doc._transforms`.
5
6
  */ export { };
6
7
 
7
8
  //# sourceMappingURL=types.js.map
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type {\n FocalPoint,\n ImageSize,\n PayloadRequest,\n ProbedImageSize,\n UploadCollectionSlug,\n UploadEdits,\n} from 'payload'\nimport type { FitEnum, ResizeOptions, Sharp, Metadata as SharpMetadata, SharpOptions } from 'sharp'\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 WithMetadata =\n | ((options: { metadata: SharpMetadata; req: PayloadRequest }) => Promise<boolean>)\n | boolean\n\n/**\n * Image size options implemented by Payload's default Sharp image processor.\n */\nexport type SharpImageSizeOptions = {\n /**\n * @deprecated prefer position\n */\n crop?: string // comes from sharp package\n formatOptions?: ImageUploadFormatOptions\n trimOptions?: ImageUploadTrimOptions\n /** Image sizes generated for each upload, stored under the document's `variants`. */\n variants?: ImageSize[]\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\ndeclare module 'payload' {\n interface RegisteredImageSizeOptions {\n sharp: SharpImageSizeOptions\n }\n}\n\n/**\n * A collection's Sharp-owned upload-time settings, authored via\n * `sharpTransformer({ collections: { <slug>: {...} } })`. `init()` writes a\n * narrowed, Sharp-agnostic projection of `variants`/`crop`/`focalPoint`\n * back onto the sanitized collection's `upload` config for core's own use (Admin UI,\n * field generation); this richer shape is what the transformer itself reads.\n */\nexport type SharpCollectionConfig = {\n constructorOptions?: SharpOptions\n crop?: boolean\n focalPoint?: boolean\n formatOptions?: ImageUploadFormatOptions\n resizeOptions?: ResizeOptions\n trimOptions?: ImageUploadTrimOptions\n /** Image sizes generated for each upload, stored under the document's `variants`. */\n variants?: ImageSize[]\n withMetadata?: WithMetadata\n}\n\n/**\n * Matches core's (soon-removed) `SharpDependency` shape, for advanced injection\n * of a compatible custom Sharp build or version via `sharpTransformer({ sharp })`.\n */\nexport type SharpDependency = (\n input?:\n | ArrayBuffer\n | Buffer\n | Float32Array\n | Float64Array\n | Int8Array\n | Int16Array\n | Int32Array\n | string\n | Uint8Array\n | Uint8ClampedArray\n | Uint16Array\n | Uint32Array,\n options?: SharpOptions,\n) => Sharp\n\nexport type SharpDynamicDefaults = {\n /** @default 'cover' */\n fit?: keyof FitEnum\n /** @default 4096 */\n maxHeight?: number\n /**\n * Total output pixels, counted across every frame of an animated image.\n * @default 16_777_216\n */\n maxPixels?: number\n /** @default 4096 */\n maxWidth?: number\n /** @default 'center' */\n position?: ResizeOptions['position']\n /** @default false */\n withoutEnlargement?: boolean\n}\n\n/**\n * Enables request-time resizing and tunes its limits. `collections` restricts it\n * to the listed upload collections; omit it to allow every upload collection.\n */\nexport type SharpDynamicOptions = {\n collections?: UploadCollectionSlug[]\n} & SharpDynamicDefaults\n\n/**\n * The result of parsing a request's dynamic resize query parameters.\n * `isRouted: false` means none of the recognized parameters were present at\n * all — an ordinary file read, not a dynamic transformation attempt.\n */\nexport type DynamicResizeParseResult =\n | {\n error: string\n isRouted: true\n valid: false\n }\n | {\n height?: number\n isRouted: true\n valid: true\n width?: number\n withoutEnlargement?: boolean\n }\n | {\n isRouted: false\n }\n\nexport type SharpTransformerOptions = {\n /** Per-collection upload-time image processing settings. */\n collections?: Partial<Record<UploadCollectionSlug, SharpCollectionConfig>>\n /**\n * Request-time resizing via `?width=`/`?height=` on the file endpoint. `true`\n * enables it with default limits for every upload collection; an object enables\n * it with custom limits, optionally restricted to specific collections.\n *\n * @default false\n */\n dynamic?: boolean | SharpDynamicOptions\n /** Inject a compatible custom Sharp build or version. Defaults to the bundled dependency. */\n sharp?: SharpDependency\n /** @default 'sharp' */\n slug?: string\n}\n\n/**\n * `options` for the one-file-in/one-file-out `transformFile` primitive, computed\n * by `prepareLegacyUpload` for each task it hands to the injected `transform`\n * callback: the main file (optionally a crop), or one named legacy image size.\n */\nexport type SharpUploadTaskOptions =\n | {\n collectionUpload: SharpCollectionConfig\n crop?: {\n cropData: NonNullable<UploadEdits['crop']>\n heightInPixels: number\n originalDimensions: ProbedImageSize\n widthInPixels: number\n }\n kind: 'main'\n }\n | {\n collectionUpload: SharpCollectionConfig\n focalPoint?: FocalPoint\n imageResizeConfig: ImageSize\n kind: 'size'\n originalDimensions: ProbedImageSize\n }\n"],"names":[],"mappings":"AAoKA;;;;CAIC,GACD,WAiBK"}
1
+ {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { ImageSize, PayloadRequest, ProbedImageSize, UploadCollectionSlug } from 'payload'\nimport type { FitEnum, ResizeOptions, Sharp, Metadata as SharpMetadata, SharpOptions } from 'sharp'\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 WithMetadata =\n | ((options: { metadata: SharpMetadata; req: PayloadRequest }) => Promise<boolean>)\n | boolean\n\n/**\n * Image size options implemented by Payload's default Sharp image processor.\n */\nexport type SharpImageSizeOptions = {\n /**\n * @deprecated prefer position\n */\n crop?: string // comes from sharp package\n formatOptions?: ImageUploadFormatOptions\n trimOptions?: ImageUploadTrimOptions\n /** Image sizes generated for each upload, stored under the document's `variants`. */\n variants?: ImageSize[]\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\ndeclare module 'payload' {\n interface RegisteredImageSizeOptions {\n sharp: SharpImageSizeOptions\n }\n}\n\n/**\n * A collection's Sharp-owned upload-time settings, authored via\n * `sharpTransformer({ collections: { <slug>: {...} } })`. `init()` writes a\n * narrowed, Sharp-agnostic projection of `variants`/`crop`/`focalPoint`\n * back onto the sanitized collection's `upload` config for core's own use (Admin UI,\n * field generation); this richer shape is what the transformer itself reads.\n */\nexport type SharpCollectionConfig = {\n constructorOptions?: SharpOptions\n crop?: boolean\n focalPoint?: boolean\n formatOptions?: ImageUploadFormatOptions\n resizeOptions?: ResizeOptions\n trimOptions?: ImageUploadTrimOptions\n /** Image sizes generated for each upload, stored under the document's `variants`. */\n variants?: ImageSize[]\n withMetadata?: WithMetadata\n}\n\n/**\n * Matches core's (soon-removed) `SharpDependency` shape, for advanced injection\n * of a compatible custom Sharp build or version via `sharpTransformer({ sharp })`.\n */\nexport type SharpDependency = (\n input?:\n | ArrayBuffer\n | Buffer\n | Float32Array\n | Float64Array\n | Int8Array\n | Int16Array\n | Int32Array\n | string\n | Uint8Array\n | Uint8ClampedArray\n | Uint16Array\n | Uint32Array,\n options?: SharpOptions,\n) => Sharp\n\nexport type SharpDynamicDefaults = {\n /** @default 'cover' */\n fit?: keyof FitEnum\n /** @default 4096 */\n maxHeight?: number\n /**\n * Total output pixels, counted across every frame of an animated image.\n * @default 16_777_216\n */\n maxPixels?: number\n /** @default 4096 */\n maxWidth?: number\n /** @default 'center' */\n position?: ResizeOptions['position']\n /** @default false */\n withoutEnlargement?: boolean\n}\n\n/**\n * Enables request-time resizing and tunes its limits. `collections` restricts it\n * to the listed upload collections; omit it to allow every upload collection.\n */\nexport type SharpDynamicOptions = {\n collections?: UploadCollectionSlug[]\n} & SharpDynamicDefaults\n\n/**\n * The result of parsing a request's dynamic resize query parameters.\n * `isRouted: false` means none of the recognized parameters were present at\n * all — an ordinary file read, not a dynamic transformation attempt.\n */\nexport type DynamicResizeParseResult =\n | {\n error: string\n isRouted: true\n valid: false\n }\n | {\n height?: number\n isRouted: true\n valid: true\n width?: number\n withoutEnlargement?: boolean\n }\n | {\n isRouted: false\n }\n\nexport type SharpTransformerOptions = {\n /** Per-collection upload-time image processing settings. */\n collections?: Partial<Record<UploadCollectionSlug, SharpCollectionConfig>>\n /**\n * Request-time resizing via `?width=`/`?height=` on the file endpoint. `true`\n * enables it with default limits for every upload collection; an object enables\n * it with custom limits, optionally restricted to specific collections.\n *\n * @default false\n */\n dynamic?: boolean | SharpDynamicOptions\n /** Inject a compatible custom Sharp build or version. Defaults to the bundled dependency. */\n sharp?: SharpDependency\n /** @default 'sharp' */\n slug?: string\n}\n\n/**\n * `options` for the one-file-in/one-file-out `transformFile` primitive, computed\n * by `createTransformUpload` for each task it hands to the injected `transform`\n * callback: the main file, or one named legacy image size. The crop and focal point\n * are not options: `transformFile` reads them from `doc._transforms`.\n */\nexport type SharpUploadTaskOptions =\n | {\n /**\n * Whether this size may be cut around a focal point: the focal point is enabled, and the\n * size's `fit` allows a cut. `transformFile` cuts around it only when one is saved, and\n * otherwise resizes with the size's own config.\n */\n canUseFocalPoint?: boolean\n collectionUpload: SharpCollectionConfig\n imageResizeConfig: ImageSize\n kind: 'size'\n originalDimensions: ProbedImageSize\n }\n | {\n collectionUpload: SharpCollectionConfig\n /**\n * The pixel size of a crop sent in the request (`uploadEdits.widthInPixels` and\n * `heightInPixels`). It replaces the saved crop's size for this upload only.\n */\n cropSize?: { height: number; width: number }\n kind: 'main'\n /** The original's size. Without it, the saved crop cannot be applied. */\n originalDimensions?: ProbedImageSize\n }\n"],"names":[],"mappings":"AA6JA;;;;;CAKC,GACD,WAuBK"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/transformer-sharp",
3
- "version": "4.0.0-beta.8",
3
+ "version": "4.0.0-canary.20261117",
4
4
  "description": "Official Sharp-based file transformer for Payload: request-time image resizing and upload-time image processing",
5
5
  "homepage": "https://payloadcms.com",
6
6
  "license": "MIT",
@@ -35,13 +35,13 @@
35
35
  "sharp": "0.35.5"
36
36
  },
37
37
  "devDependencies": {
38
- "payload": "4.0.0-beta.8"
38
+ "payload": "4.0.0-canary.20261117"
39
39
  },
40
40
  "peerDependencies": {
41
- "payload": "4.0.0-beta.8"
41
+ "payload": "4.0.0-canary.20261117"
42
42
  },
43
43
  "engines": {
44
- "node": ">=24.22.1"
44
+ "node": "^24.22.3 || >=26.13.1"
45
45
  },
46
46
  "scripts": {
47
47
  "build": "pnpm build:types && pnpm build:swc",
@@ -1,14 +0,0 @@
1
- import type { UploadTransformerInternal } from 'payload/internal';
2
- import type { SharpCollectionConfig, SharpDependency } from './types.js';
3
- /**
4
- * Computes the legacy upload tasks (the main file, optionally cropped, and every
5
- * configured legacy image size) and hands each to the injected `transform` callback
6
- * exactly once. Reads the Sharp-owned config from `sharpTransformer({ collections })`
7
- * at factory-construction time — not from the sanitized collection, which only gets
8
- * the narrowed projection `init()` writes back.
9
- */
10
- export declare function createPrepareLegacyUpload({ collections, sharpDependency, }: {
11
- collections: Partial<Record<string, SharpCollectionConfig>>;
12
- sharpDependency: SharpDependency;
13
- }): NonNullable<UploadTransformerInternal['prepareUpload']>;
14
- //# sourceMappingURL=prepareLegacyUpload.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"prepareLegacyUpload.d.ts","sourceRoot":"","sources":["../src/prepareLegacyUpload.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAgC,yBAAyB,EAAE,MAAM,kBAAkB,CAAA;AAI/F,OAAO,KAAK,EAAE,qBAAqB,EAAE,eAAe,EAA0B,MAAM,YAAY,CAAA;AAsBhG;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CAAC,EACxC,WAAW,EACX,eAAe,GAChB,EAAE;IACD,WAAW,EAAE,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,qBAAqB,CAAC,CAAC,CAAA;IAC3D,eAAe,EAAE,eAAe,CAAA;CACjC,GAAG,WAAW,CAAC,yBAAyB,CAAC,eAAe,CAAC,CAAC,CAqG1D"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/prepareLegacyUpload.ts"],"sourcesContent":["import type { FocalPoint, ProbedImageSize } from 'payload'\nimport type { PreparedUploadTransformation, UploadTransformerInternal } from 'payload/internal'\n\nimport { isNumber } from 'payload/shared'\n\nimport type { SharpCollectionConfig, SharpDependency, SharpUploadTaskOptions } from './types.js'\n\nimport { canResizeImage } from './canResizeImage.js'\nimport { createSharpFromFile } from './createSharpFromFile.js'\nimport { getImageResizeAction } from './getImageResizeAction.js'\nimport { mapWithBoundedConcurrency } from './mapWithBoundedConcurrency.js'\nimport { sanitizeResizeConfig } from './sanitizeResizeConfig.js'\n\n/**\n * Sharp throws on truncated/header-only files. Returns `undefined` instead —\n * matching core's dependency-free probe — since unreadable dimensions shouldn't fail the upload.\n */\nasync function tryProbe(file: File, sharpDependency: SharpDependency) {\n try {\n const sharpFile = await createSharpFromFile({ file, sharpDependency })\n const metadata = await sharpFile.metadata()\n return metadata.width && metadata.height ? metadata : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Computes the legacy upload tasks (the main file, optionally cropped, and every\n * configured legacy image size) and hands each to the injected `transform` callback\n * exactly once. Reads the Sharp-owned config from `sharpTransformer({ collections })`\n * at factory-construction time — not from the sanitized collection, which only gets\n * the narrowed projection `init()` writes back.\n */\nexport function createPrepareLegacyUpload({\n collections,\n sharpDependency,\n}: {\n collections: Partial<Record<string, SharpCollectionConfig>>\n sharpDependency: SharpDependency\n}): NonNullable<UploadTransformerInternal['prepareUpload']> {\n return async ({ collectionSlug, file, req, transform, uploadEdits }) => {\n const collectionUpload = collections[collectionSlug] ?? {}\n\n const fileSupportsResize = canResizeImage(file.type)\n\n const cropData =\n uploadEdits && typeof uploadEdits === 'object' && 'crop' in uploadEdits\n ? uploadEdits.crop\n : undefined\n\n let originalDimensions: ProbedImageSize | undefined\n\n if (fileSupportsResize) {\n const originalMeta = await tryProbe(file, sharpDependency)\n if (originalMeta) {\n originalDimensions = { height: originalMeta.height, width: originalMeta.width }\n }\n }\n\n // Unreadable dimensions can't be cropped/resized — treat as non-resizable rather than failing the upload.\n const canProcessAsImage = fileSupportsResize && originalDimensions !== undefined\n\n const crop =\n cropData && originalDimensions\n ? {\n cropData,\n heightInPixels: uploadEdits.heightInPixels!,\n originalDimensions,\n widthInPixels: uploadEdits.widthInPixels!,\n }\n : undefined\n\n const mainResultFile = await transform({\n fieldPath: 'filename',\n options: { collectionUpload, crop, kind: 'main' } satisfies SharpUploadTaskOptions,\n })\n\n const mainResult = await describeResult({\n fieldPath: 'filename',\n fileSupportsResize: canProcessAsImage,\n resultFile: mainResultFile,\n sharpDependency,\n })\n\n const results: PreparedUploadTransformation[] = [mainResult]\n\n // Same precedence `init()` applies: Sharp's setting, else the collection's own `focalPoint`.\n const effectiveFocalPoint =\n collectionUpload.focalPoint ??\n req.payload.collections[collectionSlug]?.config.upload?.focalPoint\n const focalPointEnabled = effectiveFocalPoint !== false\n const variants = collectionUpload.variants\n\n if (canProcessAsImage && Array.isArray(variants) && originalDimensions) {\n const focalPoint: FocalPoint | undefined =\n focalPointEnabled && 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 sizeResults = await mapWithBoundedConcurrency(variants, async (rawConfig) => {\n const imageResizeConfig = sanitizeResizeConfig(rawConfig)\n const fieldPath = `variants.${imageResizeConfig.name}` as const\n\n const resizeAction = getImageResizeAction({\n dimensions: originalDimensions,\n hasFocalPoint: Boolean(focalPoint),\n imageResizeConfig,\n })\n\n if (resizeAction === 'omit') {\n return { fieldPath } satisfies PreparedUploadTransformation\n }\n\n const sizeResultFile = await transform({\n fieldPath,\n options: {\n collectionUpload,\n focalPoint: resizeAction === 'resizeWithFocalPoint' ? focalPoint : undefined,\n imageResizeConfig,\n kind: 'size',\n originalDimensions,\n } satisfies SharpUploadTaskOptions,\n })\n\n return describeResult({\n fieldPath,\n fileSupportsResize: true,\n resultFile: sizeResultFile,\n sharpDependency,\n })\n })\n\n results.push(...sizeResults)\n }\n\n return results\n }\n}\n\nasync function describeResult({\n fieldPath,\n fileSupportsResize,\n resultFile,\n sharpDependency,\n}: {\n fieldPath: PreparedUploadTransformation['fieldPath']\n fileSupportsResize: boolean\n resultFile: File\n sharpDependency: SharpDependency\n}): Promise<PreparedUploadTransformation> {\n if (!fileSupportsResize) {\n return { fieldPath, file: resultFile, mimeType: resultFile.type }\n }\n\n const meta = await tryProbe(resultFile, sharpDependency)\n\n if (!meta) {\n return { fieldPath, file: resultFile, mimeType: resultFile.type }\n }\n\n // `tryProbe` never sets `animated: true`, so `meta.height` is already the\n // single-frame height — do not divide by page count here.\n return {\n fieldPath,\n file: resultFile,\n height: meta.height,\n mimeType: resultFile.type,\n width: meta.width,\n }\n}\n"],"names":["isNumber","canResizeImage","createSharpFromFile","getImageResizeAction","mapWithBoundedConcurrency","sanitizeResizeConfig","tryProbe","file","sharpDependency","sharpFile","metadata","width","height","undefined","createPrepareLegacyUpload","collections","collectionSlug","req","transform","uploadEdits","collectionUpload","fileSupportsResize","type","cropData","crop","originalDimensions","originalMeta","canProcessAsImage","heightInPixels","widthInPixels","mainResultFile","fieldPath","options","kind","mainResult","describeResult","resultFile","results","effectiveFocalPoint","focalPoint","payload","config","upload","focalPointEnabled","variants","Array","isArray","x","Math","round","y","sizeResults","rawConfig","imageResizeConfig","name","resizeAction","dimensions","hasFocalPoint","Boolean","sizeResultFile","push","mimeType","meta"],"mappings":"AAGA,SAASA,QAAQ,QAAQ,iBAAgB;AAIzC,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,mBAAmB,QAAQ,2BAA0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T;AACF;AAEA,eAAeF,eAAe,EAC5BJ,SAAS,EACTV,kBAAkB,EAClBe,UAAU,EACV5B,eAAe,EAMhB;IACC,IAAI,CAACa,oBAAoB;QACvB,OAAO;YAAEU;YAAWxB,MAAM6B;YAAYyB,UAAUzB,WAAWd,IAAI;QAAC;IAClE;IAEA,MAAMwC,OAAO,MAAMxD,SAAS8B,YAAY5B;IAExC,IAAI,CAACsD,MAAM;QACT,OAAO;YAAE/B;YAAWxB,MAAM6B;YAAYyB,UAAUzB,WAAWd,IAAI;QAAC;IAClE;IAEA,0EAA0E;IAC1E,0DAA0D;IAC1D,OAAO;QACLS;QACAxB,MAAM6B;QACNxB,QAAQkD,KAAKlD,MAAM;QACnBiD,UAAUzB,WAAWd,IAAI;QACzBX,OAAOmD,KAAKnD,KAAK;IACnB;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/prepareLegacyUpload.spec.ts"],"sourcesContent":["import type { PayloadRequest, UploadEdits } from 'payload'\nimport type { UploadTransformTask } from 'payload/internal'\n\nimport { describe, expect, it, vi } from 'vitest'\n\nimport type { SharpCollectionConfig, SharpDependency, SharpUploadTaskOptions } from './types.js'\n\nimport { createPrepareLegacyUpload } from './prepareLegacyUpload.js'\n\nconst sharpDependency = (() => ({\n metadata: async () => ({ height: 1000, width: 1000 }),\n})) as unknown as SharpDependency\n\nconst makeReq = ({ focalPoint }: { focalPoint?: boolean }): PayloadRequest =>\n ({\n payload: { collections: { media: { config: { upload: { focalPoint } } } } },\n }) as unknown as PayloadRequest\n\nconst runPrepareUpload = async ({\n collectionFocalPoint,\n sharpConfig,\n}: {\n collectionFocalPoint?: boolean\n sharpConfig: SharpCollectionConfig\n}) => {\n const transform = vi.fn(\n async (_task: UploadTransformTask) => new File(['x'], 'image.png', { type: 'image/png' }),\n )\n\n await createPrepareLegacyUpload({ collections: { media: sharpConfig }, sharpDependency })({\n collectionSlug: 'media',\n file: new File(['x'], 'image.png', { type: 'image/png' }),\n req: makeReq({ focalPoint: collectionFocalPoint }),\n transform,\n uploadEdits: { focalPoint: { x: 10, y: 90 } } as UploadEdits,\n })\n\n const sizeTask = transform.mock.calls\n .map(([task]) => task.options as SharpUploadTaskOptions)\n .find((options) => options.kind === 'size')\n\n return sizeTask?.kind === 'size' ? sizeTask.focalPoint : undefined\n}\n\nconst variants = [{ name: 'card', height: 200, width: 400 }]\n\ndescribe('createPrepareLegacyUpload', () => {\n it.each([\n { collectionFocalPoint: false, expected: undefined, sharpFocalPoint: undefined },\n { collectionFocalPoint: false, expected: { x: 10, y: 90 }, sharpFocalPoint: true },\n { collectionFocalPoint: undefined, expected: { x: 10, y: 90 }, sharpFocalPoint: undefined },\n ])(\n 'should resolve the size focal point from Sharp ($sharpFocalPoint) over the collection ($collectionFocalPoint)',\n async ({ collectionFocalPoint, expected, sharpFocalPoint }) => {\n expect(\n await runPrepareUpload({\n collectionFocalPoint,\n sharpConfig: { focalPoint: sharpFocalPoint, variants },\n }),\n ).toEqual(expected)\n },\n )\n})\n"],"names":["describe","expect","it","vi","createPrepareLegacyUpload","sharpDependency","metadata","height","width","makeReq","focalPoint","payload","collections","media","config","upload","runPrepareUpload","collectionFocalPoint","sharpConfig","transform","fn","_task","File","type","collectionSlug","file","req","uploadEdits","x","y","sizeTask","mock","calls","map","task","options","find","kind","undefined","variants","name","each","expected","sharpFocalPoint","toEqual"],"mappings":"AAGA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,EAAEC,EAAE,QAAQ,SAAQ;AAIjD,SAASC,yBAAyB,QAAQ,2BAA0B;AAEpE,MAAMC,kBAAmB,IAAO,CAAA;QAC9BC,UAAU,UAAa,CAAA;gBAAEC,QAAQ;gBAAMC,OAAO;YAAK,CAAA;IACrD,CAAA;AAEA,MAAMC,UAAU,CAAC,EAAEC,UAAU,EAA4B,GACtD,CAAA;QACCC,SAAS;YAAEC,aAAa;gBAAEC,OAAO;oBAAEC,QAAQ;wBAAEC,QAAQ;4BAAEL;wBAAW;oBAAE;gBAA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