github-overview 0.1.3 → 0.2.1

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/src/auth.mjs ADDED
@@ -0,0 +1,279 @@
1
+ import { readConfig, writeConfig, resolveToken } from "./config.mjs";
2
+ import { execFileSync, spawn } from "node:child_process";
3
+ import { randomUUID } from "node:crypto";
4
+
5
+ // 绑定 GitHub 账号有三条路,优先用最省事的:
6
+ // 1. 本机已经登录过 gh,直接借它的 token(零输入)
7
+ // 2. 设备码流:显示 8 位码,在浏览器里确认,不用手抄 token
8
+ // 3. 粘贴 PAT(没有 OAuth App 时的兜底)
9
+ // 设备码流需要一个公开的 client_id(OAuth App 的 ID,本身不是密钥)。
10
+ // 想开启就把 GITHUB_OAUTH_CLIENT_ID 写进环境变量或配置,不写就走 2、3 之外的兜底。
11
+ const GH = "https://github.com";
12
+ const API = "https://api.github.com";
13
+ const UA = "github-overview";
14
+
15
+ export function clientId(cfg = readConfig()) {
16
+ return process.env.GITHUB_OAUTH_CLIENT_ID || cfg.oauthClientId || "";
17
+ }
18
+
19
+ const json = async (res) => {
20
+ const text = await res.text();
21
+ try {
22
+ return JSON.parse(text);
23
+ } catch {
24
+ return { error: "bad_response", detail: text.slice(0, 120) };
25
+ }
26
+ };
27
+
28
+ export async function whoami(token) {
29
+ if (!token) return null;
30
+ const res = await fetch(`${API}/user`, {
31
+ headers: { accept: "application/vnd.github+json", "user-agent": UA, authorization: `Bearer ${token}` },
32
+ }).catch(() => null);
33
+ if (!res || !res.ok) return null;
34
+ const me = await json(res);
35
+ return me?.login ? { login: me.login, name: me.name || "", avatar: me.avatar_url || "" } : null;
36
+ }
37
+
38
+ // 绑定状态:返回谁在用、token 从哪来,但绝不回传 token 本身
39
+ export async function authState() {
40
+ const cfg = readConfig();
41
+ // 只有用户自己给过的凭据才算绑定:环境变量或这里存下的 token。
42
+ // 本机 gh 里躺着的登录不算——别人在这台电脑上打开,不该直接看到前一个人的账号。
43
+ const fromEnv = Boolean(process.env.GITHUB_TOKEN || process.env.GH_TOKEN);
44
+ const explicit = fromEnv || Boolean(cfg.token);
45
+ const me = explicit ? await whoami(resolveToken(cfg)) : null;
46
+ const source = !me ? "none" : fromEnv ? "env" : "config";
47
+ return {
48
+ bound: Boolean(me),
49
+ login: me?.login || null,
50
+ name: me?.name || "",
51
+ source,
52
+ deviceFlow: Boolean(clientId(cfg)),
53
+ // 前端据此决定主按钮走哪条路:浏览器授权 / 粘贴访问令牌
54
+ loginMode: loginMode(cfg),
55
+ repos: (cfg.repos || []).length,
56
+ };
57
+ }
58
+
59
+ export async function deviceStart() {
60
+ const id = clientId();
61
+ if (!id) throw new Error("改用访问令牌");
62
+ const res = await fetch(`${GH}/login/device/code`, {
63
+ method: "POST",
64
+ headers: { accept: "application/json", "content-type": "application/json", "user-agent": UA },
65
+ // repo 才能读私有仓的 traffic;read:user 只是为了显示绑定的是谁
66
+ body: JSON.stringify({ client_id: id, scope: "repo read:user" }),
67
+ }).catch((e) => {
68
+ throw new Error(`连不上 GitHub:${e.message}`);
69
+ });
70
+ const data = await json(res);
71
+ if (!data.device_code) {
72
+ throw new Error("GitHub 没给出授权码,稍后重试");
73
+ }
74
+ return {
75
+ userCode: data.user_code,
76
+ verifyUrl: data.verification_uri || `${GH}/login/device`,
77
+ interval: Math.max(5, Number(data.interval) || 5),
78
+ expiresIn: Number(data.expires_in) || 900,
79
+ deviceCode: data.device_code,
80
+ };
81
+ }
82
+
83
+ // 轮询一次:pending 就继续等,拿到 token 直接落盘(0600),不经过前端
84
+ export async function devicePoll(deviceCode) {
85
+ const id = clientId();
86
+ if (!id) throw new Error("改用访问令牌");
87
+ const res = await fetch(`${GH}/login/oauth/access_token`, {
88
+ method: "POST",
89
+ headers: { accept: "application/json", "content-type": "application/json", "user-agent": UA },
90
+ body: JSON.stringify({ client_id: id, device_code: deviceCode, grant_type: "urn:ietf:params:oauth:grant-type:device_code" }),
91
+ }).catch(() => null);
92
+ const data = res ? await json(res) : { error: "network" };
93
+ if (data.access_token) {
94
+ const me = await whoami(data.access_token);
95
+ if (!me) return { status: "error", message: "这个 token 读不到账号" };
96
+ saveToken(data.access_token, me.login);
97
+ return { status: "ok", login: me.login };
98
+ }
99
+ if (data.error === "authorization_pending" || data.error === "slow_down") return { status: "pending" };
100
+ if (data.error === "expired_token") return { status: "expired", message: "码过期了,重新开始" };
101
+ if (data.error === "access_denied") return { status: "denied", message: "你取消了这次授权" };
102
+ // 剩下的情况用户只需要知道再点一次;原文留给日志
103
+ console.warn("[auth] device poll:", data.error_description || data.error);
104
+ return { status: "error", message: "授权没完成,再点一次" };
105
+ }
106
+
107
+ // 把 token 写进配置;当前登录的 gh 账号也一并记下来,方便后面按账号列仓库
108
+ export function saveToken(token, login) {
109
+ const cfg = readConfig();
110
+ const next = { ...cfg, token };
111
+ if (login) next.user = login;
112
+ writeConfig(next);
113
+ return next;
114
+ }
115
+
116
+ // 绑定之后直接把账号名下自己有权推送的仓库填进去,不然用户还要再跑一次 init
117
+ export async function ownedRepos(token, login) {
118
+ const all = [];
119
+ for (let page = 1; page <= 10; page++) {
120
+ const res = await fetch(`${API}/user/repos?affiliation=owner&per_page=100&sort=pushed&page=${page}`, {
121
+ headers: { accept: "application/vnd.github+json", "user-agent": UA, authorization: `Bearer ${token}` },
122
+ }).catch(() => null);
123
+ if (!res || !res.ok) throw new Error(`拉取仓库失败:${res ? res.status : "网络"}`);
124
+ const rows = await json(res);
125
+ if (!Array.isArray(rows) || !rows.length) break;
126
+ all.push(...rows);
127
+ if (rows.length < 100) break;
128
+ }
129
+ return all
130
+ .filter((r) => !r.fork && (r.permissions ? r.permissions.push : true) && r.owner?.login?.toLowerCase() === String(login || r.owner?.login).toLowerCase())
131
+ .map((r) => ({ repo: r.full_name }));
132
+ }
133
+
134
+ // 绑定 + 首次填仓库合成一步:已有绑定就不覆盖
135
+ export async function adoptAccount(token, login) {
136
+ const cfg = readConfig();
137
+ if ((cfg.repos || []).length) return { added: 0, total: cfg.repos.length };
138
+ const repos = await ownedRepos(token, login);
139
+ if (!repos.length) return { added: 0, total: 0 };
140
+ const next = { ...cfg, token, user: login, repos };
141
+ delete next.repo;
142
+ delete next.npm;
143
+ writeConfig(next);
144
+ return { added: repos.length, total: repos.length };
145
+ }
146
+
147
+ // 有没有 git 命令行:有就能让 gh 自己开浏览器做设备码授权,不用我们注册 OAuth App
148
+ // 同步、不联网:只回答「用户自己给过凭据没有」,供每个请求快速判断要不要给数据
149
+ export function boundExplicit(cfg = readConfig()) {
150
+ if (process.env.GITHUB_TOKEN || process.env.GH_TOKEN) return true;
151
+ return Boolean(cfg.token);
152
+ }
153
+
154
+ export function hasGh() {
155
+ try {
156
+ execFileSync("gh", ["--version"], { encoding: "utf8", stdio: ["ignore", "ignore", "ignore"] });
157
+ return true;
158
+ } catch {
159
+ return false;
160
+ }
161
+ }
162
+
163
+ // gh 里可能存着好几个账号:必须拿到刚登录那一个,不能默认取当前活动的那个,
164
+ // 否则在别人电脑上(或本机已经登了别人)会把账号绑错。
165
+ function ghAccounts() {
166
+ try {
167
+ const raw = execFileSync("gh", ["auth", "status", "--json", "hosts"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
168
+ const rows = JSON.parse(raw)?.hosts?.["github.com"] || [];
169
+ return rows.map((r) => ({ login: r.login, active: Boolean(r.active) }));
170
+ } catch {
171
+ return [];
172
+ }
173
+ }
174
+
175
+ function ghTokenFor(login) {
176
+ const args = ["auth", "token", "--hostname", "github.com"];
177
+ if (login) args.push("--user", login);
178
+ try {
179
+ const token = execFileSync("gh", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
180
+ return token || null;
181
+ } catch {
182
+ return null;
183
+ }
184
+ }
185
+
186
+ // 浏览器登录:优先用我们自己的 OAuth App(能显示成这个应用),
187
+ // 没配就借 gh 的授权流程——同样是「浏览器里点一下确认」,但账号永远是当前的人自己登的
188
+ const LOGIN = new Map();
189
+
190
+ export function loginMode(cfg = readConfig()) {
191
+ if (clientId(cfg)) return "device";
192
+ if (hasGh()) return "gh";
193
+ return "paste";
194
+ }
195
+
196
+ export async function loginStart(cfg = readConfig()) {
197
+ if (clientId(cfg)) return { mode: "device", ...(await deviceStart()) };
198
+ if (!hasGh()) throw new Error("这台电脑只能用访问令牌");
199
+ const id = randomUUID();
200
+ const child = spawn("gh", ["auth", "login", "--web", "--hostname", "github.com", "--git-protocol", "https"], {
201
+ stdio: ["ignore", "pipe", "pipe"],
202
+ env: { ...process.env, NO_COLOR: "1", GH_PROMPT_DISABLED: "1", GH_NO_UPDATE_NOTIFIER: "1" },
203
+ });
204
+ const before = ghAccounts().map((a) => a.login);
205
+ const entry = { child, code: null, done: null, at: Date.now(), tail: "", before };
206
+ LOGIN.set(id, entry);
207
+ const watch = (buf) => {
208
+ entry.tail = (entry.tail + String(buf)).slice(-400);
209
+ const m = entry.tail.match(/([A-Z0-9]{4}-[A-Z0-9]{4})/);
210
+ if (m) entry.code = m[1];
211
+ };
212
+ child.stdout.on("data", watch);
213
+ child.stderr.on("data", watch);
214
+ child.on("error", () => { entry.done = { status: "error", message: "没能打开浏览器授权" }; });
215
+ child.on("close", (code) => {
216
+ if (entry.done) return;
217
+ if (code !== 0) {
218
+ entry.done = { status: "denied", message: "没有完成授权,再点一次" };
219
+ return;
220
+ }
221
+ try {
222
+ const now = ghAccounts();
223
+ const fresh = now.find((a) => !before.includes(a.login)) || now.find((a) => a.active) || null;
224
+ const token = ghTokenFor(fresh?.login) || ghTokenFor(null);
225
+ if (!token) {
226
+ entry.done = { status: "error", message: "没读到刚授权的账号" };
227
+ return;
228
+ }
229
+ whoami(token).then(async (me) => {
230
+ if (!me) {
231
+ entry.done = { status: "error", message: "读不到刚授权的账号" };
232
+ return;
233
+ }
234
+ saveToken(token, me.login);
235
+ const adopt = await adoptAccount(token, me.login).catch(() => null);
236
+ entry.done = { status: "ok", login: me.login, repos: adopt?.total ?? 0 };
237
+ }).catch((e) => { entry.done = { status: "error", message: e.message }; });
238
+ } catch (e) {
239
+ entry.done = { status: "error", message: e.message };
240
+ }
241
+ });
242
+ // 等 gh 把一次性码打出来,最多 15 秒
243
+ for (let i = 0; i < 60 && !entry.code && !entry.done; i++) await new Promise((r) => setTimeout(r, 250));
244
+ if (entry.done) {
245
+ LOGIN.delete(id);
246
+ throw new Error(entry.done.message || "没能开始授权");
247
+ }
248
+ if (!entry.code) {
249
+ child.kill("SIGTERM");
250
+ LOGIN.delete(id);
251
+ throw new Error("授权页没打开,再试一次");
252
+ }
253
+ return { mode: "gh", id, userCode: entry.code, verifyUrl: `${GH}/login/device`, interval: 3 };
254
+ }
255
+
256
+ // 轮询浏览器授权结果;成功后 token 已经落盘,前端只需要知道绑到了谁
257
+ export function loginPoll(id) {
258
+ const entry = LOGIN.get(id);
259
+ if (!entry) return { status: "error", message: "这次登录已结束,重新点一次" };
260
+ if (entry.done) {
261
+ LOGIN.delete(id);
262
+ return entry.done;
263
+ }
264
+ if (Date.now() - entry.at > 900000) {
265
+ entry.child.kill("SIGTERM");
266
+ LOGIN.delete(id);
267
+ return { status: "expired", message: "等太久了,重新点一次" };
268
+ }
269
+ return { status: "pending" };
270
+ }
271
+
272
+ export function ghAvailable() {
273
+ try {
274
+ const token = execFileSync("gh", ["auth", "token"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
275
+ return Boolean(token);
276
+ } catch {
277
+ return false;
278
+ }
279
+ }
package/src/config.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
1
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, chmodSync, renameSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { join, dirname } from "node:path";
4
4
  import { execFileSync } from "node:child_process";
@@ -18,7 +18,12 @@ export function readConfig() {
18
18
 
19
19
  export function writeConfig(next) {
20
20
  mkdirSync(dirname(CONFIG_PATH), { recursive: true });
21
- writeFileSync(CONFIG_PATH, JSON.stringify(next, null, 2) + "\n");
21
+ const tmp = `${CONFIG_PATH}.tmp`;
22
+ writeFileSync(tmp, JSON.stringify(next, null, 2) + "\n", { mode: 0o600 });
23
+ renameSync(tmp, CONFIG_PATH);
24
+ try {
25
+ chmodSync(CONFIG_PATH, 0o600);
26
+ } catch {}
22
27
  return next;
23
28
  }
24
29
 
@@ -52,7 +57,8 @@ export function normalizeConfig(raw = {}) {
52
57
  .filter((r) => r && r.repo)
53
58
  .map((r) => {
54
59
  const { owner, name } = parseRepo(r.repo);
55
- return { repo: `${owner}/${name}`, npm: r.npm || name };
60
+ // 只有手工写了 npm 才算绑定,否则留给 registry 核对归属
61
+ return { repo: `${owner}/${name}`, ...(r.npm ? { npm: r.npm } : {}) };
56
62
  });
57
63
  if (!cfg.user && cfg.repos.length) cfg.user = cfg.repos[0].repo.split("/")[0];
58
64
  return cfg;
@@ -65,6 +71,6 @@ export function parseRepos(spec) {
65
71
  .filter(Boolean)
66
72
  .map((s) => {
67
73
  const { owner, name } = parseRepo(s);
68
- return { repo: `${owner}/${name}`, npm: name };
74
+ return { repo: `${owner}/${name}` };
69
75
  });
70
76
  }
package/src/github.mjs CHANGED
@@ -1,11 +1,11 @@
1
1
  const API = "https://api.github.com";
2
2
 
3
3
  export function makeGithub(token, { owner, name }) {
4
- async function gh(path, { method = "GET", body } = {}) {
4
+ async function gh(path, { method = "GET", body, accept } = {}) {
5
5
  const res = await fetch(API + path, {
6
6
  method,
7
7
  headers: {
8
- accept: "application/vnd.github+json",
8
+ accept: accept || "application/vnd.github+json",
9
9
  "x-github-api-version": "2022-11-28",
10
10
  "user-agent": "github-overview",
11
11
  ...(token ? { authorization: `Bearer ${token}` } : {}),
@@ -30,6 +30,20 @@ export function makeGithub(token, { owner, name }) {
30
30
 
31
31
  const repoPath = `/repos/${owner}/${name}`;
32
32
 
33
+ // 列表页不会一次给全:翻到不满页为止,最多 5 页(500 条)
34
+ async function listPages(path, stop) {
35
+ const out = [];
36
+ for (let page = 1; page <= 5; page++) {
37
+ const rows = await gh(`${path}${path.includes("?") ? "&" : "?"}page=${page}`).catch(() => null);
38
+ // 第一页就失败说明这次没拿到,交给调用方保留上一次快照,别写成空
39
+ if (!rows) return page === 1 ? null : out;
40
+ if (!rows.length) break;
41
+ out.push(...rows);
42
+ if (rows.length < 100 || (stop && stop(rows.at(-1)))) break;
43
+ }
44
+ return out;
45
+ }
46
+
33
47
  return {
34
48
  owner,
35
49
  name,
@@ -49,46 +63,119 @@ export function makeGithub(token, { owner, name }) {
49
63
  description: r.description || "",
50
64
  };
51
65
  },
66
+ // 星标历史:带 star+json 才回 starred_at,据此算任意窗口的净增
67
+ async stargazers() {
68
+ const out = [];
69
+ for (let page = 1; page <= 10; page++) {
70
+ const rows = await gh(`${repoPath}/stargazers?per_page=100&page=${page}`, { accept: "application/vnd.github.star+json" });
71
+ if (!Array.isArray(rows) || !rows.length) break;
72
+ for (const r of rows) if (r.starred_at) out.push(String(r.starred_at).slice(0, 10));
73
+ if (rows.length < 100) break;
74
+ }
75
+ return out;
76
+ },
52
77
  // traffic endpoints need push access, and only keep 14 rolling days
53
78
  async views() { return gh(`${repoPath}/traffic/views?per=day`); },
54
79
  async clones() { return gh(`${repoPath}/traffic/clones?per=day`); },
55
80
  async referrers() { return gh(`${repoPath}/traffic/popular/referrers`); },
56
81
  async paths() { return gh(`${repoPath}/traffic/popular/paths`); },
57
82
  async releases() { return gh(`${repoPath}/releases?per_page=100`); },
83
+ // fork 自带创建时间:只取最新一页就够判断「最近有没有人 fork」
84
+ async forks() {
85
+ const rows = await gh(`${repoPath}/forks?per_page=100&sort=newest`);
86
+ if (!Array.isArray(rows)) return null;
87
+ return rows
88
+ .map((r) => ({ login: r.owner?.login || "ghost", at: r.created_at, url: r.html_url }))
89
+ .filter((r) => r.at)
90
+ .sort((x, y) => String(y.at).localeCompare(String(x.at)));
91
+ },
58
92
  // external-only: everything not authored by the repo owner (or self aliases)
59
- async activity(sinceIso, selfLogins = []) {
93
+ // 用 REST 列表而不是 search:search 有索引延迟,刚合并/关闭的状态要十几分钟才可见
94
+ // 真的没处理的活:还开着的 issue(含已经有过回复的)、还没合的 PR。
95
+ // 不能从 activity 窗口里筛——窗口外的老 issue 会让概览谎报「都已回复」
96
+ async openWork(selfLogins = []) {
97
+ const self = new Set([owner.toLowerCase(), ...selfLogins.map((x) => String(x).toLowerCase())]);
98
+ const [issueRows, pullRows] = await Promise.all([
99
+ listPages(`${repoPath}/issues?state=open&per_page=100`),
100
+ listPages(`${repoPath}/pulls?state=open&per_page=100`),
101
+ ]);
102
+ if (!issueRows || !pullRows) return null;
103
+ const out = { issues: [], pulls: [], at: new Date().toISOString() };
104
+ const norm = (it, comments) => {
105
+ const author = it.user?.login || "ghost";
106
+ if (it.user?.type === "Bot" || author.endsWith("[bot]")) return null;
107
+ if (self.has(author.toLowerCase())) return null;
108
+ return {
109
+ number: it.number,
110
+ title: it.title || "",
111
+ author,
112
+ comments: comments ?? 0,
113
+ createdAt: it.created_at,
114
+ updatedAt: it.updated_at,
115
+ url: it.html_url,
116
+ };
117
+ };
118
+ for (const it of issueRows || []) {
119
+ if (it.pull_request) continue;
120
+ const row = norm(it, it.comments);
121
+ if (row) out.issues.push(row);
122
+ }
123
+ for (const pr of pullRows || []) {
124
+ const row = norm(pr, pr.comments);
125
+ if (row) out.pulls.push(row);
126
+ }
127
+ const byNew = (a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt));
128
+ out.issues.sort(byNew);
129
+ out.pulls.sort(byNew);
130
+ return out;
131
+ },
132
+
133
+ async activity(sinceIso, selfLogins = []) {
60
134
  const self = new Set([owner.toLowerCase(), ...selfLogins.map(s => String(s).toLowerCase())]);
61
135
  const out = { issues: [], pulls: [], selfCount: 0 };
62
- for (let page = 1; page <= 5; page++) {
63
- const rows = await gh(
64
- `/search/issues?q=${encodeURIComponent(`repo:${owner}/${name} created:>=${sinceIso}`)}&per_page=100&page=${page}`
65
- );
66
- const items = rows.items || [];
67
- for (const it of items) {
68
- const kind = it.pull_request ? "pulls" : "issues";
69
- const author = it.user?.login || "ghost";
70
- if (self.has(author.toLowerCase())) { out.selfCount++; continue; }
71
- out[kind].push({
72
- number: it.number,
73
- title: it.title,
74
- author,
75
- state: it.state,
76
- createdAt: it.created_at,
77
- closedAt: it.closed_at,
78
- merged: Boolean(it.pull_request?.merged_at),
79
- mergedAt: it.pull_request?.merged_at || null,
80
- comments: it.comments,
81
- url: it.html_url,
82
- });
83
- }
84
- if (items.length < 100) break;
136
+ const byAuthor = (it) => {
137
+ const author = it.user?.login || "ghost";
138
+ if (it.user?.type === "Bot" || author.endsWith("[bot]")) { out.botCount = (out.botCount || 0) + 1; return null; }
139
+ if (self.has(author.toLowerCase())) { out.selfCount++; return null; }
140
+ return author;
141
+ };
142
+ const [issueRows, pullRows] = await Promise.all([
143
+ listPages(`${repoPath}/issues?state=all&since=${sinceIso}&per_page=100&sort=updated&direction=desc`),
144
+ listPages(`${repoPath}/pulls?state=all&sort=updated&direction=desc&per_page=100`, (last) => String(last.updated_at || last.created_at || "").slice(0, 10) < sinceIso),
145
+ ]);
146
+ if (!issueRows || !pullRows) return null;
147
+ for (const it of issueRows || []) {
148
+ if (it.pull_request) continue;
149
+ const author = byAuthor(it);
150
+ if (!author) continue;
151
+ out.issues.push({
152
+ number: it.number,
153
+ title: it.title,
154
+ author,
155
+ state: it.state,
156
+ createdAt: it.created_at,
157
+ closedAt: it.closed_at,
158
+ comments: it.comments,
159
+ url: it.html_url,
160
+ });
85
161
  }
86
- for (const pr of out.pulls) {
87
- try {
88
- const detail = await gh(`${repoPath}/pulls/${pr.number}`);
89
- pr.additions = detail.additions;
90
- pr.deletions = detail.deletions;
91
- } catch { /* older PRs can 404 on details; keep the row */ }
162
+ for (const pr of pullRows || []) {
163
+ const updated = String(pr.updated_at || pr.created_at || "").slice(0, 10);
164
+ if (sinceIso && updated && updated < sinceIso) continue;
165
+ const author = byAuthor(pr);
166
+ if (!author) continue;
167
+ out.pulls.push({
168
+ number: pr.number,
169
+ title: pr.title,
170
+ author,
171
+ state: pr.state,
172
+ createdAt: pr.created_at,
173
+ closedAt: pr.closed_at,
174
+ merged: Boolean(pr.merged_at),
175
+ mergedAt: pr.merged_at || null,
176
+ comments: pr.comments,
177
+ url: pr.html_url,
178
+ });
92
179
  }
93
180
  return out;
94
181
  },
@@ -98,8 +185,9 @@ export function makeGithub(token, { owner, name }) {
98
185
  const rows = await gh(`${path}?state=open&per_page=100`);
99
186
  return { available: true, open: Array.isArray(rows) ? rows.length : 0 };
100
187
  } catch (e) {
101
- // 403/404 means the feature is off or the token lacks scope: report, never throw
102
- return { available: false, open: null, reason: e.status === 404 ? "no-analysis" : "disabled" };
188
+ // 404: 仓库没开这个功能;403: 多半是 token 没权限;其它按错误处理
189
+ const reason = e.status === 404 ? "unsupported" : e.status === 403 ? "permission_denied" : "error";
190
+ return { available: false, open: null, reason, status: e.status ?? null };
103
191
  }
104
192
  };
105
193
  const [dependabot, codeScanning, secretScanning] = await Promise.all([
package/src/loop.mjs ADDED
@@ -0,0 +1,67 @@
1
+ // 同步节奏:CLI 和桌面端共用同一套,避免两边行为不一致。
2
+ // 绑定之前 targets 是空的,所以这里先盯着仓库数,一出现就立刻拉第一次。
3
+
4
+ export function startLoop(app, { intervalHours = 6, contribMinutes = 15, onLog = () => {} } = {}) {
5
+ let contribTimer = null;
6
+ let stopped = false;
7
+
8
+ const contribTick = async () => {
9
+ if (stopped) return;
10
+ try {
11
+ await app.syncContribs();
12
+ } catch (e) {
13
+ onLog(`贡献刷新失败:${e.message}`);
14
+ }
15
+ };
16
+
17
+ const tick = async () => {
18
+ if (stopped) return null;
19
+ if (!app.count()) return null;
20
+ try {
21
+ const out = await app.sync();
22
+ const failed = out.results.filter((r) => !r.ok);
23
+ onLog(`同步 ${out.syncedAt}${failed.length ? `,${failed.length} 个失败` : ""}`);
24
+ return out;
25
+ } catch (e) {
26
+ onLog(`同步失败:${e.message}`);
27
+ return null;
28
+ }
29
+ };
30
+
31
+ // 全量同步跑完再开高频通道,避免两边同时写同一份快照
32
+ const startContrib = () => {
33
+ if (contribTimer || stopped || contribMinutes <= 0) return;
34
+ contribTimer = setInterval(contribTick, Math.max(3, contribMinutes) * 60e3);
35
+ if (contribTimer.unref) contribTimer.unref();
36
+ };
37
+
38
+ const timer = setInterval(tick, Math.max(1, intervalHours) * 3600e3);
39
+ if (timer.unref) timer.unref();
40
+
41
+ let watch = null;
42
+ if (app.count()) {
43
+ tick().then(startContrib);
44
+ } else {
45
+ // 空配置:等前端绑完账号,仓库一出现就先拉一次,别等下一个周期
46
+ let seen = 0;
47
+ watch = setInterval(() => {
48
+ if (stopped) return;
49
+ const now = app.count();
50
+ if (now && now !== seen) {
51
+ seen = now;
52
+ tick().then(startContrib);
53
+ }
54
+ }, 2000);
55
+ if (watch.unref) watch.unref();
56
+ }
57
+
58
+ return {
59
+ tick,
60
+ stop() {
61
+ stopped = true;
62
+ clearInterval(timer);
63
+ if (watch) clearInterval(watch);
64
+ if (contribTimer) clearInterval(contribTimer);
65
+ },
66
+ };
67
+ }
package/src/npm.mjs CHANGED
@@ -23,6 +23,17 @@ export function makeNpm(pkg) {
23
23
  const safe = encodeURIComponent(pkg);
24
24
  return {
25
25
  pkg,
26
+ // 仓库名不等于 npm 包名时,先确认包归谁,别把同名包算进来
27
+ async maintainers() {
28
+ try {
29
+ const meta = await getJson(`${REGISTRY}/${safe}/latest`);
30
+ return { owners: (meta.maintainers || []).map((m) => String(m.name || "").toLowerCase()), version: meta.version || null };
31
+ } catch (e) {
32
+ // 包不存在和网络抖不一样:前者说明这个仓库没有 npm 包,别当成「有包但没采到」
33
+ if (e.status === 404) return { missing: true };
34
+ return null;
35
+ }
36
+ },
26
37
  async week() {
27
38
  try {
28
39
  return (await getJson(`${POINT}/last-week/${safe}`)).downloads ?? null;
@@ -51,17 +62,8 @@ export function makeNpm(pkg) {
51
62
  return [];
52
63
  }
53
64
  },
54
- async perVersion() {
55
- const list = await this.versions();
56
- const recent = list.slice(0, 3);
57
- const out = [];
58
- for (const v of recent) {
59
- try {
60
- const r = await getJson(`${POINT}/last-week/${encodeURIComponent(safe + "@" + v.version)}`);
61
- out.push({ version: v.version, downloads: r.downloads ?? 0 });
62
- } catch { /* unpublished or scoped edge case */ }
63
- }
64
- return out;
65
- },
65
+ // 曾有 perVersion(): 按版本查 last-week 下载。上游现在对 `pkg@ver` 一律回
66
+ // {"error":"package x@1.2.3 not found"},那条腿永远只能是空数组,已删除。
67
+ // 需要逐版本时间线就用 versions(),它读 registry 文档里的 time 表。
66
68
  };
67
69
  }