@@ -6,6 +6,7 @@ import { rgbToHex, calculateImageSizes, getSrcSet, getSizes } from "./utils"
66import { traceSVG , getImageSizeAsync , base64 , batchQueueImageResizing } from "."
77import sharp from "./safe-sharp"
88import { createTransformObject } from "./plugin-options"
9+ import { reportError } from "./report-error"
910
1011const DEFAULT_BLURRED_IMAGE_WIDTH = 20
1112
@@ -49,7 +50,7 @@ const metadataCache = new Map<string, IImageMetadata>()
4950export async function getImageMetadata (
5051 file : FileNode ,
5152 getDominantColor ?: boolean
52- ) : Promise < IImageMetadata > {
53+ ) : Promise < IImageMetadata | undefined > {
5354 if ( ! getDominantColor ) {
5455 // If we don't need the dominant color we can use the cheaper size function
5556 const { width, height, type } = await getImageSizeAsync ( file )
@@ -59,18 +60,24 @@ export async function getImageMetadata(
5960 if ( metadata && process . env . NODE_ENV !== `test` ) {
6061 return metadata
6162 }
62- const pipeline = sharp ( file . absolutePath )
6363
64- const { width, height, density, format } = await pipeline . metadata ( )
64+ try {
65+ const pipeline = sharp ( file . absolutePath )
6566
66- const { dominant } = await pipeline . stats ( )
67- // Fallback in case sharp doesn't support dominant
68- const dominantColor = dominant
69- ? rgbToHex ( dominant . r , dominant . g , dominant . b )
70- : `#000000`
67+ const { width, height, density, format } = await pipeline . metadata ( )
68+
69+ const { dominant } = await pipeline . stats ( )
70+ // Fallback in case sharp doesn't support dominant
71+ const dominantColor = dominant
72+ ? rgbToHex ( dominant . r , dominant . g , dominant . b )
73+ : `#000000`
74+
75+ metadata = { width, height, density, format, dominantColor }
76+ metadataCache . set ( file . internal . contentDigest , metadata )
77+ } catch ( err ) {
78+ reportError ( `Failed to process image ${ file . absolutePath } ` , err )
79+ }
7180
72- metadata = { width, height, density, format, dominantColor }
73- metadataCache . set ( file . internal . contentDigest , metadata )
7481 return metadata
7582}
7683
@@ -149,7 +156,7 @@ export async function generateImageData({
149156
150157 let primaryFormat : ImageFormat | undefined
151158 if ( useAuto ) {
152- primaryFormat = normalizeFormat ( metadata . format || file . extension )
159+ primaryFormat = normalizeFormat ( metadata ? .format || file . extension )
153160 } else if ( formats . has ( `png` ) ) {
154161 primaryFormat = `png`
155162 } else if ( formats . has ( `jpg` ) ) {
@@ -339,7 +346,7 @@ export async function generateImageData({
339346 imageProps . placeholder = {
340347 fallback,
341348 }
342- } else if ( metadata . dominantColor ) {
349+ } else if ( metadata ? .dominantColor ) {
343350 imageProps . backgroundColor = metadata . dominantColor
344351 }
345352
0 commit comments