@vllnt/next-llms 0.1.0-canary.06b7b79
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +131 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/llms-text.d.ts +28 -0
- package/dist/llms-text.d.ts.map +1 -0
- package/dist/llms-text.js +78 -0
- package/dist/llms-text.js.map +1 -0
- package/dist/markdown-route.d.ts +35 -0
- package/dist/markdown-route.d.ts.map +1 -0
- package/dist/markdown-route.js +91 -0
- package/dist/markdown-route.js.map +1 -0
- package/dist/types.d.ts +58 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/package.json +96 -0
- package/src/index.ts +9 -0
- package/src/llms-text.ts +89 -0
- package/src/markdown-route.ts +100 -0
- package/src/types.ts +63 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 bntvllnt
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
<!-- Badges -->
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@vllnt/next-llms)
|
|
4
|
+
[](https://github.com/vllnt/next-llms/actions/workflows/ci.yml)
|
|
5
|
+
[](./LICENSE)
|
|
6
|
+
|
|
7
|
+
# @vllnt/next-llms
|
|
8
|
+
|
|
9
|
+
Make your Next.js site legible to AI agents — generate a spec-compliant
|
|
10
|
+
`llms.txt` manifest and serve any page as raw markdown.
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
// app/llms.txt/route.ts
|
|
14
|
+
import { generateLlmsText } from "@vllnt/next-llms";
|
|
15
|
+
|
|
16
|
+
export function GET() {
|
|
17
|
+
return new Response(
|
|
18
|
+
generateLlmsText({
|
|
19
|
+
title: "Acme",
|
|
20
|
+
summary: "Acme is a widget API.",
|
|
21
|
+
sections: [
|
|
22
|
+
{
|
|
23
|
+
title: "Docs",
|
|
24
|
+
links: [{ title: "Quickstart", url: "/docs/quickstart.md" }],
|
|
25
|
+
},
|
|
26
|
+
],
|
|
27
|
+
}),
|
|
28
|
+
{ headers: { "Content-Type": "text/plain; charset=utf-8" } },
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Emit the `llms.txt` index and expose any page's markdown at `/path.md` so agents
|
|
34
|
+
skip HTML parsing. Zero runtime dependencies — pure Web-standard APIs that run
|
|
35
|
+
in any Next.js runtime (and Remix, Hono, Deno, …).
|
|
36
|
+
|
|
37
|
+
## Features
|
|
38
|
+
|
|
39
|
+
- **Spec-compliant `llms.txt`** — `generateLlmsText` emits the llmstxt.org
|
|
40
|
+
shape: an `#` title, a `>` blockquote, `## Section` link lists, and a
|
|
41
|
+
droppable `## Optional` section.
|
|
42
|
+
- **Raw-markdown routes** — `createMarkdownRoute` serves any page as
|
|
43
|
+
`text/markdown`, stripping a trailing `.md` and resolving the slug through
|
|
44
|
+
your own content source.
|
|
45
|
+
- **Zero dependencies** — pure TypeScript over Web `Request` / `Response`;
|
|
46
|
+
nothing added to your bundle.
|
|
47
|
+
- **Runtime-agnostic** — the route handler imports nothing from `next`; it runs
|
|
48
|
+
on the Edge, Node, or any Web-standard runtime.
|
|
49
|
+
- **Typed end to end** — concrete config types guide correct usage; no `any`.
|
|
50
|
+
- **Cache-friendly** — sensible `Cache-Control` defaults, overridable per route.
|
|
51
|
+
|
|
52
|
+
## Installation
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
pnpm add @vllnt/next-llms
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Node.js `>=18`; no peer dependencies (the package imports nothing from `next` or
|
|
59
|
+
`react`). Every push to `main` can publish a prerelease to the `canary` channel
|
|
60
|
+
(`pnpm add @vllnt/next-llms@canary`); stable releases are published from a
|
|
61
|
+
`vX.Y.Z` tag. The older `generateLlmsFullText` API from early canary builds is
|
|
62
|
+
not part of the stable API; use the two exports below.
|
|
63
|
+
|
|
64
|
+
## Usage
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
// app/[...slug]/route.ts — serve any page as raw markdown
|
|
68
|
+
import { createMarkdownRoute } from "@vllnt/next-llms";
|
|
69
|
+
|
|
70
|
+
export const GET = createMarkdownRoute(async (slug) => {
|
|
71
|
+
const doc = await getDoc(slug.join("/")); // your content source
|
|
72
|
+
return doc?.markdown ?? null; // null → 404
|
|
73
|
+
});
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
`/docs/intro.md` resolves the slug `["docs", "intro"]` and returns the markdown
|
|
77
|
+
with `Content-Type: text/markdown`, or `404` when the resolver returns `null`.
|
|
78
|
+
|
|
79
|
+
## API Reference
|
|
80
|
+
|
|
81
|
+
| Export | Kind | Result |
|
|
82
|
+
| ----------------------------------------- | -------- | ----------------------------------------- |
|
|
83
|
+
| `generateLlmsText(config)` | function | `string` — the `llms.txt` index |
|
|
84
|
+
| `createMarkdownRoute(resolver, options?)` | factory | `(request: Request) => Promise<Response>` |
|
|
85
|
+
|
|
86
|
+
Full reference: [docs/API.md](docs/API.md). Also see the [LLM index](llms.txt),
|
|
87
|
+
[changelog](CHANGELOG.md), and
|
|
88
|
+
[issue tracker](https://github.com/vllnt/next-llms/issues).
|
|
89
|
+
|
|
90
|
+
## Security
|
|
91
|
+
|
|
92
|
+
- No secrets touched — the package generates text and serves whatever your
|
|
93
|
+
resolver returns.
|
|
94
|
+
- Your resolver is the boundary — authorize the slug before returning content.
|
|
95
|
+
The route rejects malformed percent-encoding and slug segments that are empty,
|
|
96
|
+
`.`, `..`, or contain `/`, `\` or NUL (`400`), but you still own how a slug
|
|
97
|
+
maps to a file or record.
|
|
98
|
+
- `generateLlmsText` escapes link titles and URLs and collapses line breaks, and
|
|
99
|
+
rejects blank titles/URLs and `javascript:`, `data:` or `vbscript:` URLs with
|
|
100
|
+
a `TypeError`.
|
|
101
|
+
- Successful responses default to **public caching** (one hour in browsers, one
|
|
102
|
+
day in shared caches). For private or personalized content, explicitly pass
|
|
103
|
+
`{ cacheControl: "private, no-store" }`; authorization alone does not disable
|
|
104
|
+
caching.
|
|
105
|
+
|
|
106
|
+
See [docs/API.md](docs/API.md) and the [security reporting policy](SECURITY.md).
|
|
107
|
+
|
|
108
|
+
## Testing
|
|
109
|
+
|
|
110
|
+
```bash
|
|
111
|
+
pnpm test # single run
|
|
112
|
+
pnpm test:coverage # enforced 100% on covered files
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Contributing
|
|
116
|
+
|
|
117
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
118
|
+
|
|
119
|
+
## Author
|
|
120
|
+
|
|
121
|
+
Built by [bntvllnt](https://github.com/bntvllnt) ·
|
|
122
|
+
[bntvllnt.com](https://bntvllnt.com) · [X @bntvllnt](https://x.com/bntvllnt)
|
|
123
|
+
|
|
124
|
+
Part of the [@vllnt](https://github.com/vllnt) open-source fleet —
|
|
125
|
+
[vllnt.com](https://vllnt.com)
|
|
126
|
+
|
|
127
|
+
If this is useful, [sponsor the work](https://github.com/sponsors/bntvllnt).
|
|
128
|
+
|
|
129
|
+
## License
|
|
130
|
+
|
|
131
|
+
MIT — see [LICENSE](LICENSE).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,YAAY,EACV,UAAU,EACV,QAAQ,EACR,WAAW,EACX,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,YAAY,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { LlmsConfig } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Generate an `llms.txt` index manifest from a config, following the llms.txt
|
|
4
|
+
* specification: an `# {title}` H1, a `> {summary}` blockquote, optional free
|
|
5
|
+
* prose, `## {section}` link lists, and a droppable `## Optional` section.
|
|
6
|
+
*
|
|
7
|
+
* @param config - The manifest content.
|
|
8
|
+
* @returns The `llms.txt` file contents (no trailing newline).
|
|
9
|
+
* @throws {TypeError} When a title or link URL is blank, or a URL uses a
|
|
10
|
+
* `javascript:`, `data:` or `vbscript:` scheme. Line breaks inside titles,
|
|
11
|
+
* summaries and notes are collapsed to spaces, `[`, `]` and `\` in link titles
|
|
12
|
+
* are backslash-escaped, and whitespace, `(`, `)`, `<`, `>` and `\` in URLs
|
|
13
|
+
* are percent-encoded, so values cannot inject Markdown structure.
|
|
14
|
+
* @see https://llmstxt.org
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```ts
|
|
18
|
+
* generateLlmsText({
|
|
19
|
+
* title: "Acme Docs",
|
|
20
|
+
* summary: "Everything an agent needs to use Acme.",
|
|
21
|
+
* sections: [
|
|
22
|
+
* { title: "Docs", links: [{ title: "Quickstart", url: "/docs/quickstart.md" }] },
|
|
23
|
+
* ],
|
|
24
|
+
* });
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export declare function generateLlmsText(config: LlmsConfig): string;
|
|
28
|
+
//# sourceMappingURL=llms-text.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"llms-text.d.ts","sourceRoot":"","sources":["../src/llms-text.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAyB,MAAM,YAAY,CAAC;AAqDpE;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,UAAU,GAAG,MAAM,CAU3D"}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
const UNSAFE_URL_SCHEME = /^(?:javascript|data|vbscript):/i;
|
|
2
|
+
/** UTF-16 code units U+0000 to U+0020 (controls and space), which browsers ignore inside a URL scheme. */
|
|
3
|
+
const SCHEME_NOISE = /[^\u0021-\uFFFF]/g;
|
|
4
|
+
const LINE_BREAKS = /\s*[\n\r\u2028\u2029]+\s*/g;
|
|
5
|
+
/** Percent-encode one character that would end a Markdown link destination. */
|
|
6
|
+
function encodeUrlCharacter(character) {
|
|
7
|
+
if (character === "(")
|
|
8
|
+
return "%28";
|
|
9
|
+
if (character === ")")
|
|
10
|
+
return "%29";
|
|
11
|
+
return encodeURIComponent(character);
|
|
12
|
+
}
|
|
13
|
+
/** Collapse line breaks so a value cannot start a new Markdown block. */
|
|
14
|
+
function singleLine(value) {
|
|
15
|
+
return value.replaceAll(LINE_BREAKS, " ").trim();
|
|
16
|
+
}
|
|
17
|
+
/** Single-line value that must be a non-blank string. */
|
|
18
|
+
function requiredLine(value, label) {
|
|
19
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
20
|
+
throw new TypeError(`${label} must be a non-empty string`);
|
|
21
|
+
}
|
|
22
|
+
return singleLine(value);
|
|
23
|
+
}
|
|
24
|
+
function renderUrl(url) {
|
|
25
|
+
const text = requiredLine(url, "link url");
|
|
26
|
+
if (UNSAFE_URL_SCHEME.test(text.replaceAll(SCHEME_NOISE, ""))) {
|
|
27
|
+
throw new TypeError("link url must not use a javascript:, data: or vbscript: scheme");
|
|
28
|
+
}
|
|
29
|
+
return text.replaceAll(/[\s()<>\\]/g, encodeUrlCharacter);
|
|
30
|
+
}
|
|
31
|
+
function renderLink(link) {
|
|
32
|
+
const title = requiredLine(link.title, "link title").replaceAll(/[[\\\]]/g, String.raw `\$&`);
|
|
33
|
+
const base = `- [${title}](${renderUrl(link.url)})`;
|
|
34
|
+
const notes = link.notes ? singleLine(link.notes) : "";
|
|
35
|
+
return notes ? `${base}: ${notes}` : base;
|
|
36
|
+
}
|
|
37
|
+
function renderSection(section) {
|
|
38
|
+
const heading = `## ${requiredLine(section.title, "section title")}`;
|
|
39
|
+
const links = section.links.map(renderLink).join("\n");
|
|
40
|
+
return links ? `${heading}\n\n${links}` : heading;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Generate an `llms.txt` index manifest from a config, following the llms.txt
|
|
44
|
+
* specification: an `# {title}` H1, a `> {summary}` blockquote, optional free
|
|
45
|
+
* prose, `## {section}` link lists, and a droppable `## Optional` section.
|
|
46
|
+
*
|
|
47
|
+
* @param config - The manifest content.
|
|
48
|
+
* @returns The `llms.txt` file contents (no trailing newline).
|
|
49
|
+
* @throws {TypeError} When a title or link URL is blank, or a URL uses a
|
|
50
|
+
* `javascript:`, `data:` or `vbscript:` scheme. Line breaks inside titles,
|
|
51
|
+
* summaries and notes are collapsed to spaces, `[`, `]` and `\` in link titles
|
|
52
|
+
* are backslash-escaped, and whitespace, `(`, `)`, `<`, `>` and `\` in URLs
|
|
53
|
+
* are percent-encoded, so values cannot inject Markdown structure.
|
|
54
|
+
* @see https://llmstxt.org
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* ```ts
|
|
58
|
+
* generateLlmsText({
|
|
59
|
+
* title: "Acme Docs",
|
|
60
|
+
* summary: "Everything an agent needs to use Acme.",
|
|
61
|
+
* sections: [
|
|
62
|
+
* { title: "Docs", links: [{ title: "Quickstart", url: "/docs/quickstart.md" }] },
|
|
63
|
+
* ],
|
|
64
|
+
* });
|
|
65
|
+
* ```
|
|
66
|
+
*/
|
|
67
|
+
export function generateLlmsText(config) {
|
|
68
|
+
return [
|
|
69
|
+
`# ${requiredLine(config.title, "title")}`,
|
|
70
|
+
...(config.summary ? [`> ${singleLine(config.summary)}`] : []),
|
|
71
|
+
...(config.details ? [config.details] : []),
|
|
72
|
+
...(config.sections ?? []).map(renderSection),
|
|
73
|
+
...(config.optional && config.optional.length > 0
|
|
74
|
+
? [renderSection({ links: config.optional, title: "Optional" })]
|
|
75
|
+
: []),
|
|
76
|
+
].join("\n\n");
|
|
77
|
+
}
|
|
78
|
+
//# sourceMappingURL=llms-text.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"llms-text.js","sourceRoot":"","sources":["../src/llms-text.ts"],"names":[],"mappings":"AAEA,MAAM,iBAAiB,GAAG,iCAAiC,CAAC;AAC5D,0GAA0G;AAC1G,MAAM,YAAY,GAAG,m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,CAAC,CAAC,CAAC,aAAa,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,QAAQ,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC,CAAC;YAChE,CAAC,CAAC,EAAE,CAAC;KACR,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACjB,CAAC"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { MarkdownResolver, MarkdownRouteOptions } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Create a Next.js App Router route handler that serves a slug's markdown
|
|
4
|
+
* content. Mount it at a catch-all route (`app/[...slug]/route.ts`). The handler
|
|
5
|
+
* is a pure Web-standard `(request) => Promise<Response>` — it imports nothing
|
|
6
|
+
* from `next` and runs in any Web runtime.
|
|
7
|
+
*
|
|
8
|
+
* - Strips a trailing `.md` from the path (`/docs/intro.md` resolves the slug
|
|
9
|
+
* `["docs", "intro"]`).
|
|
10
|
+
* - Returns `200` with `Content-Type: text/markdown; charset=utf-8` and a
|
|
11
|
+
* `Cache-Control` header when the resolver returns a string.
|
|
12
|
+
* - Returns `404` (plain text) when the resolver returns `null` (or any
|
|
13
|
+
* non-string value, such as `undefined` from a missing map entry).
|
|
14
|
+
* - Returns `400` (plain text) without calling the resolver when the path has
|
|
15
|
+
* malformed percent-encoding or a segment that is empty, `.`, `..`, or
|
|
16
|
+
* contains `/`, `\` or a NUL byte.
|
|
17
|
+
* - Sets `X-Content-Type-Options: nosniff` on every response.
|
|
18
|
+
*
|
|
19
|
+
* @param resolver - Maps a slug to its markdown, or `null` when not found.
|
|
20
|
+
* @param options - Optional cache-control override.
|
|
21
|
+
* @returns A route handler suitable for `export const GET = ...`.
|
|
22
|
+
* @throws {TypeError} When `options.cacheControl` is not a valid header value.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```ts
|
|
26
|
+
* // app/[...slug]/route.ts
|
|
27
|
+
* import { createMarkdownRoute } from "@vllnt/next-llms";
|
|
28
|
+
*
|
|
29
|
+
* export const GET = createMarkdownRoute(async (slug) =>
|
|
30
|
+
* getDoc(slug.join("/")),
|
|
31
|
+
* );
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
export declare function createMarkdownRoute(resolver: MarkdownResolver, options?: MarkdownRouteOptions): (request: Request) => Promise<Response>;
|
|
35
|
+
//# sourceMappingURL=markdown-route.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"markdown-route.d.ts","sourceRoot":"","sources":["../src/markdown-route.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAmCzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,gBAAgB,EAC1B,OAAO,GAAE,oBAAyB,GACjC,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CA6BzC"}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
const DEFAULT_CACHE_CONTROL = "public, max-age=3600, s-maxage=86400, stale-while-revalidate=604800";
|
|
2
|
+
const PLAIN_TEXT_HEADERS = {
|
|
3
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
4
|
+
"X-Content-Type-Options": "nosniff",
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* Decode a URL pathname into slug segments, stripping a trailing `.md` from the
|
|
8
|
+
* last segment. `/docs/intro.md` → `["docs", "intro"]`; `/` → `[]`.
|
|
9
|
+
*
|
|
10
|
+
* Returns `null` when the path cannot name a page safely: malformed
|
|
11
|
+
* percent-encoding, or a decoded segment that is empty, `.`, `..`, or contains
|
|
12
|
+
* `/`, `\` or a NUL byte (so a resolver that maps slugs to files is never
|
|
13
|
+
* handed a traversal sequence such as `..%2F..%2Fsecret`).
|
|
14
|
+
*/
|
|
15
|
+
function pathnameToSlug(pathname) {
|
|
16
|
+
const segments = pathname.split("/").filter((segment) => segment.length > 0);
|
|
17
|
+
const last = segments.at(-1);
|
|
18
|
+
if (last?.endsWith(".md")) {
|
|
19
|
+
segments[segments.length - 1] = last.slice(0, -3);
|
|
20
|
+
}
|
|
21
|
+
try {
|
|
22
|
+
const slug = segments.map((segment) => decodeURIComponent(segment));
|
|
23
|
+
return slug.some((segment) => /^\.{0,2}$|[\0/\\]/.test(segment))
|
|
24
|
+
? null
|
|
25
|
+
: slug;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Create a Next.js App Router route handler that serves a slug's markdown
|
|
33
|
+
* content. Mount it at a catch-all route (`app/[...slug]/route.ts`). The handler
|
|
34
|
+
* is a pure Web-standard `(request) => Promise<Response>` — it imports nothing
|
|
35
|
+
* from `next` and runs in any Web runtime.
|
|
36
|
+
*
|
|
37
|
+
* - Strips a trailing `.md` from the path (`/docs/intro.md` resolves the slug
|
|
38
|
+
* `["docs", "intro"]`).
|
|
39
|
+
* - Returns `200` with `Content-Type: text/markdown; charset=utf-8` and a
|
|
40
|
+
* `Cache-Control` header when the resolver returns a string.
|
|
41
|
+
* - Returns `404` (plain text) when the resolver returns `null` (or any
|
|
42
|
+
* non-string value, such as `undefined` from a missing map entry).
|
|
43
|
+
* - Returns `400` (plain text) without calling the resolver when the path has
|
|
44
|
+
* malformed percent-encoding or a segment that is empty, `.`, `..`, or
|
|
45
|
+
* contains `/`, `\` or a NUL byte.
|
|
46
|
+
* - Sets `X-Content-Type-Options: nosniff` on every response.
|
|
47
|
+
*
|
|
48
|
+
* @param resolver - Maps a slug to its markdown, or `null` when not found.
|
|
49
|
+
* @param options - Optional cache-control override.
|
|
50
|
+
* @returns A route handler suitable for `export const GET = ...`.
|
|
51
|
+
* @throws {TypeError} When `options.cacheControl` is not a valid header value.
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* ```ts
|
|
55
|
+
* // app/[...slug]/route.ts
|
|
56
|
+
* import { createMarkdownRoute } from "@vllnt/next-llms";
|
|
57
|
+
*
|
|
58
|
+
* export const GET = createMarkdownRoute(async (slug) =>
|
|
59
|
+
* getDoc(slug.join("/")),
|
|
60
|
+
* );
|
|
61
|
+
* ```
|
|
62
|
+
*/
|
|
63
|
+
export function createMarkdownRoute(resolver, options = {}) {
|
|
64
|
+
const cacheControl = options.cacheControl ?? DEFAULT_CACHE_CONTROL;
|
|
65
|
+
// Fail at setup, not on the first request, if the header value is invalid.
|
|
66
|
+
new Headers({ "Cache-Control": cacheControl });
|
|
67
|
+
return async (request) => {
|
|
68
|
+
const slug = pathnameToSlug(new URL(request.url).pathname);
|
|
69
|
+
if (slug === null) {
|
|
70
|
+
return new Response("Bad Request", {
|
|
71
|
+
headers: PLAIN_TEXT_HEADERS,
|
|
72
|
+
status: 400,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
const content = await resolver(slug);
|
|
76
|
+
return typeof content === "string"
|
|
77
|
+
? new Response(content, {
|
|
78
|
+
headers: {
|
|
79
|
+
"Cache-Control": cacheControl,
|
|
80
|
+
"Content-Type": "text/markdown; charset=utf-8",
|
|
81
|
+
"X-Content-Type-Options": "nosniff",
|
|
82
|
+
},
|
|
83
|
+
status: 200,
|
|
84
|
+
})
|
|
85
|
+
: new Response("Not Found", {
|
|
86
|
+
headers: PLAIN_TEXT_HEADERS,
|
|
87
|
+
status: 404,
|
|
88
|
+
});
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
//# sourceMappingURL=markdown-route.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"markdown-route.js","sourceRoot":"","sources":["../src/markdown-route.ts"],"names":[],"mappings":"AAEA,MAAM,qBAAqB,GACzB,qEAAqE,CAAC;AAExE,MAAM,kBAAkB,GAAG;IACzB,cAAc,EAAE,2BAA2B;IAC3C,wBAAwB,EAAE,SAAS;CACpC,CAAC;AAEF;;;;;;;;GAQG;AACH,SAAS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IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;YAClB,OAAO,IAAI,QAAQ,CAAC,aAAa,EAAE;gBACjC,OAAO,EAAE,kBAAkB;gBAC3B,MAAM,EAAE,GAAG;aACZ,CAAC,CAAC;QACL,CAAC;QACD,MAAM,OAAO,GAAG,MAAM,QAAQ,CAAC,IAAI,CAAC,CAAC;QAErC,OAAO,OAAO,OAAO,KAAK,QAAQ;YAChC,CAAC,CAAC,IAAI,QAAQ,CAAC,OAAO,EAAE;gBACpB,OAAO,EAAE;oBACP,eAAe,EAAE,YAAY;oBAC7B,cAAc,EAAE,8BAA8B;oBAC9C,wBAAwB,EAAE,SAAS;iBACpC;gBACD,MAAM,EAAE,GAAG;aACZ,CAAC;YACJ,CAAC,CAAC,IAAI,QAAQ,CAAC,WAAW,EAAE;gBACxB,OAAO,EAAE,kBAAkB;gBAC3B,MAAM,EAAE,GAAG;aACZ,CAAC,CAAC;IACT,CAAC,CAAC;AACJ,CAAC"}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A single link entry in an `llms.txt` section — rendered as
|
|
3
|
+
* `- [title](url): notes`.
|
|
4
|
+
*/
|
|
5
|
+
export type LlmsLink = {
|
|
6
|
+
/** Human-readable link text. */
|
|
7
|
+
title: string;
|
|
8
|
+
/** Absolute or root-relative URL. */
|
|
9
|
+
url: string;
|
|
10
|
+
/** Optional one-line description shown after the link. */
|
|
11
|
+
notes?: string;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* A named H2 section of an `llms.txt` manifest (e.g. `## Docs`) and its links.
|
|
15
|
+
*/
|
|
16
|
+
export type LlmsSection = {
|
|
17
|
+
/** Section heading, rendered as `## {title}`. */
|
|
18
|
+
title: string;
|
|
19
|
+
/** Links listed under the section. */
|
|
20
|
+
links: LlmsLink[];
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Input for {@link generateLlmsText} — the `llms.txt` index manifest.
|
|
24
|
+
*
|
|
25
|
+
* @see https://llmstxt.org
|
|
26
|
+
*/
|
|
27
|
+
export type LlmsConfig = {
|
|
28
|
+
/** Site/project name, rendered as the `# {title}` H1. */
|
|
29
|
+
title: string;
|
|
30
|
+
/** One-line summary, rendered as a `> {summary}` blockquote. */
|
|
31
|
+
summary?: string;
|
|
32
|
+
/** Free-form markdown shown after the blockquote, before the sections. */
|
|
33
|
+
details?: string;
|
|
34
|
+
/** Named link-list sections (`## Docs`, `## Examples`, …). */
|
|
35
|
+
sections?: LlmsSection[];
|
|
36
|
+
/**
|
|
37
|
+
* Links placed under the special `## Optional` section. Agents may skip this
|
|
38
|
+
* section when a shorter context helps, per the llms.txt spec.
|
|
39
|
+
*/
|
|
40
|
+
optional?: LlmsLink[];
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* Maps a route slug to its markdown content, or `null` if there is no page for
|
|
44
|
+
* the slug. The slug is the path segments with any trailing `.md` stripped.
|
|
45
|
+
*/
|
|
46
|
+
export type MarkdownResolver = (slug: string[]) => string | null | Promise<string | null>;
|
|
47
|
+
/**
|
|
48
|
+
* Options for {@link createMarkdownRoute}.
|
|
49
|
+
*/
|
|
50
|
+
export type MarkdownRouteOptions = {
|
|
51
|
+
/**
|
|
52
|
+
* `Cache-Control` header value for resolved (200) responses.
|
|
53
|
+
*
|
|
54
|
+
* @defaultValue `"public, max-age=3600, s-maxage=86400, stale-while-revalidate=604800"`
|
|
55
|
+
*/
|
|
56
|
+
cacheControl?: string;
|
|
57
|
+
};
|
|
58
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,MAAM,QAAQ,GAAG;IACrB,gCAAgC;IAChC,KAAK,EAAE,MAAM,CAAC;IACd,qCAAqC;IACrC,GAAG,EAAE,MAAM,CAAC;IACZ,0DAA0D;IAC1D,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,WAAW,GAAG;IACxB,iDAAiD;IACjD,KAAK,EAAE,MAAM,CAAC;IACd,sCAAsC;IACtC,KAAK,EAAE,QAAQ,EAAE,CAAC;CACnB,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,UAAU,GAAG;IACvB,yDAAyD;IACzD,KAAK,EAAE,MAAM,CAAC;IACd,gEAAgE;IAChE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,0EAA0E;IAC1E,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,8DAA8D;IAC9D,QAAQ,CAAC,EAAE,WAAW,EAAE,CAAC;IACzB;;;OAGG;IACH,QAAQ,CAAC,EAAE,QAAQ,EAAE,CAAC;CACvB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAC7B,IAAI,EAAE,MAAM,EAAE,KACX,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;AAE5C;;GAEG;AACH,MAAM,MAAM,oBAAoB,GAAG;IACjC;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,CAAC"}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
|
package/package.json
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@vllnt/next-llms",
|
|
3
|
+
"version": "0.1.0-canary.06b7b79",
|
|
4
|
+
"description": "AI discoverability for Next.js sites — generate an llms.txt manifest and serve any page as raw markdown",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"packageManager": "pnpm@10.34.8",
|
|
8
|
+
"files": [
|
|
9
|
+
"dist",
|
|
10
|
+
"src",
|
|
11
|
+
"!src/**/*.test.ts",
|
|
12
|
+
"!src/**/*.spec.*"
|
|
13
|
+
],
|
|
14
|
+
"exports": {
|
|
15
|
+
"./package.json": "./package.json",
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"default": "./dist/index.js"
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"module": "./dist/index.js",
|
|
23
|
+
"main": "./dist/index.js",
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "tsc --project ./tsconfig.build.json",
|
|
26
|
+
"typecheck": "tsc --noEmit --incremental --tsBuildInfoFile node_modules/.cache/tsc/typecheck.tsbuildinfo",
|
|
27
|
+
"typecheck:ci": "tsc --noEmit --incremental --tsBuildInfoFile node_modules/.cache/tsc/typecheck-ci.tsbuildinfo --project tsconfig.ci.json",
|
|
28
|
+
"lint": "pnpm check:agents && eslint --cache --cache-location node_modules/.cache/eslint/ .",
|
|
29
|
+
"format": "prettier --write .",
|
|
30
|
+
"format:check": "prettier --check .",
|
|
31
|
+
"test": "vitest run --passWithNoTests",
|
|
32
|
+
"test:watch": "vitest --typecheck --clearScreen false",
|
|
33
|
+
"test:coverage": "vitest run --coverage --coverage.reporter=text",
|
|
34
|
+
"preversion": "pnpm install --frozen-lockfile && pnpm build && pnpm test:coverage && pnpm typecheck",
|
|
35
|
+
"check:agents": "node -e \"const f=require('node:fs');if(!f.existsSync('AGENTS.md')||f.existsSync('CLAUDE.md')||f.existsSync('.claude'))process.exit(1)\""
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"@types/node": "^24.19.2",
|
|
39
|
+
"@typescript/native": "npm:typescript@7.0.2",
|
|
40
|
+
"@vitest/coverage-v8": "^5.0.5",
|
|
41
|
+
"@vllnt/eslint-config": "2.0.0",
|
|
42
|
+
"@vllnt/typescript": "2.0.0",
|
|
43
|
+
"eslint": "^9.0.0",
|
|
44
|
+
"prettier": "^3.9.10",
|
|
45
|
+
"typescript": "npm:@typescript/typescript6@^6.0.2",
|
|
46
|
+
"vitest": "^5.0.5"
|
|
47
|
+
},
|
|
48
|
+
"homepage": "https://github.com/vllnt/next-llms#readme",
|
|
49
|
+
"bugs": {
|
|
50
|
+
"url": "https://github.com/vllnt/next-llms/issues"
|
|
51
|
+
},
|
|
52
|
+
"author": {
|
|
53
|
+
"name": "bntvllnt",
|
|
54
|
+
"url": "https://bntvllnt.com"
|
|
55
|
+
},
|
|
56
|
+
"funding": {
|
|
57
|
+
"type": "github",
|
|
58
|
+
"url": "https://github.com/sponsors/bntvllnt"
|
|
59
|
+
},
|
|
60
|
+
"repository": {
|
|
61
|
+
"type": "git",
|
|
62
|
+
"url": "https://github.com/vllnt/next-llms"
|
|
63
|
+
},
|
|
64
|
+
"engines": {
|
|
65
|
+
"node": ">=18"
|
|
66
|
+
},
|
|
67
|
+
"publishConfig": {
|
|
68
|
+
"access": "public"
|
|
69
|
+
},
|
|
70
|
+
"sideEffects": false,
|
|
71
|
+
"keywords": [
|
|
72
|
+
"nextjs",
|
|
73
|
+
"next",
|
|
74
|
+
"llms-txt",
|
|
75
|
+
"llms.txt",
|
|
76
|
+
"ai",
|
|
77
|
+
"llm",
|
|
78
|
+
"seo",
|
|
79
|
+
"app-router",
|
|
80
|
+
"markdown",
|
|
81
|
+
"discoverability"
|
|
82
|
+
],
|
|
83
|
+
"pnpm": {
|
|
84
|
+
"minimumReleaseAge": 10080,
|
|
85
|
+
"minimumReleaseAgeExclude": [
|
|
86
|
+
"@vllnt/*"
|
|
87
|
+
],
|
|
88
|
+
"ignoredBuiltDependencies": [
|
|
89
|
+
"esbuild"
|
|
90
|
+
],
|
|
91
|
+
"overrides": {
|
|
92
|
+
"deepmerge-ts@<8.0.0": "8.0.2",
|
|
93
|
+
"handlebars@<4.7.10": "4.7.10"
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
package/src/index.ts
ADDED
package/src/llms-text.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import type { LlmsConfig, LlmsLink, LlmsSection } from "./types.js";
|
|
2
|
+
|
|
3
|
+
const UNSAFE_URL_SCHEME = /^(?:javascript|data|vbscript):/i;
|
|
4
|
+
/** UTF-16 code units U+0000 to U+0020 (controls and space), which browsers ignore inside a URL scheme. */
|
|
5
|
+
const SCHEME_NOISE = /[^\u0021-\uFFFF]/g;
|
|
6
|
+
const LINE_BREAKS = /\s*[\n\r\u2028\u2029]+\s*/g;
|
|
7
|
+
|
|
8
|
+
/** Percent-encode one character that would end a Markdown link destination. */
|
|
9
|
+
function encodeUrlCharacter(character: string): string {
|
|
10
|
+
if (character === "(") return "%28";
|
|
11
|
+
if (character === ")") return "%29";
|
|
12
|
+
return encodeURIComponent(character);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Collapse line breaks so a value cannot start a new Markdown block. */
|
|
16
|
+
function singleLine(value: string): string {
|
|
17
|
+
return value.replaceAll(LINE_BREAKS, " ").trim();
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Single-line value that must be a non-blank string. */
|
|
21
|
+
function requiredLine(value: unknown, label: string): string {
|
|
22
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
23
|
+
throw new TypeError(`${label} must be a non-empty string`);
|
|
24
|
+
}
|
|
25
|
+
return singleLine(value);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function renderUrl(url: unknown): string {
|
|
29
|
+
const text = requiredLine(url, "link url");
|
|
30
|
+
if (UNSAFE_URL_SCHEME.test(text.replaceAll(SCHEME_NOISE, ""))) {
|
|
31
|
+
throw new TypeError(
|
|
32
|
+
"link url must not use a javascript:, data: or vbscript: scheme",
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
return text.replaceAll(/[\s()<>\\]/g, encodeUrlCharacter);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function renderLink(link: LlmsLink): string {
|
|
39
|
+
const title = requiredLine(link.title, "link title").replaceAll(
|
|
40
|
+
/[[\\\]]/g,
|
|
41
|
+
String.raw`\$&`,
|
|
42
|
+
);
|
|
43
|
+
const base = `- [${title}](${renderUrl(link.url)})`;
|
|
44
|
+
const notes = link.notes ? singleLine(link.notes) : "";
|
|
45
|
+
return notes ? `${base}: ${notes}` : base;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function renderSection(section: LlmsSection): string {
|
|
49
|
+
const heading = `## ${requiredLine(section.title, "section title")}`;
|
|
50
|
+
const links = section.links.map(renderLink).join("\n");
|
|
51
|
+
return links ? `${heading}\n\n${links}` : heading;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Generate an `llms.txt` index manifest from a config, following the llms.txt
|
|
56
|
+
* specification: an `# {title}` H1, a `> {summary}` blockquote, optional free
|
|
57
|
+
* prose, `## {section}` link lists, and a droppable `## Optional` section.
|
|
58
|
+
*
|
|
59
|
+
* @param config - The manifest content.
|
|
60
|
+
* @returns The `llms.txt` file contents (no trailing newline).
|
|
61
|
+
* @throws {TypeError} When a title or link URL is blank, or a URL uses a
|
|
62
|
+
* `javascript:`, `data:` or `vbscript:` scheme. Line breaks inside titles,
|
|
63
|
+
* summaries and notes are collapsed to spaces, `[`, `]` and `\` in link titles
|
|
64
|
+
* are backslash-escaped, and whitespace, `(`, `)`, `<`, `>` and `\` in URLs
|
|
65
|
+
* are percent-encoded, so values cannot inject Markdown structure.
|
|
66
|
+
* @see https://llmstxt.org
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* ```ts
|
|
70
|
+
* generateLlmsText({
|
|
71
|
+
* title: "Acme Docs",
|
|
72
|
+
* summary: "Everything an agent needs to use Acme.",
|
|
73
|
+
* sections: [
|
|
74
|
+
* { title: "Docs", links: [{ title: "Quickstart", url: "/docs/quickstart.md" }] },
|
|
75
|
+
* ],
|
|
76
|
+
* });
|
|
77
|
+
* ```
|
|
78
|
+
*/
|
|
79
|
+
export function generateLlmsText(config: LlmsConfig): string {
|
|
80
|
+
return [
|
|
81
|
+
`# ${requiredLine(config.title, "title")}`,
|
|
82
|
+
...(config.summary ? [`> ${singleLine(config.summary)}`] : []),
|
|
83
|
+
...(config.details ? [config.details] : []),
|
|
84
|
+
...(config.sections ?? []).map(renderSection),
|
|
85
|
+
...(config.optional && config.optional.length > 0
|
|
86
|
+
? [renderSection({ links: config.optional, title: "Optional" })]
|
|
87
|
+
: []),
|
|
88
|
+
].join("\n\n");
|
|
89
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import type { MarkdownResolver, MarkdownRouteOptions } from "./types.js";
|
|
2
|
+
|
|
3
|
+
const DEFAULT_CACHE_CONTROL =
|
|
4
|
+
"public, max-age=3600, s-maxage=86400, stale-while-revalidate=604800";
|
|
5
|
+
|
|
6
|
+
const PLAIN_TEXT_HEADERS = {
|
|
7
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
8
|
+
"X-Content-Type-Options": "nosniff",
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Decode a URL pathname into slug segments, stripping a trailing `.md` from the
|
|
13
|
+
* last segment. `/docs/intro.md` → `["docs", "intro"]`; `/` → `[]`.
|
|
14
|
+
*
|
|
15
|
+
* Returns `null` when the path cannot name a page safely: malformed
|
|
16
|
+
* percent-encoding, or a decoded segment that is empty, `.`, `..`, or contains
|
|
17
|
+
* `/`, `\` or a NUL byte (so a resolver that maps slugs to files is never
|
|
18
|
+
* handed a traversal sequence such as `..%2F..%2Fsecret`).
|
|
19
|
+
*/
|
|
20
|
+
function pathnameToSlug(pathname: string): string[] | null {
|
|
21
|
+
const segments = pathname.split("/").filter((segment) => segment.length > 0);
|
|
22
|
+
const last = segments.at(-1);
|
|
23
|
+
if (last?.endsWith(".md")) {
|
|
24
|
+
segments[segments.length - 1] = last.slice(0, -3);
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
const slug = segments.map((segment) => decodeURIComponent(segment));
|
|
28
|
+
return slug.some((segment) => /^\.{0,2}$|[\0/\\]/.test(segment))
|
|
29
|
+
? null
|
|
30
|
+
: slug;
|
|
31
|
+
} catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Create a Next.js App Router route handler that serves a slug's markdown
|
|
38
|
+
* content. Mount it at a catch-all route (`app/[...slug]/route.ts`). The handler
|
|
39
|
+
* is a pure Web-standard `(request) => Promise<Response>` — it imports nothing
|
|
40
|
+
* from `next` and runs in any Web runtime.
|
|
41
|
+
*
|
|
42
|
+
* - Strips a trailing `.md` from the path (`/docs/intro.md` resolves the slug
|
|
43
|
+
* `["docs", "intro"]`).
|
|
44
|
+
* - Returns `200` with `Content-Type: text/markdown; charset=utf-8` and a
|
|
45
|
+
* `Cache-Control` header when the resolver returns a string.
|
|
46
|
+
* - Returns `404` (plain text) when the resolver returns `null` (or any
|
|
47
|
+
* non-string value, such as `undefined` from a missing map entry).
|
|
48
|
+
* - Returns `400` (plain text) without calling the resolver when the path has
|
|
49
|
+
* malformed percent-encoding or a segment that is empty, `.`, `..`, or
|
|
50
|
+
* contains `/`, `\` or a NUL byte.
|
|
51
|
+
* - Sets `X-Content-Type-Options: nosniff` on every response.
|
|
52
|
+
*
|
|
53
|
+
* @param resolver - Maps a slug to its markdown, or `null` when not found.
|
|
54
|
+
* @param options - Optional cache-control override.
|
|
55
|
+
* @returns A route handler suitable for `export const GET = ...`.
|
|
56
|
+
* @throws {TypeError} When `options.cacheControl` is not a valid header value.
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* ```ts
|
|
60
|
+
* // app/[...slug]/route.ts
|
|
61
|
+
* import { createMarkdownRoute } from "@vllnt/next-llms";
|
|
62
|
+
*
|
|
63
|
+
* export const GET = createMarkdownRoute(async (slug) =>
|
|
64
|
+
* getDoc(slug.join("/")),
|
|
65
|
+
* );
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
68
|
+
export function createMarkdownRoute(
|
|
69
|
+
resolver: MarkdownResolver,
|
|
70
|
+
options: MarkdownRouteOptions = {},
|
|
71
|
+
): (request: Request) => Promise<Response> {
|
|
72
|
+
const cacheControl = options.cacheControl ?? DEFAULT_CACHE_CONTROL;
|
|
73
|
+
// Fail at setup, not on the first request, if the header value is invalid.
|
|
74
|
+
new Headers({ "Cache-Control": cacheControl });
|
|
75
|
+
|
|
76
|
+
return async (request: Request): Promise<Response> => {
|
|
77
|
+
const slug = pathnameToSlug(new URL(request.url).pathname);
|
|
78
|
+
if (slug === null) {
|
|
79
|
+
return new Response("Bad Request", {
|
|
80
|
+
headers: PLAIN_TEXT_HEADERS,
|
|
81
|
+
status: 400,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
const content = await resolver(slug);
|
|
85
|
+
|
|
86
|
+
return typeof content === "string"
|
|
87
|
+
? new Response(content, {
|
|
88
|
+
headers: {
|
|
89
|
+
"Cache-Control": cacheControl,
|
|
90
|
+
"Content-Type": "text/markdown; charset=utf-8",
|
|
91
|
+
"X-Content-Type-Options": "nosniff",
|
|
92
|
+
},
|
|
93
|
+
status: 200,
|
|
94
|
+
})
|
|
95
|
+
: new Response("Not Found", {
|
|
96
|
+
headers: PLAIN_TEXT_HEADERS,
|
|
97
|
+
status: 404,
|
|
98
|
+
});
|
|
99
|
+
};
|
|
100
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A single link entry in an `llms.txt` section — rendered as
|
|
3
|
+
* `- [title](url): notes`.
|
|
4
|
+
*/
|
|
5
|
+
export type LlmsLink = {
|
|
6
|
+
/** Human-readable link text. */
|
|
7
|
+
title: string;
|
|
8
|
+
/** Absolute or root-relative URL. */
|
|
9
|
+
url: string;
|
|
10
|
+
/** Optional one-line description shown after the link. */
|
|
11
|
+
notes?: string;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* A named H2 section of an `llms.txt` manifest (e.g. `## Docs`) and its links.
|
|
16
|
+
*/
|
|
17
|
+
export type LlmsSection = {
|
|
18
|
+
/** Section heading, rendered as `## {title}`. */
|
|
19
|
+
title: string;
|
|
20
|
+
/** Links listed under the section. */
|
|
21
|
+
links: LlmsLink[];
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Input for {@link generateLlmsText} — the `llms.txt` index manifest.
|
|
26
|
+
*
|
|
27
|
+
* @see https://llmstxt.org
|
|
28
|
+
*/
|
|
29
|
+
export type LlmsConfig = {
|
|
30
|
+
/** Site/project name, rendered as the `# {title}` H1. */
|
|
31
|
+
title: string;
|
|
32
|
+
/** One-line summary, rendered as a `> {summary}` blockquote. */
|
|
33
|
+
summary?: string;
|
|
34
|
+
/** Free-form markdown shown after the blockquote, before the sections. */
|
|
35
|
+
details?: string;
|
|
36
|
+
/** Named link-list sections (`## Docs`, `## Examples`, …). */
|
|
37
|
+
sections?: LlmsSection[];
|
|
38
|
+
/**
|
|
39
|
+
* Links placed under the special `## Optional` section. Agents may skip this
|
|
40
|
+
* section when a shorter context helps, per the llms.txt spec.
|
|
41
|
+
*/
|
|
42
|
+
optional?: LlmsLink[];
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Maps a route slug to its markdown content, or `null` if there is no page for
|
|
47
|
+
* the slug. The slug is the path segments with any trailing `.md` stripped.
|
|
48
|
+
*/
|
|
49
|
+
export type MarkdownResolver = (
|
|
50
|
+
slug: string[],
|
|
51
|
+
) => string | null | Promise<string | null>;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Options for {@link createMarkdownRoute}.
|
|
55
|
+
*/
|
|
56
|
+
export type MarkdownRouteOptions = {
|
|
57
|
+
/**
|
|
58
|
+
* `Cache-Control` header value for resolved (200) responses.
|
|
59
|
+
*
|
|
60
|
+
* @defaultValue `"public, max-age=3600, s-maxage=86400, stale-while-revalidate=604800"`
|
|
61
|
+
*/
|
|
62
|
+
cacheControl?: string;
|
|
63
|
+
};
|