From 862cfd84645d27c24a2e80badea0def80bcb741d Mon Sep 17 00:00:00 2001 From: Amir Husayn Panahifar Date: Fri, 6 Nov 2026 11:09:41 +0330 Subject: [PATCH] feat(generator): render SVG assets and README from profile.json and the Gitea API --- scripts/README.template.md | 40 ++ scripts/generate.mjs | 841 +++++++++++++++++++++++++++++++++++++ 2 files changed, 881 insertions(+) create mode 100644 scripts/README.template.md create mode 100644 scripts/generate.mjs diff --git a/scripts/README.template.md b/scripts/README.template.md new file mode 100644 index 0000000..122c242 --- /dev/null +++ b/scripts/README.template.md @@ -0,0 +1,40 @@ + + +

+ {{header_alt}} +

+ +

+ {{terminal_alt}} +

+ +## `~/about` + +{{about}} + +## `~/engineering-toolkit` + +{{toolkit_alt}} + +## `~/activity` + +{{activity_alt}} + +## `~/projects` + +

+{{projects}} +

+ +## `~/contact` + +

+{{contact}} +

+ +

+ {{footer_alt}} +

diff --git a/scripts/generate.mjs b/scripts/generate.mjs new file mode 100644 index 0000000..a9fb502 --- /dev/null +++ b/scripts/generate.mjs @@ -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 + * , 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, '&').replace(//g, '>').replace(/"/g, '"'); + +function svg(width, height, title, body, style = '') { + return ` +${esc(title)} + +${body} + +`; +} + +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 `${content}`; +} + +const span = (content, fill, extra = '') => `${esc(content)}`; + +/** 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 ``; +} + +/** 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 ` +`; +} + +/** A Waybar pill: base at 90%, hairline border, radius 14. */ +function pill(x, y, width, content, height = 28) { + return `${content}`; +} + +const cursor = (x, y, size = T.md) => + ``; +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 + ? `` + : ` + + +`; + + const mouthY = sleeping ? 139 : 138; + const body = ` + + + + + + + + + + + + + + + + + + + +${eye(84)}${eye(116)} + + + + +${sleeping ? '' : ` +`}`; + + return `${body}`; +} + +const MASCOT_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 += ``; + } + } + + /* 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 + ? `${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 = ` + + +${MASCOT_DEFS} + + +${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 = ''; + 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('', ``); + body += `${esc(step.image.alt)}`; + body += ``; + y = iy + h + 16 + lineHeight; + continue; + } + + if (step.quote) { + y += 4; + for (const line of step.quote.lines) { + body += ``; + 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 = ` + + + + + + + +${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' })} + +${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 + ? `` + : ``; + chips += iconName + ? icon(iconName, cx + 10, cy + 6, 14, used ? color : C.overlay1) + : ``; + chips += text(cx + 30, cy + 17.5, esc(label), { size: T.sm, fill: used ? C.text : C.subtext0 }); + cx += w + 8; + } + body += ``; + 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 += ``; + } + }); + + 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 += `${key}: ${count}`; + } + } + ['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 += ``; + }); + 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 += ``; + 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 += ``; + let bx = barX; + for (const [name, b] of segments) { + const w = (b / bytes) * barWidth; + body += ``; + bx += w; + } + body += ''; + let lx = barX; + for (const [name, b] of segments) { + const percent = ` ${((b / bytes) * 100).toFixed(1)}%`; + body += ``; + 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 += ``; + 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 += ``; + 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 += ``; + 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 })} +${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"' })} +${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) => + ` ${attr(`${project.name}: ${project.description}`)}`).join('\n'); + const contact = profile.contact.map((entry) => + ` ${attr(entry.label)}`).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 || ' projects are unavailable right now', + 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('')) { + problems.push(`${path}: not a complete SVG document`); + } + if (/]*)?>/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'}`);