Skip to content
Open
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
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,12 @@ jobs:
- name: Test redirect invariants
run: python3 scripts/test_check_redirects.py

# Replays vercel.json through @vercel/routing-utils: one URL per page
# (trailing slash), slash-agnostic legacy redirects, at most 2 hops,
# and slash-form internal links in docs content.
- name: Test trailing-slash redirects
run: npm run test:redirect-slashes

# Stdlib-only tests for the missing_docs skill scripts. The reviewer-resolver
# unit tests run fully here; the audit integration tests skip gracefully
# because the warp/warp-server code repos aren't checked out in docs CI.
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"test:heading-vars": "node --test src/plugins/heading-vars-core.test.mjs",
"test:docs-markdown": "node --test src/integrations/docs-markdown-integration.test.js",
"test:tracking-redirect": "node --test scripts/tracking-redirect.test.mjs",
"test:redirect-slashes": "node --test scripts/redirect-slashes.test.mjs",
"test:agent-discovery": "node --test scripts/agent-discovery.test.mjs",
"test:agent-doc-outputs": "node scripts/validate-agent-doc-outputs.mjs",
"test:tracking-routes": "node scripts/validate-tracking-routes.mjs",
Expand Down
36 changes: 34 additions & 2 deletions scripts/build-tracking-middleware.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { copyFile, mkdir, readFile, writeFile } from 'node:fs/promises';
import { access, copyFile, mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
import { STRIPPED_PARAMS } from '../src/lib/tracking-redirect.js';
import { isEligibleDocHtmlPath } from '../src/lib/docs-markdown.js';

// Astro's Vercel adapter serves prerendered pages before its own middleware.
// Emit native routing middleware before the filesystem phase instead:
Expand Down Expand Up @@ -32,7 +35,36 @@ await installEdgeMiddleware(
await installEdgeMiddleware(
'markdown-negotiation',
new URL('../src/lib/markdown-negotiation.js', import.meta.url),
[new URL('../src/lib/docs-markdown.js', import.meta.url)],
[
new URL('../src/lib/docs-markdown.js', import.meta.url),
new URL('../src/lib/markdown-negotiation.js', import.meta.url),
],
);

// Use deployed files, not URL guesses: aliases, unknown paths, and HTML-only
// pages must reach normal redirects or the filesystem instead of a missing .md.
const staticDir = new URL('static/', output);
const canonicalPages = [];
for (const entry of await readdir(staticDir, { recursive: true, withFileTypes: true })) {
if (!entry.isFile() || !entry.name.endsWith('.md')) continue;
const file = pathToFileURL(join(entry.parentPath, entry.name));
const relative = file.pathname.slice(staticDir.pathname.length);
const page = relative === 'index.md' ? '/' : `/${relative.slice(0, -3)}/`;
if (!isEligibleDocHtmlPath(page)) continue;
try {
await access(new URL(`${page.slice(1)}index.html`, staticDir));
} catch (error) {
if (error.code === 'ENOENT') continue;
throw error;
}
canonicalPages.push(page);
}
if (!canonicalPages.includes('/')) throw new Error('No homepage Markdown twin found');
await writeFile(
new URL('functions/markdown-negotiation.func/index.js', output),
`import negotiate from './markdown-negotiation.js';\n`
+ `const pages = new Set(${JSON.stringify(canonicalPages.sort())});\n`
+ `export default (request) => negotiate(request, pages);\n`,
);

// Entries in `has` are AND-ed, so each stripped parameter gets its own route.
Expand Down
17 changes: 13 additions & 4 deletions scripts/markdown-negotiation.test.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import markdownNegotiation from '../src/lib/markdown-negotiation.js';
import negotiate from '../src/lib/markdown-negotiation.js';

const pages = new Set(['/', '/quickstart/', '/support-and-community/', '/agents/capabilities/skills/']);
const markdownNegotiation = (req) => negotiate(req, pages);

function request(path, headers = {}) {
return new Request(`https://docs.warp.dev${path}`, { headers });
Expand All @@ -9,10 +12,9 @@ function request(path, headers = {}) {
test('rewrites eligible paths when Accept prefers markdown', () => {
const cases = [
['/', '/index.md'],
['/quickstart', '/quickstart.md'],
['/quickstart/', '/quickstart.md'],
['/support-and-community/', '/support-and-community.md'],
['/agents/capabilities/skills', '/agents/capabilities/skills.md'],
['/agents/capabilities/skills/', '/agents/capabilities/skills.md'],
];

for (const [path, expected] of cases) {
Expand Down Expand Up @@ -50,7 +52,7 @@ test('production does not rewrite on text/plain or agent UA alone', () => {

test('preserves query strings on rewrite', () => {
const response = markdownNegotiation(
request('/quickstart?utm_source=agent', { accept: 'text/markdown' }),
request('/quickstart/?utm_source=agent', { accept: 'text/markdown' }),
);
assert.equal(
response.headers.get('x-middleware-rewrite'),
Expand All @@ -65,6 +67,13 @@ test('continues for HTML clients, assets, APIs, retrieve, and direct .md URLs',
request('/_astro/page.js', { accept: 'text/markdown' }),
request('/retrieve?q=hello', { accept: 'text/markdown' }),
request('/api/support-handoff', { accept: 'text/markdown' }),
request('/api/', { accept: 'text/markdown' }),
request('/api', { accept: 'text/markdown' }),
request('/agent-platform/', { accept: 'text/markdown' }),
request('/agent-platform', { accept: 'text/markdown' }),
request('/does-not-exist/', { accept: 'text/markdown' }),
request('/quickstart', { accept: 'text/markdown' }),
request('/agents/capabilities/skills', { accept: 'text/markdown' }),
request('/llms.txt', { accept: 'text/markdown' }),
];

Expand Down
284 changes: 284 additions & 0 deletions scripts/redirect-slashes.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,284 @@
// Ordinary HTML page URLs canonicalize to the trailing-slash form. vercel.json sets
// `trailingSlash: true`, so Vercel 308s `/page` to `/page/` before any
// redirect runs. These tests compile vercel.json with @vercel/routing-utils
// (the library Vercel uses to build the routing table) and replay requests
// against the result, so a redirect that only matches one slash form, a
// shadowed page, or a long redirect chain fails CI instead of production.
import assert from 'node:assert/strict';
import { readdir, readFile } from 'node:fs/promises';
import { test } from 'node:test';
import routingUtils from '@vercel/routing-utils';

const { getTransformedRoutes } = routingUtils;
const repoFile = (path) => new URL(`../${path}`, import.meta.url);
const config = JSON.parse(await readFile(repoFile('vercel.json'), 'utf8'));
const redirects = config.redirects;

const { routes, error } = getTransformedRoutes({
trailingSlash: config.trailingSlash,
redirects,
});
assert.equal(error, null, error?.message);
const table = routes
.filter((route) => !route.handle)
.map((route) => ({
re: new RegExp(route.src),
status: route.status,
location: route.headers?.Location,
}));

const EXTENSION = /\.[A-Za-z0-9]+$/;
const lastSegment = (path) => path.replace(/\/$/, '').split('/').pop();
const isFragmentSource = (source) => source.includes('#');
const hasParams = (value) => /:[A-Za-z_]|\(\.\*\)|\$/.test(value.replace('(/?)', ''));

/** One routing pass: the redirect Location for `path`, or null. */
function step(path) {
for (const route of table) {
const match = route.re.exec(path);
if (!match) continue;
if (!route.status) return null; // e.g. /.well-known passthrough
return substitute(route.location, match);
}
return null;
}

/** Fill `$1` / `$name` placeholders from a regex match, as Vercel does. */
function substitute(template, match) {
return template.replace(/\$(\d+|[A-Za-z_]\w*)/g, (_, key) =>
(/^\d+$/.test(key) ? match[Number(key)] : match.groups?.[key]) ?? '',
);
}

/** Follow redirects; returns the final path (or URL) and the hop count. */
function follow(path) {
let current = path;
let hops = 0;
const seen = new Set();
while (hops < 6) {
assert.ok(!seen.has(current), `redirect loop from ${path} at ${current}`);
seen.add(current);
const next = step(current.split(/[?#]/)[0]);
if (next === null) break;
hops += 1;
current = next;
if (/^https?:\/\//.test(current)) return { final: current, hops, external: true };
}
return { final: current, hops, external: false };
}

async function contentFiles(dir) {
const entries = await readdir(dir, { withFileTypes: true });
const files = await Promise.all(entries.map((entry) => {
const url = new URL(entry.name + (entry.isDirectory() ? '/' : ''), dir);
return entry.isDirectory() ? contentFiles(url) : [url];
}));
return files.flat();
}

const docsRoot = repoFile('src/content/docs/');
const pages = new Set(['/api/']);
const contentSources = [];
for (const file of await contentFiles(docsRoot)) {
const rel = file.href.slice(docsRoot.href.length);
if (!/\.mdx?$/.test(rel)) continue;
contentSources.push([rel, await readFile(file, 'utf8')]);
const slug = rel.replace(/\.mdx?$/, '').replace(/(^|\/)index$/, '').toLowerCase();
pages.add(slug ? `/${slug}/` : '/');
}

function isServed(target) {
const path = target.split(/[?#]/)[0];
if (pages.has(path)) return true;
if (path.endsWith('.md')) return pages.has(`${path.slice(0, -3)}/`) || path === '/index.md';
return EXTENSION.test(lastSegment(path)); // generated asset (feed, sitemap, spec)
}

/** A concrete request path that `source` matches. */
function sampleFor(source) {
return source
.replace(/\(\/\?\)$/, '')
.replace(/:[A-Za-z_]\w*(\([^)]*\))?[*+?]?/g, 'sample-segment')
.replace(/\(\.\*\)/g, 'sample-segment')
.replace(/\\/g, '');
}

/** Collect every failure in a loop so one CI run lists them all. */
function expectNone(failures, label) {
assert.deepEqual(failures, [], `${failures.length} ${label}:\n${failures.join('\n')}`);
}

const slashForms = (path) => {
if (EXTENSION.test(lastSegment(path)) && !path.endsWith('/')) return [path];
const base = path.replace(/\/$/, '');
return [base, `${base}/`];
};

test('vercel.json enables trailing slashes', () => {
assert.equal(config.trailingSlash, true);
});

test('no-slash page URLs 308 once to the slash form and slash forms are served', () => {
assert.ok(pages.size > 100, `only ${pages.size} pages found`);
const failures = [];
for (const page of pages) {
if (page === '/') continue;
if (step(page) !== null) failures.push(`${page} is shadowed by a redirect to ${step(page)}`);
const { final, hops } = follow(page.slice(0, -1));
if (final !== page || hops !== 1) failures.push(`${page.slice(0, -1)} -> ${final} in ${hops} hops`);
}
expectNone(failures, 'page URL problems');
});

test('files, well-known paths, and Markdown twins are never slash-redirected', () => {
for (const path of [
'/llms.txt', '/llms-full.txt', '/sitemap-index.xml', '/robots.txt', '/openapi.json',
'/.well-known/ard.json', '/.well-known/mcp.json', '/.well-known/anything',
'/factories.md', '/agents/capabilities/skills.md', '/index.md',
]) {
assert.equal(step(path), null, path);
}
});

test('redirect sources match both slash forms; literal destinations are served within 2 hops', () => {
const failures = [];
for (const { source, destination } of redirects) {
if (isFragmentSource(source)) continue;
const results = slashForms(sampleFor(source)).map((form) => ({ form, ...follow(form) }));
for (const result of results) {
if (result.hops < 1) failures.push(`${source}: ${result.form} is not redirected`);
}
if (new Set(results.map((result) => result.final)).size !== 1) {
failures.push(`${source}: slash forms diverge ${JSON.stringify(results)}`);
}
if (hasParams(source) || hasParams(destination)) continue;
for (const { form, final, hops, external } of results) {
if (hops > 2) failures.push(`${source}: ${form} takes ${hops} hops`);
if (!external && !isServed(final)) failures.push(`${source}: ${form} ends at missing ${final}`);
}
}
expectNone(failures, 'redirect problems');
});

test('known underscore error aliases reach the final page within 2 hops', () => {
const aliases = redirects.filter(({ source }) =>
source.startsWith('/factories/api-and-sdk/troubleshooting/errors/') && source.includes('_'),
);
assert.ok(aliases.length > 10, 'missing underscore error fixtures');
for (const { source, destination } of aliases) {
const code = source.replace('(/?)', '').split('/').at(-1);
for (const form of slashForms(`/errors/${code}`)) {
const result = follow(form);
assert.equal(result.final, destination, form);
assert.ok(result.hops <= 2, `${form} takes ${result.hops} hops`);
assert.ok(isServed(result.final), result.final);
}
}
});

test('concrete wildcard migrations reach real pages within 2 hops', () => {
for (const [source, destination] of [
['/cli/oz-cli/api-keys', '/agents/cli/oz-cli/api-keys/'],
['/errors/authentication-required', '/factories/api-and-sdk/troubleshooting/errors/authentication-required/'],
['/guides/integrations/how-to-set-up-claude-code', '/guides/'],
['/reference/api-and-sdk/quickstart', '/factories/api-and-sdk/quickstart/'],
['/reference/cli/api-keys', '/agents/cli/oz-cli/api-keys/'],
]) {
for (const form of slashForms(source)) {
const result = follow(form);
assert.equal(result.final, destination, form);
assert.ok(result.hops <= 2, `${form} takes ${result.hops} hops`);
assert.ok(isServed(result.final), result.final);
}
}
});

test('fragment-only sources have a fragment-free redirect or page for their path', () => {
// Browsers never send #fragments, so these sources cannot match on their own.
const failures = [];
for (const { source } of redirects.filter((redirect) => isFragmentSource(redirect.source))) {
const path = slashForms(source.split('#')[0]).at(-1);
const { final } = follow(path);
if (!isServed(final)) failures.push(`${source}: ${path} ends at missing ${final}`);
}
expectNone(failures, 'uncovered fragment sources');
});

test('no duplicate or conflicting redirect sources', () => {
const failures = [];
const sources = new Set();
const byNormalized = new Map();
for (const { source, destination } of redirects) {
if (sources.has(source)) failures.push(`duplicate source ${source}`);
sources.add(source);
const key = source.replace(/\(\/\?\)$/, '').replace(/\/$/, '');
const previous = byNormalized.get(key);
if (previous !== undefined && previous !== destination) {
failures.push(`${source} conflicts: ${previous} vs ${destination}`);
}
byNormalized.set(key, destination);
}
expectNone(failures, 'duplicate or conflicting sources');
});

test('internal page destinations use the canonical slash form', () => {
const failures = redirects
.filter(({ destination }) => destination.startsWith('/') && !hasParams(destination))
.filter(({ destination }) => {
const path = destination.split(/[?#]/)[0];
return !path.endsWith('/') && !EXTENSION.test(lastSegment(path));
})
.map(({ source, destination }) => `${source} -> ${destination}`);
expectNone(failures, 'destinations without a trailing slash');
});

test('no redirect or rewrite turns a page URL into a /.md path', () => {
// Rewrites are replayed as if their `has` conditions (such as an Accept
// header) match. This guards the path shape only; it does not check what
// any rewrite serves.
const rewrites = getTransformedRoutes({ rewrites: config.rewrites ?? [] }).routes
.filter((route) => route.dest)
.map((route) => ({ re: new RegExp(route.src), dest: route.dest }));
const failures = [];
for (const page of pages) {
for (const form of new Set([page, page.replace(/\/$/, '') || '/'])) {
const seen = [form];
let current = form;
for (let hop = 0; hop < 6; hop += 1) {
const next = step(current);
if (next === null) break;
seen.push(next);
current = next.split(/[?#]/)[0];
}
const rewritten = [];
for (const path of seen) {
for (const { re, dest } of rewrites) {
const match = re.exec(path.split(/[?#]/)[0]);
if (match) rewritten.push(substitute(dest, match));
}
}
const bad = [...seen, ...rewritten].filter((path) => path.split(/[?#]/)[0].endsWith('/.md'));
if (bad.length) failures.push(`${form} -> ${bad.join(', ')}`);
}
}
expectNone(failures, 'page URLs that reach a /.md path');
});

test('internal links in docs content use the canonical slash URL', () => {
// A link to /page instead of /page/ costs every reader and crawler a 308.
// Fenced code blocks and inline code are skipped.
const link = /(\]\(|href=["'])(\/[^)\s"'#?]*[^)\s"'#?/])(?=[)\s"'#?])/g;
const failures = [];
for (const [file, text] of contentSources) {
const prose = text
.replace(/^\s*(```|~~~)[\s\S]*?^\s*\1.*$/gm, '')
.replace(/`[^`\n]*`/g, '');
for (const match of prose.matchAll(link)) {
const path = match[2];
if (!EXTENSION.test(lastSegment(path)) && pages.has(`${path}/`)) {
failures.push(`${file}: ${path} -> ${path}/`);
}
}
}
expectNone(failures, 'no-slash internal links');
});
Loading
Loading