2022-05-05 04:19:16 +02:00
|
|
|
import type { RemotePattern } from './image-config'
|
2022-05-25 22:25:06 +02:00
|
|
|
import { makeRe } from 'next/dist/compiled/micromatch'
|
2022-05-05 04:19:16 +02:00
|
|
|
|
|
|
|
export function matchRemotePattern(pattern: RemotePattern, url: URL): boolean {
|
|
|
|
if (pattern.protocol !== undefined) {
|
|
|
|
const actualProto = url.protocol.slice(0, -1)
|
|
|
|
if (pattern.protocol !== actualProto) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (pattern.port !== undefined) {
|
|
|
|
if (pattern.port !== url.port) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (pattern.hostname === undefined) {
|
|
|
|
throw new Error(
|
|
|
|
`Pattern should define hostname but found\n${JSON.stringify(pattern)}`
|
|
|
|
)
|
|
|
|
} else {
|
2022-05-25 22:25:06 +02:00
|
|
|
if (!makeRe(pattern.hostname).test(url.hostname)) {
|
|
|
|
return false
|
2022-05-05 04:19:16 +02:00
|
|
|
}
|
|
|
|
}
|
2022-05-25 22:25:06 +02:00
|
|
|
|
|
|
|
if (!makeRe(pattern.pathname ?? '**').test(url.pathname)) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2022-05-05 04:19:16 +02:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
export function hasMatch(
|
|
|
|
domains: string[],
|
|
|
|
remotePatterns: RemotePattern[],
|
|
|
|
url: URL
|
|
|
|
): boolean {
|
|
|
|
return (
|
|
|
|
domains.some((domain) => url.hostname === domain) ||
|
|
|
|
remotePatterns.some((p) => matchRemotePattern(p, url))
|
|
|
|
)
|
|
|
|
}
|