astro-ai-ready 0.0.0-stage → 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/CHANGELOG.md +6 -0
- package/LICENSE +21 -0
- package/README.md +145 -2
- package/bin/astro-ai-ready.js +28 -0
- package/package.json +59 -4
- package/src/html-to-md.js +91 -0
- package/src/index.js +241 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 (unreleased)
|
|
4
|
+
|
|
5
|
+
- First release: Astro integration and CLI that generate llms.txt (grouped sections, page descriptions) and llms-full.txt (clean Markdown of every page). Skips 404, noindex, redirects, cart, checkout and account pages. Never overwrites an existing llms.txt unless asked. Tested with Astro 7.
|
|
6
|
+
- Re-check (4 Dec 2026): pages whose canonical URL points to another page are left out (with a build warning). New `markdownPages` option writes a Markdown copy of each page at the llmstxt.org path (URL + `.md`, or `index.html.md` for folder URLs), and `linkMarkdown` points llms.txt at them; CLI flags `--md-pages` and `--link-md`. README adds an honest "What to expect" section (Google Search does not use llms.txt; most files are never fetched), a noindex header recipe for the .md copies, and an SDG section.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ahmad Zia (https://www.ahmadzia.com)
|
|
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
CHANGED
|
@@ -1,3 +1,146 @@
|
|
|
1
|
-
#
|
|
1
|
+
# astro-ai-ready
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<!-- badges -->
|
|
4
|
+
[](https://www.npmjs.com/package/astro-ai-ready) [](https://github.com/MuhammadAhmadZia/astro-ai-ready/actions/workflows/ci.yml) [](LICENSE) [](skills/astro-ai-ready-setup/SKILL.md) [](https://www.ahmadzia.com/tools/astro-ai-ready)
|
|
5
|
+
|
|
6
|
+
**Make your Astro site readable for ChatGPT, Claude, Perplexity and other AI agents.** This integration writes `llms.txt` and `llms-full.txt` from your built pages every time you run `astro build`. No config needed, no dependencies.
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
npx astro add astro-ai-ready
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
or install it by hand:
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install astro-ai-ready
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
```js
|
|
19
|
+
// astro.config.mjs
|
|
20
|
+
import { defineConfig } from 'astro/config';
|
|
21
|
+
import aiReady from 'astro-ai-ready';
|
|
22
|
+
|
|
23
|
+
export default defineConfig({
|
|
24
|
+
site: 'https://www.your-site.com', // needed for absolute links
|
|
25
|
+
integrations: [aiReady()],
|
|
26
|
+
});
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Build your site and you will find two new files in `dist/`:
|
|
30
|
+
|
|
31
|
+
- **`/llms.txt`**: your site name, a one-line summary and a list of every page with its description, grouped into sections (Blog, Products, Services...).
|
|
32
|
+
- **`/llms-full.txt`**: the clean Markdown text of every page, without navigation, footers, scripts or forms, so an AI agent can read your whole site in one request.
|
|
33
|
+
|
|
34
|
+
## What is llms.txt?
|
|
35
|
+
|
|
36
|
+
[llms.txt](https://llmstxt.org) is a simple Markdown file at the root of a site that tells AI agents what the site is and where the important pages are. It is like a sitemap written for language models. It does not replace your sitemap, robots.txt or schema markup; it adds to them.
|
|
37
|
+
|
|
38
|
+
## Options
|
|
39
|
+
|
|
40
|
+
```js
|
|
41
|
+
aiReady({
|
|
42
|
+
title: 'Crochery', // H1. Default: home page <title>, text before " | "
|
|
43
|
+
description: 'Handmade crochet gifts shipped from Lahore.', // Default: home meta description
|
|
44
|
+
details: 'Every item is made to order in 5 to 7 days.', // Optional extra paragraph
|
|
45
|
+
sections: [ // Default: one section per first URL segment
|
|
46
|
+
{ title: 'Shop', match: '/products/' },
|
|
47
|
+
{ title: 'Guides', match: '/blog/' },
|
|
48
|
+
{ title: 'Policies', match: /^\/(shipping|returns|privacy)/ },
|
|
49
|
+
{ title: 'Archive', match: '/news/', optional: true }, // goes under "## Optional"
|
|
50
|
+
],
|
|
51
|
+
exclude: ['/internal/', /\/preview$/], // added to the defaults
|
|
52
|
+
full: true, // write llms-full.txt
|
|
53
|
+
maxFullChars: 400000, // cap llms-full.txt size
|
|
54
|
+
overwrite: false, // keep an llms.txt your own endpoint already made
|
|
55
|
+
markdownPages: false, // also write /blog/post/index.html.md, /about.md ...
|
|
56
|
+
linkMarkdown: false, // point llms.txt links at those .md copies
|
|
57
|
+
});
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
**Skipped automatically:** 404 and 500 pages, pages with `noindex`, meta-refresh redirects, pages whose canonical URL points to a different page (AMP copies, filtered or duplicate listings), and paths starting with `/admin`, `/api/`, `/cart`, `/checkout`, `/account`, `/search`, `/thank-you`, `/tag/`, `/tags/`, `/page/`, `/drafts/` and `/_`.
|
|
61
|
+
|
|
62
|
+
**Already have an llms.txt endpoint?** The integration will not overwrite a file that already exists in `dist/` unless you set `overwrite: true`. It tells you in the build log.
|
|
63
|
+
|
|
64
|
+
## Markdown copies of each page
|
|
65
|
+
|
|
66
|
+
The [llms.txt proposal](https://llmstxt.org) also suggests a clean Markdown version of each page at the same URL with `.md` added (`/about` becomes `/about.md`, and a folder URL like `/blog/post/` becomes `/blog/post/index.html.md`). Set `markdownPages: true` to write these, and `linkMarkdown: true` if you want `llms.txt` to link to them instead of the HTML pages.
|
|
67
|
+
|
|
68
|
+
Leave it off unless you have a reason. The copies are duplicates of your pages, and search engines can index them. If you turn it on, send a `noindex` header for `.md` files. On Vercel:
|
|
69
|
+
|
|
70
|
+
```json
|
|
71
|
+
{ "headers": [{ "source": "/(.*)\\.md", "headers": [{ "key": "X-Robots-Tag", "value": "noindex" }] }] }
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
On Netlify, add to `_headers`:
|
|
75
|
+
|
|
76
|
+
```
|
|
77
|
+
/*.md
|
|
78
|
+
X-Robots-Tag: noindex
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## What to expect (December 2026)
|
|
82
|
+
|
|
83
|
+
Be honest with yourself about what llms.txt does today:
|
|
84
|
+
|
|
85
|
+
- **It is not a ranking factor.** Google's guidance on generative AI search says you do not need llms.txt or other machine-readable AI files to appear there, and that Search does not use them.
|
|
86
|
+
- **Most llms.txt files are never read.** Ahrefs measured 137,210 sites in May 2026 and 97% of their llms.txt files got zero requests. AI crawlers did not go looking for the file on sites that lacked one.
|
|
87
|
+
- **Where it does help:** AI coding tools and agents that a person points at your site (Claude Code, Cursor and similar) read it, which is why developer documentation sites use it. It also gives you a clean, curated map of your site at almost no cost.
|
|
88
|
+
|
|
89
|
+
So: add it because it is free and harmless, not as a replacement for the things that move AI visibility. Those are crawler access in robots.txt and your firewall, server-rendered text, and complete schema markup. [ai-ready-audit](https://www.npmjs.com/package/ai-ready-audit) checks all three.
|
|
90
|
+
|
|
91
|
+
## Not using Astro?
|
|
92
|
+
|
|
93
|
+
The same generator works on any static build folder (Hugo, Eleventy, Next.js static export, Vite SSG):
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
npx astro-ai-ready ./dist --site https://www.your-site.com
|
|
97
|
+
# add --md-pages for Markdown copies, --link-md to also link llms.txt to them
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Or from code:
|
|
101
|
+
|
|
102
|
+
```js
|
|
103
|
+
import { generate } from 'astro-ai-ready';
|
|
104
|
+
await generate({ outDir: './dist', site: 'https://www.your-site.com' });
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## Check the result
|
|
108
|
+
|
|
109
|
+
Run [ai-ready-audit](https://www.npmjs.com/package/ai-ready-audit) against your live site to confirm AI crawlers can reach it and your schema is complete:
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
npx ai-ready-audit https://www.your-site.com
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Compatibility
|
|
116
|
+
|
|
117
|
+
Tested with Astro 7. Uses only the stable `astro:config:done` and `astro:build:done` hooks, so it should also work with Astro 4, 5 and 6. Works with static output and with the prerendered pages of hybrid or server sites.
|
|
118
|
+
|
|
119
|
+
## Sustainable Development Goals
|
|
120
|
+
|
|
121
|
+
This tool indirectly supports **SDG target 9.c**: increase access to information and communications technology. A curated Markdown summary is the cheapest way for an AI agent to understand a site, so small sites and stores without an SEO budget get the same machine-readable entry point that large documentation sites build by hand. It also supports **target 8.3** (growth of micro, small and medium-sized enterprises). One request for `llms-full.txt` replaces dozens of full page fetches with scripts and images, which lowers the data and server energy an agent spends reading a small site.
|
|
122
|
+
|
|
123
|
+
## About
|
|
124
|
+
|
|
125
|
+
Built by [Ahmad Zia](https://www.ahmadzia.com), an AI and e-commerce consultant. MIT licensed.
|
|
126
|
+
|
|
127
|
+
<!-- ahmadzia-links -->
|
|
128
|
+
## Guide, help and author
|
|
129
|
+
|
|
130
|
+
- **Full guide with examples and FAQs:** [www.ahmadzia.com/tools/astro-ai-ready](https://www.ahmadzia.com/tools/astro-ai-ready)
|
|
131
|
+
- **Background reading:** [AI visibility for online stores: what gets you cited](https://www.ahmadzia.com/blog/ai-visibility-llms-txt-ai-crawlers)
|
|
132
|
+
- **All 30 free tools and agent skills:** [ahmadzia.com/tools](https://www.ahmadzia.com/tools) · [ahmadzia.com/skills](https://www.ahmadzia.com/skills)
|
|
133
|
+
- **Want it set up, fixed or tuned for your store?** [Book a free call](https://www.ahmadzia.com/contact)
|
|
134
|
+
|
|
135
|
+
Built by **[Ahmad Zia](https://www.ahmadzia.com)** (Muhammad Ahmad Zia), an AI consultant for ecommerce since 2020 and green AI researcher at the University of Lahore. [Research](https://www.ahmadzia.com/research) · [Google Scholar](https://scholar.google.com/citations?user=sqjdX2EAAAAJ&hl=en) · [ORCID](https://orcid.org/0000-0002-3208-6246) · [LinkedIn](https://www.linkedin.com/in/muhammad-ahmadzia/) · [GitHub](https://github.com/MuhammadAhmadZia)
|
|
136
|
+
<!-- /ahmadzia-links -->
|
|
137
|
+
|
|
138
|
+
## More AI search and agent readiness tools
|
|
139
|
+
|
|
140
|
+
- [ai-ready-audit](https://github.com/MuhammadAhmadZia/ai-ready-audit): Check whether ChatGPT, Claude, Perplexity and Google AI can find and cite your site
|
|
141
|
+
- [ai-traffic-insights](https://github.com/MuhammadAhmadZia/ai-traffic-insights): See what ChatGPT, Claude and Perplexity actually do on your site, from your own logs
|
|
142
|
+
- [agentic-commerce-readiness](https://github.com/MuhammadAhmadZia/agentic-commerce-readiness): Get your store ready for ChatGPT shopping and AI shopping agents
|
|
143
|
+
- [webmcp-store-tools](https://github.com/MuhammadAhmadZia/webmcp-store-tools): WebMCP tools for WooCommerce and headless stores, plus a checker for any WebMCP site
|
|
144
|
+
- [astro-seo-check](https://github.com/MuhammadAhmadZia/astro-seo-check): Catch SEO mistakes in Astro and static sites at build time
|
|
145
|
+
|
|
146
|
+
All 30 tools and agent skills: [github.com/MuhammadAhmadZia](https://github.com/MuhammadAhmadZia) · [ahmadzia.com/tools](https://www.ahmadzia.com/tools)
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Run the generator on any static build folder (Astro, Hugo, Eleventy, Next export, Vite SSG...).
|
|
3
|
+
import { generate } from '../src/index.js';
|
|
4
|
+
|
|
5
|
+
const args = process.argv.slice(2);
|
|
6
|
+
if (!args.length || args.includes('-h') || args.includes('--help')) {
|
|
7
|
+
console.log(`astro-ai-ready - generate llms.txt and llms-full.txt from a static build folder
|
|
8
|
+
|
|
9
|
+
Usage:
|
|
10
|
+
npx astro-ai-ready <build-folder> --site https://example.com [--title "Name"] [--description "One line"] [--no-full] [--overwrite] [--md-pages] [--link-md]
|
|
11
|
+
|
|
12
|
+
In an Astro project, add it as an integration instead (see README).`);
|
|
13
|
+
process.exit(args.length ? 0 : 1);
|
|
14
|
+
}
|
|
15
|
+
const opts = { outDir: args[0] };
|
|
16
|
+
for (let i = 1; i < args.length; i++) {
|
|
17
|
+
const a = args[i];
|
|
18
|
+
if (a === '--site') opts.site = args[++i];
|
|
19
|
+
else if (a === '--title') opts.title = args[++i];
|
|
20
|
+
else if (a === '--description') opts.description = args[++i];
|
|
21
|
+
else if (a === '--no-full') opts.full = false;
|
|
22
|
+
else if (a === '--overwrite') opts.overwrite = true;
|
|
23
|
+
else if (a === '--md-pages') opts.markdownPages = true;
|
|
24
|
+
else if (a === '--link-md') { opts.markdownPages = true; opts.linkMarkdown = true; }
|
|
25
|
+
}
|
|
26
|
+
const r = await generate(opts);
|
|
27
|
+
r.warnings.forEach((w) => console.warn(`! ${w}`));
|
|
28
|
+
console.log(`Wrote ${r.written.join(', ') || 'nothing'} from ${r.pages} pages in ${opts.outDir}`);
|
package/package.json
CHANGED
|
@@ -1,6 +1,61 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "astro-ai-ready",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Astro integration that generates llms.txt and llms-full.txt from your built pages, so ChatGPT, Claude, Perplexity and other AI agents can read your site. Zero config, zero dependencies, works with any Astro static or hybrid site.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "src/index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./src/index.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"bin",
|
|
12
|
+
"src",
|
|
13
|
+
"README.md",
|
|
14
|
+
"LICENSE",
|
|
15
|
+
"CHANGELOG.md"
|
|
16
|
+
],
|
|
17
|
+
"scripts": {
|
|
18
|
+
"test": "node --test test/*.test.js"
|
|
19
|
+
},
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=18.17"
|
|
22
|
+
},
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"astro": ">=4.0.0"
|
|
25
|
+
},
|
|
26
|
+
"peerDependenciesMeta": {
|
|
27
|
+
"astro": {
|
|
28
|
+
"optional": true
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"keywords": [
|
|
32
|
+
"astro",
|
|
33
|
+
"astro-integration",
|
|
34
|
+
"withastro",
|
|
35
|
+
"llms.txt",
|
|
36
|
+
"llms-full.txt",
|
|
37
|
+
"ai-seo",
|
|
38
|
+
"geo",
|
|
39
|
+
"aeo",
|
|
40
|
+
"chatgpt",
|
|
41
|
+
"claude",
|
|
42
|
+
"perplexity",
|
|
43
|
+
"ai-search"
|
|
44
|
+
],
|
|
45
|
+
"author": {
|
|
46
|
+
"name": "Ahmad Zia (Muhammad Ahmad Zia)",
|
|
47
|
+
"url": "https://www.ahmadzia.com"
|
|
48
|
+
},
|
|
49
|
+
"license": "MIT",
|
|
50
|
+
"homepage": "https://www.ahmadzia.com/tools/astro-ai-ready",
|
|
51
|
+
"repository": {
|
|
52
|
+
"type": "git",
|
|
53
|
+
"url": "git+https://github.com/MuhammadAhmadZia/astro-ai-ready.git"
|
|
54
|
+
},
|
|
55
|
+
"bugs": {
|
|
56
|
+
"url": "https://github.com/MuhammadAhmadZia/astro-ai-ready/issues"
|
|
57
|
+
},
|
|
58
|
+
"bin": {
|
|
59
|
+
"astro-ai-ready": "bin/astro-ai-ready.js"
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Small HTML to Markdown converter for page content. It keeps headings, paragraphs,
|
|
2
|
+
// lists, links, emphasis, code and simple tables, and drops navigation chrome.
|
|
3
|
+
|
|
4
|
+
const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ', '#39': "'", mdash: '-', ndash: '-', hellip: '...', rsquo: "'", lsquo: "'", rdquo: '"', ldquo: '"' };
|
|
5
|
+
|
|
6
|
+
export function decodeEntities(s) {
|
|
7
|
+
return s.replace(/&(#x[0-9a-f]+|#\d+|[a-z0-9]+);/gi, (m, e) => {
|
|
8
|
+
if (e[0] === '#') {
|
|
9
|
+
const code = e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
|
|
10
|
+
return Number.isFinite(code) ? String.fromCodePoint(code) : m;
|
|
11
|
+
}
|
|
12
|
+
return ENTITIES[e.toLowerCase()] ?? m;
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Pick the main content region: <main>, then <article>, then <body>. */
|
|
17
|
+
export function mainContent(html) {
|
|
18
|
+
const pick = (tag) => {
|
|
19
|
+
const m = new RegExp(`<${tag}\\b[^>]*>([\\s\\S]*)<\\/${tag}>`, 'i').exec(html);
|
|
20
|
+
return m ? m[1] : null;
|
|
21
|
+
};
|
|
22
|
+
return pick('main') ?? pick('article') ?? pick('body') ?? html;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function htmlToMarkdown(html, baseUrl) {
|
|
26
|
+
let s = html;
|
|
27
|
+
// drop non-content
|
|
28
|
+
s = s.replace(/<!--[\s\S]*?-->/g, '');
|
|
29
|
+
s = s.replace(/<(script|style|noscript|svg|template|iframe|form|button|select|nav|footer|aside)\b[\s\S]*?<\/\1>/gi, '');
|
|
30
|
+
s = s.replace(/<header\b[^>]*>[\s\S]*?<\/header>/gi, (m) => (/<nav\b/i.test(m) ? '' : m.replace(/<\/?header\b[^>]*>/gi, '')));
|
|
31
|
+
s = s.replace(/<(input|img|br|hr|meta|link)\b[^>]*\/?>/gi, (m, tag) => {
|
|
32
|
+
const t = tag.toLowerCase();
|
|
33
|
+
if (t === 'br') return '\n';
|
|
34
|
+
if (t === 'hr') return '\n\n---\n\n';
|
|
35
|
+
if (t === 'img') {
|
|
36
|
+
const alt = /\balt\s*=\s*["']([^"']*)["']/i.exec(m);
|
|
37
|
+
return alt && alt[1].trim() ? ` ${alt[1].trim()} ` : '';
|
|
38
|
+
}
|
|
39
|
+
return '';
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
// code blocks before inline transforms
|
|
43
|
+
const blocks = [];
|
|
44
|
+
s = s.replace(/<pre\b[^>]*>([\s\S]*?)<\/pre>/gi, (m, inner) => {
|
|
45
|
+
const code = decodeEntities(inner.replace(/<[^>]+>/g, ''));
|
|
46
|
+
blocks.push('\n\n```\n' + code.replace(/\n+$/, '') + '\n```\n\n');
|
|
47
|
+
return `\u0000${blocks.length - 1}\u0000`;
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
// tables: simple rows
|
|
51
|
+
s = s.replace(/<table\b[^>]*>([\s\S]*?)<\/table>/gi, (m, inner) => {
|
|
52
|
+
const rows = [...inner.matchAll(/<tr\b[^>]*>([\s\S]*?)<\/tr>/gi)].map((r) =>
|
|
53
|
+
[...r[1].matchAll(/<t[hd]\b[^>]*>([\s\S]*?)<\/t[hd]>/gi)].map((c) => inline(c[1], baseUrl).replace(/\|/g, '\\|').trim()));
|
|
54
|
+
if (!rows.length) return '';
|
|
55
|
+
const width = Math.max(...rows.map((r) => r.length));
|
|
56
|
+
const line = (r) => '| ' + Array.from({ length: width }, (_, i) => r[i] || '').join(' | ') + ' |';
|
|
57
|
+
return '\n\n' + [line(rows[0]), '|' + ' --- |'.repeat(width), ...rows.slice(1).map(line)].join('\n') + '\n\n';
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
s = s.replace(/<h([1-6])\b[^>]*>([\s\S]*?)<\/h\1>/gi, (m, level, inner) => `\n\n${'#'.repeat(Number(level))} ${inline(inner, baseUrl).trim()}\n\n`);
|
|
61
|
+
s = s.replace(/<li\b[^>]*>([\s\S]*?)<\/li>/gi, (m, inner) => `\n- ${inline(inner, baseUrl).trim()}`);
|
|
62
|
+
s = s.replace(/<\/?(ul|ol)\b[^>]*>/gi, '\n');
|
|
63
|
+
s = s.replace(/<blockquote\b[^>]*>([\s\S]*?)<\/blockquote>/gi, (m, inner) => '\n\n> ' + inline(inner, baseUrl).trim() + '\n\n');
|
|
64
|
+
s = s.replace(/<(p|div|section|figure|figcaption|dd|dt)\b[^>]*>([\s\S]*?)<\/\1>/gi, (m, tag, inner) => `\n\n${inline(inner, baseUrl).trim()}\n\n`);
|
|
65
|
+
s = inline(s, baseUrl);
|
|
66
|
+
|
|
67
|
+
s = s.replace(/\u0000(\d+)\u0000/g, (m, i) => blocks[Number(i)]);
|
|
68
|
+
return s
|
|
69
|
+
.split('\n')
|
|
70
|
+
.map((l) => l.replace(/[ \t]+/g, ' ').replace(/\s+$/, ''))
|
|
71
|
+
.join('\n')
|
|
72
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
73
|
+
.trim();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function inline(html, baseUrl) {
|
|
77
|
+
let s = html;
|
|
78
|
+
s = s.replace(/<a\b[^>]*\bhref\s*=\s*["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi, (m, href, text) => {
|
|
79
|
+
const t = text.replace(/<[^>]+>/g, '').trim();
|
|
80
|
+
if (!t) return '';
|
|
81
|
+
if (/^(javascript:|#)/i.test(href)) return t;
|
|
82
|
+
let url = href;
|
|
83
|
+
try { if (baseUrl) url = new URL(href, baseUrl).toString(); } catch { /* keep */ }
|
|
84
|
+
return `[${t}](${url})`;
|
|
85
|
+
});
|
|
86
|
+
s = s.replace(/<(strong|b)\b[^>]*>([\s\S]*?)<\/\1>/gi, '**$2**');
|
|
87
|
+
s = s.replace(/<(em|i)\b[^>]*>([\s\S]*?)<\/\1>/gi, '_$2_');
|
|
88
|
+
s = s.replace(/<code\b[^>]*>([\s\S]*?)<\/code>/gi, '`$1`');
|
|
89
|
+
s = s.replace(/<[^>]+>/g, '');
|
|
90
|
+
return decodeEntities(s).replace(/[ \t]*\n[ \t]*/g, (m) => (m.includes('\n') ? '\n' : ' '));
|
|
91
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import { readFile, writeFile, readdir, access } from 'node:fs/promises';
|
|
2
|
+
import { join, relative, sep } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { htmlToMarkdown, mainContent, decodeEntities } from './html-to-md.js';
|
|
5
|
+
|
|
6
|
+
const DEFAULT_EXCLUDE = ['/404', '/500', '/admin', '/api/', '/drafts/', '/_', '/cart', '/checkout', '/account', '/search', '/thank-you', '/tag/', '/tags/', '/page/'];
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @typedef {Object} Section
|
|
10
|
+
* @property {string} title Heading shown in llms.txt, for example "Blog"
|
|
11
|
+
* @property {string|RegExp} match Path prefix ("/blog/") or RegExp tested against the path
|
|
12
|
+
* @property {boolean} [optional] Put this section under "## Optional" (llms.txt convention for skippable links)
|
|
13
|
+
*
|
|
14
|
+
* @typedef {Object} Options
|
|
15
|
+
* @property {string} [title] Site name for the H1. Default: home page <title>
|
|
16
|
+
* @property {string} [description] One-line summary for the > blockquote. Default: home meta description
|
|
17
|
+
* @property {string} [details] Extra paragraph(s) under the summary
|
|
18
|
+
* @property {Section[]} [sections] Custom sections. Default: grouped by first path segment
|
|
19
|
+
* @property {(string|RegExp)[]} [exclude] Paths to leave out (added to the defaults)
|
|
20
|
+
* @property {boolean} [full] Also write llms-full.txt (default true)
|
|
21
|
+
* @property {number} [maxFullChars] Cap llms-full.txt size (default 400000 characters)
|
|
22
|
+
* @property {boolean} [overwrite] Replace an llms.txt that another route already generated (default false)
|
|
23
|
+
* @property {boolean} [markdownPages] Also write a clean Markdown copy of each page at its URL + ".md"
|
|
24
|
+
* (for directory URLs, "index.html.md"), as the llms.txt proposal suggests (default false)
|
|
25
|
+
* @property {boolean} [linkMarkdown] Point llms.txt links at those .md copies (needs markdownPages; default false)
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/** Astro integration. */
|
|
29
|
+
export default function aiReady(options = {}) {
|
|
30
|
+
let site;
|
|
31
|
+
return {
|
|
32
|
+
name: 'astro-ai-ready',
|
|
33
|
+
hooks: {
|
|
34
|
+
'astro:config:done': ({ config }) => {
|
|
35
|
+
site = config.site ? String(config.site) : undefined;
|
|
36
|
+
},
|
|
37
|
+
'astro:build:done': async ({ dir, logger }) => {
|
|
38
|
+
const outDir = dir instanceof URL ? fileURLToPath(dir) : String(dir);
|
|
39
|
+
const log = logger || { info: (m) => console.log(`[astro-ai-ready] ${m}`), warn: (m) => console.warn(`[astro-ai-ready] ${m}`) };
|
|
40
|
+
if (!site) log.warn('Set `site` in astro.config to get absolute URLs in llms.txt. Using relative URLs for now.');
|
|
41
|
+
const res = await generate({ outDir, site, ...options });
|
|
42
|
+
for (const w of res.warnings) log.warn(w);
|
|
43
|
+
log.info(`Wrote ${res.written.join(', ') || 'nothing'} (${res.pages} pages)`);
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function exists(p) {
|
|
50
|
+
try { await access(p); return true; } catch { return false; }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function* htmlFiles(dir) {
|
|
54
|
+
for (const e of await readdir(dir, { withFileTypes: true })) {
|
|
55
|
+
const full = join(dir, e.name);
|
|
56
|
+
if (e.isDirectory()) yield* htmlFiles(full);
|
|
57
|
+
else if (e.isFile() && e.name.endsWith('.html')) yield full;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function pathFromFile(outDir, file) {
|
|
62
|
+
let p = '/' + relative(outDir, file).split(sep).join('/');
|
|
63
|
+
p = p.replace(/index\.html$/, '').replace(/\.html$/, '');
|
|
64
|
+
return p || '/';
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function matches(path, pattern) {
|
|
68
|
+
return pattern instanceof RegExp ? pattern.test(path) : path.startsWith(pattern) || path === pattern.replace(/\/$/, '');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const attr = (tag, name) => {
|
|
72
|
+
const m = new RegExp(`\\b${name}\\s*=\\s*["']([^"']*)["']`, 'i').exec(tag);
|
|
73
|
+
return m ? decodeEntities(m[1]) : null;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
export function pageInfo(html) {
|
|
77
|
+
const title = (/<title[^>]*>([\s\S]*?)<\/title>/i.exec(html) || [])[1];
|
|
78
|
+
let description = null;
|
|
79
|
+
let noindex = false;
|
|
80
|
+
let canonical = null;
|
|
81
|
+
for (const tag of html.match(/<meta\b[^>]*>/gi) || []) {
|
|
82
|
+
const name = (attr(tag, 'name') || attr(tag, 'property') || '').toLowerCase();
|
|
83
|
+
if (name === 'description' && description === null) description = attr(tag, 'content');
|
|
84
|
+
if (name === 'og:description' && description === null) description = attr(tag, 'content');
|
|
85
|
+
if (name === 'robots' && /noindex/i.test(attr(tag, 'content') || '')) noindex = true;
|
|
86
|
+
}
|
|
87
|
+
for (const tag of html.match(/<link\b[^>]*>/gi) || []) {
|
|
88
|
+
if ((attr(tag, 'rel') || '').toLowerCase() === 'canonical') canonical = attr(tag, 'href');
|
|
89
|
+
}
|
|
90
|
+
const redirect = /<meta\b[^>]*http-equiv\s*=\s*["']refresh["']/i.test(html);
|
|
91
|
+
return { title: title ? decodeEntities(title).trim() : null, description: description?.trim() || null, noindex, canonical, redirect };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function sectionTitle(path) {
|
|
95
|
+
const seg = path.split('/').filter(Boolean)[0];
|
|
96
|
+
if (!seg) return 'Main';
|
|
97
|
+
return seg.replace(/[-_]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function cleanTitle(title, siteTitle) {
|
|
101
|
+
if (!title) return null;
|
|
102
|
+
if (siteTitle && title !== siteTitle) {
|
|
103
|
+
for (const sepr of [' | ', ' - ', ' · ', ' — ', ' – ']) {
|
|
104
|
+
const parts = title.split(sepr);
|
|
105
|
+
if (parts.length > 1 && siteTitle.includes(parts[parts.length - 1].trim())) return parts.slice(0, -1).join(sepr).trim();
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return title;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Core generator, usable without Astro (any static output folder). */
|
|
112
|
+
/** Where the llms.txt proposal puts a page's Markdown copy: URL + ".md", or "index.html.md" for directory URLs. */
|
|
113
|
+
export function markdownPath(path) {
|
|
114
|
+
return path.endsWith('/') ? `${path}index.html.md` : `${path}.md`;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export async function generate({ outDir, site, title, description, details, sections, exclude = [], full = true, maxFullChars = 400000, overwrite = false, markdownPages = false, linkMarkdown = false }) {
|
|
118
|
+
const warnings = [];
|
|
119
|
+
const written = [];
|
|
120
|
+
const excludes = [...DEFAULT_EXCLUDE, ...exclude];
|
|
121
|
+
const base = site ? site.replace(/\/$/, '') : '';
|
|
122
|
+
const pages = [];
|
|
123
|
+
const skippedCanonical = [];
|
|
124
|
+
|
|
125
|
+
for await (const file of htmlFiles(outDir)) {
|
|
126
|
+
const path = pathFromFile(outDir, file);
|
|
127
|
+
if (excludes.some((e) => matches(path, e))) continue;
|
|
128
|
+
const html = await readFile(file, 'utf8');
|
|
129
|
+
const info = pageInfo(html);
|
|
130
|
+
if (info.noindex || info.redirect) continue;
|
|
131
|
+
// A page whose canonical points to another page is a duplicate (filters, tracking variants, translations served twice).
|
|
132
|
+
if (info.canonical) {
|
|
133
|
+
try {
|
|
134
|
+
const c = new URL(info.canonical, base || 'https://example.invalid');
|
|
135
|
+
const norm = (x) => x.replace(/\/index\.html$/, '/').replace(/\.html$/, '').replace(/\/$/, '') || '/';
|
|
136
|
+
if (norm(c.pathname) !== norm(path)) { skippedCanonical.push(path); continue; }
|
|
137
|
+
} catch { /* bad canonical: keep the page */ }
|
|
138
|
+
}
|
|
139
|
+
pages.push({ path, url: base + path, html, ...info });
|
|
140
|
+
}
|
|
141
|
+
pages.sort((a, b) => (a.path === '/' ? -1 : b.path === '/' ? 1 : a.path.localeCompare(b.path)));
|
|
142
|
+
|
|
143
|
+
const home = pages.find((p) => p.path === '/');
|
|
144
|
+
const siteTitle = title || home?.title?.split(/ [|\-·—–] /)[0]?.trim() || 'Website';
|
|
145
|
+
const siteDesc = description || home?.description;
|
|
146
|
+
if (!siteDesc) warnings.push('No description found. Pass `description` to the integration for a better llms.txt.');
|
|
147
|
+
|
|
148
|
+
// group pages into sections
|
|
149
|
+
const groups = new Map();
|
|
150
|
+
const optional = [];
|
|
151
|
+
for (const p of pages) {
|
|
152
|
+
if (p.path === '/') continue;
|
|
153
|
+
let sectionName = null;
|
|
154
|
+
let isOptional = false;
|
|
155
|
+
if (sections?.length) {
|
|
156
|
+
const s = sections.find((x) => matches(p.path, x.match));
|
|
157
|
+
if (s) { sectionName = s.title; isOptional = !!s.optional; }
|
|
158
|
+
else sectionName = 'Other';
|
|
159
|
+
} else sectionName = sectionTitle(p.path);
|
|
160
|
+
if (isOptional) optional.push(p);
|
|
161
|
+
else {
|
|
162
|
+
if (!groups.has(sectionName)) groups.set(sectionName, []);
|
|
163
|
+
groups.get(sectionName).push(p);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
if (sections?.length) {
|
|
167
|
+
// keep the order the user gave
|
|
168
|
+
const ordered = new Map();
|
|
169
|
+
for (const s of sections) if (groups.has(s.title)) ordered.set(s.title, groups.get(s.title));
|
|
170
|
+
if (groups.has('Other')) ordered.set('Other', groups.get('Other'));
|
|
171
|
+
groups.clear();
|
|
172
|
+
for (const [k, v] of ordered) groups.set(k, v);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const line = (p) => {
|
|
176
|
+
const t = cleanTitle(p.title, siteTitle) || p.path;
|
|
177
|
+
const href = markdownPages && linkMarkdown ? base + markdownPath(p.path) : p.url;
|
|
178
|
+
return `- [${t}](${href})${p.description ? `: ${p.description}` : ''}`;
|
|
179
|
+
};
|
|
180
|
+
if (skippedCanonical.length) warnings.push(`Left out ${skippedCanonical.length} page(s) whose canonical URL points to another page: ${skippedCanonical.slice(0, 5).join(', ')}${skippedCanonical.length > 5 ? ', ...' : ''}`);
|
|
181
|
+
if (linkMarkdown && !markdownPages) warnings.push('linkMarkdown needs markdownPages: true; links point to the HTML pages.');
|
|
182
|
+
const out = [`# ${siteTitle}`, ''];
|
|
183
|
+
if (siteDesc) out.push(`> ${siteDesc}`, '');
|
|
184
|
+
if (details) out.push(details.trim(), '');
|
|
185
|
+
if (home) out.push(`- [Home](${home.url})`, '');
|
|
186
|
+
for (const [name, list] of groups) {
|
|
187
|
+
out.push(`## ${name}`, '', ...list.map(line), '');
|
|
188
|
+
}
|
|
189
|
+
if (optional.length) out.push('## Optional', '', ...optional.map(line), '');
|
|
190
|
+
if (full) out.push(`Full text of every page: ${base}/llms-full.txt`, '');
|
|
191
|
+
const llms = out.join('\n').replace(/\n{3,}/g, '\n\n').trim() + '\n';
|
|
192
|
+
|
|
193
|
+
const llmsPath = join(outDir, 'llms.txt');
|
|
194
|
+
if (!overwrite && (await exists(llmsPath))) {
|
|
195
|
+
warnings.push('llms.txt already exists in the build (probably from your own endpoint). Left it untouched. Set overwrite: true to replace it.');
|
|
196
|
+
} else {
|
|
197
|
+
await writeFile(llmsPath, llms);
|
|
198
|
+
written.push('llms.txt');
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if (full) {
|
|
202
|
+
let total = 0;
|
|
203
|
+
const parts = [`# ${siteTitle}`, '', siteDesc ? `> ${siteDesc}\n` : ''];
|
|
204
|
+
for (const p of pages) {
|
|
205
|
+
const md = htmlToMarkdown(mainContent(p.html), p.url || undefined);
|
|
206
|
+
const chunk = `\n\n---\n\nSource: ${p.url || p.path}\n\n${md}`;
|
|
207
|
+
if (total + chunk.length > maxFullChars) {
|
|
208
|
+
warnings.push(`llms-full.txt reached maxFullChars (${maxFullChars}). Some pages were left out.`);
|
|
209
|
+
break;
|
|
210
|
+
}
|
|
211
|
+
total += chunk.length;
|
|
212
|
+
parts.push(chunk);
|
|
213
|
+
}
|
|
214
|
+
const fullPath = join(outDir, 'llms-full.txt');
|
|
215
|
+
if (!overwrite && (await exists(fullPath))) {
|
|
216
|
+
warnings.push('llms-full.txt already exists in the build. Left it untouched. Set overwrite: true to replace it.');
|
|
217
|
+
} else {
|
|
218
|
+
await writeFile(fullPath, parts.join('\n').replace(/\n{3,}/g, '\n\n').trim() + '\n');
|
|
219
|
+
written.push('llms-full.txt');
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
if (markdownPages) {
|
|
223
|
+
const { mkdir } = await import('node:fs/promises');
|
|
224
|
+
const { dirname } = await import('node:path');
|
|
225
|
+
let n = 0;
|
|
226
|
+
for (const p of pages) {
|
|
227
|
+
const rel = markdownPath(p.path).replace(/^\//, '');
|
|
228
|
+
const target = join(outDir, ...rel.split('/'));
|
|
229
|
+
if (!overwrite && (await exists(target))) continue;
|
|
230
|
+
const md = htmlToMarkdown(mainContent(p.html), p.url || undefined);
|
|
231
|
+
const head = `# ${cleanTitle(p.title, siteTitle) || p.path}\n\n${p.description ? `> ${p.description}\n\n` : ''}`;
|
|
232
|
+
await mkdir(dirname(target), { recursive: true });
|
|
233
|
+
await writeFile(target, (md.startsWith('# ') ? md : head + md).trim() + '\n');
|
|
234
|
+
n++;
|
|
235
|
+
}
|
|
236
|
+
written.push(`${n} page .md file(s)`);
|
|
237
|
+
}
|
|
238
|
+
return { written, warnings, pages: pages.length, llms, skippedCanonical };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export { htmlToMarkdown, mainContent };
|