导入

js
import {
  generateStats,
  loadConfig,
  validateConfig,
  applyRuntimeOverrides,
  fetchStats,
  renderCards,
  listThemes
} from "profile-graphics";

根据配置生成

generateStats 获取统计数据,渲染 charts 中的每张卡片,并把文件写入 output.dir,与 CLI 完全一样。

js
const config = await loadConfig("profile-graphics.yml");
const { outputs } = await generateStats(config);
for (const output of outputs) console.log(output.chart, output.path);

不写入文件直接渲染

validateConfig 填入默认值,applyRuntimeOverrides 按 camelCase 名称以字符串形式应用选项,与 CLI 参数的方式相同。fetchStats 返回所有来源合并后的统计数据,renderCards 将其转为 SVG 字符串或 PNG、WebP 字节,不会写入磁盘。

js
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);

浏览器与边缘运行时

profile-graphics/core 包含 schema、主题、卡片翻译和渲染器,不依赖任何 Node.js API,因此可在浏览器、worker 和边缘函数中运行。renderBrowserCards 在未传入 stats 时渲染演示数据,同时还导出 renderConfigCards、createDemoStats、resolveWindow 和 listThemes。

js
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("");

卡片服务器

profile-graphics/server 导出 createCardHandler,即 profile-graphics serve 背后的 Fetch API 处理函数,支持 allowedUsers、cacheSeconds、cacheEntries、rateLimit、clientKey 和 counter 选项,并导出 RateLimit 类型。默认以 x-forwarded-for 中的第一个地址识别客户端,没有该头的请求不受限制。listen 在 Node.js HTTP 服务器上运行处理函数。

createVercelHandler 为 Vercel 函数包装处理函数:去掉 /api 前缀,用 GitHub 统计 JSON 响应 /api/stats?username=…,并将每个客户端限制为每 60 秒 30 次请求。设置 PG_RATE_LIMIT(例如 120/60)可修改限额,设置 PG_ALLOWED_USERS(例如 mona,octocat)则只为这些用户提供服务;其他用户会收到 HTTP 403。

js
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();

访问计数存储

访问计数器把计数保存在 CounterStore 中:一个带有 increment(key) 和 read(key) 的对象,两者都解析为 { total, days },其中 days 将 UTC 日期映射到计数。MemoryCounterStore 是默认实现,FileCounterStore 写入 JSON 文件,UpstashCounterStore 通过 fetch 调用 Upstash Redis REST API,并为每个用户保存一个 hash。传入你自己的存储即可接入任何其他数据库。

设置了 UPSTASH_REDIS_REST_URL 和 UPSTASH_REDIS_REST_TOKEN(或 KV_REST_API_URL 和 KV_REST_API_TOKEN)时,createVercelHandler 会自动选用 UpstashCounterStore。

js
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 组件

使用 <profile-graphics> 在任意页面(例如个人网站或博客)上实时渲染卡片。从 CDN 加载单文件 bundle,或在打包工具中 import "profile-graphics/element"。card 接受一个或多个以逗号分隔的卡片名(默认 streak),显示选项以属性形式提供,用连字符代替下划线:theme、locale、frame、frame-title、layout、langs-style 等。config 接受 JSON 格式的完整配置。使用原生主题时,卡片会跟随访问者的配色方案,属性变化时会重新绘制。

html
<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>

没有数据时,该元素渲染演示数据。provider="forgejo" 直接加载 Codeberg 公开主页,base-url 可将其指向其他服务器。stats-src 加载统计 JSON,例如来自 profile-graphics serve 的 /<provider>/<user>.json。views-src 从 /<provider>/<user>/views.json 读取访问量供 views 卡片使用,不会计入一次访问。stats 和 token 属性可接收脚本提供的数据或令牌。切勿把令牌写进 HTML。

核心类型

类型 取值
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