API npm
Usa la stessa pipeline da script, strumenti di build, browser, funzioni edge o dal tuo server.
Import
import {
generateStats,
loadConfig,
validateConfig,
applyRuntimeOverrides,
fetchStats,
renderCards,
listThemes
} from "profile-graphics";
Generare da una configurazione
generateStats recupera le statistiche, genera ogni scheda di charts e scrive i file in output.dir, proprio come la CLI.
const config = await loadConfig("profile-graphics.yml");
const { outputs } = await generateStats(config);
for (const output of outputs) console.log(output.chart, output.path);
Generare senza scrivere file
validateConfig completa i valori predefiniti, applyRuntimeOverrides applica le opzioni con i loro nomi in camelCase, come stringhe, come fanno i flag della CLI. fetchStats restituisce le statistiche unite di tutte le fonti e renderCards le trasforma in stringhe SVG, o in byte PNG e WebP, senza toccare il disco.
const base = validateConfig({ provider: { user: "octocat" }, charts: ["streak"] });
const config = applyRuntimeOverrides(base, { theme: "dracula", calendarMode: "rolling" });
const stats = await fetchStats(config);
const [card] = await renderCards(config, stats);
console.log(card.content);
Browser e runtime edge
profile-graphics/core contiene lo schema, i temi, le traduzioni delle schede e il renderer senza alcuna API di Node.js, quindi funziona in browser, worker e funzioni edge. renderBrowserCards genera statistiche demo quando non passi stats, ed esporta anche renderConfigCards, createDemoStats, resolveWindow e listThemes.
import { renderBrowserCards } from "profile-graphics/core";
const { cards } = renderBrowserCards({
config: {
provider: { user: "octocat" },
charts: ["streak", "langs"],
theme: { preset: "dracula" }
}
});
document.body.innerHTML = cards.map((card) => card.svg).join("");
Server delle schede
profile-graphics/server esporta createCardHandler, l’handler Fetch API dietro profile-graphics serve, con le opzioni allowedUsers, cacheSeconds, cacheEntries, rateLimit, clientKey e counter, e il tipo RateLimit. Per impostazione predefinita un client è il primo indirizzo in x-forwarded-for, e le richieste senza di esso non vengono limitate. listen esegue un handler sul server HTTP di Node.js.
createVercelHandler adatta l’handler alle funzioni Vercel: rimuove il prefisso /api, risponde a /api/stats?username=… con le statistiche GitHub in JSON e limita ogni client a 30 richieste ogni 60 secondi. Imposta PG_RATE_LIMIT (per esempio 120/60) per cambiare il limite e PG_ALLOWED_USERS (per esempio mona,octocat) per servire solo quegli utenti; gli altri ricevono HTTP 403.
import { createCardHandler, createVercelHandler } from "profile-graphics/server";
export const handler = createCardHandler({
allowedUsers: ["octocat"],
cacheSeconds: 3600,
rateLimit: { requests: 60, windowSeconds: 60 },
clientKey: (request) => request.headers.get("cf-connecting-ip") ?? ""
});
export const GET = createVercelHandler();
Archivi del contatore di visualizzazioni
Il contatore di visualizzazioni conserva i conteggi in un CounterStore: un oggetto con increment(key) e read(key) che restituiscono entrambi { total, days }, dove days associa date UTC a conteggi. MemoryCounterStore è quello predefinito, FileCounterStore scrive un file JSON e UpstashCounterStore comunica con l’API REST di Upstash Redis tramite fetch e tiene un hash per utente. Passa il tuo archivio per collegare qualsiasi altro database.
createVercelHandler sceglie da solo UpstashCounterStore quando sono impostati UPSTASH_REDIS_REST_URL e UPSTASH_REDIS_REST_TOKEN (oppure KV_REST_API_URL e KV_REST_API_TOKEN).
import { createCardHandler, UpstashCounterStore } from "profile-graphics/server";
const counter = new UpstashCounterStore({
url: process.env.UPSTASH_REDIS_REST_URL,
token: process.env.UPSTASH_REDIS_REST_TOKEN
});
export const handler = createCardHandler({ allowedUsers: ["octocat"], counter });
Web component
Usa <profile-graphics> per mostrare schede dal vivo su qualsiasi pagina, come un sito personale o un blog. Carica il bundle in un unico file da una CDN oppure usa import "profile-graphics/element" in un bundler. card accetta uno o più nomi di schede separati da virgole (predefinito streak), e le opzioni di visualizzazione sono attributi con trattini al posto dei trattini bassi: theme, locale, frame, frame-title, layout, langs-style e così via. config accetta un’intera configurazione in JSON. Con il tema nativo le schede seguono lo schema di colori di chi guarda e si ridisegnano quando cambia un attributo.
<script type="module" src="https://cdn.jsdelivr.net/npm/profile-graphics/dist/profile-graphics.element.js"></script>
<profile-graphics user="octocat" card="streak,langs" theme="tokyo-night" frame="window"
frame-title="{user} · {total} contributions"></profile-graphics>
<profile-graphics provider="forgejo" user="forgejo" card="calendar"></profile-graphics>
<profile-graphics stats-src="https://cards.example.com/github/octocat.json" card="summary"></profile-graphics>
<profile-graphics views-src="https://cards.example.com/github/octocat/views.json" card="views"></profile-graphics>
Senza dati l’elemento mostra statistiche demo. provider="forgejo" carica direttamente un profilo Codeberg pubblico, e base-url lo punta a un altro server. stats-src carica un JSON di statistiche, per esempio da profile-graphics serve in /<provider>/<user>.json. views-src legge le visualizzazioni da /<provider>/<user>/views.json per la scheda views senza contare una visita. Le proprietà stats e token accettano dati o un token da uno script. Non mettere mai un token nell’HTML.
Tipi principali
| Tipo | Valori |
|---|---|
ProviderType
|
github, gitlab, forgejo, wakatime, file
|
ChartType
|
activity, langs, streak, summary, productive-time, punch-card, calendar, calendar-3d, profile-details, profile-card, trophy, repos, coding-time, coding-languages, coding-editors, coding-os, coding-projects, views
|
OutputFormat
|
svg, png, webp
|
OutputLayout
|
separate, dashboard
|
CalendarMode
|
current-year, last-year, rolling
|
FrameStyle
|
none, border, window
|
LangsStyle
|
bar, donut, donut-compact
|
ThemeMode
|
auto, light, dark, fixed
|