astro-markdown-for-agents 0.1.0
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 +95 -0
- package/package.json +40 -0
- package/src/astro.ts +88 -0
- package/src/core/accept.ts +56 -0
- package/src/core/build.ts +74 -0
- package/src/core/convert.ts +60 -0
- package/src/core/headers.ts +43 -0
- package/src/core/index.ts +8 -0
- package/src/core/options.ts +50 -0
- package/src/core/routes.ts +101 -0
- package/src/core/server.ts +35 -0
- package/src/core/types.ts +29 -0
- package/src/index.ts +3 -0
- package/src/runtime.ts +3 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Trent Rand
|
|
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,95 @@
|
|
|
1
|
+
# astro-markdown-for-agents
|
|
2
|
+
|
|
3
|
+
Astro integration that generates markdown variants of your pages for AI agents and supports same-URL markdown negotiation in Astro dev.
|
|
4
|
+
|
|
5
|
+
## What it does
|
|
6
|
+
|
|
7
|
+
- Converts built HTML pages into markdown files under `dist/_markdown-cache` (configurable).
|
|
8
|
+
- In Astro dev, serves markdown when `Accept: text/markdown` (or `text/plain`, configurable) is preferred over HTML.
|
|
9
|
+
- Adds agent-oriented headers on markdown responses:
|
|
10
|
+
- `Content-Type: text/markdown; charset=utf-8`
|
|
11
|
+
- `Vary: Accept`
|
|
12
|
+
- `x-markdown-tokens`
|
|
13
|
+
- `content-signal`
|
|
14
|
+
|
|
15
|
+
## What it does NOT do
|
|
16
|
+
|
|
17
|
+
This package is deployment-agnostic. It does **not** include hosting-specific runtime shims.
|
|
18
|
+
|
|
19
|
+
For static hosting environments, serve-time negotiation should be implemented in the consumer app/runtime.
|
|
20
|
+
|
|
21
|
+
## Installation
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
bun add astro-markdown-for-agents
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Usage
|
|
28
|
+
|
|
29
|
+
In `astro.config.mjs`:
|
|
30
|
+
|
|
31
|
+
```js
|
|
32
|
+
import { defineConfig } from 'astro/config';
|
|
33
|
+
import markdownForAgents from 'astro-markdown-for-agents';
|
|
34
|
+
|
|
35
|
+
export default defineConfig({
|
|
36
|
+
integrations: [
|
|
37
|
+
markdownForAgents(),
|
|
38
|
+
],
|
|
39
|
+
});
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Quick verification (dev)
|
|
43
|
+
|
|
44
|
+
Start Astro dev, then compare responses for the same URL:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
curl -i -H 'Accept: text/html' http://localhost:4321/
|
|
48
|
+
curl -i -H 'Accept: text/markdown' http://localhost:4321/
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
You should see HTML for `text/html` and markdown for `text/markdown`.
|
|
52
|
+
|
|
53
|
+
## Options
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
type Matcher = string | RegExp | ((pathname: string) => boolean);
|
|
57
|
+
|
|
58
|
+
type MarkdownForAgentsOptions = {
|
|
59
|
+
include?: Matcher[];
|
|
60
|
+
exclude?: Matcher[];
|
|
61
|
+
excludePrefixes?: string[];
|
|
62
|
+
excludeExtensions?: string[];
|
|
63
|
+
markdownDir?: string;
|
|
64
|
+
contentSignals?: {
|
|
65
|
+
aiTrain?: boolean;
|
|
66
|
+
search?: boolean;
|
|
67
|
+
aiInput?: boolean;
|
|
68
|
+
};
|
|
69
|
+
maxExtractedChars?: number;
|
|
70
|
+
preferPlainText?: boolean;
|
|
71
|
+
};
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### Defaults
|
|
75
|
+
|
|
76
|
+
- `markdownDir`: `_markdown-cache`
|
|
77
|
+
- `preferPlainText`: `true`
|
|
78
|
+
- `maxExtractedChars`: `Infinity`
|
|
79
|
+
- `excludePrefixes`: `['/api/', '/_astro/']`
|
|
80
|
+
- `excludeExtensions`: common static assets (`.css`, `.js`, images, fonts, etc.)
|
|
81
|
+
- `contentSignals`: `ai-train=yes, search=yes, ai-input=yes`
|
|
82
|
+
|
|
83
|
+
## Export surfaces
|
|
84
|
+
|
|
85
|
+
- Root (`astro-markdown-for-agents`): integration entrypoint
|
|
86
|
+
- `astro-markdown-for-agents/core`: shared core helpers/types
|
|
87
|
+
- `astro-markdown-for-agents/runtime`: runtime-safe helpers for consumer-hosted negotiation shims
|
|
88
|
+
|
|
89
|
+
## Development notes
|
|
90
|
+
|
|
91
|
+
This package currently ships source files from `src/` via export maps for Astro/Vite-based consumption.
|
|
92
|
+
|
|
93
|
+
## License
|
|
94
|
+
|
|
95
|
+
MIT
|
package/package.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "astro-markdown-for-agents",
|
|
3
|
+
"description": "Astro integration that generates markdown variants of your pages for AI agents",
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"private": false,
|
|
7
|
+
"author": "Trent Rand <contact@trentrand.com>",
|
|
8
|
+
"license": "MIT",
|
|
9
|
+
"keywords": [
|
|
10
|
+
"astro",
|
|
11
|
+
"integration",
|
|
12
|
+
"markdown",
|
|
13
|
+
"ai",
|
|
14
|
+
"content-negotiation",
|
|
15
|
+
"llm"
|
|
16
|
+
],
|
|
17
|
+
"files": [
|
|
18
|
+
"src",
|
|
19
|
+
"README.md",
|
|
20
|
+
"LICENSE"
|
|
21
|
+
],
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public"
|
|
24
|
+
},
|
|
25
|
+
"peerDependencies": {
|
|
26
|
+
"astro": "^5.0.0"
|
|
27
|
+
},
|
|
28
|
+
"exports": {
|
|
29
|
+
".": "./src/index.ts",
|
|
30
|
+
"./astro": "./src/astro.ts",
|
|
31
|
+
"./core": "./src/core/index.ts",
|
|
32
|
+
"./runtime": "./src/runtime.ts"
|
|
33
|
+
},
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"turndown": "^7.2.0"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"@types/turndown": "^5.0.6"
|
|
39
|
+
}
|
|
40
|
+
}
|
package/src/astro.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import type { AstroIntegration } from 'astro';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import {
|
|
4
|
+
applyMarkdownHeaders,
|
|
5
|
+
extractPathname,
|
|
6
|
+
generateMarkdownAssets,
|
|
7
|
+
htmlToMarkdown,
|
|
8
|
+
isHtmlResponse,
|
|
9
|
+
isNegotiablePath,
|
|
10
|
+
resolveOptions,
|
|
11
|
+
ensureVaryAccept,
|
|
12
|
+
shouldHandleDevRequest,
|
|
13
|
+
type MarkdownForAgentsOptions,
|
|
14
|
+
writeNodeResponse,
|
|
15
|
+
} from './core/index';
|
|
16
|
+
const DEV_BYPASS_HEADER = 'x-markdown-negotiation-bypass';
|
|
17
|
+
|
|
18
|
+
export default function markdownForAgents(options: MarkdownForAgentsOptions = {}): AstroIntegration {
|
|
19
|
+
const resolved = resolveOptions(options);
|
|
20
|
+
|
|
21
|
+
return {
|
|
22
|
+
name: 'markdown-for-agents',
|
|
23
|
+
hooks: {
|
|
24
|
+
'astro:server:setup': ({ server }) => {
|
|
25
|
+
server.middlewares.use(async (req, res, next) => {
|
|
26
|
+
if (!shouldHandleDevRequest(req, resolved.preferPlainText, DEV_BYPASS_HEADER)) {
|
|
27
|
+
next();
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const host = req.headers.host;
|
|
32
|
+
const pathname = extractPathname(req.url);
|
|
33
|
+
|
|
34
|
+
if (!host || !pathname || !isNegotiablePath(pathname, resolved)) {
|
|
35
|
+
next();
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
try {
|
|
40
|
+
const method = (req.method ?? 'GET').toUpperCase();
|
|
41
|
+
const requestUrl = new URL(req.url ?? '/', `http://${host}`);
|
|
42
|
+
const htmlResponse = await fetch(requestUrl.toString(), {
|
|
43
|
+
method,
|
|
44
|
+
headers: {
|
|
45
|
+
accept: 'text/html',
|
|
46
|
+
[DEV_BYPASS_HEADER]: '1',
|
|
47
|
+
},
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
const headers = new Headers(htmlResponse.headers);
|
|
51
|
+
ensureVaryAccept(headers);
|
|
52
|
+
|
|
53
|
+
if (!htmlResponse.ok || !isHtmlResponse(headers.get('content-type'))) {
|
|
54
|
+
await writeNodeResponse(res, htmlResponse, headers);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const html = await htmlResponse.text();
|
|
59
|
+
const markdown = htmlToMarkdown(html, pathname, resolved.maxExtractedChars);
|
|
60
|
+
applyMarkdownHeaders(headers, markdown, resolved);
|
|
61
|
+
|
|
62
|
+
res.statusCode = htmlResponse.status;
|
|
63
|
+
res.statusMessage = htmlResponse.statusText;
|
|
64
|
+
|
|
65
|
+
for (const [key, value] of headers.entries()) {
|
|
66
|
+
res.setHeader(key, value);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (method === 'HEAD') {
|
|
70
|
+
res.end();
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
res.end(markdown);
|
|
75
|
+
} catch (error) {
|
|
76
|
+
next(error as Error);
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
},
|
|
80
|
+
|
|
81
|
+
'astro:build:done': async ({ dir, logger }) => {
|
|
82
|
+
const distDir = fileURLToPath(dir);
|
|
83
|
+
await generateMarkdownAssets({ distDir, options: resolved });
|
|
84
|
+
logger.info('[markdown-for-agents] Markdown assets generated');
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
type AcceptEntry = {
|
|
2
|
+
mediaType: string;
|
|
3
|
+
q: number;
|
|
4
|
+
index: number;
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
export function parseAcceptHeader(value: string): AcceptEntry[] {
|
|
8
|
+
if (!value) {
|
|
9
|
+
return [];
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
return value
|
|
13
|
+
.split(',')
|
|
14
|
+
.map((item, index) => {
|
|
15
|
+
const [mediaType, ...params] = item
|
|
16
|
+
.split(';')
|
|
17
|
+
.map((part) => part.trim().toLowerCase());
|
|
18
|
+
let q = 1;
|
|
19
|
+
|
|
20
|
+
for (const param of params) {
|
|
21
|
+
if (!param.startsWith('q=')) {
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
const parsed = Number(param.slice(2));
|
|
25
|
+
if (!Number.isNaN(parsed)) {
|
|
26
|
+
q = parsed;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return { mediaType, q, index };
|
|
31
|
+
})
|
|
32
|
+
.filter((entry) => entry.mediaType && entry.q > 0)
|
|
33
|
+
.sort((a, b) => (b.q !== a.q ? b.q - a.q : a.index - b.index));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function prefersMarkdown(acceptHeader: string, preferPlainText = true): boolean {
|
|
37
|
+
const accepted = parseAcceptHeader(acceptHeader);
|
|
38
|
+
if (accepted.length === 0) {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const markdownIndex = accepted.findIndex((entry) =>
|
|
43
|
+
entry.mediaType === 'text/markdown' || (preferPlainText && entry.mediaType === 'text/plain'),
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
if (markdownIndex === -1) {
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const htmlIndex = accepted.findIndex(
|
|
51
|
+
(entry) =>
|
|
52
|
+
entry.mediaType === 'text/html' || entry.mediaType === 'text/*' || entry.mediaType === '*/*',
|
|
53
|
+
);
|
|
54
|
+
|
|
55
|
+
return htmlIndex === -1 || markdownIndex < htmlIndex;
|
|
56
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { htmlToMarkdown } from './convert';
|
|
4
|
+
import { isNegotiablePath, markdownAssetPath } from './routes';
|
|
5
|
+
import type { ResolvedOptions } from './types';
|
|
6
|
+
|
|
7
|
+
type GenerateMarkdownAssetsInput = {
|
|
8
|
+
distDir: string;
|
|
9
|
+
options: ResolvedOptions;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export async function generateMarkdownAssets(input: GenerateMarkdownAssetsInput): Promise<void> {
|
|
13
|
+
const htmlFiles = await collectHtmlFiles(input.distDir, input.options.markdownDir);
|
|
14
|
+
|
|
15
|
+
for (const htmlFilePath of htmlFiles) {
|
|
16
|
+
const relativeHtmlPath = path.relative(input.distDir, htmlFilePath);
|
|
17
|
+
const pathname = htmlFileToRoutePath(relativeHtmlPath);
|
|
18
|
+
if (!isNegotiablePath(pathname, input.options)) {
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const html = await fs.readFile(htmlFilePath, 'utf-8');
|
|
23
|
+
const markdown = htmlToMarkdown(html, pathname, input.options.maxExtractedChars);
|
|
24
|
+
const outPath = path.join(
|
|
25
|
+
input.distDir,
|
|
26
|
+
markdownAssetPath(pathname, input.options.markdownDir).slice(1),
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
await fs.mkdir(path.dirname(outPath), { recursive: true });
|
|
30
|
+
await fs.writeFile(outPath, markdown, 'utf-8');
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function collectHtmlFiles(distDir: string, markdownDir: string): Promise<string[]> {
|
|
35
|
+
const entries = await fs.readdir(distDir, { withFileTypes: true });
|
|
36
|
+
const files: string[] = [];
|
|
37
|
+
|
|
38
|
+
for (const entry of entries) {
|
|
39
|
+
const absolutePath = path.join(distDir, entry.name);
|
|
40
|
+
|
|
41
|
+
if (entry.isDirectory()) {
|
|
42
|
+
if (entry.name === '_worker.js' || entry.name === markdownDir) {
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
files.push(...(await collectHtmlFiles(absolutePath, markdownDir)));
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (entry.isFile() && entry.name.endsWith('.html')) {
|
|
51
|
+
files.push(absolutePath);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return files;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function htmlFileToRoutePath(relativeHtmlPath: string): string {
|
|
59
|
+
const normalized = relativeHtmlPath.split(path.sep).join('/');
|
|
60
|
+
|
|
61
|
+
if (normalized === 'index.html') {
|
|
62
|
+
return '/';
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (normalized.endsWith('/index.html')) {
|
|
66
|
+
return `/${normalized.slice(0, -'/index.html'.length)}/`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (normalized.endsWith('.html')) {
|
|
70
|
+
return `/${normalized.slice(0, -'.html'.length)}`;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return '/';
|
|
74
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import TurndownService from 'turndown';
|
|
2
|
+
|
|
3
|
+
const turndown = new TurndownService({
|
|
4
|
+
headingStyle: 'atx',
|
|
5
|
+
codeBlockStyle: 'fenced',
|
|
6
|
+
});
|
|
7
|
+
|
|
8
|
+
export function htmlToMarkdown(
|
|
9
|
+
html: string,
|
|
10
|
+
routePath: string,
|
|
11
|
+
maxExtractedChars: number,
|
|
12
|
+
): string {
|
|
13
|
+
const title = extractMeta(html, /<title[^>]*>([^<]*)<\/title>/i);
|
|
14
|
+
const description = extractMeta(
|
|
15
|
+
html,
|
|
16
|
+
/<meta\s+name=["']description["']\s+content=["']([^"']*)["'][^>]*>/i,
|
|
17
|
+
);
|
|
18
|
+
|
|
19
|
+
const bodyHtml = extractBodyHtml(html);
|
|
20
|
+
const markdown = turndown.turndown(bodyHtml).trim().slice(0, maxExtractedChars).trim();
|
|
21
|
+
|
|
22
|
+
const lines: string[] = [
|
|
23
|
+
`# ${title || `Page ${routePath}`}`,
|
|
24
|
+
'',
|
|
25
|
+
`- Path: ${routePath}`,
|
|
26
|
+
`- Generated: ${new Date().toISOString()}`,
|
|
27
|
+
];
|
|
28
|
+
|
|
29
|
+
if (description) {
|
|
30
|
+
lines.push(`- Description: ${description}`);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
lines.push('', '## Extracted Content', '', markdown || '_No extractable body content found._');
|
|
34
|
+
|
|
35
|
+
return lines.join('\n');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function extractBodyHtml(html: string): string {
|
|
39
|
+
const stripped = html
|
|
40
|
+
.replace(/<script[\s\S]*?<\/script>/gi, ' ')
|
|
41
|
+
.replace(/<style[\s\S]*?<\/style>/gi, ' ')
|
|
42
|
+
.replace(/<noscript[\s\S]*?<\/noscript>/gi, ' ');
|
|
43
|
+
|
|
44
|
+
return stripped.match(/<body[^>]*>([\s\S]*?)<\/body>/i)?.[1] ?? stripped;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function extractMeta(html: string, pattern: RegExp): string {
|
|
48
|
+
const match = html.match(pattern);
|
|
49
|
+
return decodeHtmlEntities(match?.[1]?.trim() ?? '');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function decodeHtmlEntities(value: string): string {
|
|
53
|
+
return value
|
|
54
|
+
.replace(/&/g, '&')
|
|
55
|
+
.replace(/</g, '<')
|
|
56
|
+
.replace(/>/g, '>')
|
|
57
|
+
.replace(/"/g, '"')
|
|
58
|
+
.replace(/'/g, "'")
|
|
59
|
+
.replace(/ /g, ' ');
|
|
60
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { ResolvedOptions } from './types';
|
|
2
|
+
|
|
3
|
+
export function ensureVaryAccept(headers: Headers): void {
|
|
4
|
+
const vary = headers.get('vary');
|
|
5
|
+
if (!vary) {
|
|
6
|
+
headers.set('vary', 'Accept');
|
|
7
|
+
return;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const values = vary
|
|
11
|
+
.split(',')
|
|
12
|
+
.map((part) => part.trim().toLowerCase())
|
|
13
|
+
.filter(Boolean);
|
|
14
|
+
|
|
15
|
+
if (!values.includes('accept')) {
|
|
16
|
+
headers.set(
|
|
17
|
+
'vary',
|
|
18
|
+
[...new Set([...vary.split(',').map((part) => part.trim()), 'Accept'])]
|
|
19
|
+
.filter(Boolean)
|
|
20
|
+
.join(', '),
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function isHtmlResponse(contentType: string | null): boolean {
|
|
26
|
+
return (contentType ?? '').toLowerCase().includes('text/html');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function countTokens(markdown: string): number {
|
|
30
|
+
return markdown.trim().split(/\s+/).filter(Boolean).length;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function applyMarkdownHeaders(
|
|
34
|
+
headers: Headers,
|
|
35
|
+
markdown: string,
|
|
36
|
+
options: Pick<ResolvedOptions, 'contentSignalHeader'>,
|
|
37
|
+
): void {
|
|
38
|
+
headers.set('content-type', 'text/markdown; charset=utf-8');
|
|
39
|
+
headers.set('x-markdown-tokens', String(countTokens(markdown)));
|
|
40
|
+
headers.set('content-signal', options.contentSignalHeader);
|
|
41
|
+
headers.delete('content-length');
|
|
42
|
+
headers.delete('etag');
|
|
43
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { MarkdownForAgentsOptions, ResolvedOptions } from './types';
|
|
2
|
+
|
|
3
|
+
const DEFAULT_EXCLUDE_PREFIXES = ['/api/', '/_astro/'];
|
|
4
|
+
const DEFAULT_EXCLUDE_EXTENSIONS = [
|
|
5
|
+
'.css',
|
|
6
|
+
'.js',
|
|
7
|
+
'.mjs',
|
|
8
|
+
'.map',
|
|
9
|
+
'.json',
|
|
10
|
+
'.xml',
|
|
11
|
+
'.txt',
|
|
12
|
+
'.ico',
|
|
13
|
+
'.png',
|
|
14
|
+
'.jpg',
|
|
15
|
+
'.jpeg',
|
|
16
|
+
'.webp',
|
|
17
|
+
'.svg',
|
|
18
|
+
'.gif',
|
|
19
|
+
'.pdf',
|
|
20
|
+
'.zip',
|
|
21
|
+
'.woff',
|
|
22
|
+
'.woff2',
|
|
23
|
+
];
|
|
24
|
+
|
|
25
|
+
export function resolveOptions(options: MarkdownForAgentsOptions = {}): ResolvedOptions {
|
|
26
|
+
return {
|
|
27
|
+
include: options.include ?? [],
|
|
28
|
+
exclude: options.exclude ?? [],
|
|
29
|
+
excludePrefixes: options.excludePrefixes ?? DEFAULT_EXCLUDE_PREFIXES,
|
|
30
|
+
excludeExtensions: options.excludeExtensions ?? DEFAULT_EXCLUDE_EXTENSIONS,
|
|
31
|
+
markdownDir: options.markdownDir ?? '_markdown-cache',
|
|
32
|
+
contentSignalHeader: toContentSignalHeader(options.contentSignals),
|
|
33
|
+
maxExtractedChars: options.maxExtractedChars ?? Infinity,
|
|
34
|
+
preferPlainText: options.preferPlainText ?? true,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function toContentSignalHeader(signals: MarkdownForAgentsOptions['contentSignals']): string {
|
|
39
|
+
const resolved = {
|
|
40
|
+
aiTrain: signals?.aiTrain ?? true,
|
|
41
|
+
search: signals?.search ?? true,
|
|
42
|
+
aiInput: signals?.aiInput ?? true,
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
return [
|
|
46
|
+
`ai-train=${resolved.aiTrain ? 'yes' : 'no'}`,
|
|
47
|
+
`search=${resolved.search ? 'yes' : 'no'}`,
|
|
48
|
+
`ai-input=${resolved.aiInput ? 'yes' : 'no'}`,
|
|
49
|
+
].join(', ');
|
|
50
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { Matcher, ResolvedOptions } from './types';
|
|
2
|
+
|
|
3
|
+
export function extractPathname(requestUrl?: string): string | null {
|
|
4
|
+
if (!requestUrl) {
|
|
5
|
+
return null;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
const queryIndex = requestUrl.indexOf('?');
|
|
9
|
+
return queryIndex === -1 ? requestUrl : requestUrl.slice(0, queryIndex);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function isNegotiablePath(pathname: string, options: ResolvedOptions): boolean {
|
|
13
|
+
if (!pathname) {
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
if (matchesAny(pathname, options.exclude)) {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
if (options.include.length > 0 && !matchesAny(pathname, options.include)) {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
if (options.excludePrefixes.some((prefix) => pathname.startsWith(prefix))) {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const lastSegment = pathname.split('/').pop() ?? '';
|
|
30
|
+
const ext = extensionOf(lastSegment);
|
|
31
|
+
if (ext && options.excludeExtensions.includes(ext)) {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return !lastSegment.includes('.') || ext === '';
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function normalizePathname(pathname: string): string {
|
|
39
|
+
if (!pathname || pathname === '/') {
|
|
40
|
+
return '/';
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
if (pathname.endsWith('/')) {
|
|
44
|
+
return pathname;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const lastSegment = pathname.split('/').pop() ?? '';
|
|
48
|
+
if (lastSegment.includes('.')) {
|
|
49
|
+
return pathname;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return `${pathname}/`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function markdownAssetPath(pathname: string, markdownDir: string): string {
|
|
56
|
+
const normalized = normalizePathname(pathname);
|
|
57
|
+
|
|
58
|
+
if (normalized === '/') {
|
|
59
|
+
return `/${markdownDir}/index.md`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (normalized.endsWith('/')) {
|
|
63
|
+
return `/${markdownDir}${normalized}index.md`;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return `/${markdownDir}${normalized}.md`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function extensionOf(value: string): string {
|
|
70
|
+
const dotIndex = value.lastIndexOf('.');
|
|
71
|
+
if (dotIndex === -1) {
|
|
72
|
+
return '';
|
|
73
|
+
}
|
|
74
|
+
return value.slice(dotIndex).toLowerCase();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function matchesAny(pathname: string, matchers: Matcher[]): boolean {
|
|
78
|
+
return matchers.some((matcher) => matches(pathname, matcher));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function matches(pathname: string, matcher: Matcher): boolean {
|
|
82
|
+
if (typeof matcher === 'function') {
|
|
83
|
+
return matcher(pathname);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (matcher instanceof RegExp) {
|
|
87
|
+
return matcher.test(pathname);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (!matcher.includes('*')) {
|
|
91
|
+
return pathname === matcher;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const regex = new RegExp(
|
|
95
|
+
`^${matcher
|
|
96
|
+
.replace(/[.+?^${}()|[\]\\]/g, '\\$&')
|
|
97
|
+
.replace(/\*/g, '.*')}$`,
|
|
98
|
+
);
|
|
99
|
+
|
|
100
|
+
return regex.test(pathname);
|
|
101
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import { prefersMarkdown } from './accept';
|
|
3
|
+
|
|
4
|
+
export function shouldHandleDevRequest(
|
|
5
|
+
req: IncomingMessage,
|
|
6
|
+
preferPlainText: boolean,
|
|
7
|
+
bypassHeaderName: string,
|
|
8
|
+
): boolean {
|
|
9
|
+
const method = (req.method ?? 'GET').toUpperCase();
|
|
10
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
if (req.headers[bypassHeaderName] === '1') {
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
return prefersMarkdown(String(req.headers.accept ?? ''), preferPlainText);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function writeNodeResponse(
|
|
22
|
+
res: ServerResponse,
|
|
23
|
+
response: Response,
|
|
24
|
+
headers: Headers,
|
|
25
|
+
): Promise<void> {
|
|
26
|
+
res.statusCode = response.status;
|
|
27
|
+
res.statusMessage = response.statusText;
|
|
28
|
+
|
|
29
|
+
for (const [key, value] of headers.entries()) {
|
|
30
|
+
res.setHeader(key, value);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const body = await response.arrayBuffer();
|
|
34
|
+
res.end(Buffer.from(body));
|
|
35
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export type Matcher = string | RegExp | ((pathname: string) => boolean);
|
|
2
|
+
|
|
3
|
+
export type ContentSignals = {
|
|
4
|
+
aiTrain?: boolean;
|
|
5
|
+
search?: boolean;
|
|
6
|
+
aiInput?: boolean;
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
export type MarkdownForAgentsOptions = {
|
|
10
|
+
include?: Matcher[];
|
|
11
|
+
exclude?: Matcher[];
|
|
12
|
+
excludePrefixes?: string[];
|
|
13
|
+
excludeExtensions?: string[];
|
|
14
|
+
markdownDir?: string;
|
|
15
|
+
contentSignals?: ContentSignals;
|
|
16
|
+
maxExtractedChars?: number;
|
|
17
|
+
preferPlainText?: boolean;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export type ResolvedOptions = {
|
|
21
|
+
include: Matcher[];
|
|
22
|
+
exclude: Matcher[];
|
|
23
|
+
excludePrefixes: string[];
|
|
24
|
+
excludeExtensions: string[];
|
|
25
|
+
markdownDir: string;
|
|
26
|
+
contentSignalHeader: string;
|
|
27
|
+
maxExtractedChars: number;
|
|
28
|
+
preferPlainText: boolean;
|
|
29
|
+
};
|
package/src/index.ts
ADDED
package/src/runtime.ts
ADDED