Unverified Commit cb8113bb authored by Steven's avatar Steven Committed by GitHub

fix(next/image): handle undefined `images.localPatterns` config in `images-manifest.json` (#70813)

- Backport https://github.com/vercel/next.js/pull/70730 to `14.2.x`
parent 9c1191ab
...@@ -412,6 +412,8 @@ async function writeImagesManifest( ...@@ -412,6 +412,8 @@ async function writeImagesManifest(
const images = { ...config.images } const images = { ...config.images }
const { deviceSizes, imageSizes } = images const { deviceSizes, imageSizes } = images
;(images as any).sizes = [...deviceSizes, ...imageSizes] ;(images as any).sizes = [...deviceSizes, ...imageSizes]
// By default, remotePatterns will allow no remote images ([])
images.remotePatterns = (config?.images?.remotePatterns || []).map((p) => ({ images.remotePatterns = (config?.images?.remotePatterns || []).map((p) => ({
// Modifying the manifest should also modify matchRemotePattern() // Modifying the manifest should also modify matchRemotePattern()
protocol: p.protocol, protocol: p.protocol,
...@@ -420,11 +422,15 @@ async function writeImagesManifest( ...@@ -420,11 +422,15 @@ async function writeImagesManifest(
pathname: makeRe(p.pathname ?? '**', { dot: true }).source, pathname: makeRe(p.pathname ?? '**', { dot: true }).source,
search: p.search, search: p.search,
})) }))
images.localPatterns = (config?.images?.localPatterns || []).map((p) => ({
// Modifying the manifest should also modify matchLocalPattern() // By default, localPatterns will allow all local images (undefined)
pathname: makeRe(p.pathname ?? '**', { dot: true }).source, if (config?.images?.localPatterns) {
search: p.search, images.localPatterns = config.images.localPatterns.map((p) => ({
})) // Modifying the manifest should also modify matchLocalPattern()
pathname: makeRe(p.pathname ?? '**', { dot: true }).source,
search: p.search,
}))
}
await writeManifest(path.join(distDir, IMAGES_MANIFEST), { await writeManifest(path.join(distDir, IMAGES_MANIFEST), {
version: 1, version: 1,
......
...@@ -374,11 +374,18 @@ function assignDefaults( ...@@ -374,11 +374,18 @@ function assignDefaults(
`Specified images.localPatterns should be an Array received ${typeof images.localPatterns}.\nSee more info here: https://nextjs.org/docs/messages/invalid-images-config` `Specified images.localPatterns should be an Array received ${typeof images.localPatterns}.\nSee more info here: https://nextjs.org/docs/messages/invalid-images-config`
) )
} }
// static import images are automatically allowed // avoid double-pushing the same pattern if it already exists
images.localPatterns.push({ const hasMatch = images.localPatterns.some(
pathname: '/_next/static/media/**', (pattern) =>
search: '', pattern.pathname === '/_next/static/media/**' && pattern.search === ''
}) )
if (!hasMatch) {
// static import images are automatically allowed
images.localPatterns.push({
pathname: '/_next/static/media/**',
search: '',
})
}
} }
if (images.remotePatterns) { if (images.remotePatterns) {
...@@ -398,9 +405,9 @@ function assignDefaults( ...@@ -398,9 +405,9 @@ function assignDefaults(
matchRemotePattern(pattern, url) matchRemotePattern(pattern, url)
) )
// avoid double-pushing the same remote if it already can be matched // avoid double-pushing the same pattern if it already can be matched
if (!hasMatchForAssetPrefix) { if (!hasMatchForAssetPrefix) {
images.remotePatterns?.push({ images.remotePatterns.push({
hostname: url.hostname, hostname: url.hostname,
protocol: url.protocol.replace(/:$/, '') as 'http' | 'https', protocol: url.protocol.replace(/:$/, '') as 'http' | 'https',
port: url.port, port: url.port,
......
...@@ -5,6 +5,7 @@ import { ...@@ -5,6 +5,7 @@ import {
assertNoRedbox, assertNoRedbox,
fetchViaHTTP, fetchViaHTTP,
findPort, findPort,
getImagesManifest,
getRedboxHeader, getRedboxHeader,
killApp, killApp,
launchApp, launchApp,
...@@ -64,6 +65,48 @@ function runTests(mode: 'dev' | 'server') { ...@@ -64,6 +65,48 @@ function runTests(mode: 'dev' | 'server') {
expect(res.status).toBe(400) expect(res.status).toBe(400)
} }
}) })
if (mode === 'server') {
it('should build correct images-manifest.json', async () => {
const manifest = getImagesManifest(appDir)
expect(manifest).toEqual({
version: 1,
images: {
contentDispositionType: 'inline',
contentSecurityPolicy:
"script-src 'none'; frame-src 'none'; sandbox;",
dangerouslyAllowSVG: false,
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
disableStaticImages: false,
domains: [],
formats: ['image/webp'],
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
loader: 'default',
loaderFile: '',
remotePatterns: [],
localPatterns: [
{
pathname:
'^(?:\\/assets(?:\\/(?!\\.{1,2}(?:\\/|$))(?:(?:(?!(?:^|\\/)\\.{1,2}(?:\\/|$)).)*?)|$))$',
search: '',
},
{
pathname:
'^(?:\\/_next\\/static\\/media(?:\\/(?!\\.{1,2}(?:\\/|$))(?:(?:(?!(?:^|\\/)\\.{1,2}(?:\\/|$)).)*?)|$))$',
search: '',
},
],
minimumCacheTTL: 60,
path: '/_next/image',
sizes: [
640, 750, 828, 1080, 1200, 1920, 2048, 3840, 16, 32, 48, 64, 96,
128, 256, 384,
],
unoptimized: false,
},
})
})
}
} }
describe('Image localPatterns config', () => { describe('Image localPatterns config', () => {
......
...@@ -6,6 +6,7 @@ import { ...@@ -6,6 +6,7 @@ import {
check, check,
fetchViaHTTP, fetchViaHTTP,
findPort, findPort,
getImagesManifest,
getRedboxHeader, getRedboxHeader,
hasRedbox, hasRedbox,
killApp, killApp,
...@@ -70,7 +71,7 @@ function getRatio(width, height) { ...@@ -70,7 +71,7 @@ function getRatio(width, height) {
return height / width return height / width
} }
function runTests(mode) { function runTests(mode: 'dev' | 'server') {
it('should load the images', async () => { it('should load the images', async () => {
let browser let browser
try { try {
...@@ -1535,6 +1536,37 @@ function runTests(mode) { ...@@ -1535,6 +1536,37 @@ function runTests(mode) {
} }
} }
}) })
if (mode === 'server') {
it('should build correct images-manifest.json', async () => {
const manifest = getImagesManifest(appDir)
expect(manifest).toEqual({
version: 1,
images: {
contentDispositionType: 'inline',
contentSecurityPolicy:
"script-src 'none'; frame-src 'none'; sandbox;",
dangerouslyAllowSVG: false,
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
disableStaticImages: false,
domains: [],
formats: ['image/webp'],
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
loader: 'default',
loaderFile: '',
remotePatterns: [],
localPatterns: undefined,
minimumCacheTTL: 60,
path: '/_next/image',
sizes: [
640, 750, 828, 1080, 1200, 1920, 2048, 3840, 16, 32, 48, 64, 96,
128, 256, 384,
],
unoptimized: false,
},
})
})
}
} }
describe('Image Component Default Tests', () => { describe('Image Component Default Tests', () => {
......
...@@ -4,6 +4,7 @@ import { join } from 'path' ...@@ -4,6 +4,7 @@ import { join } from 'path'
import { import {
check, check,
findPort, findPort,
getImagesManifest,
killApp, killApp,
launchApp, launchApp,
nextBuild, nextBuild,
...@@ -15,7 +16,7 @@ const appDir = join(__dirname, '../') ...@@ -15,7 +16,7 @@ const appDir = join(__dirname, '../')
let appPort let appPort
let app let app
function runTests(url: string) { function runTests(url: string, mode: 'dev' | 'server') {
it('should not optimize any image', async () => { it('should not optimize any image', async () => {
const browser = await webdriver(appPort, url) const browser = await webdriver(appPort, url)
expect( expect(
...@@ -89,6 +90,37 @@ function runTests(url: string) { ...@@ -89,6 +90,37 @@ function runTests(url: string) {
await browser.elementById('eager-image').getAttribute('srcset') await browser.elementById('eager-image').getAttribute('srcset')
).toBeNull() ).toBeNull()
}) })
if (mode === 'server') {
it('should build correct images-manifest.json', async () => {
const manifest = getImagesManifest(appDir)
expect(manifest).toEqual({
version: 1,
images: {
contentDispositionType: 'inline',
contentSecurityPolicy:
"script-src 'none'; frame-src 'none'; sandbox;",
dangerouslyAllowSVG: false,
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
disableStaticImages: false,
domains: [],
formats: ['image/webp'],
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
loader: 'default',
loaderFile: '',
remotePatterns: [],
localPatterns: undefined,
minimumCacheTTL: 60,
path: '/_next/image',
sizes: [
640, 750, 828, 1080, 1200, 1920, 2048, 3840, 16, 32, 48, 64, 96,
128, 256, 384,
],
unoptimized: true,
},
})
})
}
} }
describe('Unoptimized Image Tests', () => { describe('Unoptimized Image Tests', () => {
...@@ -101,7 +133,7 @@ describe('Unoptimized Image Tests', () => { ...@@ -101,7 +133,7 @@ describe('Unoptimized Image Tests', () => {
await killApp(app) await killApp(app)
}) })
runTests('/') runTests('/', 'dev')
}) })
;(process.env.TURBOPACK_DEV ? describe.skip : describe)( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode - component', 'production mode - component',
...@@ -115,7 +147,7 @@ describe('Unoptimized Image Tests', () => { ...@@ -115,7 +147,7 @@ describe('Unoptimized Image Tests', () => {
await killApp(app) await killApp(app)
}) })
runTests('/') runTests('/', 'server')
} }
) )
describe('development mode - getImageProps', () => { describe('development mode - getImageProps', () => {
...@@ -127,7 +159,7 @@ describe('Unoptimized Image Tests', () => { ...@@ -127,7 +159,7 @@ describe('Unoptimized Image Tests', () => {
await killApp(app) await killApp(app)
}) })
runTests('/get-img-props') runTests('/get-img-props', 'dev')
}) })
;(process.env.TURBOPACK_DEV ? describe.skip : describe)( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode - getImageProps', 'production mode - getImageProps',
...@@ -141,7 +173,7 @@ describe('Unoptimized Image Tests', () => { ...@@ -141,7 +173,7 @@ describe('Unoptimized Image Tests', () => {
await killApp(app) await killApp(app)
}) })
runTests('/get-img-props') runTests('/get-img-props', 'server')
} }
) )
}) })
...@@ -964,6 +964,10 @@ export function getBuildManifest(dir: string) { ...@@ -964,6 +964,10 @@ export function getBuildManifest(dir: string) {
return readJson(path.join(dir, '.next/build-manifest.json')) return readJson(path.join(dir, '.next/build-manifest.json'))
} }
export function getImagesManifest(dir: string) {
return readJson(path.join(dir, '.next/images-manifest.json'))
}
export function getPageFileFromBuildManifest(dir: string, page: string) { export function getPageFileFromBuildManifest(dir: string, page: string) {
const buildManifest = getBuildManifest(dir) const buildManifest = getBuildManifest(dir)
const pageFiles = buildManifest.pages[page] const pageFiles = buildManifest.pages[page]
......
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