qq-bot-roost 1.0.12 → 1.0.13

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/gitee.js CHANGED
@@ -27,6 +27,7 @@
27
27
  import fs from 'node:fs/promises';
28
28
  import path from 'node:path';
29
29
  import { createLogger } from './logger.js';
30
+ import { netFetch } from './proxy.js';
30
31
 
31
32
  const log = createLogger('gitee');
32
33
 
@@ -82,7 +83,7 @@ async function fetchBlob(repo, sha, token = '', timeoutMs = 120000) {
82
83
  const q = new URLSearchParams();
83
84
  if (token) q.set('access_token', token);
84
85
  const url = `${giteeBlobUrl(repo, sha)}?${q}`;
85
- const res = await fetch(url, {
86
+ const res = await netFetch(url, {
86
87
  headers: { 'User-Agent': UA, accept: 'application/json' },
87
88
  signal: AbortSignal.timeout(Math.min(timeoutMs, 30000)),
88
89
  });
@@ -135,7 +136,7 @@ export async function fetchGiteeTree({
135
136
  const apiUrl = `${API}/repos/${repo}/git/trees/${encodeURIComponent(ref)}?${q}`;
136
137
  let tree;
137
138
  try {
138
- const res = await fetch(apiUrl, {
139
+ const res = await netFetch(apiUrl, {
139
140
  headers: { 'User-Agent': UA, accept: 'application/json' },
140
141
  signal: AbortSignal.timeout(Math.min(timeoutMs, 30000)),
141
142
  });
@@ -187,7 +188,7 @@ export async function fetchGiteeTree({
187
188
  let lastErr = null;
188
189
  for (let attempt = 1; attempt <= FILE_RETRIES; attempt++) {
189
190
  try {
190
- res = await fetch(giteeRawUrl(repo, ref, f.path), {
191
+ res = await netFetch(giteeRawUrl(repo, ref, f.path), {
191
192
  headers: { 'User-Agent': UA },
192
193
  signal: AbortSignal.timeout(timeoutMs),
193
194
  });
@@ -273,7 +274,7 @@ export async function detectGiteeRef(repo, probe = 'package.json') {
273
274
  const errors = [];
274
275
  for (const ref of ['master', 'main']) {
275
276
  try {
276
- const res = await fetch(giteeRawUrl(repo, ref, probe), {
277
+ const res = await netFetch(giteeRawUrl(repo, ref, probe), {
277
278
  headers: { 'User-Agent': UA },
278
279
  signal: AbortSignal.timeout(10000),
279
280
  });
package/src/main.js CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  import { DIRS, PATHS, botPaths, listBotIds, ensureDirs, rel } from './paths.js';
16
16
  import { createLogger, setLevel, getLevel, attachLogFile, flushLogs } from './logger.js';
17
17
  import { configureMirror } from './mirror.js';
18
+ import { configureProxy } from './proxy.js';
18
19
  import { BotRuntime, pluginAllowedIn } from './bot.js';
19
20
  import { toggleGroupPlugin, resetGroupPlugins, describeGroupScope } from './plugin/groupscope.js';
20
21
  import { runtime, sanitizePayload } from './runtime.js';
@@ -1021,6 +1022,8 @@ async function main() {
1021
1022
 
1022
1023
  // 下载源是全局的,模块里缓存一份,免得每个调用点都传配置
1023
1024
  configureMirror(globalCfg);
1025
+ // 代理同理:Node 的 fetch 不认系统代理,得自己接管(见 src/proxy.js)
1026
+ configureProxy(globalCfg);
1024
1027
  setLevel(globalCfg.logLevel);
1025
1028
  runtime.startedAt = Date.now();
1026
1029
 
package/src/mirror.js CHANGED
@@ -24,6 +24,7 @@
24
24
  * 逐文件拉(见 src/gitee.js)。这里的 `gitee` 映射只处理 raw 文件地址。
25
25
  */
26
26
  import { createLogger } from './logger.js';
27
+ import { netFetch } from './proxy.js';
27
28
 
28
29
  const log = createLogger('mirror');
29
30
 
@@ -264,7 +265,12 @@ export async function fetchViaMirror(url, init = {}) {
264
265
  for (let i = 0; i < candidates.length; i++) {
265
266
  const target = candidates[i];
266
267
  try {
267
- const res = await fetch(target, init);
268
+ /**
269
+ * 走 netFetch 而不是原生 fetch:Node 的 fetch 永远直连,而浏览器走系统代理。
270
+ * 不接管这一层,就会出现「浏览器能打开 raw、框架说连不上」——
271
+ * 见 src/proxy.js 开头那段实测记录。
272
+ */
273
+ const res = await netFetch(target, init);
268
274
  // 3xx:调用方多半在等 Location,不能当失败
269
275
  const accepted =
270
276
  res.ok ||
@@ -317,7 +323,7 @@ export async function probeMirrors({ timeoutMs = 6000, custom = current.custom }
317
323
  for (const probe of PROBE_FALLBACKS) {
318
324
  const target = applyMirror(probe, p, custom);
319
325
  try {
320
- const res = await fetch(target, {
326
+ const res = await netFetch(target, {
321
327
  signal: AbortSignal.timeout(timeoutMs),
322
328
  headers: { 'User-Agent': 'qq-bot-roost' },
323
329
  });
@@ -17,6 +17,23 @@ const log = createLogger('market');
17
17
  /** 同一个索引地址同时只允许一个请求在飞 */
18
18
  const indexInFlight = new Map();
19
19
 
20
+ /**
21
+ * 索引的内存缓存:`url -> { at, data }`。
22
+ *
23
+ * 为什么要有它:以前只有「并发去重 + 磁盘兜底」,等于**每次调用都真打一次网络**。
24
+ * 而面板上「插件列表」「检查更新」「市场页」是三个独立请求,各自都要索引;
25
+ * 国内直连 raw.githubusercontent.com 常常 8~11 秒才失败并切镜像(auto 模式),
26
+ * 于是进一次插件页就白等十几秒,页面整块空着。
27
+ *
28
+ * 60 秒是刻意的短:索引本身一天也变不了几次,但插件作者发完版会立刻开面板看,
29
+ * 等一分钟已经够难受了。
30
+ *
31
+ * **写路径(安装 / 更新 / 同步仓库)必须传 `maxAge: 0`**——否则刚发的新版本会被
32
+ * 这份缓存挡住,用户看到的是旧版本号,更新按钮显示「已是最新」。
33
+ */
34
+ const INDEX_TTL_MS = 60_000;
35
+ const indexCache = new Map();
36
+
20
37
  /** 官方插件仓库。改这里就能指向你自己的插件源 */
21
38
  export const DEFAULT_INDEX_URL =
22
39
  'https://raw.githubusercontent.com/tdcq9594/qq-bot-roost-plugins/main/index.json';
@@ -81,16 +98,25 @@ function assertSafeIndexUrl(raw) {
81
98
 
82
99
  /**
83
100
  * @param {string} [url]
84
- * @param {{trust?: object}} [opts] 信任策略;不传就按「没配公钥」处理(本版不验签)
101
+ * @param {{trust?: object, maxAge?: number}} [opts] 信任策略;`maxAge` 是内存缓存的新鲜期
102
+ * (毫秒,默认 60 秒;传 0 表示强制重新拉取,写路径必须这么传)
85
103
  */
86
104
  export async function fetchIndex(url = DEFAULT_INDEX_URL, opts = {}) {
87
105
  const key = String(url || DEFAULT_INDEX_URL);
88
106
  assertSafeIndexUrl(key);
107
+
108
+ const maxAge = Number.isFinite(opts.maxAge) ? Number(opts.maxAge) : INDEX_TTL_MS;
109
+ if (maxAge > 0) {
110
+ const hit = indexCache.get(key);
111
+ if (hit && Date.now() - hit.at < maxAge) return hit.data;
112
+ }
113
+
89
114
  const running = indexInFlight.get(key);
90
115
  if (running) return running;
91
116
 
92
117
  const task = fetchIndexOnce(key, opts)
93
118
  .then(async (data) => {
119
+ indexCache.set(key, { at: Date.now(), data });
94
120
  await writeIndexCache(key, data).catch(() => {});
95
121
  return data;
96
122
  })
@@ -99,6 +125,11 @@ export async function fetchIndex(url = DEFAULT_INDEX_URL, opts = {}) {
99
125
  const cached = await readIndexCache(key).catch(() => null);
100
126
  if (cached) {
101
127
  log.warn(`拉取插件市场失败(${e.message}),改用本地缓存(${cached.age})`);
128
+ /**
129
+ * **stale 结果不写进内存缓存。**
130
+ * 写进去的话,一次网络抖动就会让「离线数据」在 60 秒内被当成新鲜索引,
131
+ * 面板还可能据此说「已是最新」——而其实根本没连上。
132
+ */
102
133
  return { ...cached.data, stale: true, staleAge: cached.age };
103
134
  }
104
135
  throw e;
@@ -577,10 +608,17 @@ export function detectUpdates(indexPlugins, localVersions = {}) {
577
608
  * 否则某个插件在下载源上有个文件拉不动,整仓失败,更新其它插件也一起黄。
578
609
  *
579
610
  * @param {string[]} [only] 只拉这些路径前缀(目录以 `/` 结尾),透传给下载层
611
+ * @param {object} [index] 调用方已经拿到的索引(写路径刚 `fetchIndex(..., {maxAge:0})` 过),
612
+ * 传进来就不用再拉一次
580
613
  * @returns {Promise<{tmp:string, index:object}>}
581
614
  */
582
- export async function syncRepo({ repo, branch = 'main', indexUrl, only = null } = {}) {
583
- const index = await fetchIndex(indexUrl);
615
+ export async function syncRepo({ repo, branch = 'main', indexUrl, only = null, index: given = null } = {}) {
616
+ /**
617
+ * 这是**写路径**(装 / 更新),索引必须是新的:`maxAge: 0` 绕过内存缓存。
618
+ * 拿一份 60 秒前的索引去下仓库,会出现「索引说 4.4.6,下下来是 4.4.7」,
619
+ * 然后 sha256 对不上,用户以为仓库坏了。
620
+ */
621
+ const index = given ?? (await fetchIndex(indexUrl, { maxAge: 0 }));
584
622
  if (!repo) repo = index.repo;
585
623
  if (!repo) throw new Error('索引里缺少 repo 字段,无法同步');
586
624