Skip to content

πŸŽ₯ Make videos programmatically with React

5.3 KB
Raw Blame
import {rewrite} from '@vercel/functions';

export const config = {
	matcher: [
		'/pricing',
		'/docs/:path*',
		'/elements',
		'/elements.md',
		'/elements/:path*',
		'/assets/:path*',
	],
};

let assetManifestPromise: Promise<Set<string> | null> | null = null;

// Lists every file under /assets of the current deployment, generated by
// generate-asset-manifest.ts during the build. Fetching through the production
// alias can return another deployment's manifest during a rollout.
function getAssetManifest(request: Request): Promise<Set<string> | null> {
	if (!assetManifestPromise) {
		const manifestUrl = new URL('/asset-manifest.json', request.url);
		if (
			process.env.VERCEL_SKEW_PROTECTION_ENABLED === '1' &&
			process.env.VERCEL_DEPLOYMENT_ID
		) {
			manifestUrl.searchParams.set('dpl', process.env.VERCEL_DEPLOYMENT_ID);
		} else if (
			process.env.VERCEL_ENV === 'production' &&
			process.env.VERCEL_URL
		) {
			manifestUrl.host = process.env.VERCEL_URL;
		}

		assetManifestPromise = fetch(manifestUrl)
			.then(async (res) => {
				if (!res.ok) {
					throw new Error(`Manifest returned status ${res.status}`);
				}

				return new Set((await res.json()) as string[]);
			})
			.catch(() => {
				// Fail open: without a manifest, requests fall through to static
				// serving (the pre-existing behavior). Retry on the next request.
				assetManifestPromise = null;
				return null;
			});
	}

	return assetManifestPromise;
}

function parseAcceptHeader(acceptHeader: string): string[] {
	return acceptHeader
		.split(',')
		.map((type) => {
			const [mediaType, ...params] = type.trim().split(';');
			const qMatch = params.find((p) => p.trim().startsWith('q='));
			const quality = qMatch ? parseFloat(qMatch.split('=')[1]) : 1.0;
			return {mediaType: mediaType.trim(), quality};
		})
		.sort((a, b) => b.quality - a.quality)
		.map((item) => item.mediaType);
}

function prefersMarkdown(
	acceptHeader: string | null,
	userAgent: string | null,
): boolean {
	if (userAgent) {
		const llmAgents = ['Claude-User', 'opencode'];
		for (const agent of llmAgents) {
			if (userAgent.includes(agent)) {
				return true;
			}
		}
	}

	if (!acceptHeader) {
		return false;
	}

	const acceptedTypes = parseAcceptHeader(acceptHeader);

	const markdownTypes = ['text/markdown', 'text/x-markdown', 'text/plain'];

	for (const type of acceptedTypes) {
		if (markdownTypes.includes(type)) {
			return true;
		}

		if (type === 'text/html' || type.startsWith('text/html;')) {
			return false;
		}

		if (type === '*/*') {
			return false;
		}
	}

	return false;
}

export default async function middleware(request: Request) {
	const url = new URL(request.url);
	const pathname = url.pathname;

	if (pathname.startsWith('/assets/')) {
		// Assets are content-hashed and vercel.ts marks /assets/(.*) as
		// `max-age=31536000, immutable`. Vercel applies that header to 404s too,
		// so a missing asset (e.g. requested by stale HTML after a deploy) would
		// be cached as "not found" for a year by browsers and CDNs. Serve misses
		// as uncacheable 404s instead; real files fall through to static serving.
		let decodedPathname = pathname;
		try {
			decodedPathname = decodeURIComponent(pathname);
		} catch {
			// Not decodable - cannot match a real file, will 404 below.
		}

		const manifest = await getAssetManifest(request);
		if (manifest && !manifest.has(decodedPathname)) {
			return new Response('Not Found', {
				status: 404,
				headers: {
					'Cache-Control': 'no-store',
					'Content-Type': 'text/plain; charset=utf-8',
					'X-Asset-404': 'not-in-manifest',
				},
			});
		}

		return;
	}

	if (pathname === '/pricing') {
		return Response.redirect(
			new URL('/docs/license/pricing', request.url),
			308,
		);
	}

	if (pathname === '/docs/pricing') {
		return Response.redirect(
			new URL('/docs/license/pricing', request.url),
			308,
		);
	}

	if (pathname === '/docs/license-pricing-compliance/faq') {
		return Response.redirect(new URL('/docs/license/faq', request.url), 308);
	}

	if (pathname === '/docs/license/license-faq') {
		return Response.redirect(new URL('/docs/license/faq', request.url), 308);
	}

	if (pathname === '/elements.md') {
		return rewrite(new URL('/_raw/elements/index.md', request.url));
	}

	if (pathname === '/elements') {
		return;
	}

	if (!pathname.startsWith('/docs/') && !pathname.startsWith('/elements/')) {
		return;
	}

	// Case 1: .md extension - rewrite to raw markdown
	// Example: /docs/your-first-video.md β†’ /_raw/docs/your-first-video.md
	// Example: /elements/overlays/name-lower-third.md β†’ /_raw/elements/overlays/name-lower-third.md
	if (pathname.endsWith('.md')) {
		const targetPath = pathname.replace(/^\/(docs|elements)\//, '/_raw/$1/');
		return rewrite(new URL(targetPath, request.url));
	}

	// Case 2: Accept header or user agent prefers markdown - rewrite to raw markdown
	// Example: /docs/your-first-video + Accept: text/markdown β†’ /_raw/docs/your-first-video.md
	// Example: /elements/overlays/name-lower-third + User-Agent: Claude β†’ /_raw/elements/overlays/name-lower-third.md
	const acceptHeader = request.headers.get('accept');
	const userAgent = request.headers.get('user-agent');
	if (prefersMarkdown(acceptHeader, userAgent)) {
		const cleanPathname = pathname.replace(/\/$/, '');
		const targetPath = `/_raw${cleanPathname}.md`;
		return rewrite(new URL(targetPath, request.url));
	}
}