Elffuss BraidHub

kikocis/utopia public

dev · 10.5 KiBRawPermalink
1#!/usr/bin/env node
2/* 星标曲线:累计星标随日期变化的那一条线,别的都不画。
3 *
4 * 为什么自己画。用过 `lowlighter/metrics`,它把「累计总数」和「每天新增」
5 * 两张图**绑在同一个开关上**(`plugin_stargazers_charts`),模板里没有
6 * 只留其一的办法。而想要的就是传统的那一条累计线。
7 *
8 * 自己画还顺手去掉了一件事:那是个跑在 `contents: write` 之下的第三方
9 * action。现在这个权限底下跑的是这份脚本。
10 *
11 * **GitHub 在 2026-06-30 把星标时间线限制成只有仓库的管理员/协作者可读**,
12 * 所以必须带一个够权限的 token——匿名调用现在拿不到,star-history.com
13 * 那类站点从此只回一张占位图。
14 */
15import { writeFileSync, mkdirSync } from "node:fs";
16import { dirname } from "node:path";
17
18const [owner, repo] = (process.env.REPO ?? "").split("/");
19const token = process.env.GITHUB_TOKEN;
20const out = process.env.OUT ?? "assets/star-history.svg";
21if (!owner || !repo) throw new Error("REPO must be set as owner/name");
22if (!token) throw new Error("GITHUB_TOKEN must be set");
23
24/** 每页 100,游标翻到底。1868 颗星 = 19 页,不值得为它上并发。
25 *
26 * **走 GraphQL,不走 REST。** REST 的 `/repos/{o}/{r}/stargazers` 用同一个
27 * token 会回 404:那个接口要求 token 带仓库级 scope,而这个只有 `read:org`;
28 * GitHub 对无权访问的资源回 404 而不是 403,免得泄露它存不存在。
29 * GraphQL 的 `stargazers` 连接认这个 token——CI 上验过。
30 * 改这里,好过为了一个接口去放宽凭据。 */
31async function stargazerDates() {
32 /* `viewerPermission` 与 `totalCount` 不是装饰。**受限数据 GitHub 回的是
33 空集合,不是报错**——只看 `edges` 的话,「没权限」和「真的零颗星」
34 长得一模一样。把这两个一起取回来,失败时说得出是哪一种 */
35 const query = `query($owner:String!,$name:String!,$cursor:String){
36 repository(owner:$owner,name:$name){
37 stargazerCount
38 viewerPermission
39 stargazers(first:100,after:$cursor,orderBy:{field:STARRED_AT,direction:ASC}){
40 totalCount
41 pageInfo{hasNextPage endCursor}
42 edges{starredAt}
43 }
44 }
45 }`;
46 const dates = [];
47 let cursor = null;
48 for (let page = 1; page <= 400; page++) {
49 const res = await fetch("https://api.github.com/graphql", {
50 method: "POST",
51 headers: {
52 authorization: `Bearer ${token}`,
53 "content-type": "application/json",
54 "user-agent": `${owner}-star-history`,
55 },
56 body: JSON.stringify({ query, variables: { owner, name: repo, cursor } }),
57 });
58 if (!res.ok) {
59 throw new Error(`graphql page ${page}: ${res.status} ${await res.text()}`);
60 }
61 const body = await res.json();
62 // **GraphQL 出错也回 200**,所以必须自己看 `errors`——否则要等到下面
63 // 读出 undefined 才发现,而那时错误原文已经丢了
64 if (body.errors) {
65 throw new Error(`graphql page ${page}: ${JSON.stringify(body.errors)}`);
66 }
67 const node = body.data?.repository;
68 const conn = node?.stargazers;
69 if (!conn) throw new Error(`graphql page ${page}: no stargazers in response`);
70 if (page === 1) {
71 console.log(
72 `repo sees ${node.stargazerCount} stars; connection reports ` +
73 `${conn.totalCount}; token permission = ${node.viewerPermission}`,
74 );
75 }
76 for (const e of conn.edges) if (e.starredAt) dates.push(new Date(e.starredAt));
77 if (!conn.pageInfo.hasNextPage) return dates;
78 cursor = conn.pageInfo.endCursor;
79 }
80 return dates;
81}
82
83const dates = (await stargazerDates()).sort((a, b) => a - b);
84if (dates.length === 0) {
85 // 上面那行日志已经说了 repo 报多少颗星、连接报多少、token 是什么权限。
86 // **不要在这里静默出一张空图**——一张画着零的曲线比没有图更糟
87 throw new Error(
88 "no stargazer timestamps came back — see the line above for what the API " +
89 "reported. An empty connection with a non-zero star count means the token " +
90 "cannot read the stargazer timeline (restricted to admins and collaborators " +
91 "since 2026-06-30).",
92 );
93}
94
95/* 按天聚合成累计值。**每一天都要有点**,哪怕当天没有新增——
96 缺口跳过去的话,横轴的间距就不再代表时间,曲线的斜率也就骗人了 */
97const DAY = 86400000;
98const day0 = Date.UTC(
99 dates[0].getUTCFullYear(),
100 dates[0].getUTCMonth(),
101 dates[0].getUTCDate(),
102);
103const today = Date.now();
104const perDay = new Map();
105for (const d of dates) {
106 const k = Math.floor((Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()) - day0) / DAY);
107 perDay.set(k, (perDay.get(k) ?? 0) + 1);
108}
109const lastDay = Math.floor((today - day0) / DAY);
110const series = [];
111let total = 0;
112for (let k = 0; k <= lastDay; k++) {
113 total += perDay.get(k) ?? 0;
114 series.push({ t: day0 + k * DAY, v: total });
115}
116
117// ---- 画图
118const W = 800, H = 400;
119/* 顶部留得比别处宽:末点的数值标在它上方,而**末点永远在顶上**——
120 累计值单调不减,最后一个点就是最大值 */
121const PAD = { top: 40, right: 28, bottom: 40, left: 64 };
122const plotW = W - PAD.left - PAD.right;
123const plotH = H - PAD.top - PAD.bottom;
124const maxV = series[series.length - 1].v;
125const x = (i) => PAD.left + (plotW * i) / Math.max(1, series.length - 1);
126const y = (v) => PAD.top + plotH - (plotH * v) / Math.max(1, maxV);
127
128/** 轴上的刻度取整齐的数,不取 max/5 那种带小数的 */
129function ticks(max, count = 5) {
130 const raw = max / count;
131 const mag = 10 ** Math.floor(Math.log10(raw));
132 const step = [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw) ?? mag * 10;
133 const out = [];
134 for (let v = 0; v <= max; v += step) out.push(Math.round(v));
135 return out;
136}
137const fmtDate = (t) =>
138 new Date(t).toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" });
139
140/** 平滑成三次贝塞尔,用**单调**插值(Fritsch–Carlson)。
141 *
142 * 不用普通的 Catmull-Rom:累计星标只增不减,而普通样条会在斜率突变处
143 * 过冲,画出一段下凹——**那等于在图上说星标掉了**。单调插值把每段的
144 * 切线夹在不制造极值的范围内,曲线因此永远不会往回走。
145 *
146 * 平的那几天(当天零新增)切线为零,接上去也不会鼓出来。 */
147function smoothPath(pts) {
148 const n = pts.length;
149 if (n < 2) return `M${pts[0].x.toFixed(1)},${pts[0].y.toFixed(1)}`;
150 // 每段的斜率
151 const dx = [], dy = [], slope = [];
152 for (let i = 0; i < n - 1; i++) {
153 dx.push(pts[i + 1].x - pts[i].x);
154 dy.push(pts[i + 1].y - pts[i].y);
155 slope.push(dy[i] / dx[i]);
156 }
157 // 每个点的切线:相邻两段异号(或有一段是平的)时取零,那正是不过冲的条件
158 const m = [slope[0]];
159 for (let i = 1; i < n - 1; i++) {
160 m.push(slope[i - 1] * slope[i] <= 0 ? 0 : (slope[i - 1] + slope[i]) / 2);
161 }
162 m.push(slope[n - 2]);
163 // Fritsch–Carlson:把切线限制在每段斜率的三倍以内
164 for (let i = 0; i < n - 1; i++) {
165 if (slope[i] === 0) {
166 m[i] = 0;
167 m[i + 1] = 0;
168 continue;
169 }
170 const a = m[i] / slope[i];
171 const b = m[i + 1] / slope[i];
172 const s = a * a + b * b;
173 if (s > 9) {
174 const t = (3 / Math.sqrt(s)) * slope[i];
175 m[i] = t * a;
176 m[i + 1] = t * b;
177 }
178 }
179 let d = `M${pts[0].x.toFixed(1)},${pts[0].y.toFixed(1)}`;
180 for (let i = 0; i < n - 1; i++) {
181 const h = dx[i] / 3;
182 d +=
183 `C${(pts[i].x + h).toFixed(1)},${(pts[i].y + m[i] * h).toFixed(1)} ` +
184 `${(pts[i + 1].x - h).toFixed(1)},${(pts[i + 1].y - m[i + 1] * h).toFixed(1)} ` +
185 `${pts[i + 1].x.toFixed(1)},${pts[i + 1].y.toFixed(1)}`;
186 }
187 return d;
188}
189
190const pts = series.map((p, i) => ({ x: x(i), y: y(p.v) }));
191const line = smoothPath(pts);
192const area = `${line}L${x(series.length - 1).toFixed(1)},${(PAD.top + plotH).toFixed(1)}L${x(0).toFixed(1)},${(PAD.top + plotH).toFixed(1)}Z`;
193
194/* 末点与它的数值。**贴着右边缘时把文字改成右对齐**,
195 否则一个四位数会伸出画布外——SVG 不会替你裁,它就是没了 */
196const endX = x(series.length - 1);
197const endY = y(maxV);
198const endAnchor = endX > W - PAD.right - 40 ? "end" : "middle";
199
200const xTickIdx = [...new Set(
201 Array.from({ length: 6 }, (_, i) => Math.round((i * (series.length - 1)) / 5)),
202)];
203
204/* 出两张,深浅各一,README 用 `<picture>` 按主题选。
205 *
206 * **白线在浅色主题上是看不见的**——GitHub 浅色底就是白的。想要白色就
207 * 必须分两张:`prefers-color-scheme` 写在 SVG 里不算数,README 里的 SVG
208 * 是当图片加载的,那条媒体查询问的是操作系统,不是 GitHub 的主题设置,
209 * 两者不一致的人就会看到一张空白的图。`<picture>` 问的才是 GitHub 自己。 */
210const THEMES = {
211 dark: { ink: "#8b949e", accent: "#ffffff", grid: "#8b949e33" },
212 light: { ink: "#6e7781", accent: "#1f2328", grid: "#6e778133" },
213};
214
215function render({ ink, accent, grid }) {
216 return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif">
217<defs><linearGradient id="fill" x1="0" y1="0" x2="0" y2="1">
218<stop offset="0%" stop-color="${accent}" stop-opacity="0.22"/>
219<stop offset="100%" stop-color="${accent}" stop-opacity="0"/>
220</linearGradient></defs>
221<text x="${PAD.left}" y="24" fill="${ink}" font-size="13">${owner}/${repo}</text>
222${ticks(maxV).map((v) => `<g><line x1="${PAD.left}" y1="${y(v).toFixed(1)}" x2="${W - PAD.right}" y2="${y(v).toFixed(1)}" stroke="${grid}"/><text x="${PAD.left - 10}" y="${(y(v) + 4).toFixed(1)}" fill="${ink}" font-size="11" text-anchor="end">${v.toLocaleString("en-US")}</text></g>`).join("")}
223${xTickIdx.map((i) => `<text x="${x(i).toFixed(1)}" y="${H - 16}" fill="${ink}" font-size="11" text-anchor="middle">${fmtDate(series[i].t)}</text>`).join("")}
224<path d="${area}" fill="url(#fill)"/>
225<path d="${line}" fill="none" stroke="${accent}" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
226<circle cx="${endX.toFixed(1)}" cy="${endY.toFixed(1)}" r="3.5" fill="${accent}"/>
227<text x="${endX.toFixed(1)}" y="${(endY - 12).toFixed(1)}" fill="${accent}" font-size="14" font-weight="600" text-anchor="${endAnchor}">${maxV.toLocaleString("en-US")}</text>
228</svg>
229`;
230}
231
232mkdirSync(dirname(out), { recursive: true });
233const lightOut = out.replace(/\.svg$/, "-light.svg");
234writeFileSync(out, render(THEMES.dark));
235writeFileSync(lightOut, render(THEMES.light));
236console.log(`${series.length} days, ${maxV} stars → ${out} + ${lightOut}`);