Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 10 additions & 17 deletions proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,16 @@ import { NextRequest, NextResponse } from 'next/server';
*
* Legacy `/comparison/*` URLs (from before the comparison was unified
* into the model page via `?compare=`) are redirected to their new
* model-section homes here so middleware fires before the next.config
* `redirects()` (which only runs after middleware rewrites — too late
* to redirect a country-prefixed path).
* model-section homes here for country-prefixed URLs. The unprefixed
* URLs are handled by next.config redirects.
*/

/**
* Old /comparison/* path → new model-section path with `?compare=all`.
* Keep in sync with the `redirects()` block in `next.config.ts`, which
* handles the same paths when no country prefix is present.
*/
const LEGACY_COMPARISON_DESTINATIONS: Record<string, string> = {
export const LEGACY_COMPARISON_DESTINATIONS: Record<string, string> = {
'/comparison': '/?compare=all',
'/comparison/coverage': '/rules/coverage?compare=all',
'/comparison/modeling': '/?compare=all',
Expand All @@ -48,9 +47,7 @@ export function proxy(req: NextRequest) {
const pathname = req.nextUrl.pathname;
const match = pathname.match(/^\/(us|uk)(\/.*)?$/);

// 1. No country prefix → fall through to next.config redirects /
// static routing. Country-less legacy `/comparison/*` redirects
// live in next.config.ts.
// 1. Unprefixed requests fall through with their original headers.
if (!match) return NextResponse.next();

const country = match[1];
Expand All @@ -62,16 +59,12 @@ export function proxy(req: NextRequest) {
: rawRest;
const publicBase = hasModelMount ? `/${country}/model` : `/${country}`;

// 2. Country-prefixed legacy `/{country}/comparison/*` paths: emit
// a 308 to the country-preserved new path. (next.config redirects
// can't see country-prefixed paths because this middleware would
// have already stripped the prefix below.)
if (LEGACY_COMPARISON_DESTINATIONS[rest]) {
const dest = LEGACY_COMPARISON_DESTINATIONS[rest];
const target = `${publicBase}${dest}`;
const url = req.nextUrl.clone();
const [path, query] = target.split('?');
url.pathname = path;
// 2. Legacy comparison links redirect within their original mount.
const dest = LEGACY_COMPARISON_DESTINATIONS[rest.replace(/\/$/, '')];
if (dest) {
const url = new URL(req.url);
const [path, query] = dest.split('?');
url.pathname = `${publicBase}${path}`.replace(/\/$/, '');
// Merge the legacy `?compare=all` into existing search params.
if (query) {
for (const [k, v] of new URLSearchParams(query)) {
Expand Down
135 changes: 132 additions & 3 deletions src/test/proxy.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { readdirSync } from 'node:fs';
import { resolve, sep } from 'node:path';
import { describe, expect, it } from 'vitest';
import { NextRequest } from 'next/server';
import { unstable_doesMiddlewareMatch } from 'next/experimental/testing/server';
import { config, proxy } from '../../proxy';
import nextConfig from '../../next.config';
import { config, LEGACY_COMPARISON_DESTINATIONS, proxy } from '../../proxy';

const ORIGIN = 'https://model.test';

function runProxy(path: string) {
return proxy(new NextRequest(`${ORIGIN}${path}`));
function runProxy(path: string, headers?: HeadersInit) {
return proxy(new NextRequest(`${ORIGIN}${path}`, { headers }));
}

function headerUrl(response: Response, header: string) {
Expand All @@ -15,6 +18,43 @@ function headerUrl(response: Response, header: string) {
return new URL(value!, ORIGIN);
}

const countries = ['us', 'uk'];
const mounts = countries.flatMap((country) =>
[`/${country}`, `/${country}/model`].map((mount) => ({ country, mount })),
);
const pagePaths = readdirSync(resolve(__dirname, '../../app'), { encoding: 'utf8', recursive: true })
.map((file) => file.split(sep).join('/'))
.filter((file) => /(^|\/)page\.[jt]sx?$/.test(file))
.map((file) => `/${file.replace(/(^|\/)page\.[jt]sx?$/, '')}`)
.sort();
const queryStrings = [
'',
'?embed=true',
'?tag=one&tag=two&empty=',
'?q=two%20words&encoded=%2F%2B%26&name=%E2%82%AC',
'?compare=none&keep=1&compare=us',
];

function underMount(mount: string, path: string) {
return path === '/' ? mount : `${mount}${path}`;
}

function expectRewrite(response: Response, target: string, country: string) {
expect(response.status).toBe(200);
expect(response.headers.get('location')).toBeNull();
expect(response.headers.get('x-middleware-rewrite')).toBe(`${ORIGIN}${target}`);
expect(response.headers.get('x-middleware-override-headers')?.split(',')).toContain('x-pe-country');
expect(response.headers.get('x-middleware-request-x-pe-country')).toBe(country);
}

function expectNext(response: Response) {
expect(response.status).toBe(200);
expect(response.headers.get('x-middleware-next')).toBe('1');
expect(response.headers.get('location')).toBeNull();
expect(response.headers.get('x-middleware-rewrite')).toBeNull();
expect(response.headers.get('x-middleware-request-x-pe-country')).toBeNull();
}

describe('country proxy', () => {
it.each([
['/us/programs-us.json', '/programs-us.json'],
Expand Down Expand Up @@ -71,4 +111,93 @@ describe('country proxy', () => {
expect(location.pathname).toBe('/uk/rules/coverage');
expect(location.searchParams.get('compare')).toBe('all');
});

it('keeps the legacy comparison sources and destinations in sync', async () => {
const redirects = await nextConfig.redirects!();
const comparisonRedirects = redirects
.filter(({ source }) => source === '/comparison' || source.startsWith('/comparison/'))
.map(({ source, destination }) => [source, destination]);
expect(comparisonRedirects.sort()).toEqual(Object.entries(LEGACY_COMPARISON_DESTINATIONS).sort());
});

const internalPaths = [
...pagePaths, '/rules/coverage/federal', '/data/pipeline/inputs',
'/modeling', '/models/x', '/comparisonx', '/caf%C3%A9',
];
it.each(mounts.flatMap(({ country, mount }) => internalPaths.flatMap((path) =>
queryStrings.map((query) => ({ country, path, query, request: underMount(mount, path) + query })),
)))('rewrites $request with URL country $country', ({ country, path, query, request }) => {
const response = runProxy(request, { 'x-pe-country': country === 'us' ? 'uk' : 'us' });
expectRewrite(response, path + query, country);
});

it.each(mounts.flatMap(({ country, mount }) =>
Object.entries(LEGACY_COMPARISON_DESTINATIONS).flatMap(([source, destination]) =>
queryStrings.map((query) => ({ country, mount, destination, request: mount + source + query })),
),
))('redirects $request once under its original mount', ({ country, mount, destination, request }) => {
const response = runProxy(request);
expect(response.status).toBe(308);
expect(response.headers.get('x-middleware-rewrite')).toBeNull();
const location = headerUrl(response, 'location');
const destinationPath = new URL(destination, ORIGIN).pathname;
expect(location.origin).toBe(ORIGIN);
expect(location.pathname).toBe(underMount(mount, destinationPath));
expect(location.searchParams.getAll('compare')).toEqual(['all']);
const otherParams = (url: URL) => [...url.searchParams].filter(([key]) => key !== 'compare');
expect(otherParams(location)).toEqual(otherParams(new URL(request, ORIGIN)));
expectRewrite(runProxy(location.pathname + location.search), destinationPath + location.search, country);
});

it.each(['/us/comparison/', '/us/model/comparison/coverage/', '/us/model/', '/us/'])(
'handles the trailing slash on %s like its slashless form', (path) => {
const withSlash = runProxy(path);
const withoutSlash = runProxy(path.slice(0, -1));
expect({ status: withSlash.status, headers: [...withSlash.headers] })
.toEqual({ status: withoutSlash.status, headers: [...withoutSlash.headers] });
},
);

it.each(['/usa', '/us-states', '/ukraine', '/US/model'])('leaves the country near-miss %s alone', (path) => {
expectNext(runProxy(path));
});

it.each([
['/us/modeling', '/modeling'],
['/us/models/x', '/models/x'],
['/us/model/comparisonx', '/comparisonx'],
])('rewrites the real prefix on %s and keeps the near-miss segment', (path, target) => {
expectRewrite(runProxy(path), target, 'us');
});

it.each(['/rules', '/rules?country=us'])('passes the unprefixed request through at %s', (path) => {
const request = new NextRequest(`${ORIGIN}${path}`, { headers: { 'x-pe-country': 'uk' } });
const response = proxy(request);
expectNext(response);
// Without overrides, the app receives the original, client-supplied country hint.
expect(response.headers.get('x-middleware-override-headers')).toBeNull();
expect(request.headers.get('x-pe-country')).toBe('uk');
});

it.each(mounts.flatMap(({ mount }) => pagePaths.map((path) => underMount(mount, path))))(
'matches the App Router page at %s', (url) => {
expect(unstable_doesMiddlewareMatch({ config, nextConfig, url })).toBe(true);
},
);

const assets = [
'/logo.svg', '/nested/chunk.js', '/styles.css', '/robots.txt', '/other.json',
'/programs-ca.json', '/param-tree-ca.json', '/nested/programs-us.json', '/param-tree-uk.json.bak',
];
it.each(mounts.flatMap(({ mount }) => assets.map((path) => mount + path)))(
'excludes unrelated assets at %s', (url) => {
expect(unstable_doesMiddlewareMatch({ config, nextConfig, url })).toBe(false);
},
);

it.each(mounts.flatMap(({ mount }) => countries.flatMap((registry) =>
['programs', 'param-tree'].map((kind) => `${mount}/${kind}-${registry}.json`),
)))('matches the JSON snapshot exception at %s', (url) => {
expect(unstable_doesMiddlewareMatch({ config, nextConfig, url })).toBe(true);
});
});