Repository navigation
Expand file tree
/
Copy pathcontent.ts
More file actions
303 lines (302 loc) · 10.5 KB
/
Copy pathcontent.ts
File metadata and controls
303 lines (302 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import MarkdownIt from "markdown-it";
import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { createHash } from "node:crypto";
import legacy from "../content/legacy-anchors.json";
import { icon } from "./icons";
import { highlightCode } from "./highlight";
import { rewriteMarkdownLinks } from "./markdown-links";
export const ROOT = path.resolve(import.meta.dir, "..");
export const BASE = "/a7-py";
export const ORIGIN = "https://code5717.github.io" + BASE;
export const SOURCE = "https://github.com/code5717/a7-py/blob/master/";
export const GROUPS = ["Getting started", "Reference", "Project", "Agents"];
export type Heading = { level: number; id: string; text: string };
export type Feature = {
id: string;
status: "supported" | "limited" | "unavailable" | "planned" | "unverified";
qualification: string;
topic: string;
evidence: string[];
};
export type Doc = {
slug: string;
title: string;
nav: string;
group: string;
summary: string;
order: number;
markdown: string;
html: string;
headings: Heading[];
aliases: string[];
sources: string[];
features: Feature[];
examples: string[];
};
export const escapeHtml = (s: string) =>
s.replace(
/[&<>"']/g,
(c) =>
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[
c
]!,
);
export const slugify = (s: string) =>
s
.toLowerCase()
.replace(/`([^`]+)`/g, "$1")
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, "")
.slice(0, 72) || "section";
export const docHref = (slug: string) =>
`${BASE}/${slug === "index" ? "" : slug + "/"}`;
export function markdownHref(href: string): string {
if (!href.startsWith(BASE + "/") && !href.startsWith(ORIGIN + "/"))
return href;
const local = href.replace(ORIGIN, BASE);
const [pathname, hash] = local.split("#");
if (pathname.includes("/docs/") || /\.[a-z]+$/.test(pathname)) return href;
const slug = pathname.slice(BASE.length).replace(/^\/|\/$/g, "") || "index";
return `${BASE}/docs/${slug}.md${hash ? "#" + hash : ""}`;
}
export function renderMarkdown(markdown: string, slug = "index") {
const md = new MarkdownIt({
html: false,
linkify: false,
typographer: false,
});
const codeBlock = (source: string, language: string) => {
const label =
(
{
a7: "A7",
bash: "Terminal",
sh: "Terminal",
json: "JSON",
zig: "Zig",
text: "Output",
markdown: "Markdown",
} as Record<string, string>
)[language] || language;
const highlighted = highlightCode(source, language);
return `<div class="code-block" data-lang="${escapeHtml(language)}"><div class="code-toolbar"><span class="code-language">${escapeHtml(label)}</span><button type="button" class="copy" aria-label="Copy ${escapeHtml(label)} code" hidden>${icon("copy", 14)}${icon("check", 14)}<span data-copy-label>Copy</span></button></div><pre tabindex="0" aria-label="${escapeHtml(label)} code"><code class="language-${escapeHtml(language)}">${highlighted}</code></pre><p class="copy-status" role="status" aria-live="polite" hidden></p></div>\n`;
};
md.renderer.rules.fence = (tokens, idx) =>
codeBlock(
tokens[idx].content,
tokens[idx].info.trim().split(/\s+/)[0] || "text",
);
md.renderer.rules.code_block = (tokens, idx) =>
codeBlock(tokens[idx].content, "text");
const tokens = md.parse(markdown, {});
const headings: Heading[] = [];
const used = new Set<string>();
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
if (token.type === "heading_open") {
const text =
tokens[i + 1].children?.map((t) => t.content).join("") ||
tokens[i + 1].content;
const base = slugify(text);
let id = base,
n = 0;
while (used.has(id)) id = `${base}-${++n}`;
used.add(id);
token.attrSet("id", id);
headings.push({ level: Number(token.tag.slice(1)), id, text });
}
for (const child of token.children ?? []) {
if (child.type !== "link_open") continue;
const href = String(child.attrGet("href") || "");
// Markdown twins remain canonical in source; HTML gets equivalent page links.
const url = new URL(href, `${ORIGIN}/docs/${slug}.md`);
if (
url.origin === new URL(ORIGIN).origin &&
url.pathname.startsWith(BASE + "/docs/") &&
url.pathname.endsWith(".md")
) {
child.attrSet(
"href",
docHref(url.pathname.slice((BASE + "/docs/").length, -3)) + url.hash,
);
}
}
}
let headingIndex = 0;
md.renderer.rules.heading_close = (tokens, idx) => {
const heading = headings[headingIndex++];
const permalink =
heading.level === 2 || heading.level === 3
? `<a class="heading-anchor" href="#${heading.id}" aria-label="Link to ${escapeHtml(heading.text)}">${icon("link")}</a>`
: "";
return `${permalink}</${tokens[idx].tag}>\n`;
};
const html = md.renderer
.render(tokens, md.options, {})
.replace(/<table>/g, '<div class="table-wrap" tabindex="0"><table>')
.replace(/<\/table>/g, "</table></div>")
.replace(
/<td>(supported|limited|unavailable|planned|unverified)<\/td>/g,
'<td><span class="status-badge status-$1">$1</span></td>',
);
return { html, headings };
}
export function parseFrontmatter(raw: string) {
const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/.exec(raw);
const data: Record<string, string> = {};
if (match)
for (const line of match[1].split("\n")) {
const i = line.indexOf(":");
if (i >= 0)
data[line.slice(0, i).trim()] = line
.slice(i + 1)
.trim()
.replace(/^["']|["']$/g, "");
}
return { data, body: raw.slice(match?.[0].length ?? 0).trim() };
}
async function discover(dir: string, prefix = ""): Promise<string[]> {
const files: string[] = [];
for (const e of await readdir(dir, { withFileTypes: true })) {
if (e.isDirectory())
files.push(
...(await discover(path.join(dir, e.name), prefix + e.name + "/")),
);
else if (e.name.endsWith(".md")) files.push(prefix + e.name);
}
return files.sort();
}
export async function readRegistry(): Promise<Doc[]> {
let features: Feature[] = [];
try {
features = JSON.parse(
await readFile(path.join(ROOT, "content/features.json"), "utf8"),
);
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
}
const docs: Doc[] = [];
for (const file of await discover(path.join(ROOT, "public/docs"))) {
const slug = file.slice(0, -3);
const { data, body } = parseFrontmatter(
await readFile(path.join(ROOT, "public/docs", file), "utf8"),
);
const rendered = renderMarkdown(body, slug);
if (rendered.headings.filter((h) => h.level === 1).length !== 1)
throw new Error(`${slug}: expected exactly one H1`);
const aliases = ((legacy as Record<string, string[]>)[slug] ?? []).filter(
(id) => !rendered.headings.some((h) => h.id === id),
);
docs.push({
slug,
title: data.title || rendered.headings[0].text,
nav: data.nav || data.title || rendered.headings[0].text,
group: data.group || "Reference",
summary: data.summary || "",
order: Number(data.order ?? 50),
markdown: body,
...rendered,
aliases,
sources: [
SOURCE + "site/public/docs/" + file,
...new Set(
Array.from(
body.matchAll(
/https:\/\/github\.com\/code5717\/a7-py\/(?:blob|tree)\/[^\s)]+/g,
),
(m) => m[0],
),
),
],
features: features.filter((f) => f.topic === slug),
examples: [
...new Set(
Array.from(body.matchAll(/examples\/([\w/.-]+\.a7)/g), (m) => m[1]),
),
],
});
}
const ordered = docs.sort(
(a, b) => a.order - b.order || a.slug.localeCompare(b.slug),
);
for (const f of features)
if (!ordered.some((d) => d.slug === f.topic))
throw new Error(`Unknown feature topic ${f.topic}`);
return ordered;
}
export function exportsFor(docs: Doc[]) {
const index = [
"# A7 documentation",
"",
"Experimental A7 compiler and language reference. Start with the relevant pages below. Retrieve the full corpus only when needed.",
"",
];
for (const group of GROUPS) {
index.push(`## ${group}`, "");
for (const d of docs.filter((d) => d.group === group))
index.push(`- [${d.title}](${ORIGIN}/docs/${d.slug}.md): ${d.summary}`);
index.push("");
}
index.push(
`## Optional`,
"",
`- [Full corpus](${ORIGIN}/llms-full.txt)`,
`- [Structured manifest](${ORIGIN}/docs/manifest.json)`,
"",
);
const markdown = (source: string, slug: string) =>
rewriteMarkdownLinks(source, (href) => {
const converted = markdownHref(href);
const url = new URL(converted, `${ORIGIN}/docs/${slug}.md`);
return url.origin === new URL(ORIGIN).origin
? url.pathname + url.hash
: converted;
});
const full = [
"# A7 full documentation",
"",
...docs.flatMap((d) => [
`Source: ${ORIGIN}/docs/${d.slug}.md`,
"",
markdown(d.markdown, d.slug),
"",
"---",
"",
]),
].join("\n");
const revision = createHash("sha256")
.update(JSON.stringify(docs.map(({ html, ...source }) => source)))
.digest("hex");
const manifest = {
schemaVersion: 1,
sourceRevision: { kind: "documentation-sha256", value: revision },
qualification:
"Documentation content digest, not a compiler verification result. Evidence links identify the source authority.",
pages: docs.map((d) => ({
id: d.slug,
title: d.title,
summary: d.summary,
group: d.group,
url: ORIGIN + docHref(d.slug).slice(BASE.length),
markdown: ORIGIN + "/docs/" + d.slug + ".md",
sections: d.headings,
aliases: d.aliases,
sources: d.sources,
examples: d.examples,
})),
features: docs.flatMap((d) =>
d.features.map((f) => ({
...f,
documentationUrl: ORIGIN + docHref(d.slug).slice(BASE.length),
markdownUrl: ORIGIN + "/docs/" + d.slug + ".md",
})),
),
};
return {
"llms.txt": index.join("\n"),
"llms-full.txt": full,
"docs/manifest.json": JSON.stringify(manifest, null, 2) + "\n",
"sitemap.xml": `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${docs.map((d) => ` <url><loc>${ORIGIN + docHref(d.slug).slice(BASE.length)}</loc></url>`).join("\n")}\n</urlset>\n`,
};
}