@cubicecho/agent-docs 0.0.0-stage → 0.2.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.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +52 -2
  3. package/_agents/docs/01-install.md +55 -0
  4. package/_agents/docs/checks.md +16 -0
  5. package/_agents/docs/ci.md +71 -0
  6. package/_agents/docs/cli.md +39 -0
  7. package/_agents/docs/common-mistakes.md +54 -0
  8. package/_agents/docs/config.md +25 -0
  9. package/dist/bin.d.ts +7 -0
  10. package/dist/bin.js +11 -0
  11. package/dist/check/check-agent-docs.d.ts +23 -0
  12. package/dist/check/check-agent-docs.js +314 -0
  13. package/dist/check/generation.d.ts +37 -0
  14. package/dist/check/generation.js +86 -0
  15. package/dist/cli/run.d.ts +24 -0
  16. package/dist/cli/run.js +131 -0
  17. package/dist/consts.d.ts +16 -0
  18. package/dist/consts.js +16 -0
  19. package/dist/core/config.d.ts +31 -0
  20. package/dist/core/config.js +69 -0
  21. package/dist/core/errors.d.ts +17 -0
  22. package/dist/core/errors.js +21 -0
  23. package/dist/core/files.d.ts +28 -0
  24. package/dist/core/files.js +67 -0
  25. package/dist/core/json.d.ts +26 -0
  26. package/dist/core/json.js +44 -0
  27. package/dist/core/package-manifest.d.ts +38 -0
  28. package/dist/core/package-manifest.js +58 -0
  29. package/dist/defaults.d.ts +26 -0
  30. package/dist/defaults.js +14 -0
  31. package/dist/exports/entry-points.d.ts +30 -0
  32. package/dist/exports/entry-points.js +119 -0
  33. package/dist/exports/export-index.d.ts +44 -0
  34. package/dist/exports/export-index.js +233 -0
  35. package/dist/exports/module-source.d.ts +74 -0
  36. package/dist/exports/module-source.js +161 -0
  37. package/dist/exports/scan.d.ts +29 -0
  38. package/dist/exports/scan.js +156 -0
  39. package/dist/exports/summary.d.ts +36 -0
  40. package/dist/exports/summary.js +84 -0
  41. package/dist/index.d.ts +16 -0
  42. package/dist/index.js +16 -0
  43. package/dist/llms/identity.d.ts +21 -0
  44. package/dist/llms/identity.js +67 -0
  45. package/dist/llms/plan.d.ts +53 -0
  46. package/dist/llms/plan.js +318 -0
  47. package/dist/llms/sync.d.ts +16 -0
  48. package/dist/llms/sync.js +36 -0
  49. package/dist/markdown/anchors.d.ts +35 -0
  50. package/dist/markdown/anchors.js +66 -0
  51. package/dist/markdown/page.d.ts +20 -0
  52. package/dist/markdown/page.js +57 -0
  53. package/llms.txt +42 -0
  54. package/package.json +64 -4
