Unverified Commit 12e173dd authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[16.3.x] Re-enable AVIF image optimization and require sharp 0.35.4 (#97949)

parent 5d9022ed
...@@ -130,7 +130,7 @@ ...@@ -130,7 +130,7 @@
} }
}, },
"optionalDependencies": { "optionalDependencies": {
"sharp": "^0.35.3" "sharp": "^0.35.4"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "7.26.10", "@babel/core": "7.26.10",
......
...@@ -3,7 +3,7 @@ import { optimizeImage } from '../../../../server/image-optimizer' ...@@ -3,7 +3,7 @@ import { optimizeImage } from '../../../../server/image-optimizer'
const BLUR_IMG_SIZE = 8 const BLUR_IMG_SIZE = 8
const BLUR_QUALITY = 70 const BLUR_QUALITY = 70
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp'] // should match other usages const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match other usages
export async function getBlurImage( export async function getBlurImage(
content: Buffer, content: Buffer,
......
...@@ -748,7 +748,6 @@ export default function Image({ ...@@ -748,7 +748,6 @@ export default function Image({
} }
let staticSrc = '' let staticSrc = ''
let isStaticAvif = false
if (isStaticImport(src)) { if (isStaticImport(src)) {
const staticImageData = isStaticRequire(src) ? src.default : src const staticImageData = isStaticRequire(src) ? src.default : src
...@@ -761,7 +760,6 @@ export default function Image({ ...@@ -761,7 +760,6 @@ export default function Image({
} }
blurDataURL = blurDataURL || staticImageData.blurDataURL blurDataURL = blurDataURL || staticImageData.blurDataURL
staticSrc = staticImageData.src staticSrc = staticImageData.src
isStaticAvif = /\.avif(?:\?|$)/i.test(staticSrc)
if (!layout || layout !== 'fill') { if (!layout || layout !== 'fill') {
height = height || staticImageData.height height = height || staticImageData.height
width = width || staticImageData.width width = width || staticImageData.width
...@@ -776,12 +774,6 @@ export default function Image({ ...@@ -776,12 +774,6 @@ export default function Image({
} }
src = typeof src === 'string' ? src : staticSrc src = typeof src === 'string' ? src : staticSrc
// Generating a blurDataURL requires decoding the source image, so static AVIF
// imports do not receive one while AVIF input optimization is disabled.
if (isStaticAvif && placeholder === 'blur' && !blurDataURL) {
placeholder = 'empty'
}
warnOnce( warnOnce(
`Image with src "${src}" is using next/legacy/image which is deprecated and will be removed in a future version of Next.js.` `Image with src "${src}" is using next/legacy/image which is deprecated and will be removed in a future version of Next.js.`
) )
...@@ -916,7 +908,7 @@ export default function Image({ ...@@ -916,7 +908,7 @@ export default function Image({
) )
} }
if (!blurDataURL) { if (!blurDataURL) {
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp'] // should match next-image-loader const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match next-image-loader
throw new Error( throw new Error(
`Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property. `Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property.
......
...@@ -54,7 +54,7 @@ const BMP = 'image/bmp' ...@@ -54,7 +54,7 @@ const BMP = 'image/bmp'
const PDF = 'application/pdf' const PDF = 'application/pdf'
const CACHE_VERSION = 4 const CACHE_VERSION = 4
const ANIMATABLE_TYPES = [WEBP, PNG, GIF] const ANIMATABLE_TYPES = [WEBP, PNG, GIF]
const BYPASS_TYPES = [SVG, ICO, ICNS, BMP, JXL, HEIC, AVIF] const BYPASS_TYPES = [SVG, ICO, ICNS, BMP, JXL, HEIC]
const BLUR_IMG_SIZE = 8 // should match `next-image-loader` const BLUR_IMG_SIZE = 8 // should match `next-image-loader`
const BLUR_QUALITY = 70 // should match `next-image-loader` const BLUR_QUALITY = 70 // should match `next-image-loader`
...@@ -95,6 +95,7 @@ export function getSharp( ...@@ -95,6 +95,7 @@ export function getSharp(
_sharp.block({ operation: ['VipsForeignLoad'] }) _sharp.block({ operation: ['VipsForeignLoad'] })
_sharp.unblock({ _sharp.unblock({
operation: [ operation: [
'VipsForeignLoadHeif', // avif
'VipsForeignLoadJpeg', 'VipsForeignLoadJpeg',
'VipsForeignLoadNsgif', 'VipsForeignLoadNsgif',
'VipsForeignLoadPng', 'VipsForeignLoadPng',
......
...@@ -398,7 +398,6 @@ export function getImgProps( ...@@ -398,7 +398,6 @@ export function getImgProps(
let heightInt = getInt(height) let heightInt = getInt(height)
let blurWidth: number | undefined let blurWidth: number | undefined
let blurHeight: number | undefined let blurHeight: number | undefined
let isStaticAvif = false
if (isStaticImport(src)) { if (isStaticImport(src)) {
const staticImageData = isStaticRequire(src) ? src.default : src const staticImageData = isStaticRequire(src) ? src.default : src
...@@ -421,7 +420,6 @@ export function getImgProps( ...@@ -421,7 +420,6 @@ export function getImgProps(
blurHeight = staticImageData.blurHeight blurHeight = staticImageData.blurHeight
blurDataURL = blurDataURL || staticImageData.blurDataURL blurDataURL = blurDataURL || staticImageData.blurDataURL
staticSrc = staticImageData.src staticSrc = staticImageData.src
isStaticAvif = /\.avif(?:\?|$)/i.test(staticSrc)
if (!fill) { if (!fill) {
if (!widthInt && !heightInt) { if (!widthInt && !heightInt) {
...@@ -438,12 +436,6 @@ export function getImgProps( ...@@ -438,12 +436,6 @@ export function getImgProps(
} }
src = typeof src === 'string' ? src : staticSrc src = typeof src === 'string' ? src : staticSrc
// Generating a blurDataURL requires decoding the source image, so static AVIF
// imports do not receive one while AVIF input optimization is disabled.
if (isStaticAvif && placeholder === 'blur' && !blurDataURL) {
placeholder = 'empty'
}
let isLazy = let isLazy =
!priority && !priority &&
!preload && !preload &&
...@@ -594,7 +586,7 @@ export function getImgProps( ...@@ -594,7 +586,7 @@ export function getImgProps(
) )
} }
if (placeholder === 'blur' && !blurDataURL) { if (placeholder === 'blur' && !blurDataURL) {
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp'] // should match next-image-loader const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match next-image-loader
throw new Error( throw new Error(
`Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property. `Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property.
......
This diff is collapsed.
...@@ -52,4 +52,5 @@ minimumReleaseAgeExclude: ...@@ -52,4 +52,5 @@ minimumReleaseAgeExclude:
- react-is - react-is
- react-server-dom-* - react-server-dom-*
- scheduler - scheduler
- sharp@0.35.4
- turbo - turbo
import fs from 'fs-extra'
import { join } from 'path'
import { optimizeImage } from 'next/dist/server/image-optimizer'
import { setupTests } from './util' import { setupTests } from './util'
describe('with latest sharp', () => { describe('with latest sharp', () => {
it('should block avif decoding below the optimizer bypass', async () => {
const buffer = await fs.readFile(join(__dirname, 'app/public/test.avif'))
await expect(
optimizeImage({
buffer,
contentType: 'image/webp',
quality: 75,
width: 100,
})
).rejects.toThrow()
})
setupTests({}) setupTests({})
}) })
...@@ -122,15 +122,6 @@ export async function expectWidth(res, w, { expectAnimated = false } = {}) { ...@@ -122,15 +122,6 @@ export async function expectWidth(res, w, { expectAnimated = false } = {}) {
expect(isAnimated(buffer)).toBe(expectAnimated) expect(isAnimated(buffer)).toBe(expectAnimated)
} }
async function expectUnoptimizedImage(res, filename: string) {
const buffer = Buffer.from(await res.arrayBuffer())
const source = await fs.readFile(join(__dirname, 'app/public', filename))
expect(buffer).toEqual(source)
expect(res.headers.get('Content-Length')).toBe(
Buffer.byteLength(source).toString()
)
}
export const cleanImagesDir = async (imagesDir) => { export const cleanImagesDir = async (imagesDir) => {
console.warn('Cleaning', imagesDir) console.warn('Cleaning', imagesDir)
await fs.remove(imagesDir) await fs.remove(imagesDir)
...@@ -614,23 +605,23 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -614,23 +605,23 @@ export function runTests(ctx: RunTestsCtx) {
await expectWidth(res, ctx.w) await expectWidth(res, ctx.w)
}) })
it('should bypass avif input for old Safari', async () => { it('should downlevel avif format to jpeg for old Safari', async () => {
const accept = const accept =
'image/png,image/svg+xml,image/*;q=0.8,video/*;q=0.8,*/*;q=0.5' 'image/png,image/svg+xml,image/*;q=0.8,video/*;q=0.8,*/*;q=0.5'
const query = { w: ctx.w, q: ctx.q, url: '/test.avif' } const query = { w: ctx.w, q: ctx.q, url: '/test.avif' }
const opts = { headers: { accept } } const opts = { headers: { accept } }
const res = await next.fetch(`/_next/image?${toQueryString(query)}`, opts) const res = await next.fetch(`/_next/image?${toQueryString(query)}`, opts)
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toContain('image/avif') expect(res.headers.get('Content-Type')).toContain('image/jpeg')
expect(res.headers.get('Cache-Control')).toBe( expect(res.headers.get('Cache-Control')).toBe(
`public, max-age=${isDev ? 0 : minimumCacheTTL}, must-revalidate` `public, max-age=${isDev ? 0 : minimumCacheTTL}, must-revalidate`
) )
expect(res.headers.get('Vary')).toBe('Accept') expect(res.headers.get('Vary')).toBe('Accept')
expect(res.headers.get('etag')).toBeTruthy() expect(res.headers.get('etag')).toBeTruthy()
expect(res.headers.get('Content-Disposition')).toBe( expect(res.headers.get('Content-Disposition')).toBe(
`${contentDispositionType}; filename="test.avif"` `${contentDispositionType}; filename="test.jpeg"`
) )
await expectUnoptimizedImage(res, 'test.avif') await expectWidth(res, ctx.w)
}) })
it('should fail when url is missing', async () => { it('should fail when url is missing', async () => {
...@@ -941,21 +932,21 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -941,21 +932,21 @@ export function runTests(ctx: RunTestsCtx) {
await expectWidth(res, ctx.w) await expectWidth(res, ctx.w)
}) })
it('should bypass optimization for avif input', async () => { it('should resize avif', async () => {
const query = { url: '/test.avif', w: ctx.w, q: ctx.q } const query = { url: '/test.avif', w: ctx.w, q: ctx.q }
const opts = { headers: { accept: 'image/webp' } } const opts = { headers: { accept: 'image/webp' } }
const res = await next.fetch(`/_next/image?${toQueryString(query)}`, opts) const res = await next.fetch(`/_next/image?${toQueryString(query)}`, opts)
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('image/avif') expect(res.headers.get('Content-Type')).toBe('image/webp')
expect(res.headers.get('Cache-Control')).toBe( expect(res.headers.get('Cache-Control')).toBe(
`public, max-age=${isDev ? 0 : minimumCacheTTL}, must-revalidate` `public, max-age=${isDev ? 0 : minimumCacheTTL}, must-revalidate`
) )
expect(res.headers.get('Vary')).toBe('Accept') expect(res.headers.get('Vary')).toBe('Accept')
expect(res.headers.get('etag')).toBeTruthy() expect(res.headers.get('etag')).toBeTruthy()
expect(res.headers.get('Content-Disposition')).toBe( expect(res.headers.get('Content-Disposition')).toBe(
`${contentDispositionType}; filename="test.avif"` `${contentDispositionType}; filename="test.webp"`
) )
await expectUnoptimizedImage(res, 'test.avif') await expectWidth(res, ctx.w)
}) })
it('should resize relative url and old Chrome accept header as webp', async () => { it('should resize relative url and old Chrome accept header as webp', async () => {
...@@ -999,7 +990,7 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -999,7 +990,7 @@ export function runTests(ctx: RunTestsCtx) {
await expectWidth(res, ctx.w) await expectWidth(res, ctx.w)
}) })
it('should bypass avif input when avif output is enabled', async () => { it('should resize avif and maintain format', async () => {
const query = { url: '/test.avif', w: ctx.w, q: ctx.q } const query = { url: '/test.avif', w: ctx.w, q: ctx.q }
const opts = { headers: { accept: 'image/avif' } } const opts = { headers: { accept: 'image/avif' } }
const res = await next.fetch(`/_next/image?${toQueryString(query)}`, opts) const res = await next.fetch(`/_next/image?${toQueryString(query)}`, opts)
...@@ -1013,7 +1004,7 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -1013,7 +1004,7 @@ export function runTests(ctx: RunTestsCtx) {
expect(res.headers.get('Content-Disposition')).toBe( expect(res.headers.get('Content-Disposition')).toBe(
`${contentDispositionType}; filename="test.avif"` `${contentDispositionType}; filename="test.avif"`
) )
await expectUnoptimizedImage(res, 'test.avif') await expectWidth(res, ctx.w)
}) })
it('should compress avif smaller than webp at q=100', async () => { it('should compress avif smaller than webp at q=100', async () => {
......
...@@ -90,36 +90,6 @@ describe('getImageProps()', () => { ...@@ -90,36 +90,6 @@ describe('getImageProps()', () => {
expect(props.srcSet).toBeString() expect(props.srcSet).toBeString()
}) })
it('should disable an automatic blur placeholder for a static avif', () => {
const { props } = getImageProps({
alt: 'a nice desc',
src: {
src: '/_next/static/media/test.abc123.avif',
width: 100,
height: 200,
},
placeholder: 'blur',
})
expect(props.style).toStrictEqual({ color: 'transparent' })
})
it('should preserve a custom blur placeholder for a static avif', () => {
const blurDataURL = 'data:image/png;base64,custom'
const { props } = getImageProps({
alt: 'a nice desc',
src: {
src: '/_next/static/media/test.abc123.avif',
width: 100,
height: 200,
},
placeholder: 'blur',
blurDataURL,
})
expect(props.style?.backgroundImage).toContain(blurDataURL)
})
it('should handle preload', async () => { it('should handle preload', async () => {
const { props } = getImageProps({ const { props } = getImageProps({
alt: 'a nice desc', alt: 'a nice desc',
......
...@@ -103,40 +103,6 @@ describe('Image Legacy Rendering', () => { ...@@ -103,40 +103,6 @@ describe('Image Legacy Rendering', () => {
expect($3('noscript').length).toBe(1) expect($3('noscript').length).toBe(1)
}) })
it('should disable an automatic blur placeholder for a static avif', () => {
const element = React.createElement(Image, {
src: {
src: '/_next/static/media/test.abc123.avif',
width: 100,
height: 200,
},
placeholder: 'blur',
loading: 'eager',
})
const $ = cheerio.load(ReactDOM.renderToString(element))
expect($('noscript').length).toBe(0)
expect($.html()).not.toContain('background-image')
})
it('should preserve a custom blur placeholder for a static avif', () => {
const blurDataURL = 'data:image/png;base64,custom'
const element = React.createElement(Image, {
src: {
src: '/_next/static/media/test.abc123.avif',
width: 100,
height: 200,
},
placeholder: 'blur',
blurDataURL,
loading: 'eager',
})
const $ = cheerio.load(ReactDOM.renderToString(element))
expect($('noscript').length).toBe(1)
expect($.html()).toContain(blurDataURL)
})
it('should render the correct sizes passed when a noscript element is rendered', async () => { it('should render the correct sizes passed when a noscript element is rendered', async () => {
const element = React.createElement(Image, { const element = React.createElement(Image, {
src: '/test.png', src: '/test.png',
......
...@@ -35,22 +35,4 @@ describe('getBlurImage', () => { ...@@ -35,22 +35,4 @@ describe('getBlurImage', () => {
expect(result).toBeObject() expect(result).toBeObject()
expect(result.dataURL).toBeUndefined() expect(result.dataURL).toBeUndefined()
}) })
it('should not generate a blur placeholder for avif', async () => {
const buffer = await getImage('../image-optimizer/images/test.avif')
const result = await getBlurImage(
buffer,
'avif',
{ width: 400, height: 400 },
{
...context,
outputPath: '/_next/static/media/test.avif',
}
)
expect(result).toBeObject()
expect(result).toStrictEqual({
dataURL: undefined,
width: 0,
height: 0,
})
})
}) })
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment