qq-bot-roost 1.0.11 → 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/README.md +3 -3
- package/package.json +3 -3
- package/src/bot.js +12 -0
- package/src/config.js +777 -759
- package/src/gitee.js +5 -4
- package/src/main.js +3 -0
- package/src/message.js +2 -0
- package/src/mirror.js +8 -2
- package/src/outbound.js +39 -0
- package/src/plugin/loader.js +42 -10
- package/src/plugin/market.js +41 -3
- package/src/plugin/runtime-errors.js +27 -0
- package/src/plugin/snapshot.js +64 -0
- package/src/proxy.js +675 -0
- package/src/runtime.js +18 -0
- package/src/services/config-watch.js +2 -0
- package/src/tarball.js +3 -2
- package/src/updater.js +2 -1
- package/src/web/server.js +3741 -3620
- package/web/app.js +4934 -4701
- package/web/index.html +1337 -1315
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
|
|
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
|
|
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
|
|
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
|
|
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/message.js
CHANGED
|
@@ -1061,6 +1061,8 @@ export function buildMessage(eventName, d, { api, cfg, outbound, session, traceI
|
|
|
1061
1061
|
return await send({ ...payload, ...(rid ? { requestId: rid } : {}) }, true);
|
|
1062
1062
|
} catch (e) {
|
|
1063
1063
|
log.error(`replyAuto 发送失败(${plan.mode}):`, e.message);
|
|
1064
|
+
/** 失败也要给诊断回调一个终态:只返回 null,调用方分不清「空内容」和「没发出去」 */
|
|
1065
|
+
report({ mode: plan.mode, ok: false, reason: 'send-failed', error: e.message });
|
|
1064
1066
|
return null;
|
|
1065
1067
|
}
|
|
1066
1068
|
}
|
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
|
-
|
|
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
|
|
326
|
+
const res = await netFetch(target, {
|
|
321
327
|
signal: AbortSignal.timeout(timeoutMs),
|
|
322
328
|
headers: { 'User-Agent': 'qq-bot-roost' },
|
|
323
329
|
});
|
package/src/outbound.js
CHANGED
|
@@ -293,6 +293,13 @@ export class Outbound {
|
|
|
293
293
|
this.dailyActive = Math.max(0, o.dailyActive ?? 1000);
|
|
294
294
|
this.activePerMin = Math.max(0, o.activePerMinute ?? 20);
|
|
295
295
|
this.downgrade = o.downgradeToActive !== false;
|
|
296
|
+
/**
|
|
297
|
+
* E3:dry 出站截获。开着时 `send()` 不真发,只记下本来会发什么。
|
|
298
|
+
* **只能截本进程内建插件的出站**:外部子进程插件走 NDJSON,不经过这里。
|
|
299
|
+
*/
|
|
300
|
+
this.dry = Boolean(o.dryRun);
|
|
301
|
+
/** 最近 50 条「本来会发出去」的消息,面板只读展示 */
|
|
302
|
+
this.dryLog = [];
|
|
296
303
|
|
|
297
304
|
/** msgId -> 已用被动回复次数。官方:同一条消息最多 5 次 */
|
|
298
305
|
this.passiveCount = new Map();
|
|
@@ -317,6 +324,36 @@ export class Outbound {
|
|
|
317
324
|
};
|
|
318
325
|
}
|
|
319
326
|
|
|
327
|
+
/* ---------------- E3:dry 出站截获 ---------------- */
|
|
328
|
+
|
|
329
|
+
/** 面板开关。返回切换后的状态 */
|
|
330
|
+
setDry(on) {
|
|
331
|
+
this.dry = on === true;
|
|
332
|
+
if (!this.dry) this.dryLog.length = 0;
|
|
333
|
+
return this.dry;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
#drySend(opts) {
|
|
337
|
+
const p = opts?.payload ?? {};
|
|
338
|
+
const text = String(p.markdown?.content ?? p.content ?? '');
|
|
339
|
+
const row = {
|
|
340
|
+
at: Date.now(),
|
|
341
|
+
kind: String(opts?.kind || ''),
|
|
342
|
+
target: String(opts?.target || ''),
|
|
343
|
+
/** 有 msgId / receivedAt 就是被动回复,否则是主动推送 */
|
|
344
|
+
passive: Boolean(p.msgId || opts?.receivedAt),
|
|
345
|
+
text: text.slice(0, 200),
|
|
346
|
+
files: Array.isArray(p.files) ? p.files.length : 0,
|
|
347
|
+
keyboard: Boolean(p.keyboard),
|
|
348
|
+
};
|
|
349
|
+
this.dryLog.push(row);
|
|
350
|
+
if (this.dryLog.length > 50) this.dryLog.shift();
|
|
351
|
+
this.stats.dry = (this.stats.dry || 0) + 1;
|
|
352
|
+
log.info(`[dry] ${row.kind} ${row.target}:${row.text.slice(0, 40)}`);
|
|
353
|
+
/** 形状和真实发送一致,调用方不用分叉;`dry:true` 让它知道没真发 */
|
|
354
|
+
return { ok: true, dry: true, id: '', pending: false };
|
|
355
|
+
}
|
|
356
|
+
|
|
320
357
|
/* ---------------- 对外主入口 ---------------- */
|
|
321
358
|
|
|
322
359
|
/**
|
|
@@ -340,6 +377,8 @@ export class Outbound {
|
|
|
340
377
|
* 账本是**增强**不是主链路:`claim` 失败一律退回「照发」,不能让记账把消息堵死。
|
|
341
378
|
*/
|
|
342
379
|
async send(opts) {
|
|
380
|
+
/** E3:dry 模式在**最顶层**截住,连投递账本和限速都不进——它本来就没发 */
|
|
381
|
+
if (this.dry) return this.#drySend(opts);
|
|
343
382
|
const requestId = String(opts?.requestId ?? '').trim();
|
|
344
383
|
if (!requestId || !this.delivery) {
|
|
345
384
|
/**
|
package/src/plugin/loader.js
CHANGED
|
@@ -14,6 +14,8 @@ import { satisfies, frameworkVersion } from '../semver.js';
|
|
|
14
14
|
import { PageRegistry } from './pages.js';
|
|
15
15
|
import { RouteRegistry } from './routes.js';
|
|
16
16
|
import { Declarations, normalizeManifest, checkEngines } from './manifest.js';
|
|
17
|
+
import { pushRuntimeError } from './runtime-errors.js';
|
|
18
|
+
import { makeSnapshot, pruneSnapshots } from './snapshot.js';
|
|
17
19
|
|
|
18
20
|
const log = createLogger('plugins');
|
|
19
21
|
|
|
@@ -73,6 +75,12 @@ export class PluginManager {
|
|
|
73
75
|
* 完全看不出是哪一行,插件作者只能靠猜。面板上展开就能看到调用栈。
|
|
74
76
|
*/
|
|
75
77
|
this.errorStacks = new Map();
|
|
78
|
+
/**
|
|
79
|
+
* id -> 最近 8 条**运行期**错误。
|
|
80
|
+
* 加载期错误看 errorStacks;这里是「装得上、面板显示成功,但 handler 每轮抛错」,
|
|
81
|
+
* 以前一点痕迹都没有,用户只看到机器人不回话。
|
|
82
|
+
*/
|
|
83
|
+
this.runtimeErrors = new Map();
|
|
76
84
|
/**
|
|
77
85
|
* id -> 插件自己的内存状态对象。
|
|
78
86
|
*
|
|
@@ -336,12 +344,11 @@ export class PluginManager {
|
|
|
336
344
|
/**
|
|
337
345
|
* 「热重载只对入口生效」是个容易踩的坑,报错里点名说清楚。
|
|
338
346
|
*
|
|
339
|
-
*
|
|
340
|
-
*
|
|
341
|
-
*
|
|
342
|
-
* `
|
|
343
|
-
*
|
|
344
|
-
* ESM 没有清缓存的 API,所以只能提示重启——但至少要让人知道为什么。
|
|
347
|
+
* 历史坑:早年只给 `index.js` 加 `?t=`,子模块(`outbound.js` 之类)
|
|
348
|
+
* 还在 Node 的模块缓存里,改了子模块再重载就成了「新入口 + 旧子模块」,
|
|
349
|
+
* 表现为 `does not provide an export named 'xxx'`。
|
|
350
|
+
* 现在 `#loadInternal` 用快照法整目录换路径加载,这个坑已消;
|
|
351
|
+
* 这条提示留作其他原因导致同名报错时的解释。
|
|
345
352
|
*/
|
|
346
353
|
const msg = String(e?.message ?? '');
|
|
347
354
|
if (/does not provide an export named/.test(msg)) {
|
|
@@ -416,9 +423,15 @@ export class PluginManager {
|
|
|
416
423
|
});
|
|
417
424
|
}
|
|
418
425
|
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
426
|
+
/**
|
|
427
|
+
* 快照法热重载:整目录复制到 `.roost-cache/<stamp>/` 再 import。
|
|
428
|
+
* ESM 按路径缓存,只给入口加 `?t=` 重不了子模块;换整条路径才会连带重载。
|
|
429
|
+
* 外部插件走 `#loadExternal`,stop/start 本来就是干净重载,不需要这一步。
|
|
430
|
+
* 先清旧快照再 import:即使这次 import 失败,下次也不会越积越多。
|
|
431
|
+
*/
|
|
432
|
+
const snap = await makeSnapshot(dir, entryFile);
|
|
433
|
+
await pruneSnapshots(snap.snapRoot, snap.stamp);
|
|
434
|
+
const mod = await import(pathToFileURL(snap.entry).href);
|
|
422
435
|
const meta = mod.default ?? mod.plugin;
|
|
423
436
|
if (!meta || typeof meta.setup !== 'function') {
|
|
424
437
|
throw new Error('默认导出必须是 { id, setup(ctx) } 形式的对象');
|
|
@@ -674,8 +687,18 @@ export class PluginManager {
|
|
|
674
687
|
return true;
|
|
675
688
|
}
|
|
676
689
|
|
|
690
|
+
/** 记一条插件 handler 的运行期异常(环形 8 条,面板可见)。 */
|
|
691
|
+
noteRuntimeError(id, err) {
|
|
692
|
+
if (!id) return;
|
|
693
|
+
const ring = this.runtimeErrors.get(id) ?? [];
|
|
694
|
+
pushRuntimeError(ring, err);
|
|
695
|
+
this.runtimeErrors.set(id, ring);
|
|
696
|
+
}
|
|
697
|
+
|
|
677
698
|
async reload(id) {
|
|
678
699
|
await this.unload(id);
|
|
700
|
+
/** 新实例是干净的:旧 handler 抛过的错别留在面板上冒充「还在报错」 */
|
|
701
|
+
this.runtimeErrors.delete(id);
|
|
679
702
|
return this.load(id);
|
|
680
703
|
}
|
|
681
704
|
|
|
@@ -695,6 +718,7 @@ export class PluginManager {
|
|
|
695
718
|
}
|
|
696
719
|
this.errors.delete(id);
|
|
697
720
|
this.errorStacks.delete(id);
|
|
721
|
+
this.runtimeErrors.delete(id);
|
|
698
722
|
this.stateStore.delete(id);
|
|
699
723
|
this.meta.delete(id);
|
|
700
724
|
this.diskIds.delete(id);
|
|
@@ -704,7 +728,14 @@ export class PluginManager {
|
|
|
704
728
|
async setEnabled(id, enabled) {
|
|
705
729
|
this.state[id] = enabled;
|
|
706
730
|
await this.#writeState();
|
|
707
|
-
if (enabled)
|
|
731
|
+
if (enabled) {
|
|
732
|
+
/**
|
|
733
|
+
* 已经加载的插件再点「启用」不能二次 load:会重复注册路由并抛错,
|
|
734
|
+
* load() 的 catch 反而把 loaded/routes 清掉,插件被自己卸了(审查实测 1→0)。
|
|
735
|
+
*/
|
|
736
|
+
if (this.loaded.has(id)) return true;
|
|
737
|
+
return this.load(id);
|
|
738
|
+
}
|
|
708
739
|
return this.unload(id);
|
|
709
740
|
}
|
|
710
741
|
|
|
@@ -1015,6 +1046,7 @@ export class PluginManager {
|
|
|
1015
1046
|
menuMissing: Boolean(item?.menuMissing),
|
|
1016
1047
|
error: this.errors.get(id) ?? ext?.error ?? '',
|
|
1017
1048
|
errorStack: this.errorStacks.get(id) ?? '',
|
|
1049
|
+
runtimeErrors: (this.runtimeErrors.get(id) ?? []).slice(),
|
|
1018
1050
|
};
|
|
1019
1051
|
});
|
|
1020
1052
|
}
|
package/src/plugin/market.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 插件**运行期**错误的环形缓冲。
|
|
3
|
+
*
|
|
4
|
+
* 加载期错误一直有 `errorStacks`;但「装得上、面板显示成功、handler 每轮抛错」
|
|
5
|
+
* 以前一点痕迹都没有,用户只看到机器人不回话。留最近 8 条就够看出
|
|
6
|
+
* 「一直在报同一个错」,又不会把内存吃穿。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export const RUNTIME_ERROR_MAX = 8;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @param {Array} ring 已有条目(原地追加后返回同一个数组)
|
|
13
|
+
* @param {unknown} err 异常对象或字符串
|
|
14
|
+
* @param {number} [at] 时间戳,测试里可注入
|
|
15
|
+
* @returns {Array} 截断到 8 条的环形缓冲
|
|
16
|
+
*/
|
|
17
|
+
export function pushRuntimeError(ring, err, at = Date.now()) {
|
|
18
|
+
const list = Array.isArray(ring) ? ring : [];
|
|
19
|
+
list.push({
|
|
20
|
+
at,
|
|
21
|
+
message: String(err?.message ?? err ?? ''),
|
|
22
|
+
// 完整堆栈太长,面板只展得开前几行;第一行通常就够定位
|
|
23
|
+
stack: String(err?.stack ?? '').split('\n').slice(0, 4).join('\n'),
|
|
24
|
+
});
|
|
25
|
+
if (list.length > RUNTIME_ERROR_MAX) list.splice(0, list.length - RUNTIME_ERROR_MAX);
|
|
26
|
+
return list;
|
|
27
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
/** 插件目录里不该进快照的**一级**子目录。 */
|
|
5
|
+
const SKIP_TOP = new Set(['node_modules', '.roost-cache', 'data', 'logs', 'config', '.git']);
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* 自己遍历复制,不用 `fs.cp`:快照在插件目录**内部**,而 fs.cp 会在开复制前
|
|
9
|
+
* 直接拒绝「目标是源的子目录」(ERR_FS_CP_EINVAL),哪怕 filter 排除了它。
|
|
10
|
+
* 排除只在**插件根目录那一层**生效:嵌套的 `src/data`、`lib/config` 是插件
|
|
11
|
+
* 自己的代码/资源,不该被一并丢掉(审查实测 S11/S12)。
|
|
12
|
+
*/
|
|
13
|
+
async function copyTree(srcDir, destDir, top = false) {
|
|
14
|
+
await fs.mkdir(destDir, { recursive: true });
|
|
15
|
+
for (const e of await fs.readdir(srcDir, { withFileTypes: true })) {
|
|
16
|
+
if (top && SKIP_TOP.has(e.name)) continue;
|
|
17
|
+
const from = path.join(srcDir, e.name);
|
|
18
|
+
const to = path.join(destDir, e.name);
|
|
19
|
+
if (e.isDirectory()) await copyTree(from, to, false);
|
|
20
|
+
else if (e.isFile()) await fs.copyFile(from, to);
|
|
21
|
+
else if (e.isSymbolicLink()) {
|
|
22
|
+
/**
|
|
23
|
+
* symlink 原先被静默漏掉。指向普通文件时按目标内容复制成快照里的真文件;
|
|
24
|
+
* 指向目录的链接不跟随(避免成环),插件不该靠这种结构装代码。
|
|
25
|
+
*/
|
|
26
|
+
const real = await fs.realpath(from).catch(() => null);
|
|
27
|
+
const st = real ? await fs.stat(real).catch(() => null) : null;
|
|
28
|
+
if (st?.isFile()) await fs.copyFile(real, to).catch(() => {});
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 把内建插件复制成一份带唯一戳的快照,返回快照入口路径。
|
|
35
|
+
*
|
|
36
|
+
* 为什么不再用 `?t=`:ESM 按**路径**缓存,入口加查询参数只会重加载入口,
|
|
37
|
+
* 它 import 的子模块还留在旧缓存里——典型表现是「改了 outbound.js,重载后
|
|
38
|
+
* 报 does not provide an export named xxx」,只能重启进程。整目录换路径,
|
|
39
|
+
* 入口和所有相对 import 的子模块才会一起重载。
|
|
40
|
+
*
|
|
41
|
+
* 快照放在**插件目录内部**(`.roost-cache/<stamp>/`):这样插件 `import '某个 npm 包'`
|
|
42
|
+
* 时,Node 向上查找能落到插件自己的 `node_modules`;复制时把依赖、数据目录、
|
|
43
|
+
* 旧快照都排除掉,避免每次重载把目录越滚越大。
|
|
44
|
+
*
|
|
45
|
+
* @returns {Promise<{snapRoot:string, snapDir:string, stamp:string, entry:string}>}
|
|
46
|
+
*/
|
|
47
|
+
export async function makeSnapshot(dir, entryFile) {
|
|
48
|
+
const snapRoot = path.join(dir, '.roost-cache');
|
|
49
|
+
const stamp = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
50
|
+
const snapDir = path.join(snapRoot, stamp);
|
|
51
|
+
await fs.mkdir(snapRoot, { recursive: true });
|
|
52
|
+
await copyTree(dir, snapDir, true);
|
|
53
|
+
return { snapRoot, snapDir, stamp, entry: path.join(snapDir, path.basename(entryFile)) };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 只留当前这一份快照。旧的不删会随每次重载线性增长。 */
|
|
57
|
+
export async function pruneSnapshots(snapRoot, keepStamp) {
|
|
58
|
+
const entries = await fs.readdir(snapRoot).catch(() => []);
|
|
59
|
+
await Promise.all(
|
|
60
|
+
entries
|
|
61
|
+
.filter((x) => x !== keepStamp)
|
|
62
|
+
.map((x) => fs.rm(path.join(snapRoot, x), { recursive: true, force: true }).catch(() => {})),
|
|
63
|
+
);
|
|
64
|
+
}
|