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

feat(next/image): add `images.localPatterns` config (#70802)

- Backport https://github.com/vercel/next.js/pull/70529 to `14.2.x`
parent 540ea2d8
...@@ -89,6 +89,21 @@ export default function Page() { ...@@ -89,6 +89,21 @@ export default function Page() {
> **Warning:** Dynamic `await import()` or `require()` are _not_ supported. The `import` must be static so it can be analyzed at build time. > **Warning:** Dynamic `await import()` or `require()` are _not_ supported. The `import` must be static so it can be analyzed at build time.
You can optionally configure `localPatterns` in your `next.config.js` file in order to allow specific images and block all others.
```js filename="next.config.js"
module.exports = {
images: {
localPatterns: [
{
pathname: '/assets/images/**',
search: '',
},
],
},
}
```
### Remote Images ### Remote Images
To use a remote image, the `src` property should be a URL string. To use a remote image, the `src` property should be a URL string.
......
...@@ -484,6 +484,25 @@ Other properties on the `<Image />` component will be passed to the underlying ...@@ -484,6 +484,25 @@ Other properties on the `<Image />` component will be passed to the underlying
In addition to props, you can configure the Image Component in `next.config.js`. The following options are available: In addition to props, you can configure the Image Component in `next.config.js`. The following options are available:
## `localPatterns`
You can optionally configure `localPatterns` in your `next.config.js` file in order to allow specific paths to be optimized and block all others paths.
```js filename="next.config.js"
module.exports = {
images: {
localPatterns: [
{
pathname: '/assets/images/**',
search: '',
},
],
},
}
```
> **Good to know**: The example above will ensure the `src` property of `next/image` must start with `/assets/images/` and must not have a query string. Attempting to optimize any other path will respond with 400 Bad Request.
### `remotePatterns` ### `remotePatterns`
To protect your application from malicious users, configuration is required in order to use external images. This ensures that only external images from your account can be served from the Next.js Image Optimization API. These external images can be configured with the `remotePatterns` property in your `next.config.js` file, as shown below: To protect your application from malicious users, configuration is required in order to use external images. This ensures that only external images from your account can be served from the Next.js Image Optimization API. These external images can be configured with the `remotePatterns` property in your `next.config.js` file, as shown below:
......
...@@ -37,6 +37,8 @@ module.exports = { ...@@ -37,6 +37,8 @@ module.exports = {
contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;", contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
// sets the Content-Disposition header (inline or attachment) // sets the Content-Disposition header (inline or attachment)
contentDispositionType: 'inline', contentDispositionType: 'inline',
// limit of 25 objects
localPatterns: [],
// limit of 50 objects // limit of 50 objects
remotePatterns: [], remotePatterns: [],
// when true, every image will be unoptimized // when true, every image will be unoptimized
......
---
title: '`next/image` Un-configured localPatterns'
---
## Why This Error Occurred
One of your pages that leverages the `next/image` component, passed a `src` value that uses a URL that isn't defined in the `images.localPatterns` property in `next.config.js`.
## Possible Ways to Fix It
Add an entry to `images.localPatterns` array in `next.config.js` with the expected URL pattern. For example:
```js filename="next.config.js"
module.exports = {
images: {
localPatterns: [
{
pathname: '/assets/**',
search: '',
},
],
},
}
```
## Useful Links
- [Image Optimization Documentation](/docs/pages/building-your-application/optimizing/images)
- [Local Patterns Documentation](/docs/pages/api-reference/components/image#localpatterns)
...@@ -420,6 +420,11 @@ async function writeImagesManifest( ...@@ -420,6 +420,11 @@ 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()
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,
...@@ -1885,18 +1890,18 @@ export default async function build( ...@@ -1885,18 +1890,18 @@ export default async function build(
config.experimental.gzipSize config.experimental.gzipSize
) )
const middlewareManifest: MiddlewareManifest = require(path.join( const middlewareManifest: MiddlewareManifest = require(
distDir, path.join(distDir, SERVER_DIRECTORY, MIDDLEWARE_MANIFEST)
SERVER_DIRECTORY, )
MIDDLEWARE_MANIFEST
))
const actionManifest = appDir const actionManifest = appDir
? (require(path.join( ? (require(
path.join(
distDir, distDir,
SERVER_DIRECTORY, SERVER_DIRECTORY,
SERVER_REFERENCE_MANIFEST + '.json' SERVER_REFERENCE_MANIFEST + '.json'
)) as ActionManifest) )
) as ActionManifest)
: null : null
const entriesWithAction = actionManifest ? new Set() : null const entriesWithAction = actionManifest ? new Set() : null
if (actionManifest && entriesWithAction) { if (actionManifest && entriesWithAction) {
......
...@@ -117,6 +117,7 @@ function getImageConfig( ...@@ -117,6 +117,7 @@ function getImageConfig(
// pass domains in development to allow validating on the client // pass domains in development to allow validating on the client
domains: config.images.domains, domains: config.images.domains,
remotePatterns: config.images?.remotePatterns, remotePatterns: config.images?.remotePatterns,
localPatterns: config.images?.localPatterns,
output: config.output, output: config.output,
} }
: {}), : {}),
......
...@@ -139,6 +139,25 @@ function defaultLoader({ ...@@ -139,6 +139,25 @@ function defaultLoader({
) )
} }
if (src.startsWith('/') && config.localPatterns) {
if (
process.env.NODE_ENV !== 'test' &&
// micromatch isn't compatible with edge runtime
process.env.NEXT_RUNTIME !== 'edge'
) {
// We use dynamic require because this should only error in development
const {
hasLocalMatch,
} = require('../../shared/lib/match-local-pattern')
if (!hasLocalMatch(config.localPatterns, src)) {
throw new Error(
`Invalid src prop (${src}) on \`next/image\` does not match \`images.localPatterns\` configured in your \`next.config.js\`\n` +
`See more info: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns`
)
}
}
}
if (!src.startsWith('/') && (config.domains || config.remotePatterns)) { if (!src.startsWith('/') && (config.domains || config.remotePatterns)) {
let parsedSrc: URL let parsedSrc: URL
try { try {
...@@ -156,8 +175,10 @@ function defaultLoader({ ...@@ -156,8 +175,10 @@ function defaultLoader({
process.env.NEXT_RUNTIME !== 'edge' process.env.NEXT_RUNTIME !== 'edge'
) { ) {
// We use dynamic require because this should only error in development // We use dynamic require because this should only error in development
const { hasMatch } = require('../../shared/lib/match-remote-pattern') const {
if (!hasMatch(config.domains, config.remotePatterns, parsedSrc)) { hasRemoteMatch,
} = require('../../shared/lib/match-remote-pattern')
if (!hasRemoteMatch(config.domains, config.remotePatterns, parsedSrc)) {
throw new Error( throw new Error(
`Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` + `Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` +
`See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host` `See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host`
......
...@@ -461,6 +461,15 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -461,6 +461,15 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.optional(), .optional(),
images: z images: z
.strictObject({ .strictObject({
localPatterns: z
.array(
z.strictObject({
pathname: z.string().optional(),
search: z.string().optional(),
})
)
.max(25)
.optional(),
remotePatterns: z remotePatterns: z
.array( .array(
z.strictObject({ z.strictObject({
......
...@@ -368,6 +368,19 @@ function assignDefaults( ...@@ -368,6 +368,19 @@ function assignDefaults(
) )
} }
if (images.localPatterns) {
if (!Array.isArray(images.localPatterns)) {
throw new Error(
`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
images.localPatterns.push({
pathname: '/_next/static/media/**',
search: '',
})
}
if (images.remotePatterns) { if (images.remotePatterns) {
if (!Array.isArray(images.remotePatterns)) { if (!Array.isArray(images.remotePatterns)) {
throw new Error( throw new Error(
......
...@@ -12,7 +12,8 @@ import nodeUrl, { type UrlWithParsedQuery } from 'url' ...@@ -12,7 +12,8 @@ import nodeUrl, { type UrlWithParsedQuery } from 'url'
import { getImageBlurSvg } from '../shared/lib/image-blur-svg' import { getImageBlurSvg } from '../shared/lib/image-blur-svg'
import type { ImageConfigComplete } from '../shared/lib/image-config' import type { ImageConfigComplete } from '../shared/lib/image-config'
import { hasMatch } from '../shared/lib/match-remote-pattern' import { hasLocalMatch } from '../shared/lib/match-local-pattern'
import { hasRemoteMatch } from '../shared/lib/match-remote-pattern'
import type { NextConfigComplete } from './config-shared' import type { NextConfigComplete } from './config-shared'
import { createRequestResponseMocks } from './lib/mock-request' import { createRequestResponseMocks } from './lib/mock-request'
// Do not import anything other than types from this module // Do not import anything other than types from this module
...@@ -173,6 +174,7 @@ export class ImageOptimizerCache { ...@@ -173,6 +174,7 @@ export class ImageOptimizerCache {
formats = ['image/webp'], formats = ['image/webp'],
} = imageData } = imageData
const remotePatterns = nextConfig.images?.remotePatterns || [] const remotePatterns = nextConfig.images?.remotePatterns || []
const localPatterns = nextConfig.images?.localPatterns
const { url, w, q } = query const { url, w, q } = query
let href: string let href: string
...@@ -212,6 +214,9 @@ export class ImageOptimizerCache { ...@@ -212,6 +214,9 @@ export class ImageOptimizerCache {
errorMessage: '"url" parameter cannot be recursive', errorMessage: '"url" parameter cannot be recursive',
} }
} }
if (!hasLocalMatch(localPatterns, url)) {
return { errorMessage: '"url" parameter is not allowed' }
}
} else { } else {
let hrefParsed: URL let hrefParsed: URL
...@@ -227,7 +232,7 @@ export class ImageOptimizerCache { ...@@ -227,7 +232,7 @@ export class ImageOptimizerCache {
return { errorMessage: '"url" parameter is invalid' } return { errorMessage: '"url" parameter is invalid' }
} }
if (!hasMatch(domains, remotePatterns, hrefParsed)) { if (!hasRemoteMatch(domains, remotePatterns, hrefParsed)) {
return { errorMessage: '"url" parameter is not allowed' } return { errorMessage: '"url" parameter is not allowed' }
} }
} }
......
...@@ -18,6 +18,21 @@ export type ImageLoaderPropsWithConfig = ImageLoaderProps & { ...@@ -18,6 +18,21 @@ export type ImageLoaderPropsWithConfig = ImageLoaderProps & {
config: Readonly<ImageConfig> config: Readonly<ImageConfig>
} }
export type LocalPattern = {
/**
* Can be literal or wildcard.
* Single `*` matches a single path segment.
* Double `**` matches any number of path segments.
*/
pathname?: string
/**
* Can be literal query string such as `?v=1` or
* empty string meaning no query string.
*/
search?: string
}
export type RemotePattern = { export type RemotePattern = {
/** /**
* Must be `http` or `https`. * Must be `http` or `https`.
...@@ -100,6 +115,9 @@ export type ImageConfigComplete = { ...@@ -100,6 +115,9 @@ export type ImageConfigComplete = {
/** @see [Remote Patterns](https://nextjs.org/docs/api-reference/next/image#remotepatterns) */ /** @see [Remote Patterns](https://nextjs.org/docs/api-reference/next/image#remotepatterns) */
remotePatterns: RemotePattern[] remotePatterns: RemotePattern[]
/** @see [Remote Patterns](https://nextjs.org/docs/api-reference/next/image#localPatterns) */
localPatterns: LocalPattern[] | undefined
/** @see [Unoptimized](https://nextjs.org/docs/api-reference/next/image#unoptimized) */ /** @see [Unoptimized](https://nextjs.org/docs/api-reference/next/image#unoptimized) */
unoptimized: boolean unoptimized: boolean
} }
...@@ -119,6 +137,7 @@ export const imageConfigDefault: ImageConfigComplete = { ...@@ -119,6 +137,7 @@ export const imageConfigDefault: ImageConfigComplete = {
dangerouslyAllowSVG: false, dangerouslyAllowSVG: false,
contentSecurityPolicy: `script-src 'none'; frame-src 'none'; sandbox;`, contentSecurityPolicy: `script-src 'none'; frame-src 'none'; sandbox;`,
contentDispositionType: 'inline', contentDispositionType: 'inline',
remotePatterns: [], localPatterns: undefined, // default: allow all local images
remotePatterns: [], // default: allow no remote images
unoptimized: false, unoptimized: false,
} }
...@@ -29,6 +29,23 @@ function defaultLoader({ ...@@ -29,6 +29,23 @@ function defaultLoader({
) )
} }
if (src.startsWith('/') && config.localPatterns) {
if (
process.env.NODE_ENV !== 'test' &&
// micromatch isn't compatible with edge runtime
process.env.NEXT_RUNTIME !== 'edge'
) {
// We use dynamic require because this should only error in development
const { hasLocalMatch } = require('./match-local-pattern')
if (!hasLocalMatch(config.localPatterns, src)) {
throw new Error(
`Invalid src prop (${src}) on \`next/image\` does not match \`images.localPatterns\` configured in your \`next.config.js\`\n` +
`See more info: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns`
)
}
}
}
if (!src.startsWith('/') && (config.domains || config.remotePatterns)) { if (!src.startsWith('/') && (config.domains || config.remotePatterns)) {
let parsedSrc: URL let parsedSrc: URL
try { try {
...@@ -46,8 +63,8 @@ function defaultLoader({ ...@@ -46,8 +63,8 @@ function defaultLoader({
process.env.NEXT_RUNTIME !== 'edge' process.env.NEXT_RUNTIME !== 'edge'
) { ) {
// We use dynamic require because this should only error in development // We use dynamic require because this should only error in development
const { hasMatch } = require('./match-remote-pattern') const { hasRemoteMatch } = require('./match-remote-pattern')
if (!hasMatch(config.domains, config.remotePatterns, parsedSrc)) { if (!hasRemoteMatch(config.domains, config.remotePatterns, parsedSrc)) {
throw new Error( throw new Error(
`Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` + `Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` +
`See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host` `See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host`
......
import type { LocalPattern } from './image-config'
import { makeRe } from 'next/dist/compiled/picomatch'
// Modifying this function should also modify writeImagesManifest()
export function matchLocalPattern(pattern: LocalPattern, url: URL): boolean {
if (pattern.search !== undefined) {
if (pattern.search !== url.search) {
return false
}
}
if (!makeRe(pattern.pathname ?? '**', { dot: true }).test(url.pathname)) {
return false
}
return true
}
export function hasLocalMatch(
localPatterns: LocalPattern[] | undefined,
urlPathAndQuery: string
): boolean {
if (!localPatterns) {
// if the user didn't define "localPatterns", we allow all local images
return true
}
const url = new URL(urlPathAndQuery, 'http://n')
return localPatterns.some((p) => matchLocalPattern(p, url))
}
...@@ -39,7 +39,7 @@ export function matchRemotePattern(pattern: RemotePattern, url: URL): boolean { ...@@ -39,7 +39,7 @@ export function matchRemotePattern(pattern: RemotePattern, url: URL): boolean {
return true return true
} }
export function hasMatch( export function hasRemoteMatch(
domains: string[], domains: string[],
remotePatterns: RemotePattern[], remotePatterns: RemotePattern[],
url: URL url: URL
......
...@@ -23,6 +23,7 @@ type EventCliSessionStarted = { ...@@ -23,6 +23,7 @@ type EventCliSessionStarted = {
localeDetectionEnabled: boolean | null localeDetectionEnabled: boolean | null
imageDomainsCount: number | null imageDomainsCount: number | null
imageRemotePatternsCount: number | null imageRemotePatternsCount: number | null
imageLocalPatternsCount: number | null
imageSizes: string | null imageSizes: string | null
imageLoader: string | null imageLoader: string | null
imageFormats: string | null imageFormats: string | null
...@@ -75,6 +76,7 @@ export function eventCliSession( ...@@ -75,6 +76,7 @@ export function eventCliSession(
| 'localeDetectionEnabled' | 'localeDetectionEnabled'
| 'imageDomainsCount' | 'imageDomainsCount'
| 'imageRemotePatternsCount' | 'imageRemotePatternsCount'
| 'imageLocalPatternsCount'
| 'imageSizes' | 'imageSizes'
| 'imageLoader' | 'imageLoader'
| 'imageFormats' | 'imageFormats'
...@@ -114,6 +116,9 @@ export function eventCliSession( ...@@ -114,6 +116,9 @@ export function eventCliSession(
imageRemotePatternsCount: images?.remotePatterns imageRemotePatternsCount: images?.remotePatterns
? images.remotePatterns.length ? images.remotePatterns.length
: null, : null,
imageLocalPatternsCount: images?.localPatterns
? images.localPatterns.length
: null,
imageSizes: images?.imageSizes ? images.imageSizes.join(',') : null, imageSizes: images?.imageSizes ? images.imageSizes.join(',') : null,
imageLoader: images?.loader, imageLoader: images?.loader,
imageFormats: images?.formats ? images.formats.join(',') : null, imageFormats: images?.formats ? images.formats.join(',') : null,
......
...@@ -48,6 +48,58 @@ describe('Image Optimizer', () => { ...@@ -48,6 +48,58 @@ describe('Image Optimizer', () => {
) )
}) })
it('should error when localPatterns length exceeds 25', async () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
images: {
localPatterns: Array.from({ length: 26 }).map((_) => ({
pathname: '/foo/**',
})),
},
})
)
let stderr = ''
app = await launchApp(appDir, await findPort(), {
onStderr(msg) {
stderr += msg || ''
},
})
await waitFor(1000)
await killApp(app).catch(() => {})
await nextConfig.restore()
expect(stderr).toContain(
'Array must contain at most 25 element(s) at "images.localPatterns"'
)
})
it('should error when localPatterns has invalid prop', async () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
images: {
localPatterns: [{ pathname: '/foo/**', foo: 'bar' }],
},
})
)
let stderr = ''
app = await launchApp(appDir, await findPort(), {
onStderr(msg) {
stderr += msg || ''
},
})
await waitFor(1000)
await killApp(app).catch(() => {})
await nextConfig.restore()
expect(stderr).toContain(
`Unrecognized key(s) in object: 'foo' at "images.localPatterns[0]"`
)
})
it('should error when remotePatterns length exceeds 50', async () => { it('should error when remotePatterns length exceeds 50', async () => {
await nextConfig.replace( await nextConfig.replace(
'{ /* replaceme */ }', '{ /* replaceme */ }',
......
import Image from 'next/image'
const Page = () => {
return (
<main>
<Image
id="does-not-exist"
src="/does-not-exist.png"
width="200"
height="200"
alt="should fail"
/>
</main>
)
}
export default Page
export const metadata = {
title: 'Next.js',
description: 'Generated by Next.js',
}
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import Image from 'next/image'
const Page = () => {
return (
<main>
<Image
id="nested-assets-query"
src="/assets/test.png?v=1"
width="200"
height="200"
alt="should fail"
/>
</main>
)
}
export default Page
import Image from 'next/image'
const Page = () => {
return (
<main>
<Image
id="nested-blocked"
src="/blocked/test.png"
width="200"
height="200"
alt="should fail"
/>
</main>
)
}
export default Page
import Image from 'next/image'
import staticImg from './images/static-img.png'
const Page = () => {
return (
<main>
<Image
id="nested-assets"
src="/assets/test.png"
width="200"
height="200"
alt="should work"
/>
<Image
id="static-img"
src={staticImg}
width="200"
height="200"
alt="should work"
/>
</main>
)
}
export default Page
import Image from 'next/image'
const Page = () => {
return (
<main>
<Image
id="top-level"
src="/test.png"
width="200"
height="200"
alt="should fail"
/>
</main>
)
}
export default Page
module.exports = {
images: {
localPatterns: [
{
pathname: '/assets/**',
search: '',
},
],
},
}
.displayFlex {
display: flex;
}
.mainContainer span {
margin: 57px;
}
.mainContainer img {
border-radius: 139px;
}
.overrideImg {
filter: opacity(0.5);
background-size: 30%;
background-image: url('data:image/png;base64,iVBORw0KGgo=');
background-position: 1px 2px;
}
/* eslint-env jest */
import {
assertHasRedbox,
assertNoRedbox,
fetchViaHTTP,
findPort,
getRedboxHeader,
killApp,
launchApp,
nextBuild,
nextStart,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
import { join } from 'path'
const appDir = join(__dirname, '../')
let appPort: number
let app: Awaited<ReturnType<typeof launchApp>>
async function getSrc(
browser: Awaited<ReturnType<typeof webdriver>>,
id: string
) {
const src = await browser.elementById(id).getAttribute('src')
if (src) {
const url = new URL(src, `http://localhost:${appPort}`)
return url.href.slice(url.origin.length)
}
}
function runTests(mode: 'dev' | 'server') {
it('should load matching images', async () => {
const browser = await webdriver(appPort, '/')
if (mode === 'dev') {
await assertNoRedbox(browser)
}
const ids = ['nested-assets', 'static-img']
const urls = await Promise.all(ids.map((id) => getSrc(browser, id)))
const responses = await Promise.all(
urls.map((url) => fetchViaHTTP(appPort, url))
)
const statuses = responses.map((res) => res.status)
expect(statuses).toStrictEqual([200, 200])
})
it.each([
'does-not-exist',
'nested-assets-query',
'nested-blocked',
'top-level',
])('should block unmatched image %s', async (id: string) => {
const page = '/' + id
const browser = await webdriver(appPort, page)
if (mode === 'dev') {
await assertHasRedbox(browser)
expect(await getRedboxHeader(browser)).toMatch(
/Invalid src prop (.+) on `next\/image` does not match `images.localPatterns` configured/g
)
} else {
const url = await getSrc(browser, id)
const res = await fetchViaHTTP(appPort, url)
expect(res.status).toBe(400)
}
})
}
describe('Image localPatterns config', () => {
;(process.env.TURBOPACK_BUILD ? describe.skip : describe)(
'development mode',
() => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(async () => {
await killApp(app)
})
runTests('dev')
}
)
;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode',
() => {
beforeAll(async () => {
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(async () => {
await killApp(app)
})
runTests('server')
}
)
})
...@@ -5,6 +5,7 @@ module.exports = phase => { ...@@ -5,6 +5,7 @@ module.exports = phase => {
imageSizes: [64, 128, 256, 512, 1024], imageSizes: [64, 128, 256, 512, 1024],
domains: ['example.com', 'another.com'], domains: ['example.com', 'another.com'],
remotePatterns: [{ protocol: 'https', hostname: '**.example.com' }], remotePatterns: [{ protocol: 'https', hostname: '**.example.com' }],
localPatterns: [{ pathname: '/assets/**', search: '' }],
}, },
i18n: { i18n: {
locales: ['en','nl','fr'], locales: ['en','nl','fr'],
......
...@@ -75,6 +75,7 @@ describe('config telemetry', () => { ...@@ -75,6 +75,7 @@ describe('config telemetry', () => {
expect(event1).toMatch(/"imageFutureEnabled": true/) expect(event1).toMatch(/"imageFutureEnabled": true/)
expect(event1).toMatch(/"imageDomainsCount": 2/) expect(event1).toMatch(/"imageDomainsCount": 2/)
expect(event1).toMatch(/"imageRemotePatternsCount": 1/) expect(event1).toMatch(/"imageRemotePatternsCount": 1/)
expect(event1).toMatch(/"imageLocalPatternsCount": 2/)
expect(event1).toMatch(/"imageSizes": "64,128,256,512,1024"/) expect(event1).toMatch(/"imageSizes": "64,128,256,512,1024"/)
expect(event1).toMatch(/"imageFormats": "image\/avif,image\/webp"/) expect(event1).toMatch(/"imageFormats": "image\/avif,image\/webp"/)
expect(event1).toMatch(/"nextConfigOutput": null/) expect(event1).toMatch(/"nextConfigOutput": null/)
...@@ -121,6 +122,7 @@ describe('config telemetry', () => { ...@@ -121,6 +122,7 @@ describe('config telemetry', () => {
expect(event2).toMatch(/"localeDetectionEnabled": true/) expect(event2).toMatch(/"localeDetectionEnabled": true/)
expect(event2).toMatch(/"imageDomainsCount": 2/) expect(event2).toMatch(/"imageDomainsCount": 2/)
expect(event2).toMatch(/"imageRemotePatternsCount": 1/) expect(event2).toMatch(/"imageRemotePatternsCount": 1/)
expect(event2).toMatch(/"imageLocalPatternsCount": 2/)
expect(event2).toMatch(/"imageSizes": "64,128,256,512,1024"/) expect(event2).toMatch(/"imageSizes": "64,128,256,512,1024"/)
expect(event2).toMatch(/"nextConfigOutput": null/) expect(event2).toMatch(/"nextConfigOutput": null/)
expect(event2).toMatch(/"trailingSlashEnabled": false/) expect(event2).toMatch(/"trailingSlashEnabled": false/)
......
/* eslint-env jest */
import type { LocalPattern } from 'next/dist/shared/lib/image-config'
import {
matchLocalPattern,
hasLocalMatch as hasMatch,
} from 'next/dist/shared/lib/match-local-pattern'
const m = (p: LocalPattern, urlPathAndQuery: string) =>
matchLocalPattern(p, new URL(urlPathAndQuery, 'http://n'))
describe('matchLocalPattern', () => {
it('should match anything when no pattern is defined', () => {
const p = {} as const
expect(m(p, '/')).toBe(true)
expect(m(p, '/path')).toBe(true)
expect(m(p, '/path/to')).toBe(true)
expect(m(p, '/path/to/file')).toBe(true)
expect(m(p, '/path/to/file.txt')).toBe(true)
expect(m(p, '/path/to/file?q=1')).toBe(true)
expect(m(p, '/path/to/file?q=1&a=two')).toBe(true)
})
it('should match any path without a search query string', () => {
const p = {
search: '',
} as const
expect(m(p, '/')).toBe(true)
expect(m(p, '/path')).toBe(true)
expect(m(p, '/path/to')).toBe(true)
expect(m(p, '/path/to/file')).toBe(true)
expect(m(p, '/path/to/file.txt')).toBe(true)
expect(m(p, '/path/to/file?q=1')).toBe(false)
expect(m(p, '/path/to/file?q=1&a=two')).toBe(false)
expect(m(p, '/path/to/file.txt?q=1&a=two')).toBe(false)
})
it('should match literal pathname and any search query string', () => {
const p = {
pathname: '/path/to/file',
} as const
expect(m(p, '/')).toBe(false)
expect(m(p, '/path')).toBe(false)
expect(m(p, '/path/to')).toBe(false)
expect(m(p, '/path/to/file')).toBe(true)
expect(m(p, '/path/to/file.txt')).toBe(false)
expect(m(p, '/path/to/file?q=1')).toBe(true)
expect(m(p, '/path/to/file?q=1&a=two')).toBe(true)
expect(m(p, '/path/to/file.txt?q=1&a=two')).toBe(false)
})
it('should match pathname with double asterisk', () => {
const p = {
pathname: '/path/to/**',
} as const
expect(m(p, '/')).toBe(false)
expect(m(p, '/path')).toBe(false)
expect(m(p, '/path/to')).toBe(true)
expect(m(p, '/path/to/file')).toBe(true)
expect(m(p, '/path/to/file.txt')).toBe(true)
expect(m(p, '/path/to/file?q=1')).toBe(true)
expect(m(p, '/path/to/file?q=1&a=two')).toBe(true)
expect(m(p, '/path/to/file.txt?q=1&a=two')).toBe(true)
})
it('should properly work with hasMatch', () => {
const url = '/path/to/file?q=1&a=two'
expect(hasMatch(undefined, url)).toBe(true)
expect(hasMatch([], url)).toBe(false)
expect(hasMatch([{ pathname: '/path' }], url)).toBe(false)
expect(hasMatch([{ pathname: '/path/to' }], url)).toBe(false)
expect(hasMatch([{ pathname: '/path/to/file' }], url)).toBe(true)
expect(hasMatch([{ pathname: '/path/to/file' }], url)).toBe(true)
expect(hasMatch([{ pathname: '/path/to/file', search: '' }], url)).toBe(
false
)
expect(hasMatch([{ pathname: '/path/to/file', search: '?q=1' }], url)).toBe(
false
)
expect(
hasMatch([{ pathname: '/path/to/file', search: '?q=1&a=two' }], url)
).toBe(true)
expect(hasMatch([{ pathname: '/path/**' }], url)).toBe(true)
expect(hasMatch([{ pathname: '/path/to/**' }], url)).toBe(true)
expect(hasMatch([{ pathname: '/path/to/f*' }], url)).toBe(true)
expect(hasMatch([{ pathname: '/path/to/*le' }], url)).toBe(true)
expect(hasMatch([{ pathname: '/path/*/file' }], url)).toBe(true)
expect(hasMatch([{ pathname: '/*/to/file' }], url)).toBe(true)
expect(hasMatch([{ pathname: '/foo' }, { pathname: '/bar' }], url)).toBe(
false
)
expect(
hasMatch(
[{ pathname: '/foo' }, { pathname: '/bar' }, { pathname: '/path/**' }],
url
)
).toBe(true)
})
})
/* eslint-env jest */ /* eslint-env jest */
import { import {
matchRemotePattern as m, matchRemotePattern as m,
hasMatch, hasRemoteMatch as hasMatch,
} from 'next/dist/shared/lib/match-remote-pattern' } from 'next/dist/shared/lib/match-remote-pattern'
describe('matchRemotePattern', () => { describe('matchRemotePattern', () => {
......
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