/** * Helpers for making the per-page Markdown (createMarkdownRenderer) discoverable * and negotiable, so AI agents reliably find and read it. * * Two mechanisms: * - `markdownHref` — the `` href a * page advertises, so an agent fetching the HTML sees there's a Markdown * version and can switch to it. * - `prefersMarkdown` — reads the Accept header, so the same URL can serve * Markdown when asked (content negotiation via a proxy rewrite). */ /** Default URL prefix the Markdown route is mounted at (see createMarkdownRenderer). */ export const MARKDOWN_PREFIX = '/md' /** * The Markdown URL for a given page path. Keeps the `/md` prefix in ONE place so * the discovery link and the route agree. * * markdownHref('/pl/o-nas') // '/md/pl/o-nas' * markdownHref('/pl/o-nas', '/ai') // '/ai/pl/o-nas' * * Advertise it from Next metadata so every page's points to its Markdown: * * // generateMetadata * return { ...meta, alternates: { ...meta.alternates, types: { 'text/markdown': markdownHref(path) } } } */ export function markdownHref(pathname: string, prefix: string = MARKDOWN_PREFIX): string { const clean = pathname.startsWith('/') ? pathname : `/${pathname}` const p = prefix.replace(/\/$/, '') return `${p}${clean === '/' ? '' : clean}` || p } /** * True when the client asked for Markdown via the Accept header (q-values * respected: a higher-weighted text/html wins). Accepts a header string, a * Headers object, or a Request. Use it in proxy.ts to serve the same URL as * Markdown when an agent negotiates for it: * * // proxy.ts * if (prefersMarkdown(request)) { * return NextResponse.rewrite(new URL(markdownHref(request.nextUrl.pathname), request.url)) * } */ export function prefersMarkdown(input: Headers | null | Request | string | undefined): boolean { let accept: null | string = null if (!input) {return false} if (typeof input === 'string') {accept = input} else if (input instanceof Headers) {accept = input.get('accept')} else if ('headers' in input && input.headers) {accept = input.headers.get('accept')} if (!accept) {return false} // Parse "type/subtype;q=0.8" entries into {type, q}. const entries = accept.split(',').map((part) => { const [type, ...params] = part.trim().split(';') const qParam = params.find((p) => p.trim().startsWith('q=')) const q = qParam ? Number(qParam.split('=')[1]) : 1 return { type: type.trim().toLowerCase(), q: Number.isFinite(q) ? q : 1 } }) const md = entries.find((e) => e.type === 'text/markdown') if (!md) {return false} // Markdown must be at least as preferred as html (and html not strictly higher). const html = entries.find((e) => e.type === 'text/html') return !html || md.q >= html.q }