@@ -0,0 +1,84 @@
1
+ /** A period, `!` or `?` (and any closing quote or bracket) followed by whitespace or the end: a sentence end. */
2
+ const SENTENCE_END = /[.!?]['")\]]*(?=\s|$)/g;
3
+ /** Text ending in one of these abbreviations has not ended a sentence, whatever comes before it: `(e.g.`. */
4
+ const ABBREVIATION = /(?:^|[^\p{L}])(?:e\.g|i\.e|cf|vs|viz|approx|incl|resp)\.$/iu;
5
+ /** `etc.` ends a sentence only when a capital letter opens the next. */
6
+ const ETC = /(?:^|[^\p{L}])etc\.$/iu;
7
+ const CAPITAL_NEXT = /^\s+\p{Lu}/u;
8
+ const BACKTICK = /`/g;
9
+ const TSDOC_LINK = /\{@link(?:code|plain)?\s+([^}|]+?)(?:\s*\|\s*([^}]+?))?\s*\}/g;
10
+ const MARKDOWN_LINK = /\[([^\]]+)\]\([^)]*\)/g;
11
+ /**
12
+ * The paragraphs of a doc comment ahead of its first tag, each on one line.
13
+ *
14
+ * @param body - The comment's lines, `*` margin stripped.
15
+ * @returns The paragraphs, blank-line separated in the comment.
16
+ *
17
+ * @remarks
18
+ * Tags, and the `@remarks` prose under them, are not the summary's; a block written without the blank line above
19
+ * its tags would otherwise run its summary on into them.
20
+ */
21
+ export function paragraphs(body) {
22
+ const out = [];
23
+ let current = [];
24
+ for (const line of body) {
25
+ const trimmed = line.trim();
26
+ if (trimmed.startsWith('@')) {
27
+ break;
28
+ }
29
+ if (trimmed === '') {
30
+ out.push(current.join(' '));
31
+ current = [];
32
+ }
33
+ else {
34
+ current.push(trimmed);
35
+ }
36
+ }
37
+ out.push(current.join(' '));
38
+ return out.filter((entry) => entry !== '');
39
+ }
40
+ /**
41
+ * Reduces TSDoc and markdown links to their text.
42
+ *
43
+ * @param text - One paragraph of a doc comment.
44
+ * @returns `{@link X | label}` as `label`, `{@link X}` as `X`, and `[text](url)` as `text`.
45
+ */
46
+ export function plainText(text) {
47
+ return text
48
+ .replace(TSDOC_LINK, (_whole, target, label) => label ?? target)
49
+ .replace(MARKDOWN_LINK, '$1');
50
+ }
51
+ /**
52
+ * The first sentence of a paragraph.
53
+ *
54
+ * @param text - One paragraph, on one line.
55
+ * @returns Its text up to the first sentence end, or all of it when it has none.
56
+ *
57
+ * @remarks
58
+ * A period inside a code span, or after an abbreviation such as `e.g.` or `i.e.` (also after a bracket, as in
59
+ * `(e.g. a host)`), does not end the sentence.
60
+ */
61
+ export function firstSentence(text) {
62
+ for (const match of text.matchAll(SENTENCE_END)) {
63
+ const head = text.slice(0, match.index + match[0].length);
64
+ const tail = text.slice(head.length);
65
+ const backticks = head.match(BACKTICK)?.length ?? 0;
66
+ const isInCode = backticks % 2 === 1;
67
+ const isAbbreviation = ABBREVIATION.test(head) || (ETC.test(head) && CAPITAL_NEXT.test(tail) === false);
68
+ if (isInCode || isAbbreviation) {
69
+ continue;
70
+ }
71
+ return head;
72
+ }
73
+ return text;
74
+ }
75
+ /**
76
+ * The one-line summary a doc comment gives the index.
77
+ *
78
+ * @param body - The comment's lines, `*` margin stripped.
79
+ * @returns The first sentence of its first paragraph, links reduced to text; empty when it has no prose.
80
+ */
81
+ export function summarize(body) {
82
+ const [first = ''] = paragraphs(body);
83
+ return firstSentence(plainText(first));
84
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Generates and checks the agent docs a package ships.
3
+ *
4
+ * `planLlms` works out llms.txt from the `_agents/docs/` pages and, for TypeScript, the doc comments behind each
5
+ * package.json `exports` entry; `writeLlms` writes it and `findStaleFiles` compares it with the copy on disk.
6
+ * `checkAgentDocs` checks the README, AGENTS.md, links, page sizes and package contents against the standard. The
7
+ * `agent-docs` command runs the same functions.
8
+ */
9
+ export { type CheckResult, checkAgentDocs } from './check/check-agent-docs.ts';
10
+ export { type CliOutput, ExitCode, runCli } from './cli/run.ts';
11
+ export { type LlmsConfig, loadLlmsConfig } from './core/config.ts';
12
+ export { AgentDocsError } from './core/errors.ts';
13
+ export { LAYOUT_DEFAULTS, type LayoutSettings, LIMIT_DEFAULTS, type LimitSettings } from './defaults.ts';
14
+ export { firstSentence, summarize } from './exports/summary.ts';
15
+ export { ExportPlacement, type GeneratedFile, type LlmsOptions, type LlmsPlan, planLlms } from './llms/plan.ts';
16
+ export { findStaleFiles, writeLlms } from './llms/sync.ts';
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Generates and checks the agent docs a package ships.
3
+ *
4
+ * `planLlms` works out llms.txt from the `_agents/docs/` pages and, for TypeScript, the doc comments behind each
5
+ * package.json `exports` entry; `writeLlms` writes it and `findStaleFiles` compares it with the copy on disk.
6
+ * `checkAgentDocs` checks the README, AGENTS.md, links, page sizes and package contents against the standard. The
7
+ * `agent-docs` command runs the same functions.
8
+ */
9
+ export { checkAgentDocs } from './check/check-agent-docs.js';
10
+ export { ExitCode, runCli } from './cli/run.js';
11
+ export { loadLlmsConfig } from './core/config.js';
12
+ export { AgentDocsError } from './core/errors.js';
13
+ export { LAYOUT_DEFAULTS, LIMIT_DEFAULTS } from './defaults.js';
14
+ export { firstSentence, summarize } from './exports/summary.js';
15
+ export { ExportPlacement, planLlms } from './llms/plan.js';
16
+ export { findStaleFiles, writeLlms } from './llms/sync.js';
@@ -0,0 +1,21 @@
1
+ import type { LlmsConfig } from '../core/config.ts';
2
+ /** The llms.txt title and summary. */
3
+ export interface PackageIdentity {
4
+ /** The `# H1`. */
5
+ title: string;
6
+ /** The `>` line, on one line. */
7
+ summary: string;
8
+ }
9
+ /**
10
+ * The package's title and one-line summary, from the first manifest that has them.
11
+ *
12
+ * @param root - Package root.
13
+ * @param config - `_agents/llms.json`, whose `title` and `summary` win.
14
+ * @returns The title and summary.
15
+ * @throws {@link AgentDocsError} If no manifest or config gives one of them.
16
+ *
17
+ * @remarks
18
+ * Manifests are read in this order: package.json, haxelib.json, pyproject.toml (`[project]`), and Home
19
+ * Assistant's manifest.json.
20
+ */
21
+ export declare function packageIdentity(root: string, config: LlmsConfig): PackageIdentity;
@@ -0,0 +1,67 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { AgentDocsError } from '../core/errors.js';
4
+ import { isJsonObject, readJsonFile, stringField } from '../core/json.js';
5
+ /**
6
+ * The package's title and one-line summary, from the first manifest that has them.
7
+ *
8
+ * @param root - Package root.
9
+ * @param config - `_agents/llms.json`, whose `title` and `summary` win.
10
+ * @returns The title and summary.
11
+ * @throws {@link AgentDocsError} If no manifest or config gives one of them.
12
+ *
13
+ * @remarks
14
+ * Manifests are read in this order: package.json, haxelib.json, pyproject.toml (`[project]`), and Home
15
+ * Assistant's manifest.json.
16
+ */
17
+ export function packageIdentity(root, config) {
18
+ const manifests = [
19
+ jsonManifest(root, 'package.json'),
20
+ jsonManifest(root, 'haxelib.json'),
21
+ pyprojectManifest(root),
22
+ jsonManifest(root, 'manifest.json'),
23
+ ].filter((manifest) => manifest !== undefined);
24
+ const title = config.title ?? manifests.find((m) => m.name)?.name;
25
+ const summary = config.summary ?? manifests.find((m) => m.description)?.description;
26
+ const problems = [];
27
+ if (!title) {
28
+ problems.push('no title: add "name" to a manifest, or "title" to _agents/llms.json.');
29
+ }
30
+ if (!summary) {
31
+ problems.push('no summary: add "description" to a manifest, or "summary" to _agents/llms.json.');
32
+ }
33
+ if (!title || !summary) {
34
+ throw new AgentDocsError(problems);
35
+ }
36
+ return { title, summary: summary.replace(/\s+/g, ' ').trim() };
37
+ }
38
+ /**
39
+ * The name and description of a JSON manifest.
40
+ *
41
+ * @param root - Package root.
42
+ * @param path - Manifest file name.
43
+ * @returns Its fields, or undefined when the file is absent or not an object.
44
+ */
45
+ function jsonManifest(root, path) {
46
+ const parsed = readJsonFile(root, path);
47
+ if (isJsonObject(parsed) === false) {
48
+ return undefined;
49
+ }
50
+ return { name: stringField(parsed, 'name'), description: stringField(parsed, 'description') };
51
+ }
52
+ /**
53
+ * The `name` and `description` of pyproject.toml's `[project]` table.
54
+ *
55
+ * @param root - Package root.
56
+ * @returns Its fields, or undefined when there is no pyproject.toml.
57
+ */
58
+ function pyprojectManifest(root) {
59
+ const full = join(root, 'pyproject.toml');
60
+ if (existsSync(full) === false) {
61
+ return undefined;
62
+ }
63
+ const text = readFileSync(full, 'utf8');
64
+ const table = text.split(/^\[project\]\s*$/m)[1]?.split(/^\[/m)[0] ?? '';
65
+ const field = (key) => table.match(new RegExp(`^${key}\\s*=\\s*"([^"]*)"`, 'm'))?.[1];
66
+ return { name: field('name'), description: field('description') };
67
+ }
@@ -0,0 +1,53 @@
1
+ import { type LimitSettings } from '../defaults.ts';
2
+ /** What {@link planLlms} reads. */
3
+ export interface LlmsOptions {
4
+ /** Package root: where package.json and llms.txt are. */
5
+ root: string;
6
+ /** Adds a `Base URL:` line, for a copy served from a site. */
7
+ baseUrl?: string;
8
+ /** Limits to change, for a test or an unusual repo. */
9
+ limits?: Partial<LimitSettings>;
10
+ }
11
+ /** One file the plan writes. */
12
+ export interface GeneratedFile {
13
+ /** Path relative to the package root, with `/` separators. */
14
+ path: string;
15
+ /** The whole file. */
16
+ content: string;
17
+ }
18
+ /** Where the export index went. */
19
+ export declare const ExportPlacement: {
20
+ /** The package has no TypeScript source, or `"exports": false` turned the index off. */
21
+ readonly None: 'none';
22
+ /** One `##` section per entry point, inside llms.txt. */
23
+ readonly Inline: 'inline';
24
+ /** One generated page per entry point under the docs folder, which llms.txt links like any other page. */
25
+ readonly Pages: 'pages';
26
+ };
27
+ export type ExportPlacement = (typeof ExportPlacement)[keyof typeof ExportPlacement];
28
+ /** Everything one run of `llms` writes, before anything is written. */
29
+ export interface LlmsPlan {
30
+ /** llms.txt first, then any generated export pages. */
31
+ files: GeneratedFile[];
32
+ /** Export pages a previous run generated that this one no longer does. */
33
+ obsolete: string[];
34
+ /** Where the export index went. */
35
+ placement: ExportPlacement;
36
+ /** Exports that have no doc comment, as `name (import path)`. */
37
+ undocumented: string[];
38
+ }
39
+ /**
40
+ * Works out llms.txt, and the export pages when there are any, without writing anything.
41
+ *
42
+ * @param options - The package root, and an optional base URL and limits.
43
+ * @returns The files to write and the ones to delete.
44
+ * @throws {@link AgentDocsError} With one line per problem: a page with no title or summary, a missing manifest
45
+ * field, an export that can't be traced, or a result over the size limit.
46
+ *
47
+ * @remarks
48
+ * Each page in the docs folder becomes one link, under `## Docs` or a section named after its subfolder. When the
49
+ * package has TypeScript in `src/`, each package.json `exports` entry adds a `## Exports: <import path>` section.
50
+ * If that would take llms.txt over `llmsLimitKb`, the sections become generated pages in `<docsDir>/exports/`
51
+ * instead, and llms.txt links them.
52
+ */
53
+ export declare function planLlms(options: LlmsOptions): LlmsPlan;
@@ -0,0 +1,318 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { BYTES_PER_KB, GENERATED_MARKER, LLMS_FILE, PACKAGE_NAME } from '../consts.js';
4
+ import { loadLlmsConfig } from '../core/config.js';
5
+ import { AgentDocsError } from '../core/errors.js';
6
+ import { compareWalkOrder, hasTypeScript, markdownFiles } from '../core/files.js';
7
+ import { readPackageManifest } from '../core/package-manifest.js';
8
+ import { LAYOUT_DEFAULTS, LIMIT_DEFAULTS } from '../defaults.js';
9
+ import { findEntryPoints } from '../exports/entry-points.js';
10
+ import { buildExportIndex } from '../exports/export-index.js';
11
+ import { describePage } from '../markdown/page.js';
12
+ import { packageIdentity } from './identity.js';
13
+ /** Where the export index went. */
14
+ export const ExportPlacement = {
15
+ /** The package has no TypeScript source, or `"exports": false` turned the index off. */
16
+ None: 'none',
17
+ /** One `##` section per entry point, inside llms.txt. */
18
+ Inline: 'inline',
19
+ /** One generated page per entry point under the docs folder, which llms.txt links like any other page. */
20
+ Pages: 'pages',
21
+ };
22
+ const { exportsFolder, sourceDir, topLevelSection } = LAYOUT_DEFAULTS;
23
+ /** Stands in for a ` (part N of M)` title suffix while a page's parts are still being counted. */
24
+ const PART_SUFFIX_ROOM = ' (part 99 of 99)';
25
+ /**
26
+ * Works out llms.txt, and the export pages when there are any, without writing anything.
27
+ *
28
+ * @param options - The package root, and an optional base URL and limits.
29
+ * @returns The files to write and the ones to delete.
30
+ * @throws {@link AgentDocsError} With one line per problem: a page with no title or summary, a missing manifest
31
+ * field, an export that can't be traced, or a result over the size limit.
32
+ *
33
+ * @remarks
34
+ * Each page in the docs folder becomes one link, under `## Docs` or a section named after its subfolder. When the
35
+ * package has TypeScript in `src/`, each package.json `exports` entry adds a `## Exports: <import path>` section.
36
+ * If that would take llms.txt over `llmsLimitKb`, the sections become generated pages in `<docsDir>/exports/`
37
+ * instead, and llms.txt links them.
38
+ */
39
+ export function planLlms(options) {
40
+ const { root, baseUrl } = options;
41
+ const { llmsLimitKb, pageLimitKb } = { ...LIMIT_DEFAULTS, ...options.limits };
42
+ const config = loadLlmsConfig(root);
43
+ const manifest = readPackageManifest(root);
44
+ const identity = packageIdentity(root, config);
45
+ const entries = exportIndexFor(root, config, manifest);
46
+ const generatedDir = `${config.docsDir}/${exportsFolder}`;
47
+ const { pages, previouslyGenerated } = readPages(root, config, generatedDir, entries.length > 0);
48
+ const hasExports = entries.length > 0;
49
+ const intro = introLines(identity.title, config.docsDir, hasExports, manifest);
50
+ const head = [`# ${identity.title}`, '', `> ${identity.summary}`, ''];
51
+ if (baseUrl) {
52
+ head.push(`Base URL: ${baseUrl}`, '');
53
+ }
54
+ head.push(...intro);
55
+ const render = (linked, inline) => {
56
+ const out = [...head, ...pageSections(linked, config)];
57
+ for (const entry of inline) {
58
+ out.push(`## ${entryTitle(entry)}`, '', ...(entry.summary ? [entry.summary, ''] : []), ...exportLines(entry), '');
59
+ }
60
+ if (config.extra) {
61
+ out.push(config.extra.trim(), '');
62
+ }
63
+ return out.join('\n');
64
+ };
65
+ const limitBytes = llmsLimitKb * BYTES_PER_KB;
66
+ const inlined = render(pages, entries);
67
+ const fitsInline = Buffer.byteLength(inlined) <= limitBytes;
68
+ const undocumented = entries.flatMap((entry) => entry.exports.filter((e) => e.summary === '').map((e) => `${e.name} (${entry.importPath})`));
69
+ if (hasExports === false || fitsInline) {
70
+ return {
71
+ files: [{ path: LLMS_FILE, content: inlined }],
72
+ obsolete: previouslyGenerated,
73
+ placement: hasExports ? ExportPlacement.Inline : ExportPlacement.None,
74
+ undocumented,
75
+ };
76
+ }
77
+ const pageLimitBytes = pageLimitKb * BYTES_PER_KB;
78
+ const generated = entries.flatMap((entry, index) => entryPages(entry, generatedDir, index + 1, pageLimitBytes));
79
+ const problems = generated.flatMap((page) => {
80
+ const clashes = pages.some((existing) => existing.path === page.path);
81
+ const size = Buffer.byteLength(page.text);
82
+ return [
83
+ ...(clashes
84
+ ? [`${page.path} was written by hand, where the export index goes: move it out of ${generatedDir}/.`]
85
+ : []),
86
+ ...(size > pageLimitBytes
87
+ ? [
88
+ `${page.path} would be ${Math.round(size / BYTES_PER_KB)} KB, over ${pageLimitKb} KB: shorten the first sentence of its longest doc comments.`,
89
+ ]
90
+ : []),
91
+ ];
92
+ });
93
+ const linked = [...pages, ...generated].sort((a, b) => compareWalkOrder(a.path, b.path));
94
+ const content = render(linked, []);
95
+ const size = Buffer.byteLength(content);
96
+ if (size > limitBytes) {
97
+ problems.push(`${LLMS_FILE} would be ${Math.round(size / BYTES_PER_KB)} KB, over ${llmsLimitKb} KB even with the export index on its own pages: shorten the page summaries or merge small pages.`);
98
+ }
99
+ if (problems.length > 0) {
100
+ throw new AgentDocsError(problems);
101
+ }
102
+ const generatedPaths = new Set(generated.map((page) => page.path));
103
+ return {
104
+ files: [{ path: LLMS_FILE, content }, ...generated.map((page) => ({ path: page.path, content: page.text }))],
105
+ obsolete: previouslyGenerated.filter((path) => generatedPaths.has(path) === false),
106
+ placement: ExportPlacement.Pages,
107
+ undocumented,
108
+ };
109
+ }
110
+ /**
111
+ * The export index, when the package has TypeScript source and the config leaves it on.
112
+ *
113
+ * @param root - Package root.
114
+ * @param config - `_agents/llms.json`.
115
+ * @param manifest - package.json, if any.
116
+ * @returns One index per entry point; empty when there is nothing to index.
117
+ * @throws {@link AgentDocsError} If an entry point or a re-export can't be traced to its source.
118
+ */
119
+ function exportIndexFor(root, config, manifest) {
120
+ const isIndexed = config.exports && manifest?.name !== undefined && hasTypeScript(root, sourceDir);
121
+ if (isIndexed === false || manifest?.name === undefined) {
122
+ return [];
123
+ }
124
+ const { entries, problems } = findEntryPoints(root, manifest.name, manifest.exports);
125
+ if (problems.length > 0) {
126
+ throw new AgentDocsError(problems);
127
+ }
128
+ return buildExportIndex(root, entries);
129
+ }
130
+ /**
131
+ * The pages on disk, apart from the export pages a previous run generated.
132
+ *
133
+ * @param root - Package root.
134
+ * @param config - `_agents/llms.json`, for the docs folder.
135
+ * @param generatedDir - Where generated export pages live.
136
+ * @param mayBeEmpty - Whether a missing docs folder is allowed, as it is when the export index fills llms.txt.
137
+ * @returns The hand-written pages and the paths of the generated ones.
138
+ * @throws {@link AgentDocsError} If the docs folder is missing and nothing else would fill llms.txt.
139
+ */
140
+ function readPages(root, config, generatedDir, mayBeEmpty) {
141
+ const paths = markdownFiles(root, config.docsDir);
142
+ const isMissing = paths.length === 0 && mayBeEmpty === false;
143
+ if (isMissing) {
144
+ throw new AgentDocsError([`${config.docsDir}/ has no pages: write the agent docs there first.`]);
145
+ }
146
+ const pages = [];
147
+ const previouslyGenerated = [];
148
+ for (const path of paths) {
149
+ const text = readFileSync(join(root, path), 'utf8');
150
+ const isGenerated = path.startsWith(`${generatedDir}/`) && text.startsWith(GENERATED_MARKER);
151
+ if (isGenerated) {
152
+ previouslyGenerated.push(path);
153
+ }
154
+ else {
155
+ pages.push({ path, text });
156
+ }
157
+ }
158
+ return { pages, previouslyGenerated };
159
+ }
160
+ /**
161
+ * The `##` sections that link the pages: top-level pages under `## Docs`, each subfolder under its own heading.
162
+ *
163
+ * @param pages - Pages in walk order.
164
+ * @param config - `_agents/llms.json`, for the docs folder and the section names.
165
+ * @returns The lines, each section followed by a blank line.
166
+ * @throws {@link AgentDocsError} With a line for each page that has no title or no summary.
167
+ */
168
+ function pageSections(pages, config) {
169
+ const sections = new Map();
170
+ const problems = [];
171
+ for (const { path, text } of pages) {
172
+ const folders = path
173
+ .slice(config.docsDir.length + 1)
174
+ .split('/')
175
+ .slice(0, -1);
176
+ const heading = folders.length > 0 ? folderHeading(folders[0], config) : topLevelSection;
177
+ try {
178
+ const { title, note } = describePage(path, text);
179
+ sections.set(heading, [...(sections.get(heading) ?? []), `- [${title}](${path}): ${note}`]);
180
+ }
181
+ catch (error) {
182
+ if (error instanceof AgentDocsError) {
183
+ problems.push(...error.problems);
184
+ }
185
+ else {
186
+ throw error;
187
+ }
188
+ }
189
+ }
190
+ if (problems.length > 0) {
191
+ throw new AgentDocsError(problems);
192
+ }
193
+ return [...sections].flatMap(([heading, links]) => [`## ${heading}`, '', ...links, '']);
194
+ }
195
+ /**
196
+ * Turns a folder name into a heading: `getting-started` → `Getting started`.
197
+ *
198
+ * @param folder - The subfolder's name.
199
+ * @param config - `_agents/llms.json`, whose `sections` names win.
200
+ * @returns The heading text.
201
+ */
202
+ function folderHeading(folder, config) {
203
+ const named = config.sections[folder];
204
+ if (named) {
205
+ return named;
206
+ }
207
+ const words = folder.replace(/^\d+[-_]/, '').replace(/[-_]/g, ' ');
208
+ return words.charAt(0).toUpperCase() + words.slice(1);
209
+ }
210
+ /**
211
+ * The paragraph under the summary that says what llms.txt indexes and where it comes from.
212
+ *
213
+ * @param title - The package's title.
214
+ * @param docsDir - The docs folder.
215
+ * @param hasExports - Whether the export index is part of it.
216
+ * @param manifest - package.json, for the Node range and peers.
217
+ * @returns The lines, each paragraph followed by a blank line.
218
+ */
219
+ function introLines(title, docsDir, hasExports, manifest) {
220
+ if (hasExports === false) {
221
+ return [
222
+ `Agent-facing docs for ${title}, one task or concept per page. Generated from ${docsDir}/ by ${PACKAGE_NAME}; edit the pages, not this file.`,
223
+ '',
224
+ ];
225
+ }
226
+ const lines = [
227
+ `Agent-facing docs for ${title}: one task or concept per page, then what each package.json "exports" entry exports. Generated from ${docsDir}/ and the doc comments in ${sourceDir}/ by ${PACKAGE_NAME}; edit those, not this file.`,
228
+ '',
229
+ ];
230
+ const requirements = [];
231
+ if (manifest?.nodeRange) {
232
+ requirements.push(`Requires Node ${manifest.nodeRange}.`);
233
+ }
234
+ const peers = (manifest?.peers ?? []).map((peer) => `\`${peer.name}\` ${peer.range}${peer.isOptional ? ' (optional)' : ''}`);
235
+ if (peers.length > 0) {
236
+ requirements.push(`Peer dependencies: ${peers.join(', ')}.`);
237
+ }
238
+ if (requirements.length > 0) {
239
+ lines.push(requirements.join(' '), '');
240
+ }
241
+ return lines;
242
+ }
243
+ /**
244
+ * The heading an entry point's exports go under.
245
+ *
246
+ * @param entry - One entry's index.
247
+ * @returns `Exports: <import path>`.
248
+ */
249
+ function entryTitle(entry) {
250
+ return `Exports: ${entry.importPath}`;
251
+ }
252
+ /**
253
+ * One list line per export, then one per package the entry re-exports from.
254
+ *
255
+ * @param entry - One entry's index.
256
+ * @returns The lines.
257
+ */
258
+ function exportLines(entry) {
259
+ const own = entry.exports.map((item) => {
260
+ const label = item.isType ? `\`${item.name}\` (type)` : `\`${item.name}\``;
261
+ return item.summary ? `- ${label}: ${item.summary}` : `- ${label}`;
262
+ });
263
+ const foreign = entry.foreign.map((item) => {
264
+ const names = item.names.includes('*') ? 'everything it exports' : item.names.map((n) => `\`${n}\``).join(', ');
265
+ return `- Re-exported unchanged from \`${item.specifier}\`, which documents them: ${names}.`;
266
+ });
267
+ return [...own, ...foreign];
268
+ }
269
+ /**
270
+ * The file name stem of an entry's generated page.
271
+ *
272
+ * @param entry - One entry's index.
273
+ * @returns `index` for the root entry, else the subpath with `/` turned to `-`.
274
+ */
275
+ function entryFileStem(entry) {
276
+ const subpath = entry.importPath.split('/').slice(entry.importPath.startsWith('@') ? 2 : 1);
277
+ return subpath.length === 0 ? 'index' : subpath.join('-').replace(/[^\w.-]+/g, '-');
278
+ }
279
+ /**
280
+ * The generated pages for one entry point: one page, or numbered parts when one would pass the page limit.
281
+ *
282
+ * @param entry - One entry's index.
283
+ * @param generatedDir - Where generated pages go.
284
+ * @param position - The entry's 1-based place in `exports`, which prefixes its file names.
285
+ * @param limitBytes - The largest a page may be.
286
+ * @returns The pages, each starting with the generated marker.
287
+ */
288
+ function entryPages(entry, generatedDir, position, limitBytes) {
289
+ const stem = `${generatedDir}/${String(position).padStart(2, '0')}-${entryFileStem(entry)}`;
290
+ const summary = entry.summary || `What \`${entry.importPath}\` exports, with the first sentence of each doc comment.`;
291
+ const page = (title, lines) => [
292
+ `${GENERATED_MARKER} from ${entry.source}; edit its doc comments, not this page. -->`,
293
+ `# ${title}`,
294
+ '',
295
+ summary,
296
+ '',
297
+ ...lines,
298
+ '',
299
+ ].join('\n');
300
+ const parts = [[]];
301
+ for (const line of exportLines(entry)) {
302
+ const current = parts[parts.length - 1];
303
+ const wouldOverflow = Buffer.byteLength(page(`${entryTitle(entry)}${PART_SUFFIX_ROOM}`, [...current, line])) > limitBytes;
304
+ if (wouldOverflow && current.length > 0) {
305
+ parts.push([line]);
306
+ }
307
+ else {
308
+ current.push(line);
309
+ }
310
+ }
311
+ if (parts.length === 1) {
312
+ return [{ path: `${stem}.md`, text: page(entryTitle(entry), parts[0]) }];
313
+ }
314
+ return parts.map((lines, index) => ({
315
+ path: `${stem}-${index + 1}.md`,
316
+ text: page(`${entryTitle(entry)} (part ${index + 1} of ${parts.length})`, lines),
317
+ }));
318
+ }
@@ -0,0 +1,16 @@
1
+ import type { LlmsPlan } from './plan.ts';
2
+ /**
3
+ * Writes a plan's files and deletes the export pages it no longer generates.
4
+ *
5
+ * @param root - Package root.
6
+ * @param plan - What {@link planLlms} worked out for the same root.
7
+ */
8
+ export declare function writeLlms(root: string, plan: LlmsPlan): void;
9
+ /**
10
+ * Compares a plan with the files on disk, for CI.
11
+ *
12
+ * @param root - Package root.
13
+ * @param plan - What {@link planLlms} worked out for the same root.
14
+ * @returns One line per file that is missing, differs, or should have been deleted; empty when all match.
15
+ */
16
+ export declare function findStaleFiles(root: string, plan: LlmsPlan): string[];
@@ -0,0 +1,36 @@
1
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { LLMS_COMMAND } from '../consts.js';
4
+ /**
5
+ * Writes a plan's files and deletes the export pages it no longer generates.
6
+ *
7
+ * @param root - Package root.
8
+ * @param plan - What {@link planLlms} worked out for the same root.
9
+ */
10
+ export function writeLlms(root, plan) {
11
+ for (const { path, content } of plan.files) {
12
+ const full = join(root, path);
13
+ mkdirSync(dirname(full), { recursive: true });
14
+ writeFileSync(full, content);
15
+ }
16
+ for (const path of plan.obsolete) {
17
+ rmSync(join(root, path), { force: true });
18
+ }
19
+ }
20
+ /**
21
+ * Compares a plan with the files on disk, for CI.
22
+ *
23
+ * @param root - Package root.
24
+ * @param plan - What {@link planLlms} worked out for the same root.
25
+ * @returns One line per file that is missing, differs, or should have been deleted; empty when all match.
26
+ */
27
+ export function findStaleFiles(root, plan) {
28
+ const stale = plan.files
29
+ .filter(({ path, content }) => {
30
+ const full = join(root, path);
31
+ return existsSync(full) === false || readFileSync(full, 'utf8') !== content;
32
+ })
33
+ .map(({ path }) => `${path} is stale or missing: run "${LLMS_COMMAND}" and commit it.`);
34
+ const leftover = plan.obsolete.map((path) => `${path} is no longer generated: run "${LLMS_COMMAND}" to delete it, and commit that.`);
35
+ return [...stale, ...leftover];
36
+ }
@@ -0,0 +1,35 @@
1
+ /** A heading as a link can target it. */
2
+ export interface Heading {
3
+ /** Number of `#` marks, 1 to 6. */
4
+ level: number;
5
+ /** GitHub's anchor for it, with the `-1` suffix a repeat gets. */
6
+ anchor: string;
7
+ }
8
+ /**
9
+ * GitHub's heading anchor: lower case, punctuation dropped, spaces to hyphens.
10
+ *
11
+ * @param heading - Heading text without its `#` marks.
12
+ * @returns The anchor without `#`; underscores and hyphens are kept.
13
+ */
14
+ export declare function slug(heading: string): string;
15
+ /**
16
+ * The lines of a markdown text that sit outside code fences.
17
+ *
18
+ * @param text - Markdown source.
19
+ * @returns The lines in order, fence lines themselves left out.
20
+ */
21
+ export declare function proseLines(text: string): string[];
22
+ /**
23
+ * Every heading outside code fences, anchored the way GitHub anchors them.
24
+ *
25
+ * @param text - Markdown source.
26
+ * @returns The headings in order.
27
+ */
28
+ export declare function headings(text: string): Heading[];
29
+ /**
30
+ * Link targets outside code fences and code spans.
31
+ *
32
+ * @param text - Markdown source.
33
+ * @returns Each `](target)` target, in order.
34
+ */
35
+ export declare function links(text: string): string[];