가져오기

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는 CLI 플래그처럼 camelCase 이름의 문자열로 옵션을 적용합니다. 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에는 스키마, 테마, 카드 번역, 렌더러가 Node.js API 없이 들어 있어 브라우저, 워커, 엣지 함수에서 동작합니다. 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는 profile-graphics serve의 기반인 Fetch API 핸들러 createCardHandler와 RateLimit 타입을 내보냅니다. 핸들러는 allowedUsers, cacheSeconds, cacheEntries, rateLimit, clientKey, counter 옵션을 받습니다. 기본적으로 클라이언트는 x-forwarded-for의 첫 번째 주소로 식별하며, 이 주소가 없는 요청은 제한하지 않습니다. listen은 Node.js HTTP 서버에서 핸들러를 실행합니다.

createVercelHandler는 Vercel 함수용으로 핸들러를 감쌉니다. /api 접두사를 떼고, /api/stats?username=…에 GitHub 통계 JSON으로 응답하며, 클라이언트마다 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 });

웹 컴포넌트

<profile-graphics>를 쓰면 개인 사이트나 블로그 같은 어떤 페이지에서든 카드를 실시간으로 렌더링할 수 있습니다. CDN에서 단일 파일 번들을 불러오거나 번들러에서 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