Unverified Commit 840643f2 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add experimental routing package for resolving adapter routes (#86404)

This adds a shared routing package which can be used to resolve routes
provided from the adapter API to the final output that should be
served/invoked. It aims to handle all the routing done in `next-server`
and allows a simplified interface for invoking the middleware output
however that is deployed.

---------
Co-authored-by: 's avatarvercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
parent 4fa7d80e
......@@ -16,6 +16,7 @@ const customJestConfig = {
'<rootDir>/../packages/next-codemod/',
'<rootDir>/../packages/eslint-plugin-internal/',
'<rootDir>/../packages/font/src/',
'<rootDir>/../packages/next-routing/',
],
modulePathIgnorePatterns: ['/\\.next/'],
modulePaths: ['<rootDir>/lib'],
......
# @next/routing
Shared route resolving package for Next.js.
**NOTE: This package is experimental and will become stable along with adapters API**
## Overview
This package provides a comprehensive route resolution system that handles rewrites, redirects, middleware invocation, and dynamic route matching with support for conditional routing based on headers, cookies, queries, and host.
## Installation
```bash
npm install @next/routing
```
## Usage
```typescript
import { resolveRoutes } from '@next/routing'
const result = await resolveRoutes({
url: new URL('https://example.com/api/users'),
basePath: '',
requestBody: readableStream,
headers: new Headers(),
pathnames: ['/api/users', '/api/posts'],
routes: {
beforeMiddleware: [],
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [],
onMatch: [],
fallback: [],
},
invokeMiddleware: async (ctx) => {
// Your middleware logic
return {}
},
})
if (result.matchedPathname) {
console.log('Matched:', result.matchedPathname)
}
```
## Route Resolution Flow
1. **beforeMiddleware routes** - Applied before middleware execution
2. **invokeMiddleware** - Custom middleware logic
3. **beforeFiles routes** - Applied before checking filesystem
4. **Static pathname matching** - Check against provided pathnames
5. **afterFiles routes** - Applied after filesystem checks
6. **dynamicRoutes** - Dynamic route matching with parameter extraction
7. **fallback routes** - Final fallback routes
## Route Configuration
Each route can have:
- `sourceRegex` - Regular expression to match against pathname
- `destination` - Destination path with support for replacements ($1, $name)
- `headers` - Headers to apply on match
- `has` - Conditions that must match
- `missing` - Conditions that must not match
- `status` - HTTP status code (3xx for redirects)
### Redirects
When a route has:
- A redirect status code (300-399)
- Headers containing `Location` or `Refresh`
The routing will end immediately and return a `redirect` result with the destination URL and status code.
### Has/Missing Conditions
Conditions support:
- `header` - Match HTTP headers
- `cookie` - Match cookies
- `query` - Match query parameters
- `host` - Match hostname
Values can be:
- `undefined` - Match if key exists
- String - Direct string match
- Regex string - Match against regex pattern
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['**/__tests__/**/*.test.ts'],
collectCoverageFrom: ['src/**/*.ts', '!src/**/*.d.ts'],
moduleFileExtensions: ['ts', 'js'],
}
{
"name": "@next/routing",
"version": "16.1.1-canary.6",
"keywords": [
"react",
"next",
"next.js",
"routing"
],
"description": "Next.js shared route resolving",
"repository": {
"type": "git",
"url": "https://github.com/vercel/next.js",
"directory": "packages/next-routing"
},
"author": "Next.js Team <support@vercel.com>",
"license": "MIT",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"dev": "ncc build ./src/index.ts -w -o dist/",
"prerelease": "node ../../scripts/rm.mjs dist",
"types": "tsc --declaration --emitDeclarationOnly --declarationDir dist",
"release": "ncc build ./src/index.ts -o ./dist/ --minify --no-cache --no-source-map-register",
"build": "pnpm release && pnpm types",
"test": "jest",
"test:watch": "jest --watch",
"prepublishOnly": "cd ../../ && turbo run build"
},
"devDependencies": {
"@types/jest": "^29.5.0",
"@vercel/ncc": "0.34.0",
"jest": "^29.5.0",
"ts-jest": "^29.1.0"
}
}
This diff is collapsed.
This diff is collapsed.
import { resolveRoutes } from '../resolve-routes'
import type { ResolveRoutesParams } from '../types'
describe('resolveRoutes with i18n', () => {
const baseParams: Omit<ResolveRoutesParams, 'url' | 'headers'> = {
buildId: 'BUILD_ID',
basePath: '',
requestBody: new ReadableStream(),
pathnames: ['/en/about', '/fr/about', '/de/about', '/about'],
routes: {
beforeMiddleware: [],
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [],
onMatch: [],
fallback: [],
},
invokeMiddleware: async () => ({ bodySent: false }),
}
const i18nConfig = {
defaultLocale: 'en',
locales: ['en', 'fr', 'de', 'ja'],
domains: [
{ domain: 'example.com', defaultLocale: 'en' },
{ domain: 'example.fr', defaultLocale: 'fr' },
{ domain: 'example.de', defaultLocale: 'de' },
],
}
const i18nConfigNoDomains = {
defaultLocale: 'en',
locales: ['en', 'fr', 'de', 'ja'],
}
describe('locale detection from accept-language header', () => {
it('should redirect to locale prefix when accept-language is set', async () => {
const result = await resolveRoutes({
...baseParams,
url: new URL('http://example.com/about'),
headers: new Headers({
'accept-language': 'fr,en;q=0.9',
}),
i18n: i18nConfigNoDomains,
})
expect(result.redirect).toBeDefined()
expect(result.redirect?.url.pathname).toBe('/fr/about')
expect(result.redirect?.status).toBe(307)
})
it('should use quality values from accept-language', async () => {
const result = await resolveRoutes({
...baseParams,
url: new URL('http://example.com/about'),
headers: new Headers({
'accept-language': 'de;q=0.8,fr;q=0.9,en;q=0.7',
}),
i18n: i18nConfigNoDomains,
})
expect(result.redirect).toBeDefined()
expect(result.redirect?.url.pathname).toBe('/fr/about')
})
it('should not redirect when locale matches default', async () => {
const result = await resolveRoutes({
...baseParams,
url: new URL('http://example.com/about'),
headers: new Headers({
'accept-language': 'en',
}),
i18n: i18nConfig,
})
// Should prefix internally but not redirect
expect(result.redirect).toBeUndefined()
})
})
describe('locale detection from cookie', () => {
it('should redirect to locale from NEXT_LOCALE cookie', async () => {
const result = await resolveRoutes({
...baseParams,
url: new URL('http://example.com/about'),
headers: new Headers({
cookie: 'NEXT_LOCALE=ja',
}),
i18n: i18nConfigNoDomains,
})
expect(result.redirect).toBeDefined()
expect(result.redirect?.url.pathname).toBe('/ja/about')
})
it('should prioritize cookie over accept-language', async () => {
const result = await resolveRoutes({
...baseParams,
url: new URL('http://example.com/about'),
headers: new Headers({
cookie: 'session=abc; NEXT_LOCALE=ja; theme=dark',
'accept-language': 'fr',
}),
i18n: i18nConfigNoDomains,
})
expect(result.redirect).toBeDefined()
expect(result.redirect?.url.pathname).toBe('/ja/about')
})
})
describe('domain locale handling', () => {
it('should use domain default locale without redirect', async () => {
const result = await resolveRoutes({
...baseParams,
url: new URL('http://example.fr/about'),
headers: new Headers({}),
i18n: i18nConfig,
})
// Should not redirect since we're on the FR domain
expect(result.redirect).toBeUndefined()
})
it('should redirect to correct domain for preferred locale', async () => {
const result = await resolveRoutes({
...baseParams,
url: new URL('http://example.com/about'),
headers: new Headers({
'accept-language': 'fr',
}),
i18n: i18nConfig,
})
expect(result.redirect).toBeDefined()
expect(result.redirect?.url.hostname).toBe('example.fr')
expect(result.redirect?.url.pathname).toBe('/about')
})
it('should not include locale prefix for domain default locale', async () => {
const result = await resolveRoutes({
...baseParams,
url: new URL('http://example.com/about'),
headers: new Headers({
'accept-language': 'de',
}),
i18n: i18nConfig,
})
expect(result.redirect).toBeDefined()
expect(result.redirect?.url.hostname).toBe('example.de')
expect(result.redirect?.url.pathname).toBe('/about')
})
})
describe('locale prefix in pathname', () => {
it('should use locale from pathname', async () => {
const result = await resolveRoutes({
...baseParams,
url: new URL('http://example.com/fr/about'),
headers: new Headers({
'accept-language': 'de',
}),
i18n: i18nConfig,
})
// Path locale takes priority, so no redirect
expect(result.redirect).toBeUndefined()
expect(result.matchedPathname).toBe('/fr/about')
})
it('should handle locale prefix with trailing slash', async () => {
const result = await resolveRoutes({
...baseParams,
url: new URL('http://example.com/fr/about/'),
headers: new Headers({}),
pathnames: ['/fr/about/', '/fr/about'],
i18n: i18nConfig,
})
expect(result.redirect).toBeUndefined()
expect(result.matchedPathname).toBe('/fr/about/')
})
})
describe('_next/data routes', () => {
it('should not handle locale for _next/data routes', async () => {
const result = await resolveRoutes({
...baseParams,
buildId: 'build123',
url: new URL('http://example.com/_next/data/build123/about.json'),
headers: new Headers({
'accept-language': 'fr',
}),
i18n: i18nConfig,
routes: {
...baseParams.routes,
shouldNormalizeNextData: true,
},
})
// Should not redirect for _next/data routes
expect(result.redirect).toBeUndefined()
})
})
describe('localeDetection disabled', () => {
it('should not redirect when localeDetection is false', async () => {
const result = await resolveRoutes({
...baseParams,
url: new URL('http://example.com/about'),
headers: new Headers({
'accept-language': 'fr',
cookie: 'NEXT_LOCALE=de',
}),
i18n: { ...i18nConfig, localeDetection: false },
})
// Should prefix internally with default locale but not redirect
expect(result.redirect).toBeUndefined()
})
it('should still use domain locale when localeDetection is false', async () => {
const result = await resolveRoutes({
...baseParams,
url: new URL('http://example.fr/about'),
headers: new Headers({
'accept-language': 'de',
}),
i18n: { ...i18nConfig, localeDetection: false },
})
// Domain locale still applies
expect(result.redirect).toBeUndefined()
})
})
describe('basePath with i18n', () => {
it('should handle basePath with locale prefix redirect', async () => {
const result = await resolveRoutes({
...baseParams,
basePath: '/base',
url: new URL('http://example.com/base/about'),
headers: new Headers({
'accept-language': 'ja',
}),
i18n: i18nConfigNoDomains,
})
expect(result.redirect).toBeDefined()
expect(result.redirect?.url.pathname).toBe('/base/ja/about')
})
it('should handle basePath with domain redirect', async () => {
const result = await resolveRoutes({
...baseParams,
basePath: '/base',
url: new URL('http://example.com/base/about'),
headers: new Headers({
'accept-language': 'de',
}),
i18n: i18nConfig,
})
expect(result.redirect).toBeDefined()
expect(result.redirect?.url.hostname).toBe('example.de')
expect(result.redirect?.url.pathname).toBe('/base/about')
})
})
describe('edge cases', () => {
it('should handle root path', async () => {
const result = await resolveRoutes({
...baseParams,
url: new URL('http://example.com/'),
headers: new Headers({
'accept-language': 'ja',
}),
pathnames: ['/', '/ja/', '/en/'],
i18n: i18nConfigNoDomains,
})
expect(result.redirect).toBeDefined()
expect(result.redirect?.url.pathname).toBe('/ja/')
})
it('should handle query strings', async () => {
const result = await resolveRoutes({
...baseParams,
url: new URL('http://example.com/about?foo=bar'),
headers: new Headers({
'accept-language': 'ja',
}),
i18n: i18nConfigNoDomains,
})
expect(result.redirect).toBeDefined()
expect(result.redirect?.url.pathname).toBe('/ja/about')
expect(result.redirect?.url.search).toBe('?foo=bar')
})
it('should skip locale handling for _next routes', async () => {
const result = await resolveRoutes({
...baseParams,
url: new URL('http://example.com/_next/static/chunk.js'),
headers: new Headers({
'accept-language': 'fr',
}),
i18n: i18nConfig,
})
// Should not redirect for _next routes
expect(result.redirect).toBeUndefined()
})
})
})
import {
detectDomainLocale,
normalizeLocalePath,
getAcceptLanguageLocale,
getCookieLocale,
detectLocale,
} from '../i18n'
import type { I18nConfig } from '../i18n'
describe('i18n utilities', () => {
describe('detectDomainLocale', () => {
const domains = [
{ domain: 'example.com', defaultLocale: 'en', locales: ['en', 'en-US'] },
{ domain: 'example.fr', defaultLocale: 'fr' },
{ domain: 'example.de:3000', defaultLocale: 'de' },
]
it('should detect locale by hostname', () => {
expect(detectDomainLocale(domains, 'example.com')).toEqual(domains[0])
expect(detectDomainLocale(domains, 'example.fr')).toEqual(domains[1])
})
it('should detect locale by hostname without port', () => {
expect(detectDomainLocale(domains, 'example.de')).toEqual(domains[2])
})
it('should detect locale by detected locale', () => {
expect(detectDomainLocale(domains, 'other.com', 'fr')).toEqual(domains[1])
expect(detectDomainLocale(domains, 'other.com', 'en-US')).toEqual(
domains[0]
)
})
it('should return undefined for no match', () => {
expect(detectDomainLocale(domains, 'unknown.com')).toBeUndefined()
expect(detectDomainLocale(undefined, 'example.com')).toBeUndefined()
})
it('should be case-insensitive', () => {
expect(detectDomainLocale(domains, 'EXAMPLE.COM')).toEqual(domains[0])
expect(detectDomainLocale(domains, 'other.com', 'FR')).toEqual(domains[1])
})
})
describe('normalizeLocalePath', () => {
const locales = ['en', 'fr', 'de', 'en-US']
it('should detect and remove locale from pathname', () => {
expect(normalizeLocalePath('/en/about', locales)).toEqual({
pathname: '/about',
detectedLocale: 'en',
})
expect(normalizeLocalePath('/fr/products/item', locales)).toEqual({
pathname: '/products/item',
detectedLocale: 'fr',
})
})
it('should handle root path with locale', () => {
expect(normalizeLocalePath('/en', locales)).toEqual({
pathname: '/',
detectedLocale: 'en',
})
})
it('should return original pathname when no locale detected', () => {
expect(normalizeLocalePath('/about', locales)).toEqual({
pathname: '/about',
})
expect(normalizeLocalePath('/', locales)).toEqual({
pathname: '/',
})
})
it('should be case-insensitive', () => {
expect(normalizeLocalePath('/EN/about', locales)).toEqual({
pathname: '/about',
detectedLocale: 'en',
})
expect(normalizeLocalePath('/Fr/products', locales)).toEqual({
pathname: '/products',
detectedLocale: 'fr',
})
})
it('should handle locales with hyphens', () => {
expect(normalizeLocalePath('/en-US/about', locales)).toEqual({
pathname: '/about',
detectedLocale: 'en-US',
})
})
})
describe('getAcceptLanguageLocale', () => {
const locales = ['en', 'fr', 'de', 'ja']
it('should parse simple accept-language header', () => {
expect(getAcceptLanguageLocale('fr', locales)).toBe('fr')
expect(getAcceptLanguageLocale('de', locales)).toBe('de')
})
it('should parse accept-language with quality values', () => {
expect(getAcceptLanguageLocale('fr;q=0.9,en;q=0.8', locales)).toBe('fr')
expect(getAcceptLanguageLocale('en;q=0.8,fr;q=0.9', locales)).toBe('fr')
})
it('should handle multiple locales', () => {
expect(getAcceptLanguageLocale('ja,en;q=0.9,fr;q=0.8', locales)).toBe(
'ja'
)
})
it('should match prefix for regional variants', () => {
expect(getAcceptLanguageLocale('fr-FR', locales)).toBe('fr')
expect(getAcceptLanguageLocale('en-US,en;q=0.9', locales)).toBe('en')
})
it('should return undefined for no match', () => {
expect(getAcceptLanguageLocale('es', locales)).toBeUndefined()
expect(getAcceptLanguageLocale('', locales)).toBeUndefined()
})
it('should handle malformed headers gracefully', () => {
expect(getAcceptLanguageLocale('invalid;;;', locales)).toBeUndefined()
})
})
describe('getCookieLocale', () => {
const locales = ['en', 'fr', 'de']
it('should extract locale from NEXT_LOCALE cookie', () => {
expect(getCookieLocale('NEXT_LOCALE=fr', locales)).toBe('fr')
expect(getCookieLocale('NEXT_LOCALE=de', locales)).toBe('de')
})
it('should handle multiple cookies', () => {
expect(
getCookieLocale('session=abc123; NEXT_LOCALE=fr; theme=dark', locales)
).toBe('fr')
})
it('should be case-insensitive for locale value', () => {
expect(getCookieLocale('NEXT_LOCALE=FR', locales)).toBe('fr')
expect(getCookieLocale('NEXT_LOCALE=De', locales)).toBe('de')
})
it('should return undefined for no match', () => {
expect(getCookieLocale('NEXT_LOCALE=es', locales)).toBeUndefined()
expect(getCookieLocale('session=abc123', locales)).toBeUndefined()
expect(getCookieLocale('', locales)).toBeUndefined()
expect(getCookieLocale(undefined, locales)).toBeUndefined()
})
it('should handle URL-encoded values', () => {
expect(getCookieLocale('NEXT_LOCALE=fr%2DFR', locales)).toBeUndefined()
})
})
describe('detectLocale', () => {
const i18nConfig: I18nConfig = {
defaultLocale: 'en',
locales: ['en', 'fr', 'de', 'ja'],
domains: [
{ domain: 'example.com', defaultLocale: 'en' },
{ domain: 'example.fr', defaultLocale: 'fr' },
],
}
it('should prioritize locale in pathname', () => {
const result = detectLocale({
pathname: '/fr/about',
hostname: 'example.com',
cookieHeader: 'NEXT_LOCALE=de',
acceptLanguageHeader: 'ja',
i18n: i18nConfig,
})
expect(result.locale).toBe('fr')
expect(result.pathnameWithoutLocale).toBe('/about')
expect(result.localeInPath).toBe(true)
})
it('should use domain locale when no locale in path', () => {
const result = detectLocale({
pathname: '/about',
hostname: 'example.fr',
cookieHeader: undefined,
acceptLanguageHeader: undefined,
i18n: i18nConfig,
})
expect(result.locale).toBe('fr')
expect(result.localeInPath).toBe(false)
})
it('should use cookie locale when no path or domain match', () => {
const result = detectLocale({
pathname: '/about',
hostname: 'other.com',
cookieHeader: 'NEXT_LOCALE=de',
acceptLanguageHeader: 'ja',
i18n: i18nConfig,
})
expect(result.locale).toBe('de')
expect(result.localeInPath).toBe(false)
})
it('should use accept-language when no other match', () => {
const result = detectLocale({
pathname: '/about',
hostname: 'other.com',
cookieHeader: undefined,
acceptLanguageHeader: 'ja,en;q=0.9',
i18n: i18nConfig,
})
expect(result.locale).toBe('ja')
expect(result.localeInPath).toBe(false)
})
it('should fallback to default locale', () => {
const result = detectLocale({
pathname: '/about',
hostname: 'other.com',
cookieHeader: undefined,
acceptLanguageHeader: undefined,
i18n: i18nConfig,
})
expect(result.locale).toBe('en')
expect(result.localeInPath).toBe(false)
})
it('should use default locale when localeDetection is disabled', () => {
const result = detectLocale({
pathname: '/about',
hostname: 'other.com',
cookieHeader: 'NEXT_LOCALE=fr',
acceptLanguageHeader: 'ja',
i18n: { ...i18nConfig, localeDetection: false },
})
expect(result.locale).toBe('en')
expect(result.localeInPath).toBe(false)
})
it('should respect domain locale even with localeDetection disabled', () => {
const result = detectLocale({
pathname: '/about',
hostname: 'example.fr',
cookieHeader: 'NEXT_LOCALE=de',
acceptLanguageHeader: 'ja',
i18n: { ...i18nConfig, localeDetection: false },
})
expect(result.locale).toBe('fr')
expect(result.localeInPath).toBe(false)
})
})
})
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
/**
* Replaces $1, $2, etc. and $name placeholders in the destination string
* with matches from the regex and has conditions
*/
export function replaceDestination(
destination: string,
regexMatches: RegExpMatchArray | null,
hasCaptures: Record<string, string>
): string {
let result = destination
// Replace numbered captures from regex ($1, $2, etc.)
if (regexMatches) {
// Replace numbered groups (skip index 0 which is the full match)
for (let i = 1; i < regexMatches.length; i++) {
const value = regexMatches[i]
if (value !== undefined) {
result = result.replace(new RegExp(`\\$${i}`, 'g'), value)
}
}
// Replace named groups ($name)
if (regexMatches.groups) {
for (const [name, value] of Object.entries(regexMatches.groups)) {
if (value !== undefined) {
result = result.replace(new RegExp(`\\$${name}`, 'g'), value)
}
}
}
}
// Replace named captures from has conditions
for (const [name, value] of Object.entries(hasCaptures)) {
result = result.replace(new RegExp(`\\$${name}`, 'g'), value)
}
return result
}
/**
* Checks if a destination is an external rewrite (starts with http/https)
*/
export function isExternalDestination(destination: string): boolean {
return destination.startsWith('http://') || destination.startsWith('https://')
}
/**
* Applies a destination to a URL, updating the pathname or creating a new URL
* if it's external
*/
export function applyDestination(currentUrl: URL, destination: string): URL {
if (isExternalDestination(destination)) {
return new URL(destination)
}
// Create a new URL with the updated pathname
const newUrl = new URL(currentUrl.toString())
// Handle destinations with query strings
const [pathname, search] = destination.split('?')
newUrl.pathname = pathname
if (search) {
// Merge query parameters
const newParams = new URLSearchParams(search)
for (const [key, value] of newParams.entries()) {
newUrl.searchParams.set(key, value)
}
}
return newUrl
}
/**
* Checks if a status code is a redirect status code
*/
export function isRedirectStatus(status: number | undefined): boolean {
if (!status) return false
return status >= 300 && status < 400
}
/**
* Checks if headers contain redirect headers (Location or Refresh)
*/
export function hasRedirectHeaders(headers: Record<string, string>): boolean {
const lowerCaseKeys = Object.keys(headers).map((k) => k.toLowerCase())
return lowerCaseKeys.includes('location') || lowerCaseKeys.includes('refresh')
}
This diff is collapsed.
export { resolveRoutes } from './resolve-routes'
export type {
RouteHas,
Route,
MiddlewareContext,
MiddlewareResult,
ResolveRoutesParams,
ResolveRoutesResult,
} from './types'
export type { I18nConfig, I18nDomain } from './i18n'
export {
detectLocale,
detectDomainLocale,
normalizeLocalePath,
getAcceptLanguageLocale,
getCookieLocale,
} from './i18n'
export { responseToMiddlewareResult } from './middleware'
import type { RouteHas } from './types'
/**
* Checks if a value matches the condition.
* If conditionValue is undefined, returns the key's value if it exists.
* If conditionValue is defined, it can be a regex string or a direct match.
*/
function matchesCondition(
actualValue: string | undefined,
conditionValue: string | undefined
): { matched: boolean; capturedValue?: string } {
if (actualValue === undefined) {
return { matched: false }
}
// If no value condition is specified, match if key exists and return its value
if (conditionValue === undefined) {
return { matched: true, capturedValue: actualValue }
}
// Try to match as regex first
try {
const regex = new RegExp(conditionValue)
const match = actualValue.match(regex)
if (match) {
return { matched: true, capturedValue: match[0] }
}
} catch (e) {
// Not a valid regex, fall through to direct match
}
// Direct string match
if (actualValue === conditionValue) {
return { matched: true, capturedValue: actualValue }
}
return { matched: false }
}
/**
* Extracts the value for a RouteHas condition from the request context
*/
function getConditionValue(
condition: RouteHas,
url: URL,
headers: Headers
): string | undefined {
switch (condition.type) {
case 'header':
return headers.get(condition.key) || undefined
case 'cookie': {
const cookieHeader = headers.get('cookie')
if (!cookieHeader) return undefined
// Parse cookies
const cookies = cookieHeader.split(';').reduce(
(acc, cookie) => {
const [key, ...valueParts] = cookie.trim().split('=')
if (key) {
acc[key] = valueParts.join('=')
}
return acc
},
{} as Record<string, string>
)
return cookies[condition.key]
}
case 'query':
return url.searchParams.get(condition.key) || undefined
case 'host':
return url.hostname
default:
return ''
}
}
/**
* Normalizes a capture key to only contain a-zA-Z characters
*/
function normalizeCaptureKey(key: string): string {
return key.replace(/[^a-zA-Z]/g, '')
}
/**
* Checks if all "has" conditions are satisfied
*/
export function checkHasConditions(
has: RouteHas[] | undefined,
url: URL,
headers: Headers
): { matched: boolean; captures: Record<string, string> } {
if (!has || has.length === 0) {
return { matched: true, captures: {} }
}
const captures: Record<string, string> = {}
for (const condition of has) {
const actualValue = getConditionValue(condition, url, headers)
const result = matchesCondition(actualValue, condition.value)
if (!result.matched) {
return { matched: false, captures: {} }
}
// Store captured value with normalized key name for named replacements
if (result.capturedValue !== undefined && condition.type !== 'host') {
const normalizedKey = normalizeCaptureKey(condition.key)
captures[normalizedKey] = result.capturedValue
}
}
return { matched: true, captures }
}
/**
* Checks if all "missing" conditions are satisfied (i.e., none of them match)
*/
export function checkMissingConditions(
missing: RouteHas[] | undefined,
url: URL,
headers: Headers
): boolean {
if (!missing || missing.length === 0) {
return true
}
for (const condition of missing) {
const actualValue = getConditionValue(condition, url, headers)
const result = matchesCondition(actualValue, condition.value)
// If any missing condition matches, the check fails
if (result.matched) {
return false
}
}
return true
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
{
"compilerOptions": {
"target": "es2022",
"moduleResolution": "node",
"strict": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"skipLibCheck": false,
"lib": ["es2022", "dom"]
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "dist"]
}
This diff is collapsed.
......@@ -37,7 +37,7 @@ describe('adapter-config export', () => {
const {
outputs,
routes,
routing,
config,
...ctx
}: Parameters<NextAdapter['onBuildComplete']>[0] = await next.readJSON(
......@@ -80,11 +80,14 @@ describe('adapter-config export', () => {
expect(stats.isFile()).toBe(true)
}
expect(routes).toEqual({
expect(routing).toEqual({
beforeMiddleware: expect.toBeArray(),
beforeFiles: expect.toBeArray(),
afterFiles: expect.toBeArray(),
dynamicRoutes: expect.toBeArray(),
rewrites: expect.toBeObject(),
redirects: expect.toBeArray(),
headers: expect.toBeArray(),
onMatch: expect.toBeArray(),
fallback: expect.toBeArray(),
shouldNormalizeNextData: expect.toBeBoolean(),
})
})
})
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