From 57f71c4d5f7e4e87eae2e9b27e9e84e0d849c0cf Mon Sep 17 00:00:00 2001 From: Piotr Mlocek Date: Fri, 20 Nov 2026 16:23:42 -0800 Subject: [PATCH 1/2] feat(site): serve Markdown to clients that ask for it on Netlify A Netlify edge function serves each page's Markdown copy (.md) at the page's own URL when the request's Accept header prefers text/markdown. It runs only for GET and HEAD requests whose Accept mentions text/markdown, so browser traffic never invokes it. netlify.toml adds Vary: Accept to static responses. scripts/serve.mjs negotiates the same way locally. Signed-off-by: Piotr Mlocek --- README.md | 5 ++ netlify.toml | 10 +++ netlify/edge-functions/markdown.js | 69 +++++++++++++++++++++ scripts/redirects.mjs | 2 +- scripts/serve.mjs | 11 +++- test/markdown.test.mjs | 99 ++++++++++++++++++++++++++++++ 6 files changed, 192 insertions(+), 4 deletions(-) create mode 100644 netlify/edge-functions/markdown.js create mode 100644 test/markdown.test.mjs diff --git a/README.md b/README.md index 30e0145..f5a70ef 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,11 @@ repository is published without a version in the URL, such as versions have their own path, such as `/0.1.8/about/overview/` or `/sdks/go/dev/`. +Every page also has a Markdown copy at its path plus `.md`, listed in +`/llms.txt`. On Netlify, an [edge function](netlify/edge-functions/markdown.js) +serves that copy at the page's own URL to clients that send +`Accept: text/markdown`. + Broken links in fetched versions are warnings, so one repository can't block the site. To check a change to a repository's docs, build with `--local` (see [CONTRIBUTING.md](CONTRIBUTING.md)), where broken links are errors. Pull request diff --git a/netlify.toml b/netlify.toml index d3cd242..9bee9a6 100644 --- a/netlify.toml +++ b/netlify.toml @@ -4,7 +4,17 @@ # `npm run build` fetches the sources and assembles the pages before # building the site; `npm run site` alone expects them to be assembled already. # Netlify serves the site at the root, so BASE_PATH stays unset. +# netlify/edge-functions/ is picked up automatically; markdown.js serves each +# page's Markdown copy to clients that send `Accept: text/markdown`. [build] command = "npm run build" publish = "site/dist" + +# A page's URL serves HTML or Markdown depending on Accept (see +# netlify/edge-functions/markdown.js), so tell caches to key on it. The edge +# function runs only for Markdown requests, so the static responses set it here. +[[headers]] +for = "/*" +[headers.values] +Vary = "Accept" diff --git a/netlify/edge-functions/markdown.js b/netlify/edge-functions/markdown.js new file mode 100644 index 0000000..92d2224 --- /dev/null +++ b/netlify/edge-functions/markdown.js @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Serve a page's Markdown copy to clients that ask for Markdown with +// `Accept: text/markdown`. Every page has one at its path plus .md (the site's +// root page uses /index.md; see markdownHref in site/src/versioning.ts). +// Netlify runs it only for GET and HEAD requests whose Accept header mentions +// text/markdown, so browser traffic never invokes it (or costs anything); +// netlify.toml adds `Vary: Accept` to the static responses. Paths without a +// Markdown copy, such as redirect pages, fall back to the normal response. +// scripts/serve.mjs uses the same helpers to do this locally. + +// The quality a media range list gives one type, or 0 when it isn't acceptable. +// `exact` counts only ranges that name the type, not text/* or */*. +export function quality(accept, type, { exact = false } = {}) { + const [major] = type.split('/'); + let best = -1; + let q = 0; + for (const part of (accept ?? '').toLowerCase().split(',')) { + const [range, ...params] = part.split(';').map((s) => s.trim()); + const specificity = range === type ? 2 : exact ? -1 : range === `${major}/*` ? 1 : range === '*/*' ? 0 : -1; + if (specificity <= best) continue; + const qParam = params.find((p) => p.startsWith('q=')); + const value = qParam ? Number(qParam.slice(2)) : 1; + best = specificity; + q = Number.isFinite(value) ? value : 0; + } + return q; +} + +// Markdown only when the client names it, and likes it at least as much as HTML. +export function prefersMarkdown(accept) { + const md = quality(accept, 'text/markdown', { exact: true }); + return md > 0 && md >= quality(accept, 'text/html'); +} + +// /about/overview/ -> /about/overview.md; the root page -> /index.md. +export const markdownPath = (pathname, base = '/') => + pathname === base ? `${base}index.md` : `${pathname.replace(/\/$/, '')}.md`; + +export default async (request, context) => { + if (!['GET', 'HEAD'].includes(request.method) || !prefersMarkdown(request.headers.get('accept'))) { + return context.next(); + } + const url = new URL(request.url); + url.pathname = markdownPath(url.pathname); + // Forward the request's headers so password-protected deploy previews work. + const md = await fetch(url, { method: request.method, headers: request.headers }); + if (!md.ok && md.status !== 304) return context.next(); + // fetch has already decoded the body, so don't copy Content-Encoding or Length. + const headers = new Headers({ + 'Content-Type': 'text/markdown; charset=utf-8', + 'Content-Location': url.pathname, + Vary: 'Accept', + }); + for (const name of ['Cache-Control', 'ETag', 'Last-Modified']) { + if (md.headers.has(name)) headers.set(name, md.headers.get(name)); + } + return new Response(md.status === 304 ? null : md.body, { status: md.status, headers }); +}; + +// Pages have no file extension; assets, .md copies, llms.txt and the like skip +// this function. The header value is a regular expression matched against the +// whole Accept header; prefersMarkdown then weighs q-values. +export const config = { + pattern: '^/.*$', + excludedPattern: '\\.[A-Za-z0-9]+$', + method: ['GET', 'HEAD'], + header: { accept: '[Tt][Ee][Xx][Tt]/[Mm][Aa][Rr][Kk][Dd][Oo][Ww][Nn]' }, +}; diff --git a/scripts/redirects.mjs b/scripts/redirects.mjs index 407cdfc..aae3f37 100644 --- a/scripts/redirects.mjs +++ b/scripts/redirects.mjs @@ -11,7 +11,7 @@ // // -> //, from `redirects:` in docset.yml // (and Fern section URLs without an overview page) // Existing pages are never overwritten. A production host would use edge -// rules instead (and could also negotiate Markdown). +// rules instead. // Usage: node scripts/redirects.mjs site/dist import fs from 'node:fs'; import path from 'node:path'; diff --git a/scripts/serve.mjs b/scripts/serve.mjs index 3a6dfe5..75dd404 100644 --- a/scripts/serve.mjs +++ b/scripts/serve.mjs @@ -5,6 +5,7 @@ import fs from 'node:fs'; // Usage: node scripts/serve.mjs site/dist 4410 /openshell-docs/ import http from 'node:http'; import path from 'node:path'; +import { markdownPath, prefersMarkdown } from '../netlify/edge-functions/markdown.js'; const [dir = 'site/dist', port = '4410', base = '/'] = process.argv.slice(2); const root = path.resolve(dir); @@ -25,9 +26,13 @@ http .createServer((req, res) => { const u = decodeURIComponent(new URL(req.url, 'http://x').pathname); if (!u.startsWith(base) && `${u}/` !== base) return res.writeHead(404).end('not found'); - let f = path.join(root, u.slice(base.length - 1)); + // Serve the Markdown copy to clients that ask for it, like the Netlify edge + // function does. + const md = path.join(root, markdownPath(u, base).slice(base.length - 1)); + const negotiate = prefersMarkdown(req.headers.accept) && md.startsWith(root) && fs.existsSync(md); + let f = negotiate ? md : path.join(root, u.slice(base.length - 1)); if (!f.startsWith(root)) return res.writeHead(403).end(); - if (fs.existsSync(f) && fs.statSync(f).isDirectory()) { + if (!negotiate && fs.existsSync(f) && fs.statSync(f).isDirectory()) { if (!u.endsWith('/')) return res.writeHead(301, { location: `${u}/` }).end(); f = path.join(f, 'index.html'); } @@ -35,7 +40,7 @@ http res.writeHead(404, { 'content-type': types['.html'] }); return fs.createReadStream(path.join(root, '404.html')).pipe(res); } - res.writeHead(200, { 'content-type': types[path.extname(f)] ?? 'application/octet-stream' }); + res.writeHead(200, { 'content-type': types[path.extname(f)] ?? 'application/octet-stream', vary: 'Accept' }); fs.createReadStream(f).pipe(res); }) .listen(Number(port), '127.0.0.1', () => console.log(`serving ${dir} at http://127.0.0.1:${port}${base}`)); diff --git a/test/markdown.test.mjs b/test/markdown.test.mjs new file mode 100644 index 0000000..cdfcd8d --- /dev/null +++ b/test/markdown.test.mjs @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Tests the Netlify edge function that serves Markdown to clients that ask for it. +import assert from 'node:assert/strict'; +import { afterEach, describe, test } from 'node:test'; +import negotiate, { config, markdownPath, prefersMarkdown } from '../netlify/edge-functions/markdown.js'; + +describe('prefersMarkdown', () => { + for (const [accept, want] of [ + ['text/markdown', true], + ['text/markdown, text/html, */*', true], + ['text/html;q=0.9, text/markdown', true], + ['TEXT/Markdown; charset=utf-8', true], + ['text/markdown;q=0.5, text/html', false], + ['text/markdown;q=0', false], + ['text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', false], + ['*/*', false], + ['text/*', false], + ['', false], + [null, false], + ]) { + test(`${JSON.stringify(accept)} -> ${want}`, () => assert.equal(prefersMarkdown(accept), want)); + } +}); + +test('markdownPath', () => { + assert.equal(markdownPath('/'), '/index.md'); + assert.equal(markdownPath('/about/overview/'), '/about/overview.md'); + assert.equal(markdownPath('/0.1.8/about/overview'), '/0.1.8/about/overview.md'); + assert.equal(markdownPath('/docs/', '/docs/'), '/docs/index.md'); + assert.equal(markdownPath('/docs/sdks/go/', '/docs/'), '/docs/sdks/go.md'); +}); + +// Netlify invokes the function only when the Accept header matches this, so it +// must match every Accept that prefersMarkdown accepts. +test('header rule matches Markdown requests only', () => { + const rule = new RegExp(config.header.accept); + for (const accept of ['text/markdown', 'TEXT/Markdown; q=1', 'text/html;q=0.9, text/markdown']) + assert.ok(rule.test(accept), accept); + assert.ok(!rule.test('text/html,application/xhtml+xml,*/*;q=0.8')); +}); + +describe('edge function', () => { + const realFetch = globalThis.fetch; + afterEach(() => { + globalThis.fetch = realFetch; + }); + const html = { next: async () => new Response('', { headers: { 'Content-Type': 'text/html' } }) }; + const files = (map) => { + const fetched = []; + globalThis.fetch = async (url) => { + const { pathname } = new URL(url); + fetched.push(pathname); + return pathname in map + ? new Response(map[pathname], { headers: { ETag: '"md"' } }) + : new Response('', { status: 404 }); + }; + return fetched; + }; + const get = (path, accept, init = {}) => + new Request(`https://docs.example${path}`, { ...init, headers: { accept, ...init.headers } }); + + test('serves the Markdown copy', async () => { + const fetched = files({ '/about/overview.md': '# Overview' }); + const res = await negotiate(get('/about/overview/', 'text/markdown'), html); + assert.deepEqual(fetched, ['/about/overview.md']); + assert.equal(res.status, 200); + assert.equal(res.headers.get('content-type'), 'text/markdown; charset=utf-8'); + assert.equal(res.headers.get('content-location'), '/about/overview.md'); + assert.equal(res.headers.get('etag'), '"md"'); + assert.equal(res.headers.get('vary'), 'Accept'); + assert.equal(await res.text(), '# Overview'); + }); + + test('serves the root page as /index.md', async () => { + files({ '/index.md': '# Home' }); + assert.equal(await (await negotiate(get('/', 'text/markdown'), html)).text(), '# Home'); + }); + + test('serves HTML to browsers without fetching', async () => { + const fetched = files({}); + const res = await negotiate(get('/about/overview/', 'text/html,*/*;q=0.8'), html); + assert.deepEqual(fetched, []); + assert.equal(await res.text(), ''); + }); + + test('falls back to the page when there is no Markdown copy', async () => { + files({}); + const res = await negotiate(get('/latest/about/overview/', 'text/markdown'), html); + assert.equal(await res.text(), ''); + }); + + test('ignores other methods', async () => { + const fetched = files({ '/about/overview.md': '# Overview' }); + const res = await negotiate(get('/about/overview/', 'text/markdown', { method: 'POST' }), html); + assert.deepEqual(fetched, []); + assert.equal(await res.text(), ''); + }); +}); From 18e5ec69223d269eb45f585c7c20ebd5d46580c6 Mon Sep 17 00:00:00 2001 From: Piotr Mlocek Date: Mon, 23 Nov 2026 11:19:02 -0800 Subject: [PATCH 2/2] fix(site): drop the edge function's method filter Netlify's manifest accepts only GET, POST, PUT, PATCH, DELETE and OPTIONS, so listing HEAD failed the bundle. The Accept header rule already limits the function to Markdown requests, and the handler checks the method itself. Signed-off-by: Piotr Mlocek --- netlify/edge-functions/markdown.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/netlify/edge-functions/markdown.js b/netlify/edge-functions/markdown.js index 92d2224..4f10a4f 100644 --- a/netlify/edge-functions/markdown.js +++ b/netlify/edge-functions/markdown.js @@ -3,7 +3,7 @@ // Serve a page's Markdown copy to clients that ask for Markdown with // `Accept: text/markdown`. Every page has one at its path plus .md (the site's // root page uses /index.md; see markdownHref in site/src/versioning.ts). -// Netlify runs it only for GET and HEAD requests whose Accept header mentions +// Netlify runs it only for requests whose Accept header mentions // text/markdown, so browser traffic never invokes it (or costs anything); // netlify.toml adds `Vary: Accept` to the static responses. Paths without a // Markdown copy, such as redirect pages, fall back to the normal response. @@ -60,10 +60,10 @@ export default async (request, context) => { // Pages have no file extension; assets, .md copies, llms.txt and the like skip // this function. The header value is a regular expression matched against the -// whole Accept header; prefersMarkdown then weighs q-values. +// whole Accept header; prefersMarkdown then weighs q-values. The handler checks +// the method itself: Netlify's `method` filter doesn't accept HEAD. export const config = { pattern: '^/.*$', excludedPattern: '\\.[A-Za-z0-9]+$', - method: ['GET', 'HEAD'], header: { accept: '[Tt][Ee][Xx][Tt]/[Mm][Aa][Rr][Kk][Dd][Oo][Ww][Nn]' }, };