forked from MetaMask/metamask-docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
42 lines (37 loc) · 1.62 KB
/
Copy pathmiddleware.ts
File metadata and controls
42 lines (37 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { next, rewrite } from '@vercel/edge'
/**
* Accept: text/markdown content negotiation.
*
* The corresponding `rewrites` rule in vercel.json does NOT fire for paths
* that resolve to an existing static asset (e.g. `/embedded-wallets/index.html`),
* which is every documentation page on this site. Vercel Edge Middleware
* runs before static file serving, so it's the only place we can route
* `Accept: text/markdown` requests to the `.md` sibling that
* `docusaurus-plugin-llms` (wrapped by `src/plugins/llms-html-injector`) emits
* next to each page.
*
* The matcher excludes static asset directories so the middleware doesn't run
* on every image, font, or script request. The `\.[a-zA-Z0-9]+$` clause
* excludes any path that already ends in an extension (`/foo.md`, `/foo.png`,
* `/llms-snaps.txt`, etc.) so those are served unmodified.
*/
export const config = {
matcher: ['/((?!_next|api|img|js|fonts|logos|.*\\.[a-zA-Z0-9]+$).*)'],
}
export default function middleware(request: Request) {
const accept = request.headers.get('accept') || ''
if (!/text\/markdown/i.test(accept)) return next()
const url = new URL(request.url)
if (url.pathname.endsWith('.md')) return next()
let pathname = url.pathname
if (pathname.endsWith('/')) pathname = pathname.slice(0, -1)
if (!pathname) {
// The homepage has no `.md` sibling (the root index.html is skipped by the
// llms-html-injector by design), so route agents to the documentation
// index, which is already served as text/markdown.
url.pathname = '/llms.txt'
return rewrite(url)
}
url.pathname = `${pathname}.md`
return rewrite(url)
}