feat(generator): render SVG assets and README from profile.json and the Gitea API

This commit is contained in:
ahp committed 2026-11-06 11:09:41 +03:30
1 parent a5d7b34df2
commit 862cfd8464
2 files changed
+881

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
<!--
Generated file. Do not edit README.md by hand.
Content: profile.json · Layout: scripts/README.template.md · Build: node scripts/generate.mjs
-->
<p align="center">
<img src="assets/header.svg" width="100%" alt="{{header_alt}}">
</p>
<p align="center">
<img src="assets/terminal.svg" width="100%" alt="{{terminal_alt}}">
</p>
## `~/about`
{{about}}
## `~/engineering-toolkit`
<img src="assets/toolkit.svg" width="100%" alt="{{toolkit_alt}}">
## `~/activity`
<img src="assets/activity.svg" width="100%" alt="{{activity_alt}}">
## `~/projects`
<p align="center">
{{projects}}
</p>
## `~/contact`
<p align="center">
{{contact}}
</p>
<p align="center">
<img src="assets/footer.svg" width="100%" alt="{{footer_alt}}">
</p>
+841
View File
@@ -0,0 +1,841 @@
#!/usr/bin/env node
/**
* Builds the Gitea profile: every SVG in assets/ and README.md itself.
*
* profile.json curated facts (identity, terminal, toolkit, contact, repo selection)
* scripts/README.template.md page layout with {{placeholders}}
* scripts/icons.json vendored icon paths (Simple Icons CC0, Phosphor MIT)
* assets/data.json last good API data, reused when a source is down
*
* Live data comes from the public, unauthenticated Gitea API, so only public
* information can appear and no token is needed. Images used by the terminal
* (scripts/media/) are embedded as data URIs, since Gitea serves SVGs inside
* <img>, where external references never load. Everything is rendered in
* memory and validated before any file is written: a failed run leaves the last
* good README and assets untouched.
*
* Visual language: Catppuccin Mocha, shaped by the Hyprland desktop in ~/.dotfiles
* (rounding 10, sapphire→mauve active border, eww-style panels, Waybar pills,
* lavender = active, mauve = titles, yellow/red = warnings only).
*
* Usage: node scripts/generate.mjs (Node 18+, no dependencies)
*/
import { access, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
const assets = join(root, 'assets');
const profile = JSON.parse(await readFile(join(root, 'profile.json'), 'utf8'));
const icons = JSON.parse(await readFile(join(root, 'scripts/icons.json'), 'utf8'));
const template = await readFile(join(root, 'scripts/README.template.md'), 'utf8');
const { sources, repositories } = profile;
const giteaUrl = sources.gitea.url.replace(/\/$/, '');
const giteaHost = new URL(giteaUrl).host;
/* ── Tokens ───────────────────────────────────────────────────────── */
/** Catppuccin Mocha; rosewater is used for the mascot's skin only. */
const C = {
base: '#1e1e2e', mantle: '#181825', crust: '#11111b',
surface0: '#313244', surface1: '#45475a', surface2: '#585b70', overlay1: '#7f849c',
text: '#cdd6f4', subtext0: '#a6adc8', lavender: '#b4befe', rosewater: '#f5e0dc',
blue: '#89b4fa', sapphire: '#74c7ec', sky: '#89dceb', teal: '#94e2d5',
green: '#a6e3a1', yellow: '#f9e2af', peach: '#fab387', mauve: '#cba6f7',
pink: '#f5c2e7', red: '#f38ba8',
};
/** Type scale and radii from ~/.dotfiles/ops/gen-tokens. */
const T = { xs: 10, sm: 12, md: 13, lg: 15, xl: 19 };
const R = { window: 10, pill: 14 };
const GAP = 9; // Hyprland gaps_out
const LANGUAGE_COLORS = {
Go: C.sapphire, TypeScript: C.blue, Python: C.green, Shell: C.teal,
JavaScript: C.peach, Rust: C.peach, HCL: C.mauve, CSS: C.pink, SCSS: C.pink,
Dockerfile: C.sky, Makefile: C.surface2, 'Go Template': C.sky, HTML: C.pink,
};
const languageColor = (name) => LANGUAGE_COLORS[name] ?? C.lavender;
const FONT = `'JetBrainsMono Nerd Font','JetBrains Mono',ui-monospace,'Cascadia Code',SFMono-Regular,Menlo,Consolas,'DejaVu Sans Mono','Liberation Mono',monospace`;
/** Advance width of one monospace glyph, close enough for every font above. */
const cw = (size) => size * 0.6;
/* ── Data ─────────────────────────────────────────────────────────── */
class HttpError extends Error {
constructor(url, status) {
super(`${status} ${url}`);
this.status = status;
}
}
async function get(url) {
const response = await fetch(url, {
headers: { accept: 'application/json', 'user-agent': 'ahp-profile-generator' },
signal: AbortSignal.timeout(20_000),
});
if (!response.ok) {
throw new HttpError(url, response.status);
}
return { body: await response.json(), headers: response.headers };
}
const getJson = async (url) => (await get(url)).body;
/** Resolves to null on 404, so "no release" is not mistaken for an outage. */
async function getOptional(url) {
try {
return await getJson(url);
} catch (error) {
if (error instanceof HttpError && error.status === 404) {
return null;
}
throw error;
}
}
const dayKey = (seconds) =>
new Date((seconds + sources.utcOffsetMinutes * 60) * 1000).toISOString().slice(0, 10);
const today = () => dayKey(Date.now() / 1000);
function isOwn(repo) {
return !repo.fork && !repo.mirror && !repo.original_url && !repo.private
&& !repositories.notOwn.includes(repo.name);
}
async function collectGitea() {
const api = `${giteaUrl}/api/v1`;
const user = sources.gitea.user;
const account = await getJson(`${api}/users/${user}`);
const repos = [];
for (let page = 1; ; page++) {
const batch = await getJson(`${api}/users/${user}/repos?limit=50&page=${page}`);
repos.push(...batch.filter((repo) => !repo.private));
if (batch.length < 50) {
break;
}
}
const own = repos.filter(isOwn);
const languageBytes = {};
for (const repo of own) {
if (repositories.languageIgnoreRepos.includes(repo.name)) {
continue;
}
for (const [name, bytes] of Object.entries(await getJson(`${api}/repos/${repo.full_name}/languages`))) {
if (!repositories.languageIgnore.includes(name)) {
languageBytes[name] = (languageBytes[name] ?? 0) + bytes;
}
}
}
const days = {};
for (const { timestamp, contributions } of await getJson(`${api}/users/${user}/heatmap`)) {
const key = dayKey(timestamp);
days[key] = (days[key] ?? 0) + contributions;
}
const featured = [];
for (const name of repositories.featured) {
const repo = repos.find((candidate) => candidate.name === name);
if (!repo) {
console.warn(`featured repository not found or not public: ${name}`);
continue;
}
const release = await getOptional(`${api}/repos/${repo.full_name}/releases/latest`);
const commits = await get(`${api}/repos/${repo.full_name}/commits?limit=1&stat=false&verification=false&files=false`);
featured.push({
name: repo.name,
url: repo.html_url,
description: repo.description || '',
language: repo.language || null,
stars: repo.stars_count,
forks: repo.forks_count,
updated: repo.updated_at.slice(0, 10),
release: release?.tag_name ?? null,
commits: Number(commits.headers.get('x-total-count')) || null,
});
}
return {
created: account.created.slice(0, 10),
publicRepos: repos.length,
ownRepos: own.length,
languages: Object.entries(languageBytes).sort((a, b) => b[1] - a[1]),
days,
featured,
};
}
async function collect() {
const previous = await readFile(join(assets, 'data.json'), 'utf8').then(JSON.parse, () => ({}));
try {
return { synced: today(), gitea: await collectGitea() };
} catch (error) {
console.warn(`gitea: ${error.message}; keeping the last good data`);
return { synced: previous.synced ?? null, gitea: previous.gitea ?? null };
}
}
/* ── SVG primitives ───────────────────────────────────────────────── */
const esc = (value) => String(value)
.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
function svg(width, height, title, body, style = '') {
return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" xml:space="preserve" role="img" aria-label="${esc(title)}">
<title>${esc(title)}</title>
<style>
text{font-family:${FONT};white-space:pre;}
.b{font-weight:700;}
${style}
@media (prefers-reduced-motion:reduce){*{animation:none!important;}}
</style>
${body}
</svg>
`;
}
function text(x, y, content, { size = T.md, fill = C.text, anchor, cls, extra = '' } = {}) {
const attributes = [
`x="${x}"`, `y="${y}"`, `font-size="${size}"`, `fill="${fill}"`,
anchor ? `text-anchor="${anchor}"` : '', cls ? `class="${cls}"` : '', extra,
].filter(Boolean).join(' ');
return `<text ${attributes}>${content}</text>`;
}
const span = (content, fill, extra = '') => `<tspan fill="${fill}"${extra ? ` ${extra}` : ''}>${esc(content)}</tspan>`;
/** A brand (Simple Icons, 24 grid) or UI (Phosphor Fill, 256 grid) icon. */
function icon(name, x, y, size, fill) {
const brand = icons.brand[name];
const path = brand ?? icons.ui[name];
if (!path) {
throw new Error(`unknown icon: ${name}`);
}
const scale = size / (brand ? 24 : 256);
return `<path transform="translate(${x} ${y}) scale(${+scale.toFixed(5)})" d="${path}" fill="${fill}"/>`;
}
/** An eww-style panel: mantle, hairline surface2 border, lavender top edge. */
function panel(width, height) {
const x = GAP;
const y = GAP;
const w = width - GAP * 2;
const h = height - GAP * 2;
const r = R.window;
return `<rect x="${x + 0.5}" y="${y + 0.5}" width="${w - 1}" height="${h - 1}" rx="${r}" fill="${C.mantle}" stroke="${C.surface2}" stroke-opacity="0.4"/>
<path d="M${x + 0.5} ${y + r + 0.5}A${r} ${r} 0 0 1 ${x + r + 0.5} ${y + 0.5}H${x + w - r - 0.5}A${r} ${r} 0 0 1 ${x + w - 0.5} ${y + r + 0.5}" fill="none" stroke="${C.lavender}" stroke-opacity="0.28"/>`;
}
/** A Waybar pill: base at 90%, hairline border, radius 14. */
function pill(x, y, width, content, height = 28) {
return `<rect x="${x}" y="${y}" width="${width}" height="${height}" rx="${R.pill}" fill="${C.base}" fill-opacity="0.9" stroke="${C.surface2}" stroke-opacity="0.3"/>${content}`;
}
const cursor = (x, y, size = T.md) =>
`<rect class="cursor" x="${x}" y="${y - size * 0.82}" width="${cw(size)}" height="${size * 1.05}" fill="${C.lavender}"/>`;
const CURSOR_CSS = '.cursor{animation:blink 1.1s steps(1) infinite;}@keyframes blink{50%{opacity:0;}}';
function mix(hex, over, amount) {
const channel = (value, index) => parseInt(value.slice(1 + index * 2, 3 + index * 2), 16);
return '#' + [0, 1, 2]
.map((i) => Math.round(channel(hex, i) * amount + channel(over, i) * (1 - amount)).toString(16).padStart(2, '0'))
.join('');
}
/** Small seeded PRNG, so regenerating a static asset never changes its bytes. */
function random(seed) {
return () => {
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function jalali(isoDate) {
try {
return new Intl.DateTimeFormat('en-u-ca-persian', { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' })
.format(new Date(`${isoDate}T00:00:00Z`)).replace(/\s*AP$/, '');
} catch {
return isoDate;
}
}
/* ── The mascot ───────────────────────────────────────────────────── */
/**
* An original chibi companion in a hoodie whose hood rises to an Arch-like peak.
* Unofficial and personal: the chest mark is a plain chevron, not the Arch logo.
* Drawn on a 200×220 grid; `scale` sizes it, `sleeping` closes the eyes.
*/
function mascot(x, y, scale, { sleeping = false } = {}) {
const line = mix(C.crust, C.base, 0.9);
const hood = C.blue;
const hoodShade = mix(C.blue, C.base, 0.72);
const hoodInner = mix(C.blue, C.crust, 0.32);
const hair = mix(C.lavender, C.crust, 0.3);
const hairShine = mix(C.lavender, C.crust, 0.62);
const outline = (width = 2.4) => `stroke="${line}" stroke-width="${width}" stroke-linejoin="round" stroke-linecap="round"`;
const stroke = outline();
const eye = (cx) => sleeping
? `<path d="M${cx - 8} 123Q${cx} 129 ${cx + 8} 123" fill="none" ${stroke}/>`
: `<g class="blink"><ellipse cx="${cx}" cy="121" rx="9" ry="11.5" fill="url(#iris)" ${outline(1.8)}/>
<ellipse cx="${cx}" cy="123" rx="4.2" ry="5.6" fill="${C.crust}"/>
<circle cx="${cx - 3.4}" cy="116" r="3.4" fill="#ffffff"/><circle cx="${cx + 3.4}" cy="126.5" r="1.6" fill="#ffffff" opacity="0.85"/>
<path d="M${cx - 9.5} 114.5Q${cx} 106.5 ${cx + 9.5} 114.5" fill="none" stroke="${line}" stroke-width="3" stroke-linecap="round"/></g>`;
const mouthY = sleeping ? 139 : 138;
const body = `
<ellipse cx="100" cy="211" rx="50" ry="6" fill="${C.crust}" opacity="0.6"/>
<g class="${sleeping ? '' : 'bob'}">
<path d="M56 198C56 172 70 152 100 150C130 152 144 172 144 198Q144 206 136 206H64Q56 206 56 198Z" fill="${hood}" ${stroke}/>
<path d="M64 206Q60 186 72 168" fill="none" stroke="${hoodShade}" stroke-width="5" stroke-linecap="round" opacity="0.7"/>
<ellipse cx="62" cy="186" rx="10" ry="14" transform="rotate(18 62 186)" fill="${hood}" ${stroke}/>
<ellipse cx="138" cy="186" rx="10" ry="14" transform="rotate(-18 138 186)" fill="${hood}" ${stroke}/>
<circle cx="58" cy="198" r="5.5" fill="${C.rosewater}" ${outline(2)}/>
<circle cx="142" cy="198" r="5.5" fill="${C.rosewater}" ${outline(2)}/>
<path d="M100 170L109 189Q100 184 91 189Z" fill="${C.text}" opacity="0.92"/>
<path d="M90 156L88 178M110 156L112 178" stroke="${C.lavender}" stroke-width="2.4" stroke-linecap="round"/>
<circle cx="88" cy="180" r="2.6" fill="${C.lavender}"/><circle cx="112" cy="180" r="2.6" fill="${C.lavender}"/>
<path d="M100 10C110 36 124 62 146 86C170 110 184 128 182 148C178 166 142 176 100 176C58 176 22 166 18 148C16 128 30 110 54 86C76 62 90 36 100 10Z" fill="${hood}" ${stroke}/>
<path d="M96 26C90 46 78 66 58 88" fill="none" stroke="#ffffff" stroke-opacity="0.28" stroke-width="4" stroke-linecap="round"/>
<path d="M48 132C48 100 72 76 100 74C128 76 152 100 152 132C152 154 130 166 100 166C70 166 48 154 48 132Z" fill="${hoodInner}"/>
<path d="M54 130C54 100 74 83 100 82C126 83 146 100 146 130C146 144 143 153 138 160H62C57 153 54 144 54 130Z" fill="${hair}"/>
<path d="M62 114C62 94 78 87 100 87C122 87 138 94 138 114C138 138 122 154 100 154C78 154 62 138 62 114Z" fill="${C.rosewater}" ${stroke}/>
<path d="M57 112C57 92 76 81 100 81C124 81 143 92 143 112C138 104 133 99 127 98L122 101C118 96 112 94 106 94L100 99C96 95 90 94 84 96L79 101C73 98 66 100 57 112Z" fill="${hair}" ${outline(2)}/>
<path d="M76 92C84 86 94 84 104 85" fill="none" stroke="${hairShine}" stroke-width="3" stroke-linecap="round"/>
<path d="M99 82C95 68 103 61 111 58C104 65 104 73 103 82Z" fill="${hair}" ${outline(2)}/>
${eye(84)}${eye(116)}
<ellipse cx="72" cy="134" rx="7" ry="3.5" fill="${C.pink}" opacity="0.6"/>
<ellipse cx="128" cy="134" rx="7" ry="3.5" fill="${C.pink}" opacity="0.6"/>
<path d="M95.5 ${mouthY}Q97.75 ${mouthY + 3.5} 100 ${mouthY}Q102.25 ${mouthY + 3.5} 104.5 ${mouthY}" fill="none" stroke="${line}" stroke-width="1.8" stroke-linecap="round"/>
</g>
${sleeping ? '' : `<path class="spark" d="M166 38l2.5 6.5 6.5 2.5-6.5 2.5-2.5 6.5-2.5-6.5-6.5-2.5 6.5-2.5z" fill="${C.lavender}"/>
<path class="spark" style="animation-delay:1.3s" d="M34 62l1.6 4.2 4.2 1.6-4.2 1.6-1.6 4.2-1.6-4.2-4.2-1.6 4.2-1.6z" fill="${C.sapphire}"/>`}`;
return `<g transform="translate(${x} ${y}) scale(${scale})">${body}</g>`;
}
const MASCOT_DEFS = `<defs><linearGradient id="iris" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${C.sapphire}"/><stop offset="0.55" stop-color="${C.blue}"/><stop offset="1" stop-color="${C.lavender}"/></linearGradient></defs>`;
const MASCOT_CSS = `.bob{animation:bob 4.5s ease-in-out infinite;}
@keyframes bob{50%{transform:translateY(-3px);}}
.blink{transform-box:fill-box;transform-origin:center;animation:blink-eye 6s infinite;}
@keyframes blink-eye{0%,93%,100%{transform:scaleY(1);}96%{transform:scaleY(0.08);}}
.spark{transform-box:fill-box;transform-origin:center;animation:spark 3s ease-in-out infinite;}
@keyframes spark{50%{opacity:0.25;transform:scale(0.7);}}`;
/* ── Assets ───────────────────────────────────────────────────────── */
/** The desktop: a slim Waybar, the identity, wallpaper and the mascot. */
function header(data) {
const width = 860;
const height = 280;
const { name, title, tagline } = profile.identity;
/* wallpaper: chaos settling into a grid, ending where the mascot stands */
const rand = random(7);
const rows = [C.mauve, C.pink, C.peach, C.green, C.teal, C.sky, C.sapphire, C.blue, C.lavender];
const accents = [C.lavender, C.blue, C.sapphire, C.sky, C.teal, C.green, C.peach, C.mauve, C.pink];
const cols = 10;
let field = '';
for (let c = 0; c < cols; c++) {
const order = c / (cols - 1);
for (let r = 0; r < rows.length; r++) {
if (rand() > 0.35 + 0.6 * order) {
rand(); rand(); rand(); rand();
continue;
}
const jitter = (1 - order) ** 1.5 * 20;
const x = 486 + c * 17 + (rand() - 0.5) * 2 * jitter;
const y = 72 + r * 19 + (rand() - 0.5) * 2 * jitter;
const angle = ((1 - order) * (rand() - 0.5) * 120).toFixed(1);
const fill = rand() > order ? accents[Math.floor(rand() * accents.length)] : rows[r];
const opacity = (0.2 + 0.55 * order).toFixed(2);
const twinkle = (c * 7 + r * 3) % 11 === 0 ? ` class="tw" style="animation-delay:${((c + r) % 5) * 0.7}s"` : '';
field += `<rect x="${x.toFixed(1)}" y="${y.toFixed(1)}" width="7" height="7" rx="2" fill="${fill}" opacity="${opacity}" transform="rotate(${angle} ${(x + 3.5).toFixed(1)} ${(y + 3.5).toFixed(1)})"${twinkle}/>`;
}
}
/* waybar */
const barY = GAP;
let bar = pill(GAP, barY, 36, icon('archlinux', GAP + 10, barY + 6, 16, C.blue));
const bx = GAP + 36 + 6;
const workspaces = 5;
bar += pill(bx, barY, workspaces * 24 + 8, [...Array(workspaces)].map((_, i) => {
const cx = bx + 4 + i * 24;
return i === 0
? `<rect x="${cx}" y="${barY + 4}" width="24" height="20" rx="10" fill="${C.lavender}"/>${text(cx + 12, barY + 18.5, '1', { size: T.sm, fill: C.crust, anchor: 'middle', cls: 'b' })}`
: text(cx + 12, barY + 18.5, String(i + 1), { size: T.sm, fill: C.overlay1, anchor: 'middle' });
}).join(''));
const date = jalali(data.synced ?? today());
const dw = cw(T.sm) * date.length + 40;
bar += pill(width - GAP - dw, barY, dw, icon('clock', width - GAP - dw + 10, barY + 6, 16, C.lavender)
+ text(width - GAP - dw + 31, barY + 18.5, esc(date), { size: T.sm, fill: C.text }));
const body = `<defs>
<linearGradient id="name" x1="0" x2="1"><stop offset="0" stop-color="${C.mauve}"/><stop offset="1" stop-color="${C.sapphire}"/></linearGradient>
<radialGradient id="glow" cx="0.84" cy="0.6" r="0.45"><stop offset="0" stop-color="${C.blue}" stop-opacity="0.13"/><stop offset="1" stop-color="${C.blue}" stop-opacity="0"/></radialGradient>
</defs>${MASCOT_DEFS}
<rect width="${width}" height="${height}" rx="${R.window}" fill="${C.crust}"/>
<rect width="${width}" height="${height}" rx="${R.window}" fill="url(#glow)"/>
${field}
${bar}
${text(40, 124, esc(name), { size: 34, fill: 'url(#name)', cls: 'b' })}
${text(42, 164, esc(title), { size: T.xl, fill: C.text })}
${text(42, 210, span('» ', C.green) + span(tagline, C.lavender, 'font-style="italic"'), { size: T.lg })}
${mascot(668, 52, 0.95)}`;
return svg(width, height, `${name}, ${title}. ${tagline}`, body,
'.tw{animation:tw 3.6s ease-in-out infinite;}@keyframes tw{50%{opacity:0.1;}}' + MASCOT_CSS);
}
/**
* The focused window: a zsh session on joshua. A step prints plain `output`
* lines, an inline `image` (as kitty's icat would), or a `quote` with its source.
*/
function terminal(media) {
const width = 860;
const { user, host, session } = profile.terminal;
const lineHeight = 22;
const left = 36;
const contentWidth = width - left * 2;
const top = 84;
let y = top;
let lastLine = null;
let body = '<defs><clipPath id="frame"><rect id="frame-rect" rx="8"/></clipPath></defs>';
for (const step of session) {
body += text(left, y, span(user, C.mauve, 'class="b"') + span('@', C.overlay1) + span(host, C.blue, 'class="b"')
+ span(' ~ ', C.sapphire) + span('% ', C.overlay1) + span(step.command, C.text), { size: T.md });
y += lineHeight;
if (step.image) {
const h = step.image.height;
const iy = y - 8;
body = body.replace('<rect id="frame-rect" rx="8"/>', `<rect x="${left}" y="${iy}" width="${contentWidth}" height="${h}" rx="8"/>`);
body += `<image x="${left}" y="${iy}" width="${contentWidth}" height="${h}" preserveAspectRatio="xMidYMid slice" clip-path="url(#frame)" href="${media[step.image.file]}"><title>${esc(step.image.alt)}</title></image>`;
body += `<rect x="${left + 0.5}" y="${iy + 0.5}" width="${contentWidth - 1}" height="${h - 1}" rx="8" fill="none" stroke="${C.surface1}"/>`;
y = iy + h + 16 + lineHeight;
continue;
}
if (step.quote) {
y += 4;
for (const line of step.quote.lines) {
body += `<rect x="${left}" y="${y - 14}" width="2" height="19" fill="${C.mauve}" opacity="0.7"/>`;
body += text(left + 16, y, esc(line), { size: T.lg - 1, fill: C.lavender, extra: 'font-style="italic"' });
y += lineHeight + 4;
}
body += text(left + 16, y + 2, span('— ', C.overlay1) + span(step.quote.source, C.mauve), { size: T.md });
if (step === session[session.length - 1]) {
/* the session ends here: the cursor waits right after the source */
body += cursor(left + 16 + cw(T.md) * (step.quote.source.length + 3), y + 2, T.md);
lastLine = y + 2;
}
y += lineHeight + 18;
continue;
}
for (const output of step.output ?? []) {
const ok = output.match(/^\[(\s*OK\s*)\](.*)$/);
body += ok
? text(36, y, span('[', C.subtext0) + span(ok[1], C.green, 'class="b"') + span(']', C.subtext0) + span(ok[2], C.subtext0), { size: T.md })
: text(36, y, esc(output), { size: T.md, fill: C.subtext0 });
y += lineHeight;
}
}
if (lastLine === null) {
body += cursor(left, y, T.md);
lastLine = y;
}
const height = lastLine + 22 + GAP;
const r = R.window;
const output = `<defs>
<linearGradient id="border" x1="0" y1="1" x2="1" y2="0"><stop offset="0" stop-color="${C.sapphire}"/><stop offset="1" stop-color="${C.mauve}"/></linearGradient>
<filter id="shadow" x="-5%" y="-10%" width="110%" height="125%"><feDropShadow dx="0" dy="3" stdDeviation="3" flood-color="${C.crust}" flood-opacity="0.9"/></filter>
</defs>
<rect x="${GAP}" y="${GAP}" width="${width - GAP * 2}" height="${height - GAP * 2}" rx="${r}" fill="${C.base}" filter="url(#shadow)"/>
<path d="M${GAP + 1} ${GAP + 40}V${GAP + r}A${r - 1} ${r - 1} 0 0 1 ${GAP + r} ${GAP + 1}H${width - GAP - r}A${r - 1} ${r - 1} 0 0 1 ${width - GAP - 1} ${GAP + r}V${GAP + 40}Z" fill="${C.mantle}"/>
<line x1="${GAP + 1}" y1="${GAP + 40}" x2="${width - GAP - 1}" y2="${GAP + 40}" stroke="${C.surface0}"/>
<circle cx="${GAP + 22}" cy="${GAP + 20}" r="5" fill="${C.surface2}"/><circle cx="${GAP + 40}" cy="${GAP + 20}" r="5" fill="${C.surface2}"/><circle cx="${GAP + 58}" cy="${GAP + 20}" r="5" fill="${C.lavender}" opacity="0.85"/>
${text(width / 2, GAP + 25, span(`${user}@${host}`, C.subtext0) + span(': ~', C.overlay1), { size: T.sm, anchor: 'middle' })}
${text(width - GAP - 22, GAP + 25, 'zsh', { size: T.sm, fill: C.overlay1, anchor: 'end' })}
<rect x="${GAP + 1}" y="${GAP + 1}" width="${width - GAP * 2 - 2}" height="${height - GAP * 2 - 2}" rx="${r - 1}" fill="none" stroke="url(#border)" stroke-width="2"/>
${body}`;
const transcript = session.map((step) => {
const shown = step.image ? step.image.alt
: step.quote ? `${step.quote.lines.join(' ')} (${step.quote.source})`
: (step.output ?? []).join(' ');
return `${user}@${host} % ${step.command}: ${shown}`;
}).join('. ');
return svg(width, height, `Terminal on ${user}@${host}. ${transcript}`, output, CURSOR_CSS);
}
function toolkit() {
const width = 860;
const left = 36;
const chipsX = 286;
const chipsRight = width - 36;
const { legend, groups } = profile.toolkit;
let y = 46;
let body = text(chipsRight, y, span('● ', C.lavender) + span(legend.used, C.subtext0) + span(' ○ ', C.overlay1) + span(legend.listed, C.subtext0), { size: T.sm, anchor: 'end' });
y += 16;
const seen = new Set();
groups.forEach((group, index) => {
const color = C[group.color];
const top = y;
let cx = chipsX;
let cy = top;
let chips = '';
for (const [label, iconName, used] of group.tools) {
if (seen.has(label)) {
throw new Error(`toolkit lists "${label}" twice`);
}
seen.add(label);
const w = cw(T.sm) * label.length + 38;
if (cx + w > chipsRight) {
cx = chipsX;
cy += 34;
}
chips += used
? `<rect x="${cx}" y="${cy}" width="${w}" height="26" rx="13" fill="${C.surface0}"/>`
: `<rect x="${cx + 0.5}" y="${cy + 0.5}" width="${w - 1}" height="25" rx="12.5" fill="none" stroke="${C.surface1}"/>`;
chips += iconName
? icon(iconName, cx + 10, cy + 6, 14, used ? color : C.overlay1)
: `<circle cx="${cx + 17}" cy="${cy + 13}" r="3.5" fill="${used ? color : 'none'}" stroke="${used ? 'none' : C.overlay1}"/>`;
chips += text(cx + 30, cy + 17.5, esc(label), { size: T.sm, fill: used ? C.text : C.subtext0 });
cx += w + 8;
}
body += `<rect x="${left - 12}" y="${top + 5}" width="3" height="16" rx="1.5" fill="${color}"/>`;
body += text(left, top + 18, esc(group.name), { size: T.md, fill: color, cls: 'b' });
body += chips;
y = cy + 26 + 12;
if (index < groups.length - 1) {
body += `<line x1="${left}" y1="${y - 6}" x2="${chipsRight}" y2="${y - 6}" stroke="${C.surface0}" stroke-dasharray="2 4"/>`;
}
});
const height = y + 20;
const alt = `Engineering toolkit. ${groups.map((g) => `${g.name}: ${g.tools.map(([t]) => t).join(', ')}`).join('; ')}`;
return { svg: svg(width, height, alt, panel(width, height) + body), alt };
}
function activity(data) {
const width = 860;
const height = 350;
const gitea = data.gitea;
let body = panel(width, height);
if (!gitea) {
body += text(width / 2, height / 2, 'activity is unavailable right now', { size: T.md, fill: C.subtext0, anchor: 'middle' });
return { svg: svg(width, height, 'Gitea activity is unavailable', body), alt: 'Gitea activity is unavailable right now.' };
}
body += icon('coffee', 36, 36, 16, C.lavender) + text(60, 49, span(giteaHost, C.mauve, 'class="b"') + span(` /${sources.gitea.user}`, C.overlay1), { size: T.md });
/* contribution heatmap */
const weeks = sources.heatmapWeeks;
const cell = 11;
const gap = 3;
const gridX = 70;
const gridY = 98;
const now = new Date(`${today()}T00:00:00Z`);
const monday = new Date(now);
monday.setUTCDate(now.getUTCDate() - ((now.getUTCDay() + 6) % 7) - 7 * (weeks - 1));
const counts = Object.values(gitea.days);
const max = Math.max(1, ...counts);
const levels = [C.surface0, mix(C.lavender, C.mantle, 0.3), mix(C.lavender, C.mantle, 0.5), mix(C.lavender, C.mantle, 0.75), C.lavender];
body += text(36, 84, `contributions · last ${weeks} weeks`, { size: T.sm, fill: C.subtext0 });
let lastMonth = -1;
let lastLabelColumn = -9;
for (let w = 0; w < weeks; w++) {
for (let d = 0; d < 7; d++) {
const date = new Date(monday);
date.setUTCDate(monday.getUTCDate() + w * 7 + d);
if (date > now) {
continue;
}
if (d === 0 && date.getUTCMonth() !== lastMonth) {
lastMonth = date.getUTCMonth();
if (w - lastLabelColumn >= 3) {
body += text(gridX + w * (cell + gap), gridY + 7 * (cell + gap) + 14,
date.toLocaleString('en', { month: 'short', timeZone: 'UTC' }), { size: T.xs, fill: C.overlay1 });
lastLabelColumn = w;
}
}
const key = date.toISOString().slice(0, 10);
const count = gitea.days[key] ?? 0;
const level = count === 0 ? 0 : Math.min(4, Math.ceil((count / max) * 4));
body += `<rect x="${gridX + w * (cell + gap)}" y="${gridY + d * (cell + gap)}" width="${cell}" height="${cell}" rx="3" fill="${levels[level]}"><title>${key}: ${count}</title></rect>`;
}
}
['Mon', 'Wed', 'Fri'].forEach((label, i) => {
body += text(36, gridY + i * 2 * (cell + gap) + 9, label, { size: T.xs, fill: C.overlay1 });
});
const legendX = gridX + weeks * (cell + gap) - 5 * (cell + gap) - 3;
body += text(legendX - 8, 84, 'less', { size: T.xs, fill: C.overlay1, anchor: 'end' });
levels.forEach((fill, i) => {
body += `<rect x="${legendX + i * (cell + gap)}" y="75" width="${cell}" height="${cell}" rx="3" fill="${fill}"/>`;
});
body += text(legendX + 5 * (cell + gap) + 4, 84, 'more', { size: T.xs, fill: C.overlay1 });
/* counters */
const activeDays = Object.keys(gitea.days).filter((key) => gitea.days[key] > 0).sort();
let longest = 0;
let run = 0;
let previous = null;
for (const key of activeDays) {
const date = new Date(`${key}T00:00:00Z`);
run = previous && date - previous === 86_400_000 ? run + 1 : 1;
longest = Math.max(longest, run);
previous = date;
}
const total = counts.reduce((a, b) => a + b, 0);
const counters = [
[gitea.ownRepos, 'own repositories', C.blue],
[total, 'contributions, 1y', C.lavender],
[activeDays.length, 'active days', C.peach],
[longest, 'longest streak, days', C.mauve],
];
counters.forEach(([value, label, fill], i) => {
const cx = 512 + (i % 2) * 170;
const cy = 110 + Math.floor(i / 2) * 64;
body += `<rect x="${cx - 14}" y="${cy - 28}" width="3" height="44" rx="1.5" fill="${fill}"/>`;
body += text(cx, cy, String(value), { size: 26, fill, cls: 'b' });
body += text(cx, cy + 19, esc(label), { size: T.sm, fill: C.subtext0 });
});
/* languages */
const bytes = gitea.languages.reduce((sum, [, b]) => sum + b, 0) || 1;
const top = gitea.languages.slice(0, 5);
const rest = bytes - top.reduce((sum, [, b]) => sum + b, 0);
const segments = rest / bytes >= 0.005 ? [...top, ['other', rest]] : top;
const barX = 36;
const barWidth = width - 72;
body += text(36, 240, 'languages · by bytes in own repositories', { size: T.sm, fill: C.subtext0 });
body += `<clipPath id="bar"><rect x="${barX}" y="252" width="${barWidth}" height="10" rx="5"/></clipPath><g clip-path="url(#bar)">`;
let bx = barX;
for (const [name, b] of segments) {
const w = (b / bytes) * barWidth;
body += `<rect x="${bx.toFixed(1)}" y="252" width="${(w + 0.5).toFixed(1)}" height="10" fill="${name === 'other' ? C.surface1 : languageColor(name)}"/>`;
bx += w;
}
body += '</g>';
let lx = barX;
for (const [name, b] of segments) {
const percent = ` ${((b / bytes) * 100).toFixed(1)}%`;
body += `<circle cx="${lx + 5}" cy="283" r="5" fill="${name === 'other' ? C.surface1 : languageColor(name)}"/>`;
body += text(lx + 15, 287, span(name, C.text) + span(percent, C.overlay1), { size: T.sm });
lx += 15 + cw(T.sm) * (name.length + percent.length) + 22;
}
/* footer: account facts, also straight from the Gitea API */
const footY = height - GAP - 16;
body += `<line x1="${GAP + 1}" y1="${footY - 24}" x2="${width - GAP - 1}" y2="${footY - 24}" stroke="${C.surface0}"/>`;
const account = span(`${gitea.publicRepos} public repositories`, C.subtext0) + span(` · member since ${gitea.created}`, C.overlay1);
body += icon('folder-simple', 36, footY - 12, 14, C.overlay1) + text(56, footY, account, { size: T.sm });
body += text(width - 36, footY, esc(`synced ${data.synced ?? 'never'}`), { size: T.sm, fill: C.overlay1, anchor: 'end' });
const alt = `Gitea activity on ${giteaHost}: ${gitea.ownRepos} own repositories, ${total} contributions in the past year over ${activeDays.length} active days, longest streak ${longest} days; languages ${top.map(([n]) => n).join(', ')}. Synced ${data.synced}.`;
return { svg: svg(width, height, alt, body), alt };
}
function wrap(words, limit) {
const lines = [''];
for (const word of words.split(/\s+/).filter(Boolean)) {
const current = lines[lines.length - 1];
if (current && (current + ' ' + word).length > limit) {
lines.push(word);
} else {
lines[lines.length - 1] = current ? `${current} ${word}` : word;
}
}
return lines;
}
function projectCard(project) {
const width = 420;
const height = 152;
const lines = wrap(project.description, 46).slice(0, 2);
let body = panel(width, height);
body += icon('folder-simple', 30, 32, 17, C.lavender);
body += text(56, 46, span(project.name, C.mauve), { size: T.lg + 2, cls: 'b' });
if (project.release) {
const w = cw(T.sm) * project.release.length + 34;
const x = width - GAP - 18 - w;
body += `<rect x="${x}" y="28" width="${w}" height="24" rx="12" fill="none" stroke="${C.green}" stroke-opacity="0.55"/>`;
body += icon('tag', x + 9, 34, 12, C.green) + text(x + 25, 44.5, esc(project.release), { size: T.sm, fill: C.green });
}
lines.forEach((line, i) => {
body += text(30, 76 + i * 19, esc(line), { size: T.md - 0.5, fill: C.subtext0 });
});
const y = height - GAP - 20;
let mx = 30;
if (project.language) {
body += `<circle cx="${mx + 5}" cy="${y - 4}" r="5" fill="${languageColor(project.language)}"/>`;
body += text(mx + 16, y, esc(project.language), { size: T.sm, fill: C.text });
mx += 16 + cw(T.sm) * project.language.length + 18;
}
const meta = [];
if (project.commits) {
meta.push(['git-commit', `${project.commits} commits`]);
}
if (project.stars) {
meta.push(['star', String(project.stars)]);
}
meta.push(['clock', project.updated]);
for (const [iconName, label] of meta) {
body += icon(iconName, mx, y - 11, 13, C.overlay1) + text(mx + 18, y, esc(label), { size: T.sm, fill: C.overlay1 });
mx += 18 + cw(T.sm) * label.length + 18;
}
return svg(width, height, `${project.name}: ${project.description}`, body);
}
function contactPill({ icon: iconName, label }) {
const width = Math.ceil(cw(T.sm) * label.length + 46);
const body = pill(0.5, 0.5, width - 1, icon(iconName, 12, 6.5, 16, C.lavender) + text(35, 19, esc(label), { size: T.sm, fill: C.text }));
return svg(width, 29, label, body);
}
/** After init 0: the companion has gone to sleep. */
function footer() {
const width = 860;
const height = 104;
const body = `${MASCOT_DEFS}
${mascot(394, 2, 0.36, { sleeping: true })}
<g fill="${C.lavender}">${text(470, 30, 'z', { size: 10, cls: 'z' })}${text(478, 22, 'z', { size: 12, cls: 'z', extra: 'style="animation-delay:0.8s"' })}${text(488, 13, 'Z', { size: 14, cls: 'z', extra: 'style="animation-delay:1.6s"' })}</g>
${text(width / 2, 98, span('[', C.overlay1) + span(' OK ', C.green, 'class="b"') + span('] ', C.overlay1) + span('Reached target Sleep.', C.overlay1), { size: T.sm, anchor: 'middle' })}`;
return svg(width, height, 'The companion is asleep. Reached target Sleep.', body,
MASCOT_CSS + '.z{animation:z 2.4s ease-in-out infinite;opacity:0.8;}@keyframes z{0%{opacity:0;}30%{opacity:1;}100%{opacity:0;transform:translateY(-6px);}}');
}
/* ── README ───────────────────────────────────────────────────────── */
const attr = (value) => esc(value).replace(/\s+/g, ' ').trim();
function readme(data, alts) {
const { identity, terminal: term } = profile;
const projects = (data.gitea?.featured ?? []).map((project) =>
` <a href="${attr(project.url)}"><img src="assets/projects/${project.name}.svg" width="420" alt="${attr(`${project.name}: ${project.description}`)}"></a>`).join('\n');
const contact = profile.contact.map((entry) =>
` <a href="${attr(entry.url)}"><img src="assets/contact/${entry.id}.svg" height="29" alt="${attr(entry.label)}"></a>`).join('\n');
const values = {
header_alt: `${identity.name}, ${identity.title}. ${identity.tagline}`,
terminal_alt: `A zsh session on ${term.user}@${term.host} that ends with init 0.`,
about: identity.about,
toolkit_alt: alts.toolkit,
activity_alt: alts.activity,
projects: projects || ' <sub>projects are unavailable right now</sub>',
contact,
footer_alt: 'The companion is asleep. Reached target Sleep.',
};
return template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
if (!(key in values)) {
throw new Error(`unknown template placeholder: ${match}`);
}
return /_alt$/.test(key) ? attr(values[key]) : values[key];
});
}
/* ── Validation ───────────────────────────────────────────────────── */
async function validate(files) {
const problems = [];
for (const [path, raw] of Object.entries(files)) {
const content = raw.replace(/data:image\/[a-z]+;base64,[A-Za-z0-9+/=]+/g, 'data:');
if (/\b(undefined|NaN)\b/.test(content)) {
problems.push(`${path}: contains undefined or NaN`);
}
if (path.endsWith('.svg')) {
for (const [tag] of content.matchAll(/<[a-zA-Z][^>]*>/g)) {
const names = [...tag.matchAll(/\s([\w:-]+)=/g)].map((m) => m[1]);
const repeated = names.find((name, i) => names.indexOf(name) !== i);
if (repeated) {
problems.push(`${path}: attribute ${repeated} repeated in ${tag.slice(0, 40)}…`);
}
}
if (!content.startsWith('<svg xmlns="http://www.w3.org/2000/svg"') || !content.trimEnd().endsWith('</svg>')) {
problems.push(`${path}: not a complete SVG document`);
}
if (/<script|javascript:|<foreignObject|\bhref="http/i.test(content)) {
problems.push(`${path}: scripts or external references are not allowed`);
}
const opened = (content.match(/<(g|text|tspan|defs|linearGradient|radialGradient|filter|clipPath)(\s[^>]*)?>/g) ?? [])
.filter((tag) => !tag.endsWith('/>')).length;
const closed = (content.match(/<\/(g|text|tspan|defs|linearGradient|radialGradient|filter|clipPath)>/g) ?? []).length;
if (opened !== closed) {
problems.push(`${path}: ${opened} container tags opened, ${closed} closed`);
}
}
}
const page = files['../README.md'];
if (/\{\{|\}\}/.test(page)) {
problems.push('README.md: unrendered placeholder');
}
for (const [, src] of page.matchAll(/src="(assets\/[^"]+)"/g)) {
const key = src.slice('assets/'.length);
if (!(key in files) && !(await access(join(assets, key)).then(() => true, () => false))) {
problems.push(`README.md: image ${src} does not exist`);
}
}
if (problems.length) {
throw new Error(`validation failed, nothing written:\n ${problems.join('\n ')}`);
}
}
/* ── Main ─────────────────────────────────────────────────────────── */
const data = await collect();
const media = {};
for (const step of profile.terminal.session) {
if (step.image) {
const bytes = await readFile(join(root, step.image.file));
media[step.image.file] = `data:image/jpeg;base64,${bytes.toString('base64')}`;
}
}
const toolkitAsset = toolkit();
const activityAsset = activity(data);
const files = {
'header.svg': header(data),
'terminal.svg': terminal(media),
'toolkit.svg': toolkitAsset.svg,
'activity.svg': activityAsset.svg,
'footer.svg': footer(),
'mascot.svg': svg(200, 220, 'An original chibi companion in an Arch-peaked hoodie (unofficial)', MASCOT_DEFS + mascot(0, 0, 1), MASCOT_CSS),
'data.json': JSON.stringify(data, null, 2) + '\n',
};
for (const project of data.gitea?.featured ?? []) {
files[`projects/${project.name}.svg`] = projectCard(project);
}
for (const entry of profile.contact) {
files[`contact/${entry.id}.svg`] = contactPill(entry);
}
files['../README.md'] = readme(data, { toolkit: toolkitAsset.alt, activity: activityAsset.alt });
await validate(files);
for (const [path, content] of Object.entries(files)) {
const target = join(assets, path);
await mkdir(dirname(target), { recursive: true });
await writeFile(target, content);
}
/* drop SVGs that are no longer generated, such as a project removed from the selection */
for (const entry of await readdir(assets, { recursive: true })) {
if (entry.endsWith('.svg') && !(entry in files)) {
await rm(join(assets, entry));
console.log(`removed stale assets/${entry}`);
}
}
console.log(`wrote README.md and ${Object.keys(files).length - 1} assets, synced ${data.synced ?? 'never'}`);