-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
673 lines (573 loc) · 20.5 KB
/
index.ts
File metadata and controls
673 lines (573 loc) · 20.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
import { $, type Server } from "bun";
import { watch } from "fs";
import { createHighlighter, type Highlighter } from "shiki";
const isDev = process.argv.includes("--dev");
const PORT = 3000;
interface GitCommit {
hash: string;
date: Date;
}
interface GitHubAuthor {
login: string;
avatarUrl: string;
profileUrl: string;
}
interface RFCGitInfo {
accepted: GitCommit | null;
lastUpdated: GitCommit | null; // null if same as accepted or no git history
author: GitHubAuthor | null;
}
type RFCState = "proposed" | "accepted" | "completed";
const RFC_STATES: RFCState[] = ["proposed", "accepted", "completed"];
interface RFC {
number: string;
title: string;
filename: string;
html: string;
git: RFCGitInfo;
state: RFCState;
}
const THEME_SCRIPT = `
(function() {
const saved = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', saved);
})();
`;
const ICON_SUN = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/></svg>`;
const ICON_MOON = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/></svg>`;
const ICON_EXTERNAL = `<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 7h10v10"/><path d="M7 17 17 7"/></svg>`;
const ICON_GITHUB = `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"/></svg>`;
const TOGGLE_SCRIPT = `
function toggleTheme() {
const root = document.documentElement;
const current = root.getAttribute('data-theme');
const next = current === 'dark' ? 'light' : 'dark';
root.setAttribute('data-theme', next);
localStorage.setItem('theme', next);
updateToggleIcon();
}
function updateToggleIcon() {
const btn = document.querySelector('.theme-toggle');
if (!btn) return;
const current = document.documentElement.getAttribute('data-theme');
btn.innerHTML = current === 'dark' ? '${ICON_SUN}' : '${ICON_MOON}';
btn.setAttribute('aria-label', current === 'dark' ? 'Switch to light mode' : 'Switch to dark mode');
}
document.addEventListener('DOMContentLoaded', updateToggleIcon);
`;
const FILTER_SCRIPT = `
function filterRFCs(state) {
const items = document.querySelectorAll('.rfc-list li');
const buttons = document.querySelectorAll('.filter-btn');
buttons.forEach(btn => {
btn.classList.toggle('active', btn.dataset.state === state);
});
items.forEach(item => {
if (state === 'all' || item.dataset.state === state) {
item.style.display = '';
} else {
item.style.display = 'none';
}
});
// Save filter preference
localStorage.setItem('rfc-filter', state);
}
document.addEventListener('DOMContentLoaded', function() {
const saved = localStorage.getItem('rfc-filter') || 'all';
filterRFCs(saved);
});
`;
const LIVE_RELOAD_SCRIPT = `
(function() {
const evtSource = new EventSource('/__reload');
evtSource.onmessage = function() {
location.reload();
};
})();
`;
function baseHTML(
title: string,
content: string,
cssPath: string = "styles.css",
liveReload: boolean = false,
repoUrl: string | null = null,
): string {
const basePath = cssPath === "styles.css" ? "./" : "../";
const githubLink = repoUrl
? `<a href="${repoUrl}" class="github-link" aria-label="View on GitHub" target="_blank" rel="noopener">${ICON_GITHUB}</a>`
: "";
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${escapeHTML(title)}</title>
<link rel="icon" type="image/svg+xml" href="${basePath}vortex_logo.svg">
<link rel="stylesheet" href="${cssPath}">
<script>${THEME_SCRIPT}</script>
</head>
<body>
<div class="container">
<header>
<a href="${basePath}" class="header-brand">
<img src="${basePath}vortex_logo.svg" alt="Vortex" class="header-logo">
<h1>Vortex RFCs</h1>
</a>
<div class="header-actions">
${githubLink}
<button class="theme-toggle" onclick="toggleTheme()" aria-label="Toggle theme"></button>
</div>
</header>
<main>
${content}
</main>
<footer>
Vortex RFC Archive
</footer>
</div>
<script>${TOGGLE_SCRIPT}</script>${liveReload ? `\n <script>${LIVE_RELOAD_SCRIPT}</script>` : ""}
</body>
</html>`;
}
function escapeHTML(str: string): string {
return str
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """);
}
function stateLabel(state: RFCState): string {
return state.charAt(0).toUpperCase() + state.slice(1);
}
function indexPage(
rfcs: RFC[],
repoUrl: string | null,
liveReload: boolean = false,
): string {
// Sort in reverse numeric order (newest first)
const sorted = [...rfcs].sort((a, b) => b.number.localeCompare(a.number));
const list = sorted
.map((rfc) => {
const dateStr = rfc.git.accepted ? formatDate(rfc.git.accepted.date) : "";
let authorHTML = "";
if (rfc.git.author && rfc.git.accepted) {
const commitUrl = repoUrl
? `${repoUrl}/commit/${rfc.git.accepted.hash}`
: `https://github.com/${rfc.git.author.login}`;
authorHTML = `
<a href="${commitUrl}" class="rfc-author-link" title="${rfc.git.author.login}">
<img src="${rfc.git.author.avatarUrl}" alt="${rfc.git.author.login}" class="rfc-author-avatar">
<span class="rfc-author-name">${rfc.git.author.login}</span>
</a>`;
}
return `
<li data-state="${rfc.state}">
<a href="rfc/${rfc.number}.html" class="rfc-item">
<span class="rfc-number">RFC ${rfc.number}</span>
<span class="rfc-state-pill state-${rfc.state}">${stateLabel(rfc.state)}</span>
<span class="rfc-title">${escapeHTML(rfc.title)}</span>
<span class="rfc-date">${dateStr}</span>
</a>${authorHTML}
</li>`;
})
.join("\n");
const filterButtons = `
<div class="filter-bar">
<button class="filter-btn active" data-state="all" onclick="filterRFCs('all')">All</button>
<button class="filter-btn" data-state="proposed" onclick="filterRFCs('proposed')">Proposed</button>
<button class="filter-btn" data-state="accepted" onclick="filterRFCs('accepted')">Accepted</button>
<button class="filter-btn" data-state="completed" onclick="filterRFCs('completed')">Completed</button>
</div>`;
const content = `
<h1>Request for Comments</h1>
<p>Technical proposals for the Vortex file format.</p>
${filterButtons}
<ul class="rfc-list">
${list}
</ul>
<script>${FILTER_SCRIPT}</script>`;
return baseHTML("Vortex RFCs", content, "styles.css", liveReload, repoUrl);
}
function formatDate(date: Date): string {
return date.toLocaleDateString("en-US", {
year: "numeric",
month: "long",
day: "numeric",
});
}
function rfcPage(
rfc: RFC,
repoUrl: string | null,
liveReload: boolean = false,
): string {
let gitHeader = `
<div class="rfc-meta-header">
<div class="rfc-meta-item">
<span class="rfc-state-pill state-${rfc.state}">${stateLabel(rfc.state)}</span>
</div>`;
if (rfc.git.accepted || rfc.git.author) {
// Author section
if (rfc.git.author) {
gitHeader += `
<div class="rfc-meta-item rfc-author">
<a href="${rfc.git.author.profileUrl}" class="author-link">
<img src="${rfc.git.author.avatarUrl}" alt="${rfc.git.author.login}" class="author-avatar">
<span class="author-name">${rfc.git.author.login}</span>
</a>
</div>`;
}
// Accepted date
if (rfc.git.accepted) {
const commitLink = repoUrl
? ` <a href="${repoUrl}/commit/${rfc.git.accepted.hash}" class="commit-link" title="View commit">${ICON_EXTERNAL}</a>`
: "";
gitHeader += `
<div class="rfc-meta-item">
<span class="rfc-meta-label">Accepted:</span>
<span class="rfc-meta-value">${formatDate(rfc.git.accepted.date)}${commitLink}</span>
</div>`;
}
// Last updated date
if (rfc.git.lastUpdated) {
const commitLink = repoUrl
? ` <a href="${repoUrl}/commit/${rfc.git.lastUpdated.hash}" class="commit-link" title="View commit">${ICON_EXTERNAL}</a>`
: "";
gitHeader += `
<div class="rfc-meta-item">
<span class="rfc-meta-label">Last updated:</span>
<span class="rfc-meta-value">${formatDate(rfc.git.lastUpdated.date)}${commitLink}</span>
</div>`;
}
}
gitHeader += `
</div>`;
const content = `
<a href="../" class="back-link">← Back to index</a>${gitHeader}
<article class="rfc-content">
${rfc.html}
</article>`;
return baseHTML(
`RFC ${rfc.number} - ${rfc.title}`,
content,
"../styles.css",
liveReload,
repoUrl,
);
}
function parseRFCNumber(filename: string): string {
// Extract number from filename like "0002-patches-galp.md"
const match = filename.match(/^(\d+)/);
return match?.[1] ?? "0000";
}
async function getGitHubRepoUrl(): Promise<string | null> {
try {
const result = await $`git remote get-url origin`.quiet();
const url = result.stdout.toString().trim();
// Convert git@github.com:user/repo.git to https://github.com/user/repo
if (url.startsWith("git@github.com:")) {
return "https://github.com/" + url.slice(15).replace(/\.git$/, "");
}
// Convert https://github.com/user/repo.git to https://github.com/user/repo
if (url.startsWith("https://github.com/")) {
return url.replace(/\.git$/, "");
}
return null;
} catch {
return null;
}
}
async function getGitHubAuthor(
repoPath: string,
commitHash: string,
): Promise<GitHubAuthor | null> {
try {
// Use gh CLI to fetch commit info from GitHub API
const result =
await $`gh api repos/${repoPath}/commits/${commitHash} --jq '.author.login, .author.avatar_url, .author.html_url'`.quiet();
const lines = result.stdout.toString().trim().split("\n");
if (lines.length >= 3 && lines[0] && lines[1] && lines[2]) {
return {
login: lines[0],
avatarUrl: lines[1],
profileUrl: lines[2],
};
}
return null;
} catch {
return null;
}
}
async function getGitHistory(
filepath: string,
repoPath: string | null,
): Promise<RFCGitInfo> {
try {
const result =
await $`git log --follow --format=%H\ %aI -- ${filepath}`.quiet();
const lines = result.stdout.toString().trim().split("\n").filter(Boolean);
if (lines.length === 0) {
return { accepted: null, lastUpdated: null, author: null };
}
const parseCommit = (line: string): GitCommit => {
const parts = line.split(" ");
const hash = parts[0] ?? "";
const dateStr = parts[1] ?? "";
return { hash, date: new Date(dateStr) };
};
const mostRecent = parseCommit(lines[0]!);
const oldest = parseCommit(lines[lines.length - 1]!);
// Fetch author info from the first commit
const author = repoPath
? await getGitHubAuthor(repoPath, oldest.hash)
: null;
// If only one commit, or same commit, don't show lastUpdated
if (lines.length === 1 || mostRecent.hash === oldest.hash) {
return { accepted: oldest, lastUpdated: null, author };
}
return { accepted: oldest, lastUpdated: mostRecent, author };
} catch {
return { accepted: null, lastUpdated: null, author: null };
}
}
interface ValidationError {
filename: string;
message: string;
}
async function validateProposals(): Promise<ValidationError[]> {
const errors: ValidationError[] = [];
const glob = new Bun.Glob("*");
const seenNumbers = new Map<string, string>(); // number -> "folder/filename"
for (const state of RFC_STATES) {
const folder = `./${state}`;
for await (const filename of glob.scan(folder)) {
const fullPath = `${state}/${filename}`;
// Check filename format: NNNN-slug.md
if (!filename.match(/^\d{4}-[a-zA-Z0-9_-]+\.md$/)) {
errors.push({
filename: fullPath,
message: `Invalid filename format. Expected: NNNN-name.md (e.g., 0007-my-proposal.md)`,
});
continue;
}
// Check for duplicate RFC numbers across all folders
const number = filename.slice(0, 4);
const existing = seenNumbers.get(number);
if (existing) {
errors.push({
filename: fullPath,
message: `Duplicate RFC number ${number} (also used by ${existing})`,
});
} else {
seenNumbers.set(number, fullPath);
}
}
}
return errors;
}
function parseTitle(markdown: string, filename: string): string {
// Try to extract title from first # heading
const match = markdown.match(/^#\s+(.+)$/m);
if (match?.[1]) {
// Clean up "RFC XXX - " prefix if present
return match[1].replace(/^RFC\s+\d+\s*[-:]\s*/i, "").trim();
}
// Fallback to filename
return filename.replace(/^\d+-/, "").replace(/\.md$/, "").replace(/-/g, " ");
}
// Syntax highlighting with Shiki
let highlighter: Highlighter | null = null;
async function getHighlighter(): Promise<Highlighter> {
if (!highlighter) {
highlighter = await createHighlighter({
themes: ["github-light", "github-dark"],
langs: ["rust", "python", "markdown"],
});
}
return highlighter;
}
async function highlightCodeBlocks(html: string): Promise<string> {
const hl = await getHighlighter();
// Match <pre><code class="language-X">...</code></pre> blocks
const codeBlockRegex =
/<pre><code class="language-(\w+)">([\s\S]*?)<\/code><\/pre>/g;
const matches = [...html.matchAll(codeBlockRegex)];
let result = html;
for (const match of matches) {
const [fullMatch, lang, code] = match;
if (!lang || !code) continue;
// Decode HTML entities back to raw code
const rawCode = code
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/&/g, "&")
.replace(/"/g, '"')
.replace(/'/g, "'");
// Check if this language is supported
const loadedLangs = hl.getLoadedLanguages();
if (!loadedLangs.includes(lang)) {
// Skip unsupported languages, leave original markup
continue;
}
// Generate highlighted HTML with both themes using CSS variables
const highlighted = hl.codeToHtml(rawCode.trim(), {
lang,
themes: {
light: "github-light",
dark: "github-dark",
},
defaultColor: false,
});
result = result.replace(fullMatch, highlighted);
}
return result;
}
async function build(liveReload: boolean = false): Promise<number> {
console.log("Building Vortex RFC site...\n");
// Validate proposals first
const validationErrors = await validateProposals();
if (validationErrors.length > 0) {
console.error("Validation errors found:\n");
for (const error of validationErrors) {
console.error(` ${error.filename}: ${error.message}`);
}
console.error("");
process.exit(1);
}
// Get GitHub repo URL for commit links
const repoUrl = await getGitHubRepoUrl();
// Extract repo path (e.g., "vortex-data/rfcs") for API calls
const repoPath = repoUrl ? repoUrl.replace("https://github.com/", "") : null;
const glob = new Bun.Glob("*.md");
const rfcs: RFC[] = [];
// Parse all RFC markdown files from each state folder
for (const state of RFC_STATES) {
const folder = `./${state}`;
for await (const filename of glob.scan(folder)) {
console.log(`Processing ${state}/${filename}...`);
const path = `${folder}/${filename}`;
const content = await Bun.file(path).text();
const rawHtml = Bun.markdown.html(content, { autolinks: true });
const html = await highlightCodeBlocks(rawHtml);
const number = parseRFCNumber(filename);
const title = parseTitle(content, filename);
const git = await getGitHistory(path, repoPath);
rfcs.push({ number, title, filename, html, git, state });
}
}
if (rfcs.length === 0) {
console.log(
"No RFC files found in ./proposed/, ./accepted/, or ./completed/",
);
return 0;
}
// Clean and create dist directory
await $`rm -rf dist`.quiet();
await $`mkdir -p dist/rfc`.quiet();
// Copy CSS
await Bun.write("dist/styles.css", await Bun.file("styles.css").text());
// Copy static assets
const logo = Bun.file("static/vortex_logo.svg");
if (await logo.exists()) {
await Bun.write("dist/vortex_logo.svg", await logo.text());
}
// Generate index page
const indexHTML = indexPage(rfcs, repoUrl, liveReload);
await Bun.write("dist/index.html", indexHTML);
console.log("Generated dist/index.html");
// Generate individual RFC pages
for (const rfc of rfcs) {
const html = rfcPage(rfc, repoUrl, liveReload);
const outPath = `dist/rfc/${rfc.number}.html`;
await Bun.write(outPath, html);
console.log(`Generated ${outPath}`);
}
console.log(`\nBuild complete! ${rfcs.length} RFC(s) processed.`);
return rfcs.length;
}
// Track SSE clients for live reload
const reloadClients = new Set<ReadableStreamDefaultController>();
function notifyReload() {
for (const controller of reloadClients) {
try {
controller.enqueue("data: reload\n\n");
} catch {
reloadClients.delete(controller);
}
}
}
async function startDevServer() {
// Initial build with live reload enabled
await build(true);
console.log(`\nStarting dev server at http://localhost:${PORT}`);
console.log(
"Watching for changes in ./proposed/, ./accepted/, ./completed/, and ./styles.css\n",
);
// Debounce rebuilds
let rebuildTimeout: Timer | null = null;
const scheduleRebuild = () => {
if (rebuildTimeout) clearTimeout(rebuildTimeout);
rebuildTimeout = setTimeout(async () => {
console.log("\nFile change detected, rebuilding...");
await build(true);
notifyReload();
}, 100);
};
// Watch all state directories
for (const state of RFC_STATES) {
watch(`./${state}`, { recursive: true }, (_event, filename) => {
if (filename?.endsWith(".md")) {
scheduleRebuild();
}
});
}
// Watch styles.css
watch("./styles.css", () => {
scheduleRebuild();
});
// Start server
Bun.serve({
port: PORT,
async fetch(req) {
const url = new URL(req.url);
let pathname = url.pathname;
// SSE endpoint for live reload
if (pathname === "/__reload") {
const stream = new ReadableStream({
start(controller) {
reloadClients.add(controller);
},
cancel(controller) {
reloadClients.delete(controller);
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
},
});
}
// Serve static files from dist/
if (pathname === "/") pathname = "/index.html";
if (pathname.endsWith("/")) pathname += "index.html";
const filePath = `./dist${pathname}`;
const file = Bun.file(filePath);
if (await file.exists()) {
return new Response(file);
}
return new Response("Not Found", { status: 404 });
},
});
}
if (isDev) {
startDevServer().catch(console.error);
} else {
build()
.then((count) => {
if (count > 0) {
console.log("Output directory: ./dist/");
}
})
.catch(console.error);
}