github-overview 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -10
- package/bin/cli.mjs +57 -24
- package/docs/screenshot-dark.png +0 -0
- package/docs/screenshot-light.png +0 -0
- package/package.json +1 -1
- package/public/index.html +1261 -120
- package/src/auth.mjs +279 -0
- package/src/config.mjs +37 -2
- package/src/github.mjs +122 -34
- package/src/loop.mjs +67 -0
- package/src/npm.mjs +14 -12
- package/src/server.mjs +988 -74
- package/src/store.mjs +74 -19
- package/src/summary.mjs +270 -20
package/src/server.mjs
CHANGED
|
@@ -3,105 +3,631 @@ import { readFile } from "node:fs/promises";
|
|
|
3
3
|
import { existsSync } from "node:fs";
|
|
4
4
|
import { join, extname, dirname } from "node:path";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
|
-
import { readConfig, writeConfig, resolveToken, parseRepo } from "./config.mjs";
|
|
6
|
+
import { readConfig, writeConfig, resolveToken, parseRepo, normalizeConfig } from "./config.mjs";
|
|
7
|
+
import { authState, boundExplicit, deviceStart, devicePoll, saveToken, adoptAccount, whoami, loginStart, loginPoll } from "./auth.mjs";
|
|
7
8
|
import { makeGithub } from "./github.mjs";
|
|
8
9
|
import { makeNpm } from "./npm.mjs";
|
|
9
|
-
import { loadStore, saveStore, mergeTraffic, mergeNpm, series, storedDays } from "./store.mjs";
|
|
10
|
-
import { aiSummary, readAiConfig,
|
|
10
|
+
import { loadStore, saveStore, repoStore, mergeTraffic, mergeNpm, mergeStars, series, storedDays } from "./store.mjs";
|
|
11
|
+
import { aiSummary, askQuestion, readAiConfig, templateSummary } from "./summary.mjs";
|
|
11
12
|
|
|
12
13
|
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
13
14
|
const PUBLIC = join(ROOT, "public");
|
|
14
15
|
const MIME = { ".html": "text/html; charset=utf-8", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png", ".json": "application/json" };
|
|
16
|
+
const ALL = "all";
|
|
17
|
+
// 摘要别拖慢页面:先回模板,AI 结果进缓存下一次带出来
|
|
18
|
+
const SUM_CACHE = new Map();
|
|
15
19
|
|
|
16
|
-
export function createApp({ repo, days = 7 } = {}) {
|
|
17
|
-
|
|
18
|
-
const
|
|
19
|
-
const
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
20
|
+
export function createApp({ repo, repos, days = 7, intervalHours = 6, contribMinutes = 15, cfg: cfgIn } = {}) {
|
|
21
|
+
// 空配置也要能起来:先给绑定页,绑完 reload() 再按新配置建目标
|
|
22
|
+
const cfg = cfgIn || readConfig();
|
|
23
|
+
const list = repos || normalizeConfig(cfg).repos || (repo ? [{ repo, npm: cfg.npm }] : []);
|
|
24
|
+
const buildTargets = (rows, token) =>
|
|
25
|
+
rows.map((r) => {
|
|
26
|
+
const item = typeof r === "string" ? { repo: r } : r;
|
|
27
|
+
const { owner, name } = parseRepo(item.repo);
|
|
28
|
+
const npmPkg = item.npm || name;
|
|
29
|
+
return { key: `${owner}/${name}`, owner, name, npmPkg, npmExplicit: Boolean(item.npm), gh: makeGithub(token, { owner, name }), npm: makeNpm(npmPkg) };
|
|
30
|
+
});
|
|
31
|
+
let targets = buildTargets(list, resolveToken(cfg));
|
|
32
|
+
let self = [...new Set([cfg.user, ...(cfg.selfLogins || [])].filter(Boolean))];
|
|
33
|
+
// 绑完账号立刻换成新 token 和新仓库列表,不用重启进程
|
|
34
|
+
function reload() {
|
|
35
|
+
const fresh = normalizeConfig(readConfig());
|
|
36
|
+
targets = buildTargets(fresh.repos || [], resolveToken(readConfig()));
|
|
37
|
+
self = [...new Set([fresh.user, ...(fresh.selfLogins || [])].filter(Boolean))];
|
|
38
|
+
store = loadStore();
|
|
39
|
+
return targets.length;
|
|
40
|
+
}
|
|
24
41
|
let store = loadStore();
|
|
25
42
|
let lastSync = null;
|
|
26
|
-
let
|
|
43
|
+
let syncProgress = { running: false, done: 0, total: 0 };
|
|
27
44
|
|
|
28
|
-
async function
|
|
29
|
-
const
|
|
30
|
-
const [views, clones, paths, referrers, repoInfo, releases, activity, alerts] = await Promise.all([
|
|
31
|
-
gh.views().catch(() => null),
|
|
32
|
-
gh.clones().catch(() => null),
|
|
33
|
-
gh.paths().catch(() =>
|
|
34
|
-
gh.referrers().catch(() =>
|
|
35
|
-
gh.repo().catch(() => null),
|
|
36
|
-
gh.releases().catch(() =>
|
|
37
|
-
gh.activity(
|
|
38
|
-
gh.alerts().catch(() => null),
|
|
45
|
+
async function syncOne(t) {
|
|
46
|
+
const s = repoStore(store, t.key);
|
|
47
|
+
const [views, clones, paths, referrers, repoInfo, releases, activity, alerts, openWork, starDates, forkList] = await Promise.all([
|
|
48
|
+
t.gh.views().catch(() => null),
|
|
49
|
+
t.gh.clones().catch(() => null),
|
|
50
|
+
t.gh.paths().catch(() => null),
|
|
51
|
+
t.gh.referrers().catch(() => null),
|
|
52
|
+
t.gh.repo().catch(() => null),
|
|
53
|
+
t.gh.releases().catch(() => null),
|
|
54
|
+
t.gh.activity(new Date(Date.now() - 90 * 864e5).toISOString().slice(0, 10), self).catch(() => null),
|
|
55
|
+
t.gh.alerts().catch(() => null),
|
|
56
|
+
t.gh.openWork(self).catch(() => null),
|
|
57
|
+
t.gh.stargazers().catch(() => null),
|
|
58
|
+
t.gh.forks().catch(() => null),
|
|
59
|
+
]);
|
|
60
|
+
if (views || clones) mergeTraffic(s, views, clones);
|
|
61
|
+
if (starDates) mergeStars(s, starDates);
|
|
62
|
+
// 仓库名当包名只是默认猜测:先看 registry 的维护者,同名别人的包不算自己的下载
|
|
63
|
+
let npmOk = true;
|
|
64
|
+
if (!t.npmExplicit) {
|
|
65
|
+
const own = await t.npm.maintainers().catch(() => null);
|
|
66
|
+
npmOk = own?.missing ? false : (!own || !own.owners.length || own.owners.includes(t.owner.toLowerCase()));
|
|
67
|
+
if (!npmOk) {
|
|
68
|
+
s.npm = {};
|
|
69
|
+
delete s.meta.npmWeek;
|
|
70
|
+
delete s.meta.npmVers;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
s.meta.npmOwned = npmOk;
|
|
74
|
+
let published = null;
|
|
75
|
+
if (npmOk) {
|
|
76
|
+
// npm registry 的几个接口互相独立,一起发比排队快一半
|
|
77
|
+
const [npmRange, week, pub] = await Promise.all([
|
|
78
|
+
t.npm.range(new Date(Date.now() - 400 * 864e5), new Date()).catch(() => null),
|
|
79
|
+
t.npm.week().catch(() => null),
|
|
80
|
+
t.npm.versions().catch(() => null),
|
|
81
|
+
]);
|
|
82
|
+
if (Array.isArray(npmRange)) mergeNpm(s, npmRange);
|
|
83
|
+
if (Number.isFinite(week)) s.meta.npmWeek = week;
|
|
84
|
+
published = pub;
|
|
85
|
+
}
|
|
86
|
+
const prefix = `/${t.owner}/${t.name}`;
|
|
87
|
+
s.meta.repo = repoInfo || s.meta.repo || { owner: t.owner, name: t.name };
|
|
88
|
+
if (forkList) s.meta.forks = { at: new Date().toISOString(), items: forkList.slice(0, 200) };
|
|
89
|
+
if (paths) {
|
|
90
|
+
s.meta.paths = paths.map((p) => {
|
|
91
|
+
const raw = String(p.path || "");
|
|
92
|
+
const page = raw === prefix || raw === prefix + "/" ? "仓库主页" : raw.replace(prefix, "");
|
|
93
|
+
return { p: page || "仓库主页", n: p.count, u: p.uniques };
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
if (referrers) s.meta.referrers = referrers.map((r) => ({ from: r.referrer, n: r.count, u: r.uniques }));
|
|
97
|
+
if (alerts) s.meta.alerts = alerts;
|
|
98
|
+
if (activity) s.meta.activity = activity;
|
|
99
|
+
if (openWork) s.meta.openWork = openWork;
|
|
100
|
+
if (activity || openWork) s.meta.contribAt = new Date().toISOString();
|
|
101
|
+
// 版本时间线只来自 registry 的 time 表:逐版本下载端点已经不可用
|
|
102
|
+
if (Array.isArray(published) && published.length) {
|
|
103
|
+
s.meta.npmVers = published.map((v) => ({ v: v.version, at: v.at, url: null }));
|
|
104
|
+
}
|
|
105
|
+
if (!npmOk) s.meta.npmVers = [];
|
|
106
|
+
const merged = new Map((s.releases || []).map((r) => [r.tag, r]));
|
|
107
|
+
for (const r of releases || []) merged.set(r.tag_name, { tag: r.tag_name, at: r.published_at, url: r.html_url });
|
|
108
|
+
for (const v of published || []) if (!merged.has(v.version)) merged.set(v.version, { tag: v.version, at: v.at, url: null });
|
|
109
|
+
s.releases = [...merged.values()]
|
|
110
|
+
.filter((r) => r.at)
|
|
111
|
+
.sort((a, b) => String(b.at).localeCompare(String(a.at)))
|
|
112
|
+
// 每个仓留足够长的历史,别让截断把 90 天窗口里的发版数算少
|
|
113
|
+
.slice(0, 200);
|
|
114
|
+
s.meta.syncedAt = new Date().toISOString();
|
|
115
|
+
s.meta.error = null;
|
|
116
|
+
return { repo: t.key, ok: true };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// 贡献单独走高频通道:流量/star 是 6 小时一次,issue/PR 状态十几分钟就会变
|
|
120
|
+
async function refreshContrib(t) {
|
|
121
|
+
const s = repoStore(store, t.key);
|
|
122
|
+
const since = new Date(Date.now() - 90 * 864e5).toISOString().slice(0, 10);
|
|
123
|
+
const [activity, openWork] = await Promise.all([
|
|
124
|
+
t.gh.activity(since, self).catch(() => null),
|
|
125
|
+
t.gh.openWork(self).catch(() => null),
|
|
39
126
|
]);
|
|
40
|
-
if (
|
|
41
|
-
|
|
42
|
-
if (
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
127
|
+
if (activity) s.meta.activity = activity;
|
|
128
|
+
if (openWork) s.meta.openWork = openWork;
|
|
129
|
+
if (activity || openWork) s.meta.contribAt = new Date().toISOString();
|
|
130
|
+
return { repo: t.key, ok: Boolean(activity || openWork) };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
let contribPromise = null;
|
|
134
|
+
async function syncContribs() {
|
|
135
|
+
if (contribPromise) return contribPromise;
|
|
136
|
+
contribPromise = (async () => {
|
|
137
|
+
const results = new Array(targets.length);
|
|
138
|
+
let cursor = 0;
|
|
139
|
+
const worker = async () => {
|
|
140
|
+
while (cursor < targets.length) {
|
|
141
|
+
const idx = cursor++;
|
|
142
|
+
const t = targets[idx];
|
|
143
|
+
try {
|
|
144
|
+
results[idx] = await refreshContrib(t);
|
|
145
|
+
} catch (e) {
|
|
146
|
+
results[idx] = { repo: t.key, ok: false, error: String(e.message || e) };
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
await Promise.all(Array.from({ length: Math.min(6, targets.length) }, worker));
|
|
151
|
+
saveStore(store);
|
|
152
|
+
return { ok: results.every((r) => r.ok), at: new Date().toISOString(), results };
|
|
153
|
+
})();
|
|
154
|
+
try {
|
|
155
|
+
return await contribPromise;
|
|
156
|
+
} finally {
|
|
157
|
+
contribPromise = null;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
let syncPromise = null;
|
|
162
|
+
async function sync() {
|
|
163
|
+
// 连点刷新别再走一遍全量:正在跑就等同一个,刚跑完 1 分钟内直接返回
|
|
164
|
+
if (syncPromise) return syncPromise;
|
|
165
|
+
if (lastSync && Date.now() - Date.parse(lastSync) < 60_000) return { ok: true, cached: true, syncedAt: lastSync };
|
|
166
|
+
syncPromise = runSync();
|
|
167
|
+
try {
|
|
168
|
+
return await syncPromise;
|
|
169
|
+
} finally {
|
|
170
|
+
syncPromise = null;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async function runSync() {
|
|
175
|
+
// 并发跑:31 个仓库串行要四分钟,用户点刷新只能干等
|
|
176
|
+
const results = new Array(targets.length);
|
|
177
|
+
const state = { running: true, done: 0, total: targets.length, startedAt: new Date().toISOString() };
|
|
178
|
+
syncProgress = state;
|
|
179
|
+
let cursor = 0;
|
|
180
|
+
const worker = async () => {
|
|
181
|
+
while (cursor < targets.length) {
|
|
182
|
+
const idx = cursor++;
|
|
183
|
+
const t = targets[idx];
|
|
184
|
+
try {
|
|
185
|
+
results[idx] = await syncOne(t);
|
|
186
|
+
} catch (e) {
|
|
187
|
+
const s = repoStore(store, t.key);
|
|
188
|
+
s.meta.error = String(e.message || e);
|
|
189
|
+
s.meta.syncedAt = new Date().toISOString();
|
|
190
|
+
results[idx] = { repo: t.key, ok: false, error: s.meta.error };
|
|
191
|
+
}
|
|
192
|
+
state.done++;
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
try {
|
|
196
|
+
await Promise.all(Array.from({ length: Math.min(6, targets.length) }, worker));
|
|
197
|
+
} finally {
|
|
198
|
+
state.running = false;
|
|
199
|
+
syncProgress = state;
|
|
61
200
|
}
|
|
62
|
-
merged.sort((x, y) => Date.parse(y.at || 0) - Date.parse(x.at || 0));
|
|
63
|
-
store.releases = merged.slice(0, 30);
|
|
64
201
|
saveStore(store);
|
|
65
|
-
lastActivity = activity;
|
|
66
202
|
lastSync = new Date().toISOString();
|
|
67
|
-
return { ok:
|
|
203
|
+
return { ok: results.every((r) => r.ok), syncedAt: lastSync, results };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// 星标净增跟着图表标的区间走:起止与 range 一致,不按请求天数报
|
|
207
|
+
function starGrowthOf(from, to, list) {
|
|
208
|
+
if (!from || !to) return null;
|
|
209
|
+
let delta = 0, seen = 0;
|
|
210
|
+
for (const s of list) {
|
|
211
|
+
const ds = s.stars || [];
|
|
212
|
+
if (!ds.length) continue;
|
|
213
|
+
seen++;
|
|
214
|
+
delta += ds.filter((d) => d >= from && d <= to).length;
|
|
215
|
+
}
|
|
216
|
+
const span = Math.round((Date.parse(to) - Date.parse(from)) / 864e5) + 1;
|
|
217
|
+
return seen ? { span, from, to, delta } : null;
|
|
68
218
|
}
|
|
219
|
+
// 星标跨度和浏览/issue 的「近 N 天」用同一个口径:今天没采集到不算一天
|
|
220
|
+
const clampSpan = (sg, cov) => (sg && cov ? { ...sg, span: Math.max(1, Math.min(sg.span, cov)) } : sg);
|
|
221
|
+
|
|
222
|
+
// GitHub 只回 14 天去重访客,更长范围沿用这段窗口并说明覆盖天数
|
|
223
|
+
const coveredDays = (s) => Object.values(s.days || {}).filter((d) => d.u != null).length;
|
|
224
|
+
const firstDay = (s) => Object.values(s.days || {})
|
|
225
|
+
.filter((d) => d.v != null || d.u != null).map((d) => d.d).sort()[0] || null;
|
|
226
|
+
|
|
227
|
+
const sumOf = (get) => {
|
|
228
|
+
let has = false;
|
|
229
|
+
let v = 0;
|
|
230
|
+
for (const t of targets) {
|
|
231
|
+
const x = get(repoStore(store, t.key));
|
|
232
|
+
if (x != null) {
|
|
233
|
+
has = true;
|
|
234
|
+
v += x;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return has ? v : null;
|
|
238
|
+
};
|
|
69
239
|
|
|
70
|
-
function
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
const
|
|
74
|
-
|
|
240
|
+
function aggregate(windowDays) {
|
|
241
|
+
const slices = targets.map((t) => ({ t, s: repoStore(store, t.key) }));
|
|
242
|
+
// 漏斗固定「最近 14 个完整日」:跟随窗口末行会让今天那行 0 参与、切范围时数字还会变
|
|
243
|
+
const funnelEnd = () => {
|
|
244
|
+
const t = new Date();
|
|
245
|
+
t.setUTCHours(0, 0, 0, 0);
|
|
246
|
+
t.setUTCDate(t.getUTCDate() - 1);
|
|
247
|
+
return t.toISOString().slice(0, 10);
|
|
248
|
+
};
|
|
249
|
+
const sum14 = () => {
|
|
250
|
+
const ds = last14Days(funnelEnd());
|
|
251
|
+
return ds.length ? slices.reduce((acc, { s }) => acc + ds.reduce((b, d) => b + (s.days?.[d]?.v ?? 0), 0), 0) : null;
|
|
252
|
+
};
|
|
253
|
+
const allSeries = slices.map(({ s }) => series(s, windowDays, s.npm || {}));
|
|
254
|
+
const rows = [];
|
|
255
|
+
if (windowDays === 1) {
|
|
256
|
+
// 1 天窗口必须落在同一个日历日上:各仓自己的「最近一天」可能不同,
|
|
257
|
+
// 按位置相加会把 11-06 的数写进 11-05 那行
|
|
258
|
+
const today = new Date();
|
|
259
|
+
today.setUTCHours(0, 0, 0, 0);
|
|
260
|
+
const pick = (back) => new Date(today.getTime() - back * 864e5).toISOString().slice(0, 10);
|
|
261
|
+
// 和 store.series 同一套落点:当天那格全 0 是还没结算,别把它当「这一天没人来」
|
|
262
|
+
const settled = (d) => slices.some(({ s }) => ["v", "u", "c", "cu"].some((f) => Number(s.days?.[d]?.[f]) > 0));
|
|
263
|
+
let k = pick(1);
|
|
264
|
+
if (!slices.some(({ s }) => s.days?.[k])) k = pick(2);
|
|
265
|
+
else if (!settled(k)) k = [2, 3, 4].map(pick).find(settled) || k;
|
|
266
|
+
const cell = { d: k, v: null, u: null, c: null, cu: null, n: null };
|
|
267
|
+
for (const { s } of slices) {
|
|
268
|
+
const row = s.days?.[k];
|
|
269
|
+
// 下载逐日存在 s.npm 里,不在 s.days 那格:少读这一路,单日窗口永远没有下载数
|
|
270
|
+
const npmDay = s.npm?.[k] ?? row?.n;
|
|
271
|
+
if (npmDay != null) cell.n = (cell.n ?? 0) + npmDay;
|
|
272
|
+
if (!row) continue;
|
|
273
|
+
for (const kk of ["v", "u", "c", "cu"]) if (row[kk] != null) cell[kk] = (cell[kk] ?? 0) + row[kk];
|
|
274
|
+
}
|
|
275
|
+
rows.push(cell);
|
|
276
|
+
}
|
|
277
|
+
for (let i = 0; i < windowDays && windowDays > 1; i++) {
|
|
278
|
+
const cell = { d: allSeries[0]?.[i]?.d, v: null, u: null, c: null, cu: null, n: null };
|
|
279
|
+
for (const sr of allSeries) {
|
|
280
|
+
const r = sr[i];
|
|
281
|
+
if (!r) continue;
|
|
282
|
+
for (const k of ["v", "u", "c", "cu", "n"]) if (r[k] != null) cell[k] = (cell[k] ?? 0) + r[k];
|
|
283
|
+
}
|
|
284
|
+
rows.push(cell);
|
|
285
|
+
}
|
|
286
|
+
const paths = new Map();
|
|
287
|
+
const referrers = new Map();
|
|
288
|
+
const releases = [];
|
|
289
|
+
const issues = [];
|
|
290
|
+
const pulls = [];
|
|
291
|
+
const npmVersions = [];
|
|
292
|
+
const alertKeys = ["dependabot", "codeScanning", "secretScanning"];
|
|
293
|
+
const alerts = { dependabot: { available: false, open: 0 }, codeScanning: { available: false, open: 0 }, secretScanning: { available: false, open: 0 } };
|
|
294
|
+
for (const { t, s } of slices) {
|
|
295
|
+
const m = s.meta || {};
|
|
296
|
+
for (const p of m.paths || []) {
|
|
297
|
+
const cur = paths.get(p.p) || { p: p.p, n: 0, u: 0 };
|
|
298
|
+
cur.n += p.n || 0;
|
|
299
|
+
cur.u += p.u || 0;
|
|
300
|
+
paths.set(p.p, cur);
|
|
301
|
+
}
|
|
302
|
+
for (const r of m.referrers || []) {
|
|
303
|
+
const cur = referrers.get(r.from) || { from: r.from, n: 0, u: 0 };
|
|
304
|
+
cur.n += r.n || 0;
|
|
305
|
+
cur.u += r.u || 0;
|
|
306
|
+
referrers.set(r.from, cur);
|
|
307
|
+
}
|
|
308
|
+
for (const rel of s.releases || []) releases.push({ ...rel, repo: t.key });
|
|
309
|
+
for (const i of m.activity?.issues || []) issues.push({ ...i, repo: t.key });
|
|
310
|
+
for (const p of m.activity?.pulls || []) pulls.push({ ...p, repo: t.key });
|
|
311
|
+
for (const v of m.npmVers || []) npmVersions.push({ ...v, repo: t.key });
|
|
312
|
+
for (const k of alertKeys) {
|
|
313
|
+
const cell = m.alerts?.[k];
|
|
314
|
+
if (cell?.available) {
|
|
315
|
+
alerts[k] = {
|
|
316
|
+
available: true,
|
|
317
|
+
open: (alerts[k].open || 0) + (cell.open || 0),
|
|
318
|
+
repos: [...(alerts[k].repos || []), { key: t.key, open: cell.open || 0 }],
|
|
319
|
+
};
|
|
320
|
+
} else if (!alerts[k].available && !alerts[k].blocked && cell?.status === 403) {
|
|
321
|
+
alerts[k].blocked = "permission_denied";
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
const anyAlert = alertKeys.some((k) => alerts[k].available || alerts[k].blocked);
|
|
326
|
+
const fw = forkWindow(windowDays);
|
|
327
|
+
const repoInfo = slices.reduce(
|
|
328
|
+
(acc, { s }) => ({
|
|
329
|
+
stars: acc.stars + (s.meta?.repo?.stars || 0),
|
|
330
|
+
forks: acc.forks + (s.meta?.repo?.forks || 0),
|
|
331
|
+
openIssues: acc.openIssues + (s.meta?.repo?.openIssues || 0),
|
|
332
|
+
}),
|
|
333
|
+
{ stars: 0, forks: 0, openIssues: 0 },
|
|
334
|
+
);
|
|
335
|
+
return {
|
|
336
|
+
repo: { fullName: "全部仓库", owner: "", name: "全部仓库", stars: repoInfo.stars, forks: repoInfo.forks, openIssues: repoInfo.openIssues, count: targets.length },
|
|
337
|
+
range: { days: windowDays, from: rows[0]?.d, to: rows.at(-1)?.d, storedDays: Math.max(...slices.map(({ s }) => storedDays(s)), 0), covered: Math.max(...slices.map(({ s }) => coveredDays(s)), 0), first: slices.map(({ s }) => firstDay(s)).filter(Boolean).sort()[0] || null },
|
|
338
|
+
series: rows,
|
|
339
|
+
totals: {
|
|
340
|
+
// 这些是按区间加出来的;views.total 是每仓 14 天的量,当窗口用会把 7 天说成 19 天
|
|
341
|
+
// 和 series 行同源,1 天窗口才不会拿各仓不同的「最近一天」去加
|
|
342
|
+
views: rows.reduce((a, x) => a + (x.v ?? 0), 0),
|
|
343
|
+
uniques: sumOf((s) => s.meta?.views?.uniques),
|
|
344
|
+
clones: rows.reduce((a, x) => a + (x.c ?? 0), 0),
|
|
345
|
+
cloneUniques: sumOf((s) => s.meta?.clones?.uniques),
|
|
346
|
+
// npm 逐日是按窗口存的,npmWeek 是固定的 7 天滚动值:KPI 要用前者才跟得上范围
|
|
347
|
+
npm: rows.some((x) => x.n != null) ? rows.reduce((a, x) => a + (x.n ?? 0), 0) : null,
|
|
348
|
+
npmWeek: sumOf((s) => s.meta?.npmWeek),
|
|
349
|
+
},
|
|
350
|
+
repos: targets
|
|
351
|
+
.map((t) => {
|
|
352
|
+
const r = repoStore(store, t.key);
|
|
353
|
+
// 1 天窗口各仓必须报同一个日历日,否则排行里的下载量和上面那行对不上
|
|
354
|
+
const day1 = windowDays === 1 ? rows[0]?.d : null;
|
|
355
|
+
const w = day1
|
|
356
|
+
? [{ d: day1, v: r.days?.[day1]?.v ?? null, u: r.days?.[day1]?.u ?? null, n: r.npm?.[day1] ?? r.days?.[day1]?.n ?? null }]
|
|
357
|
+
: series(r, windowDays, r.npm || {});
|
|
358
|
+
// 单日窗口就按那一天算:这个仓那天没有浏览数据时不能退回到它自己的第一天,
|
|
359
|
+
// 否则「近 1 天」里塞进一个月的涨星
|
|
360
|
+
const sg = starGrowthOf(
|
|
361
|
+
day1 || [w.find((x) => x.v != null || x.u != null)?.d || "", firstDay(r) || ""].sort().at(-1) || null,
|
|
362
|
+
w.at(-1)?.d || null,
|
|
363
|
+
[r],
|
|
364
|
+
);
|
|
365
|
+
return {
|
|
366
|
+
key: t.key,
|
|
367
|
+
name: t.key.split("/")[1] || t.key,
|
|
368
|
+
uniques: windowDays === 1 ? (w.at(-1)?.u ?? null) : (r.meta?.views?.uniques ?? null),
|
|
369
|
+
views: w.reduce((a, x) => a + (x.v ?? 0), 0),
|
|
370
|
+
npm: w.reduce((a, x) => a + (x.n ?? 0), 0),
|
|
371
|
+
npmWeek: r.meta?.npmWeek ?? null,
|
|
372
|
+
stars: r.meta?.repo?.stars ?? null,
|
|
373
|
+
starDelta: sg ? sg.delta : null,
|
|
374
|
+
forks: r.meta?.repo?.forks ?? null,
|
|
375
|
+
newForks: (r.meta?.forks?.items || []).filter(inWindow(fw.from, fw.to)).length,
|
|
376
|
+
lastFork: (r.meta?.forks?.items || [])[0] || null,
|
|
377
|
+
};
|
|
378
|
+
})
|
|
379
|
+
.sort((a, b) => (b.uniques ?? 0) - (a.uniques ?? 0)),
|
|
380
|
+
// 漏斗的浏览用「同一段 14 天的逐日和」,别混用 meta 里的接口总数:
|
|
381
|
+
// 两者口径差几次,同时上屏就成两个数
|
|
382
|
+
funnel: {
|
|
383
|
+
views: sum14(),
|
|
384
|
+
home: [...paths.values()].filter((p) => p.p === "仓库主页").reduce((a, p) => a + p.n, 0) || null,
|
|
385
|
+
// 漏斗是一段固定 14 天的转化:下载也取同一段,混进 7 天的周汇总会让后面两级对不上
|
|
386
|
+
npm: (() => {
|
|
387
|
+
const ds = last14Days(funnelEnd());
|
|
388
|
+
return ds.length ? slices.reduce((acc, { s }) => acc + ds.reduce((b, d) => b + (s.npm?.[d] ?? 0), 0), 0) : null;
|
|
389
|
+
})(),
|
|
390
|
+
},
|
|
391
|
+
impacts: windowDays < 7 ? [] : slices
|
|
392
|
+
.map(({ t, s }) => {
|
|
393
|
+
const im = impactOf(s);
|
|
394
|
+
return im && im.before?.views?.avg ? { key: t.key, name: t.key.split("/")[1] || t.key, ...im } : null;
|
|
395
|
+
})
|
|
396
|
+
.filter((x) => x && x.at >= rows[0]?.d)
|
|
397
|
+
.sort((a, b) => (a.limited === b.limited ? b.at.localeCompare(a.at) : a.limited ? 1 : -1)),
|
|
398
|
+
paths: [...paths.values()].sort((a, b) => b.n - a.n),
|
|
399
|
+
referrers: [...referrers.values()].sort((a, b) => b.n - a.n),
|
|
400
|
+
forks: (() => {
|
|
401
|
+
const items = slices
|
|
402
|
+
.flatMap(({ t, s }) => (s.meta?.forks?.items || [])
|
|
403
|
+
.filter(inWindow(fw.from, fw.to))
|
|
404
|
+
.map((x) => ({ ...x, repo: t.key })))
|
|
405
|
+
.sort((a, b) => String(b.at).localeCompare(String(a.at)));
|
|
406
|
+
const latest = slices
|
|
407
|
+
.flatMap(({ t, s }) => (s.meta?.forks?.items || []).map((x) => ({ ...x, repo: t.key })))
|
|
408
|
+
.sort((a, b) => String(b.at).localeCompare(String(a.at)))[0] || null;
|
|
409
|
+
return {
|
|
410
|
+
total: repoInfo.forks,
|
|
411
|
+
from: fw.from,
|
|
412
|
+
to: fw.to,
|
|
413
|
+
inWindow: items.length,
|
|
414
|
+
items: items.slice(0, 100),
|
|
415
|
+
// 窗口里没有新 fork 时,也要能说清最近一次是什么时候
|
|
416
|
+
latest,
|
|
417
|
+
at: slices.map(({ s }) => s.meta?.forks?.at).filter(Boolean).sort().at(-1) || null,
|
|
418
|
+
};
|
|
419
|
+
})(),
|
|
420
|
+
releases: releases.sort((a, b) => String(b.at).localeCompare(String(a.at))).slice(0, 120),
|
|
421
|
+
npmVersions,
|
|
422
|
+
impact: windowDays < 7 ? null : (() => {
|
|
423
|
+
// 主卡也要带上仓名,否则只有一个版本号,看不出是哪个仓
|
|
424
|
+
const all = slices.map(({ t, s }) => {
|
|
425
|
+
const im = impactOf(s);
|
|
426
|
+
return im && im.before?.views ? { key: t.key, name: t.key.split("/")[1] || t.key, ...im } : null;
|
|
427
|
+
}).filter((x) => x && x.at >= rows[0]?.d);
|
|
428
|
+
const ok = all.filter((x) => !x.limited).sort((a, b) => b.at.localeCompare(a.at));
|
|
429
|
+
return ok[0] || all.sort((a, b) => b.at.localeCompare(a.at))[0] || null;
|
|
430
|
+
})(),
|
|
431
|
+
contributions: {
|
|
432
|
+
issues: issues.filter(inWindow(rows[0]?.d, rows.at(-1)?.d)),
|
|
433
|
+
pulls: pulls.filter(inWindow(rows[0]?.d, rows.at(-1)?.d)),
|
|
434
|
+
open: {
|
|
435
|
+
issues: slices.flatMap(({ t, s }) => (s.meta?.openWork?.issues || []).map((x) => ({ ...x, repo: t.key }))).sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt))),
|
|
436
|
+
pulls: slices.flatMap(({ t, s }) => (s.meta?.openWork?.pulls || []).map((x) => ({ ...x, repo: t.key }))).sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt))),
|
|
437
|
+
},
|
|
438
|
+
alerts: anyAlert ? alerts : null,
|
|
439
|
+
at: slices.map(({ s }) => s.meta?.contribAt).filter(Boolean).sort().at(-1) || null,
|
|
440
|
+
},
|
|
441
|
+
starGrowth: clampSpan(starGrowthOf(
|
|
442
|
+
[rows.find((r) => r.v != null || r.u != null)?.d || "", slices.map(({ s }) => firstDay(s)).filter(Boolean).sort()[0] || ""]
|
|
443
|
+
.sort()
|
|
444
|
+
.at(-1) || null,
|
|
445
|
+
rows.at(-1)?.d || null,
|
|
446
|
+
slices.map(({ s }) => s),
|
|
447
|
+
), Math.max(...slices.map(({ s }) => coveredDays(s)), 0)),
|
|
448
|
+
updatedAt: lastSync,
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
const shiftDay = (d, n) => {
|
|
453
|
+
const t = new Date(`${d}T00:00:00Z`);
|
|
454
|
+
t.setUTCDate(t.getUTCDate() + n);
|
|
455
|
+
return t.toISOString().slice(0, 10);
|
|
456
|
+
};
|
|
457
|
+
|
|
458
|
+
// 最近一次发版前后 7 天的日均,数据不足时如实报覆盖天数
|
|
459
|
+
function impactOf(s) {
|
|
460
|
+
const cuts = [
|
|
461
|
+
...(s.releases || []).filter((r) => r.at).map((r) => ({ version: r.tag, at: String(r.at).slice(0, 10), url: r.url || null })),
|
|
462
|
+
...((s.meta?.npmVers || []).filter((v) => v.at).map((v) => ({ version: v.v || v.version, at: String(v.at).slice(0, 10), url: null }))),
|
|
463
|
+
];
|
|
464
|
+
if (!cuts.length) return null;
|
|
465
|
+
cuts.sort((a, b) => b.at.localeCompare(a.at));
|
|
466
|
+
const ev = cuts[0];
|
|
467
|
+
const rows = series(s, 90, s.npm || {});
|
|
468
|
+
const avg = (from, to) => {
|
|
469
|
+
const hit = rows.filter((r) => r.d >= from && r.d <= to);
|
|
470
|
+
const pick = (k) => {
|
|
471
|
+
const got = hit.filter((r) => r[k] !== null && r[k] !== undefined);
|
|
472
|
+
if (!got.length) return null;
|
|
473
|
+
const sum = got.reduce((a, r) => a + r[k], 0);
|
|
474
|
+
return { avg: Math.round((sum / got.length) * 10) / 10, days: got.length, from: got[0].d, to: got.at(-1).d };
|
|
475
|
+
};
|
|
476
|
+
return { from, to, views: pick("v"), uniques: pick("u"), npm: pick("n") };
|
|
477
|
+
};
|
|
478
|
+
const at = (x) => ({ before: avg(shiftDay(x.at, -7), shiftDay(x.at, -1)), after: avg(shiftDay(x.at, 1), shiftDay(x.at, 7)) });
|
|
479
|
+
// 刚发的版本后面还没数据,退到最近一个前后都有 3 天以上的版本
|
|
480
|
+
let chosen = null;
|
|
481
|
+
for (const c of cuts.slice(0, 30)) {
|
|
482
|
+
const r = at(c);
|
|
483
|
+
if (r.before.views?.days >= 3 && r.after.views?.days >= 3) {
|
|
484
|
+
chosen = { ...c, ...r };
|
|
485
|
+
break;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
if (!chosen) {
|
|
489
|
+
const r = at(ev);
|
|
490
|
+
chosen = { ...ev, ...r };
|
|
491
|
+
}
|
|
492
|
+
const { before, after } = chosen;
|
|
493
|
+
const delta = (k) => {
|
|
494
|
+
const b = before[k]?.avg, a = after[k]?.avg;
|
|
495
|
+
return b != null && a != null && b !== 0 ? Math.round((a / b - 1) * 100) : null;
|
|
496
|
+
};
|
|
497
|
+
return { ...chosen, limited: (after.views?.days || 0) < 3, delta: { views: delta("views"), uniques: delta("uniques"), npm: delta("npm") } };
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
const inWindow = (from, to) => (x) => {
|
|
501
|
+
// fork 用 at,活动条目用 createdAt/mergedAt:两种字段都要认
|
|
502
|
+
const at = String(x.at || x.mergedAt || x.closedAt || x.createdAt || "").slice(0, 10);
|
|
503
|
+
return !from || (at >= from && at <= to);
|
|
504
|
+
};
|
|
505
|
+
// fork 按创建时间算,不受流量数据滞后一天影响
|
|
506
|
+
const forkWindow = (days) => {
|
|
507
|
+
const to = new Date().toISOString().slice(0, 10);
|
|
508
|
+
const from = new Date(Date.now() - Math.max(0, days - 1) * 864e5).toISOString().slice(0, 10);
|
|
509
|
+
return { from, to };
|
|
510
|
+
};
|
|
511
|
+
|
|
512
|
+
function buildRepo(windowDays, t) {
|
|
513
|
+
const s = repoStore(store, t.key);
|
|
514
|
+
const fw = forkWindow(windowDays);
|
|
515
|
+
const rows = series(s, windowDays, s.npm || {});
|
|
516
|
+
// 同全站:固定按「最近 14 个完整日」,不跟窗口末行走
|
|
517
|
+
const funnelEnd = () => {
|
|
518
|
+
const t = new Date();
|
|
519
|
+
t.setUTCHours(0, 0, 0, 0);
|
|
520
|
+
t.setUTCDate(t.getUTCDate() - 1);
|
|
521
|
+
return t.toISOString().slice(0, 10);
|
|
522
|
+
};
|
|
523
|
+
const sum14 = () => {
|
|
524
|
+
const ds = last14Days(funnelEnd());
|
|
525
|
+
return ds.length ? ds.reduce((b, d) => b + (s.days?.[d]?.v ?? 0), 0) : null;
|
|
526
|
+
};
|
|
527
|
+
const meta = s.meta || {};
|
|
75
528
|
const views = meta.views || {};
|
|
76
529
|
const clones = meta.clones || {};
|
|
77
|
-
const covers = storedDays(store);
|
|
78
|
-
// 访客用 API 自己的窗口去重值;窗口长于覆盖天数时退回日均估算
|
|
79
|
-
const uniques = windowDays <= 14 && views.uniques != null ? views.uniques : null;
|
|
80
530
|
return {
|
|
81
|
-
repo:
|
|
82
|
-
range: { days: windowDays, from: rows[0]?.d, to: rows.at(-1)?.d, storedDays:
|
|
531
|
+
repo: { owner: t.owner, name: t.name, npmPkg: meta.npmOwned === false ? null : t.npmPkg, ...(meta.repo || {}) },
|
|
532
|
+
range: { days: windowDays, from: rows[0]?.d, to: rows.at(-1)?.d, storedDays: storedDays(s), covered: coveredDays(s), first: firstDay(s) },
|
|
83
533
|
series: rows,
|
|
84
534
|
totals: {
|
|
85
|
-
views:
|
|
86
|
-
uniques,
|
|
87
|
-
clones:
|
|
535
|
+
views: rows.reduce((a, x) => a + (x.v ?? 0), 0),
|
|
536
|
+
uniques: views.uniques ?? null,
|
|
537
|
+
clones: rows.reduce((a, x) => a + (x.c ?? 0), 0),
|
|
88
538
|
cloneUniques: clones.uniques ?? null,
|
|
539
|
+
npm: rows.some((x) => x.n != null) ? rows.reduce((a, x) => a + (x.n ?? 0), 0) : null,
|
|
89
540
|
npmWeek: meta.npmWeek ?? null,
|
|
90
541
|
},
|
|
91
542
|
paths: meta.paths || [],
|
|
543
|
+
funnel: {
|
|
544
|
+
views: sum14(),
|
|
545
|
+
home: (meta.paths || []).filter((p) => p.p === "仓库主页").reduce((a, p) => a + (p.n || 0), 0) || null,
|
|
546
|
+
npm: (() => {
|
|
547
|
+
const ds = last14Days(funnelEnd());
|
|
548
|
+
return ds.length ? ds.reduce((b, d) => b + (s.npm?.[d] ?? 0), 0) : null;
|
|
549
|
+
})(),
|
|
550
|
+
},
|
|
551
|
+
starGrowth: clampSpan(starGrowthOf(
|
|
552
|
+
// 单日窗口就锁在那一天:这个仓那天没有流量行时退回自己的第一天,
|
|
553
|
+
// 会把一个月的涨星塞进「近 1 天」
|
|
554
|
+
windowDays === 1
|
|
555
|
+
? (rows[0]?.d || null)
|
|
556
|
+
: ([rows.find((r) => r.v != null || r.u != null)?.d || "", firstDay(s) || ""].sort().at(-1) || null),
|
|
557
|
+
rows.at(-1)?.d || null,
|
|
558
|
+
[s],
|
|
559
|
+
), coveredDays(s)),
|
|
560
|
+
// fork 是留存信号:谁在什么时候 fork 的,窗口内单独列出来
|
|
561
|
+
forks: {
|
|
562
|
+
total: meta.repo?.forks ?? null,
|
|
563
|
+
from: fw.from,
|
|
564
|
+
to: fw.to,
|
|
565
|
+
inWindow: (meta.forks?.items || []).filter(inWindow(fw.from, fw.to)).length,
|
|
566
|
+
items: (meta.forks?.items || []).filter(inWindow(fw.from, fw.to)).slice(0, 30),
|
|
567
|
+
latest: (meta.forks?.items || [])[0] || null,
|
|
568
|
+
at: meta.forks?.at || null,
|
|
569
|
+
},
|
|
92
570
|
referrers: meta.referrers || [],
|
|
93
|
-
releases:
|
|
94
|
-
npmVersions:
|
|
571
|
+
releases: s.releases || [],
|
|
572
|
+
npmVersions: meta.npmVers || [],
|
|
573
|
+
impact: windowDays < 7 ? null : (() => {
|
|
574
|
+
const im = impactOf(s);
|
|
575
|
+
return im && im.at >= rows[0]?.d ? im : null;
|
|
576
|
+
})(),
|
|
95
577
|
contributions: {
|
|
96
|
-
issues: activity
|
|
97
|
-
pulls: activity
|
|
98
|
-
|
|
578
|
+
issues: (meta.activity?.issues || []).filter(inWindow(rows[0]?.d, rows.at(-1)?.d)),
|
|
579
|
+
pulls: (meta.activity?.pulls || []).filter(inWindow(rows[0]?.d, rows.at(-1)?.d)),
|
|
580
|
+
open: meta.openWork ? { issues: meta.openWork.issues || [], pulls: meta.openWork.pulls || [] } : null,
|
|
99
581
|
alerts: meta.alerts || null,
|
|
582
|
+
at: meta.contribAt || null,
|
|
100
583
|
},
|
|
101
|
-
updatedAt: lastSync,
|
|
584
|
+
updatedAt: meta.syncedAt || lastSync,
|
|
102
585
|
};
|
|
103
586
|
}
|
|
104
587
|
|
|
588
|
+
// 未知 repo 不能悄悄退回全部仓库:那会把全站数字显示成一个仓的,看起来像这个仓的数据
|
|
589
|
+
function resolveKey(raw) {
|
|
590
|
+
const q = String(raw || "").trim();
|
|
591
|
+
if (!q || q === ALL) return ALL;
|
|
592
|
+
const hit = targets.find((x) => x.key.toLowerCase() === q.toLowerCase());
|
|
593
|
+
if (hit) return hit.key;
|
|
594
|
+
const tail = targets.filter((x) => x.key.toLowerCase().endsWith("/" + q.toLowerCase()));
|
|
595
|
+
return tail.length === 1 ? tail[0].key : null;
|
|
596
|
+
}
|
|
597
|
+
const noRepo = (key) => `没有绑定这个仓库:${key}。右上角切换范围,或在 config 里加上它。`;
|
|
598
|
+
// 以当前窗口最后一天为终点、往前 14 个日历日的逐日浏览和
|
|
599
|
+
const last14Days = (endD) => {
|
|
600
|
+
if (!endD) return [];
|
|
601
|
+
const end = Date.parse(endD + "T00:00:00Z");
|
|
602
|
+
const out = [];
|
|
603
|
+
for (let i = 13; i >= 0; i--) out.push(new Date(end - i * 864e5).toISOString().slice(0, 10));
|
|
604
|
+
return out;
|
|
605
|
+
};
|
|
606
|
+
|
|
607
|
+
function build(windowDays, key = ALL) {
|
|
608
|
+
if (key === ALL) return aggregate(windowDays);
|
|
609
|
+
const t = targets.find((x) => x.key === key);
|
|
610
|
+
// 只接受已解析的 key:未绑定的仓库不能悄悄落到全站数据上
|
|
611
|
+
if (!t) throw new Error("没有绑定这个仓库:" + key);
|
|
612
|
+
return t ? buildRepo(windowDays, t) : aggregate(windowDays);
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
const repoRows = () => ({
|
|
616
|
+
repos: targets.map((t) => {
|
|
617
|
+
const s = repoStore(store, t.key);
|
|
618
|
+
return {
|
|
619
|
+
key: t.key,
|
|
620
|
+
label: t.key,
|
|
621
|
+
npmPkg: s.meta?.npmOwned === false ? null : t.npmPkg,
|
|
622
|
+
stars: s.meta?.repo?.stars ?? null,
|
|
623
|
+
storedDays: storedDays(s),
|
|
624
|
+
syncedAt: s.meta?.syncedAt ?? null,
|
|
625
|
+
error: s.meta?.error ?? null,
|
|
626
|
+
};
|
|
627
|
+
}),
|
|
628
|
+
default: ALL,
|
|
629
|
+
});
|
|
630
|
+
|
|
105
631
|
const server = createServer(async (req, res) => {
|
|
106
632
|
const url = new URL(req.url, "http://localhost");
|
|
107
633
|
const send = (code, body, type = "application/json; charset=utf-8") => {
|
|
@@ -109,25 +635,409 @@ export function createApp({ repo, days = 7 } = {}) {
|
|
|
109
635
|
res.end(typeof body === "string" || Buffer.isBuffer(body) ? body : JSON.stringify(body));
|
|
110
636
|
};
|
|
111
637
|
try {
|
|
638
|
+
// 绑定账号:设备码流不需要用户手抄 token,也支持直接粘贴 PAT
|
|
639
|
+
if (url.pathname === "/api/auth") {
|
|
640
|
+
if (req.method === "POST") {
|
|
641
|
+
let raw = "";
|
|
642
|
+
for await (const chunk of req) raw += chunk;
|
|
643
|
+
const body = JSON.parse(raw || "{}");
|
|
644
|
+
const token = String(body.token || "").trim();
|
|
645
|
+
if (!token) return send(400, { error: "没有收到 token" });
|
|
646
|
+
const me = await whoami(token);
|
|
647
|
+
if (!me) return send(400, { error: "这个 token 读不到 GitHub 账号" });
|
|
648
|
+
saveToken(token, me.login);
|
|
649
|
+
const adopted = await adoptAccount(token, me.login).catch(() => ({ added: 0, total: 0 }));
|
|
650
|
+
const count = reload();
|
|
651
|
+
return send(200, { bound: true, login: me.login, repos: count, adopted: adopted.added });
|
|
652
|
+
}
|
|
653
|
+
return send(200, await authState());
|
|
654
|
+
}
|
|
655
|
+
// 保留给命令行/打包脚本:本机已经登录过 gh 时直接接管这个账号,界面不再提供这条路
|
|
656
|
+
if (url.pathname === "/api/auth/gh" && req.method === "POST") {
|
|
657
|
+
const token = resolveToken(readConfig());
|
|
658
|
+
const me = await whoami(token);
|
|
659
|
+
if (!me) return send(400, { error: "这台机器上没有可用的 gh 登录" });
|
|
660
|
+
saveToken(token, me.login);
|
|
661
|
+
const adopted = await adoptAccount(token, me.login).catch(() => ({ added: 0 }));
|
|
662
|
+
return send(200, { bound: true, login: me.login, repos: reload(), adopted: adopted.added });
|
|
663
|
+
}
|
|
664
|
+
// 浏览器授权:一次点击 → 屏幕上给一次性码 + 打开 GitHub 确认页。
|
|
665
|
+
// 谁登的 GitHub 就绑谁,不读本机已有登录,别人打开不会绑到这台机器的账号上。
|
|
666
|
+
if (url.pathname === "/api/auth/login" && req.method === "POST") {
|
|
667
|
+
try {
|
|
668
|
+
return send(200, await loginStart());
|
|
669
|
+
} catch (e) {
|
|
670
|
+
return send(400, { error: String(e.message || e) });
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
if (url.pathname === "/api/auth/login/poll" && req.method === "POST") {
|
|
674
|
+
let raw = "";
|
|
675
|
+
for await (const chunk of req) raw += chunk;
|
|
676
|
+
const body = JSON.parse(raw || "{}");
|
|
677
|
+
if (body.mode === "device") {
|
|
678
|
+
if (!body.deviceCode) return send(400, { error: "缺 deviceCode" });
|
|
679
|
+
const out = await devicePoll(body.deviceCode);
|
|
680
|
+
if (out.status === "ok") {
|
|
681
|
+
await adoptAccount(resolveToken(readConfig()), out.login).catch(() => null);
|
|
682
|
+
return send(200, { ...out, repos: reload(), ...(await authState()) });
|
|
683
|
+
}
|
|
684
|
+
return send(200, out);
|
|
685
|
+
}
|
|
686
|
+
const out = loginPoll(body.id);
|
|
687
|
+
if (out.status === "ok") return send(200, { ...out, repos: reload(), ...(await authState()) });
|
|
688
|
+
return send(200, out);
|
|
689
|
+
}
|
|
690
|
+
if (url.pathname === "/api/auth/device" && req.method === "POST") {
|
|
691
|
+
try {
|
|
692
|
+
return send(200, await deviceStart());
|
|
693
|
+
} catch (e) {
|
|
694
|
+
return send(400, { error: String(e.message || e) });
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
if (url.pathname === "/api/auth/poll" && req.method === "POST") {
|
|
698
|
+
let raw = "";
|
|
699
|
+
for await (const chunk of req) raw += chunk;
|
|
700
|
+
const body = JSON.parse(raw || "{}");
|
|
701
|
+
if (!body.deviceCode) return send(400, { error: "缺 deviceCode" });
|
|
702
|
+
const out = await devicePoll(body.deviceCode);
|
|
703
|
+
if (out.status === "ok") {
|
|
704
|
+
await adoptAccount(resolveToken(readConfig()), out.login).catch(() => null);
|
|
705
|
+
return send(200, { ...out, repos: reload(), ...(await authState()) });
|
|
706
|
+
}
|
|
707
|
+
return send(200, out);
|
|
708
|
+
}
|
|
709
|
+
if (url.pathname === "/api/repos") {
|
|
710
|
+
return send(200, targets.length && boundExplicit() ? repoRows() : []);
|
|
711
|
+
}
|
|
712
|
+
// 没绑账号(或只剩本机 gh 的登录,用户自己没授权过)时给空载荷,前端只显示绑定页
|
|
713
|
+
const bound = boundExplicit();
|
|
714
|
+
if ((!targets.length || !bound) && /^\/api\/(data|summary|ask|sync)$/.test(url.pathname)) {
|
|
715
|
+
return send(200, { empty: true, needsBinding: true, totals: {}, series: [], range: { days } });
|
|
716
|
+
}
|
|
112
717
|
if (url.pathname === "/api/data") {
|
|
113
|
-
|
|
718
|
+
const windowDays = Number(url.searchParams.get("days") || days);
|
|
719
|
+
const rawKey = url.searchParams.get("repo");
|
|
720
|
+
const key = resolveKey(rawKey);
|
|
721
|
+
if (key === null) return send(404, { error: noRepo(rawKey), repo: rawKey });
|
|
722
|
+
// 绑定之后、第一次同步落盘之前快照是空的:标出来,让前端显示进度而不是一屏 0
|
|
723
|
+
const seeded = Object.values(store.repos).some((r) => Object.keys(r?.days || {}).length || (r?.stars || []).length);
|
|
724
|
+
return send(200, seeded ? build(windowDays, key) : { ...build(windowDays, key), empty: true });
|
|
725
|
+
}
|
|
726
|
+
if (url.pathname === "/api/progress") {
|
|
727
|
+
return send(200, { ...syncProgress, intervalHours, contribMinutes });
|
|
114
728
|
}
|
|
115
729
|
if (url.pathname === "/api/sync" && req.method === "POST") {
|
|
116
730
|
return send(200, await sync());
|
|
117
731
|
}
|
|
118
732
|
if (url.pathname === "/api/summary") {
|
|
119
733
|
const windowDays = Number(url.searchParams.get("days") || days);
|
|
120
|
-
const
|
|
121
|
-
const
|
|
734
|
+
const rawKey = url.searchParams.get("repo");
|
|
735
|
+
const key = resolveKey(rawKey);
|
|
736
|
+
if (key === null) return send(404, { error: noRepo(rawKey) });
|
|
737
|
+
const data = build(windowDays, key);
|
|
738
|
+
const winViews = data.series.reduce((a, r) => a + (r.v ?? 0), 0);
|
|
739
|
+
const single = data.range.days === 1 ? data.series[0] : null;
|
|
740
|
+
const ctx = {
|
|
122
741
|
days: windowDays,
|
|
123
|
-
|
|
124
|
-
|
|
742
|
+
// 日历跨度会把「今天还没采集到」算成一天;只承诺真正有数据的天数
|
|
743
|
+
span: Math.max(1, Math.min(windowDays, data.range.covered || windowDays)),
|
|
744
|
+
day: single ? single.d : null,
|
|
745
|
+
covered: data.range.covered,
|
|
746
|
+
uniques: single ? single.u : data.totals.uniques,
|
|
747
|
+
// 1 天窗口的访客是当天去重,不能按 14 天去重去折算用户规模
|
|
748
|
+
uniqSpan: single ? 1 : Math.min(data.range.covered || 14, 14),
|
|
749
|
+
views: single ? single.v : winViews,
|
|
125
750
|
external: data.contributions,
|
|
126
751
|
stars: data.repo.stars,
|
|
752
|
+
starGrowth: data.starGrowth,
|
|
127
753
|
npmWeek: data.totals.npmWeek,
|
|
754
|
+
// 漏斗自带 14 天窗口;没有 npm 包的仓把下载写成 null,别拿 0 冒充
|
|
755
|
+
funnel: data.funnel ? { ...data.funnel, npm: data.repo?.npmPkg === null ? null : data.funnel.npm } : null,
|
|
128
756
|
paths: data.paths,
|
|
129
|
-
|
|
130
|
-
|
|
757
|
+
scope: key === ALL ? `你的 ${targets.length} 个仓库` : key,
|
|
758
|
+
};
|
|
759
|
+
// 数据一同步,旧的摘要就该作废,否则会拿上一版的星数继续讲
|
|
760
|
+
const ck = `${key}|${windowDays}|${data.updatedAt || ""}`;
|
|
761
|
+
const hit = SUM_CACHE.get(ck);
|
|
762
|
+
const now = Date.now();
|
|
763
|
+
if (hit?.val && now - hit.at < 300000) return send(200, hit.val);
|
|
764
|
+
if (!hit?.busy) {
|
|
765
|
+
SUM_CACHE.set(ck, { at: hit?.at || 0, val: hit?.val || null, busy: true });
|
|
766
|
+
if (SUM_CACHE.size > 200) SUM_CACHE.clear();
|
|
767
|
+
aiSummary(ctx)
|
|
768
|
+
.then((r) => SUM_CACHE.set(ck, { at: Date.now(), val: r, busy: false }))
|
|
769
|
+
.catch((e) => {
|
|
770
|
+
console.error("summary failed", key, windowDays, e?.message || e);
|
|
771
|
+
SUM_CACHE.set(ck, { at: hit?.at || 0, val: hit?.val || null, busy: false });
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
return send(200, hit?.val || { source: "template", lines: templateSummary(ctx) });
|
|
775
|
+
}
|
|
776
|
+
if (url.pathname === "/api/ask" && req.method === "POST") {
|
|
777
|
+
let raw = "";
|
|
778
|
+
for await (const chunk of req) raw += chunk;
|
|
779
|
+
const body = JSON.parse(raw || "{}");
|
|
780
|
+
const question = String(body.question || "").trim();
|
|
781
|
+
if (!question) return send(400, { error: "缺少问题" });
|
|
782
|
+
const windowDays = Number(body.days || days);
|
|
783
|
+
const rawKey = body.repo;
|
|
784
|
+
const key = resolveKey(rawKey);
|
|
785
|
+
if (key === null) return send(200, { answer: noRepo(rawKey), source: "data" });
|
|
786
|
+
const data = build(windowDays, key);
|
|
787
|
+
const allData = key === ALL ? null : build(windowDays, ALL);
|
|
788
|
+
// 「有没有没处理的」这类问题不该由模型凭窗口数据猜:窗口外的老 issue 会让它答「都处理了」。
|
|
789
|
+
// 直接读实时清单,答案和链接都来自数据本身。
|
|
790
|
+
if (/未处理|没处理|未回|没回|待处理|待办|没人回|没有回|没合|未合并|没合并/i.test(question)) {
|
|
791
|
+
const op = data.contributions?.open;
|
|
792
|
+
const scope = key === ALL ? `全部 ${targets.length} 个仓库` : key;
|
|
793
|
+
if (!op) return send(200, { answer: `${scope}的未处理清单还没同步到,先刷新一次。`, source: "data" });
|
|
794
|
+
const rows = [
|
|
795
|
+
...op.issues.map((x) => ({ ...x, kind: "issue" })),
|
|
796
|
+
...op.pulls.map((x) => ({ ...x, kind: "PR" })),
|
|
797
|
+
];
|
|
798
|
+
// 一个都别丢:没回的和没合的全都给出链接,不截断成「最新 5 个」
|
|
799
|
+
const links = rows.map((x) => ({
|
|
800
|
+
label: `${(x.repo || "").split("/")[1] || "本仓"} #${x.number} ${x.kind}`,
|
|
801
|
+
url: x.url,
|
|
802
|
+
}));
|
|
803
|
+
const noReply = op.issues.filter((x) => !((x.comments || 0) > 0)).length;
|
|
804
|
+
// 两侧都写出来:问 PR 的时候不能只回 issue 的数
|
|
805
|
+
const head = [
|
|
806
|
+
op.issues.length
|
|
807
|
+
? (noReply === op.issues.length
|
|
808
|
+
? `${op.issues.length} 个 issue 没人回`
|
|
809
|
+
: (noReply === 0
|
|
810
|
+
? `${op.issues.length} 个 issue 还开着(都有回复)`
|
|
811
|
+
: `${op.issues.length} 个 issue 还开着(${noReply} 个没人回)`))
|
|
812
|
+
: "没有还开着的 issue",
|
|
813
|
+
op.pulls.length ? `${op.pulls.length} 个 PR 没合` : "没有没合的 PR",
|
|
814
|
+
].join(",");
|
|
815
|
+
if (!rows.length) {
|
|
816
|
+
// GitHub 的 open_issues_count 含 PR、也含已经回过话的老单,和这份「没人回」清单不是一个口径
|
|
817
|
+
const counter = Number(data.repo?.openIssues || 0);
|
|
818
|
+
const tail = counter ? `(GitHub 计数 ${counter} 个,含 PR 和回过话的老单)` : "";
|
|
819
|
+
return send(200, { answer: `${scope}:没有还开着的 issue,也没有没合的 PR${tail}。`, source: "data" });
|
|
820
|
+
}
|
|
821
|
+
return send(200, { answer: `${scope}:${head}。`, links, source: "data" });
|
|
822
|
+
}
|
|
823
|
+
// 排名类问题直接算,不花几十秒等模型:数据都在手里,答案和链接都准确。
|
|
824
|
+
const num = (x) => Number(x || 0).toLocaleString("en-US");
|
|
825
|
+
const rankBy = (metric) =>
|
|
826
|
+
targets
|
|
827
|
+
.map((t) => {
|
|
828
|
+
const d = build(windowDays, t.key);
|
|
829
|
+
return { key: t.key, name: t.name, v: metric(d) };
|
|
830
|
+
})
|
|
831
|
+
.filter((r) => r.v > 0)
|
|
832
|
+
.sort((a, b) => b.v - a.v)
|
|
833
|
+
.slice(0, 3);
|
|
834
|
+
// 「发版后哪个涨得多」里也有「浏览」,别被流量排名抢走
|
|
835
|
+
if (!/发版|发布|版本/.test(question) && /最热|流量最高|浏览最多|哪个(仓库|项目).*(流量|浏览)/.test(question)) {
|
|
836
|
+
const rows = rankBy((d) => d.totals.views);
|
|
837
|
+
if (!rows.length) return send(200, { answer: "这段时间还没有浏览记录。", source: "data" });
|
|
838
|
+
const body = rows.map((r, i) => `${["", "其次 ", "再次 ", "还有 "][Math.min(i, 3)]}${r.name} ${num(r.v)} 次浏览`).join(",");
|
|
839
|
+
const cov = data.range.covered || windowDays;
|
|
840
|
+
const spanTxt = cov < windowDays ? `${cov} 天(图上选了 ${windowDays} 天,其余没数据)` : `${windowDays} 天`;
|
|
841
|
+
const own = key === ALL ? "" : `本仓近 ${spanTxt} ${num(data.totals.views)} 次浏览;全站`;
|
|
842
|
+
return send(200, { answer: `${own || "近 " + windowDays + " 天"}浏览最多:${body}。`, links: rows.map((r) => ({ label: r.name, url: `https://github.com/${r.key}` })), source: "data" });
|
|
843
|
+
}
|
|
844
|
+
if (/访客最多|哪个(仓库|项目).*(访客|人数)/.test(question)) {
|
|
845
|
+
const rows = rankBy((d) => d.totals.uniques);
|
|
846
|
+
if (!rows.length) return send(200, { answer: "这段时间还没有访客记录。", source: "data" });
|
|
847
|
+
const body = rows.map((r, i) => `${["", "其次 ", "再次 ", "还有 "][Math.min(i, 3)]}${r.name} ${num(r.v)} 位访客`).join(",");
|
|
848
|
+
const own = key === ALL ? "" : `本仓 ${num(data.totals.uniques)} 位访客;全站`;
|
|
849
|
+
return send(200, { answer: `${own || "近 " + Math.min(data.range.covered || 14, 14) + " 天"}访客最多:${body}。`, links: rows.map((r) => ({ label: r.name, url: `https://github.com/${r.key}` })), source: "data" });
|
|
850
|
+
}
|
|
851
|
+
if (/star|关注数|收藏/.test(question)) {
|
|
852
|
+
const grown = /涨|增|新|多了|加/.test(question);
|
|
853
|
+
const askWho = /哪个|哪几个|最多|排行|谁/.test(question);
|
|
854
|
+
const sg = data.starGrowth;
|
|
855
|
+
const total = num(data.repo?.stars ?? 0);
|
|
856
|
+
const delta = sg && sg.delta != null ? `近 ${sg.span} 天 ${sg.delta > 0 ? "+" : ""}${num(sg.delta)} 个` : "";
|
|
857
|
+
// 面板已经选了某个仓,就先答这个仓,不拿全站排名冒充它
|
|
858
|
+
if (key !== ALL) {
|
|
859
|
+
return send(200, {
|
|
860
|
+
answer: `${key} 现在 ${total} 个 star${delta ? "," + delta : ""}。`,
|
|
861
|
+
links: [{ label: key, url: `https://github.com/${key}` }],
|
|
862
|
+
source: "data",
|
|
863
|
+
});
|
|
864
|
+
}
|
|
865
|
+
if (askWho && grown) {
|
|
866
|
+
const rows = rankBy((d) => d.starGrowth?.delta ?? 0);
|
|
867
|
+
if (!rows.length) return send(200, { answer: `近 ${windowDays} 天没有仓库涨 star(有 star 记录的只有 ${data.range.covered || windowDays} 天)。`, source: "data" });
|
|
868
|
+
const body = rows.map((r, i) => `${["", "其次 ", "再次 ", "还有 "][Math.min(i, 3)]}${r.name} +${num(r.v)}`).join(",");
|
|
869
|
+
return send(200, {
|
|
870
|
+
answer: `全站近 ${sg?.span ?? windowDays} 天新增 ${num(sg?.delta ?? 0)} 个 star,涨得最多:${body}。`,
|
|
871
|
+
links: rows.map((r) => ({ label: r.name, url: `https://github.com/${r.key}` })),
|
|
872
|
+
source: "data",
|
|
873
|
+
});
|
|
874
|
+
}
|
|
875
|
+
if (askWho) {
|
|
876
|
+
const rows = rankBy((d) => d.repo?.stars ?? 0);
|
|
877
|
+
if (!rows.length) return send(200, { answer: "还没有 star 记录。", source: "data" });
|
|
878
|
+
const body = rows.map((r, i) => `${["", "其次 ", "再次 ", "还有 "][Math.min(i, 3)]}${r.name} ${num(r.v)}`).join(",");
|
|
879
|
+
return send(200, {
|
|
880
|
+
answer: `全站现在共 ${total} 个 star,总数最多:${body}。`,
|
|
881
|
+
links: rows.map((r) => ({ label: r.name, url: `https://github.com/${r.key}` })),
|
|
882
|
+
source: "data",
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
return send(200, { answer: `全站现在共 ${total} 个 star${delta ? "," + delta : ""}。`, source: "data" });
|
|
886
|
+
}
|
|
887
|
+
if (/npm|下载/.test(question)) {
|
|
888
|
+
// 下载逐日按窗口存,问几天就答几天;没采到就说没采到,不拿 7 天滚动值顶
|
|
889
|
+
const spanTxt = data.range?.covered ? `近 ${Math.min(data.range.days, data.range.covered)} 天` : "最近";
|
|
890
|
+
if (key !== ALL) {
|
|
891
|
+
const w = data.totals.npm;
|
|
892
|
+
if (data.repo && data.repo.npmPkg === null) {
|
|
893
|
+
return send(200, { answer: `${key} 没有关联 npm 包。`, links: [{ label: key, url: `https://github.com/${key}` }], source: "data" });
|
|
894
|
+
}
|
|
895
|
+
if (w == null) return send(200, { answer: `${key} 这段窗口还没采集到 npm 下载。`, links: [{ label: key, url: `https://github.com/${key}` }], source: "data" });
|
|
896
|
+
return send(200, {
|
|
897
|
+
answer: w ? `${key} ${spanTxt} npm 下载 ${num(w)} 次。` : `${key} 这段窗口没有 npm 下载。`,
|
|
898
|
+
links: [{ label: key, url: `https://github.com/${key}` }],
|
|
899
|
+
source: "data",
|
|
900
|
+
});
|
|
901
|
+
}
|
|
902
|
+
const rows = rankBy((d) => d.totals.npm);
|
|
903
|
+
if (!rows.length) return send(200, { answer: `${spanTxt}还没有 npm 下载数据。`, source: "data" });
|
|
904
|
+
const body = rows.map((r, i) => `${["", "其次 ", "再次 ", "还有 "][Math.min(i, 3)]}${r.name} ${num(r.v)} 次`).join(",");
|
|
905
|
+
return send(200, { answer: `全站 ${spanTxt} npm 下载最多:${body}。`, links: rows.map((r) => ({ label: r.name, url: `https://github.com/${r.key}` })), source: "data" });
|
|
906
|
+
}
|
|
907
|
+
if (/发版|发布.*(效果|影响)|涨了多少/.test(question)) {
|
|
908
|
+
if (key !== ALL) {
|
|
909
|
+
const it = data.impact;
|
|
910
|
+
if (!it || it.before?.views?.avg == null) return send(200, { answer: `${key} 近期的发版还看不出效果。`, source: "data" });
|
|
911
|
+
const b = Math.round(it.before.views.avg * 10) / 10, a = Math.round((it.after?.views?.avg ?? 0) * 10) / 10;
|
|
912
|
+
const pct = it.delta?.views != null ? `${it.delta.views >= 0 ? "+" : ""}${Math.round(it.delta.views)}%` : "";
|
|
913
|
+
// 前后窗口不一定等长(默认前 7 天、后 3 天),写出来才不会被当同期对比
|
|
914
|
+
const bd = it.before?.days, ad = it.after?.days;
|
|
915
|
+
const win = bd && ad && bd !== ad ? `(前 ${bd} 天 vs 后 ${ad} 天)` : "";
|
|
916
|
+
return send(200, {
|
|
917
|
+
answer: `${key} ${String(it.version).replace(/^v/i, "")} 发版前后,浏览日均 ${num(b)} → ${num(a)}${pct ? "(" + pct + ")" : ""}${win}。`,
|
|
918
|
+
links: [{ label: key, url: `https://github.com/${key}` }],
|
|
919
|
+
source: "data",
|
|
920
|
+
});
|
|
921
|
+
}
|
|
922
|
+
// 基线太小的仓,倍数只是噪声(0.3 → 12 也是 ×39),低于日均 5 次浏览的不参与排名
|
|
923
|
+
const rows = rankBy((d) => ((d.impact?.before?.views?.avg ?? 0) >= 5 ? (d.impact?.delta?.views ?? 0) : 0));
|
|
924
|
+
if (!rows.length) return send(200, { answer: "近期的发版还看不出效果。", source: "data" });
|
|
925
|
+
const body = rows
|
|
926
|
+
.map((r, i) => {
|
|
927
|
+
const im = data.impacts.find((x) => x.key === r.key);
|
|
928
|
+
const b = im?.before?.views?.avg, a = im?.after?.views?.avg;
|
|
929
|
+
const pair = b != null && a != null ? ` ${num(Math.round(b * 10) / 10)} → ${num(Math.round(a * 10) / 10)}` : "";
|
|
930
|
+
return `${["", "其次 ", "再次 ", "还有 "][Math.min(i, 3)]}${r.name}${pair}`;
|
|
931
|
+
})
|
|
932
|
+
.join(",");
|
|
933
|
+
// 排名口径写在答案里:按浏览日均涨幅、日均不到 5 次的不参与、前后窗口不等长
|
|
934
|
+
const im0 = data.impacts.find((x) => x.before?.days && x.after?.days);
|
|
935
|
+
const relWin = im0 && im0.before.days !== im0.after.days ? `;前 ${im0.before.days} 天 vs 后 ${im0.after.days} 天` : "";
|
|
936
|
+
return send(200, { answer: `全站发版后浏览涨得最多:${body}。(按发版前后浏览日均的涨幅排,日均不到 5 次的不参与${relWin})`, links: rows.map((r) => ({ label: r.name, url: `https://github.com/${r.key}` })), source: "data" });
|
|
937
|
+
}
|
|
938
|
+
const topRepos = key === ALL ? null : targets
|
|
939
|
+
.map((t) => ({ name: t.name, u: repoStore(store, t.key).meta?.views?.uniques ?? 0 }))
|
|
940
|
+
.sort((a, b) => b.u - a.u)
|
|
941
|
+
.slice(0, 5);
|
|
942
|
+
const ans = await askQuestion(
|
|
943
|
+
{
|
|
944
|
+
allTotal: allData ? allData.totals.uniques : null,
|
|
945
|
+
topRepos,
|
|
946
|
+
days: windowDays,
|
|
947
|
+
covered: data.range.covered,
|
|
948
|
+
day: data.range.days === 1 ? data.series[0]?.d ?? null : null,
|
|
949
|
+
// 单日窗口的访客是当天去重,估算跨度得跟着它走,否则会被当成 14 天去重量
|
|
950
|
+
uniqSpan: data.range.days === 1 ? 1 : Math.min(data.range.covered || 14, 14),
|
|
951
|
+
uniques: data.range.days === 1 ? data.series[0]?.u ?? data.totals.uniques : data.totals.uniques,
|
|
952
|
+
views: data.range.days === 1 ? data.series[0]?.v ?? data.totals.views : data.totals.views,
|
|
953
|
+
external: data.contributions,
|
|
954
|
+
impact: data.impact,
|
|
955
|
+
funnel: data.funnel,
|
|
956
|
+
impacts: data.impacts,
|
|
957
|
+
stars: data.repo.stars,
|
|
958
|
+
starGrowth: data.starGrowth,
|
|
959
|
+
npmWeek: data.totals.npmWeek,
|
|
960
|
+
paths: data.paths,
|
|
961
|
+
scope: key === ALL ? `你的 ${targets.length} 个仓库` : key,
|
|
962
|
+
},
|
|
963
|
+
question,
|
|
964
|
+
[
|
|
965
|
+
{
|
|
966
|
+
name: "traffic",
|
|
967
|
+
description: "查一段时间内某个仓库或全部仓库的访客、浏览、外部 issue/PR、stars、npm 周下载",
|
|
968
|
+
parameters: { type: "object", properties: { days: { type: "integer", description: "7、30 或 90" }, repo: { type: "string", description: "owner/name,不填就是当前面板范围" } } },
|
|
969
|
+
run: ({ days: d, repo }) => {
|
|
970
|
+
const dd = [7, 30, 90].includes(Number(d)) ? Number(d) : windowDays;
|
|
971
|
+
const k2 = repo && targets.some((t) => t.key === repo) ? repo : key;
|
|
972
|
+
const data = build(dd, k2);
|
|
973
|
+
return {
|
|
974
|
+
scope: k2 === ALL ? "全部仓库" : k2,
|
|
975
|
+
days: dd,
|
|
976
|
+
covered: data.range.covered,
|
|
977
|
+
visitors: data.totals.uniques,
|
|
978
|
+
views: data.totals.views,
|
|
979
|
+
issues: data.contributions.issues.length,
|
|
980
|
+
pulls: data.contributions.pulls.length,
|
|
981
|
+
openIssues: data.contributions.open?.issues?.length ?? null,
|
|
982
|
+
openPulls: data.contributions.open?.pulls?.length ?? null,
|
|
983
|
+
contribAt: data.contributions.at || null,
|
|
984
|
+
stars: data.repo.stars,
|
|
985
|
+
starGrowth: data.starGrowth,
|
|
986
|
+
npmWeek: data.totals.npmWeek,
|
|
987
|
+
impact: data.impact,
|
|
988
|
+
topPaths: data.paths.slice(0, 3),
|
|
989
|
+
};
|
|
990
|
+
},
|
|
991
|
+
},
|
|
992
|
+
{ name: "list_repos", description: "列出看板绑定的所有仓库", parameters: { type: "object", properties: {} }, run: () => targets.map((t) => t.key) },
|
|
993
|
+
{
|
|
994
|
+
name: "daily",
|
|
995
|
+
description: "按天查浏览/访客曲线,用来回答哪天下滑或上涨",
|
|
996
|
+
parameters: { type: "object", properties: { days: { type: "integer", description: "7、30 或 90" }, repo: { type: "string", description: "owner/name,不填就是当前面板范围" } } },
|
|
997
|
+
run: ({ days: d, repo }) => {
|
|
998
|
+
const dd = [7, 30, 90].includes(Number(d)) ? Number(d) : windowDays;
|
|
999
|
+
const k2 = repo && targets.some((t) => t.key === repo) ? repo : key;
|
|
1000
|
+
return build(dd, k2).series.map((r) => `${r.d.slice(5)} 浏览${r.v ?? 0} 访客${r.u ?? 0}`).join(",")
|
|
1001
|
+
+ "(访客是当天去重人数,加起来会大于整段去重人数;最后一天常是当天,还没同步完,别当成下滑)";
|
|
1002
|
+
},
|
|
1003
|
+
},
|
|
1004
|
+
{
|
|
1005
|
+
name: "activity",
|
|
1006
|
+
description: "查外部 issue 和 PR 的明细:编号、标题、作者、状态、是否合并、时间、链接",
|
|
1007
|
+
parameters: { type: "object", properties: { repo: { type: "string", description: "owner/name,不填就是当前面板范围" } } },
|
|
1008
|
+
run: ({ repo }) => {
|
|
1009
|
+
const k2 = repo && targets.some((t) => t.key === repo) ? repo : key;
|
|
1010
|
+
const d = build(windowDays, k2).contributions;
|
|
1011
|
+
const pick = (x, kind) => ({ kind, n: x.number, title: x.title, by: x.author, state: x.merged ? "merged" : x.state, at: x.mergedAt || x.closedAt || x.createdAt, url: x.url });
|
|
1012
|
+
const all = [...d.pulls.map((x) => pick(x, "PR")), ...d.issues.map((x) => pick(x, "issue"))];
|
|
1013
|
+
// 还开着/没合的单子可能落在窗口外,明细里必须带上,不然模型只能报个数
|
|
1014
|
+
const openItems = [
|
|
1015
|
+
...(d.open?.pulls || []).map((x) => ({ ...pick(x, "PR"), repo: x.repo, comments: x.comments ?? 0 })),
|
|
1016
|
+
...(d.open?.issues || []).map((x) => ({ ...pick(x, "issue"), repo: x.repo, comments: x.comments ?? 0 })),
|
|
1017
|
+
];
|
|
1018
|
+
return {
|
|
1019
|
+
total: all.length,
|
|
1020
|
+
open: { issues: d.open?.issues?.length ?? null, pulls: d.open?.pulls?.length ?? null },
|
|
1021
|
+
openItems: openItems.slice(0, 30),
|
|
1022
|
+
items: all.slice(0, 30),
|
|
1023
|
+
};
|
|
1024
|
+
},
|
|
1025
|
+
},
|
|
1026
|
+
{
|
|
1027
|
+
name: "sync",
|
|
1028
|
+
description: "实时拉一次某个仓库的最新流量,几秒",
|
|
1029
|
+
parameters: { type: "object", properties: { repo: { type: "string", description: "owner/name" } }, required: ["repo"] },
|
|
1030
|
+
run: async ({ repo }) => {
|
|
1031
|
+
const t = targets.find((x) => x.key === repo);
|
|
1032
|
+
if (!t) return "没有这个仓库";
|
|
1033
|
+
await syncOne(t);
|
|
1034
|
+
const s2 = repoStore(store, t.key);
|
|
1035
|
+
return { repo: t.key, syncedAt: s2.meta?.syncedAt, visitors: s2.meta?.views?.uniques, error: s2.meta?.error || null };
|
|
1036
|
+
},
|
|
1037
|
+
},
|
|
1038
|
+
],
|
|
1039
|
+
);
|
|
1040
|
+
return send(200, ans);
|
|
131
1041
|
}
|
|
132
1042
|
if (url.pathname === "/api/config") {
|
|
133
1043
|
if (req.method === "POST") {
|
|
@@ -153,6 +1063,10 @@ export function createApp({ repo, days = 7 } = {}) {
|
|
|
153
1063
|
return {
|
|
154
1064
|
server,
|
|
155
1065
|
sync,
|
|
1066
|
+
syncContribs,
|
|
1067
|
+
build,
|
|
1068
|
+
reload,
|
|
1069
|
+
count: () => targets.length,
|
|
156
1070
|
listen(port = 4317, host = "127.0.0.1") {
|
|
157
1071
|
return new Promise((resolve) => server.listen(port, host, () => resolve(server.address())));
|
|
158
1072
|
},
|