Compare commits
43 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f2840c7074 | ||
|
|
ad081e2149 | ||
|
|
0e4b881f76 | ||
|
|
90f26ca4f4 | ||
|
|
c4413dabb5 | ||
|
|
71be3ae2e1 | ||
|
|
3cfac51811 | ||
|
|
76c6ebc700 | ||
|
|
74b6fe97e5 | ||
|
|
4a0626f00b | ||
|
|
ba19cee07d | ||
|
|
624959f099 | ||
|
|
0110b71dd3 | ||
|
|
00ca582f1a | ||
|
|
bf932477dd | ||
|
|
f2b7ef0056 | ||
|
|
54c4641a0e | ||
|
|
08b7ab7f15 | ||
|
|
4a92dd71ad | ||
|
|
1bd0cbc359 | ||
|
|
fe567caeec | ||
|
|
231d60411b | ||
|
|
bee1e67c60 | ||
|
|
71b0bda8f4 | ||
|
|
133cfc0c0e | ||
|
|
b959783ded | ||
|
|
463e0ffb5d | ||
|
|
9d55e86b1c | ||
|
|
07449788c6 | ||
|
|
fe4af70562 | ||
|
|
545a732385 | ||
|
|
c2f22d8daf | ||
|
|
9216b54427 | ||
|
|
fd9a239241 | ||
|
|
5a4028d5dc | ||
|
|
d02e7cc3ab | ||
|
|
9938545788 | ||
|
|
7149bc8689 | ||
|
|
9802128421 | ||
|
|
a572d05c25 | ||
|
|
cb06624d12 | ||
|
|
7b93839186 | ||
|
|
d0085ec052 |
40
.github/logo.svg
vendored
Normal file
40
.github/logo.svg
vendored
Normal file
@@ -0,0 +1,40 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 120" width="100%" height="100%" style="background-color: transparent;">
|
||||
<defs>
|
||||
<style>
|
||||
@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@800&display=swap');
|
||||
|
||||
.title-font {
|
||||
font-family: 'Plus Jakarta Sans', sans-serif;
|
||||
font-size: 48px;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.02em;
|
||||
text-anchor: middle;
|
||||
}
|
||||
|
||||
.star-fx {
|
||||
animation: floatAnimation 4s ease-in-out infinite;
|
||||
}
|
||||
.star-top { transform-origin: 265px 25px; fill: #cec1e6; }
|
||||
.star-bottom { transform-origin: 45px 95px; animation-delay: 0.5s; fill: #fad6e6; }
|
||||
|
||||
@keyframes floatAnimation {
|
||||
0% { transform: translateY(0px) rotate(0deg); opacity: 0.9; }
|
||||
50% { transform: translateY(-8px) rotate(10deg); opacity: 1; }
|
||||
100% { transform: translateY(0px) rotate(0deg); opacity: 0.9; }
|
||||
}
|
||||
</style>
|
||||
</defs>
|
||||
|
||||
<g transform="translate(160, 75)">
|
||||
<text class="title-font" dx="2" dy="2">
|
||||
<tspan fill="#f9d5e7">Snow</tspan><tspan fill="#a5c9ff">Luma</tspan>
|
||||
</text>
|
||||
|
||||
<text class="title-font" dx="0" dy="0">
|
||||
<tspan fill="#a5c9ff">Snow</tspan><tspan fill="#cec1e6">Luma</tspan>
|
||||
</text>
|
||||
</g>
|
||||
|
||||
<path class="star-fx star-top" d="M265,13 L267.8,21.1 L276,24 L267.8,26.9 L265,35 L262.2,26.9 L254,24 L262.2,21.1 Z"/>
|
||||
<path class="star-fx star-bottom" d="M45,84 L47.1,90.2 L53.5,92.2 L47.1,94.2 L45,100 L42.9,94.2 L36.5,92.2 L42.9,90.2 Z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
117
README.md
117
README.md
@@ -1,4 +1,6 @@
|
||||
<h1 align="center">❄️ SnowLuma</h1>
|
||||
<h1 align="center">
|
||||
<img src=".github/logo.svg" width="100%" alt="SnowLuma" />
|
||||
</h1>
|
||||
|
||||
<p align="center">
|
||||
<i>Next Remote Protocol Framework.</i>
|
||||
@@ -7,8 +9,7 @@
|
||||
<p align="center">
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/releases"><img alt="Release" src="https://img.shields.io/github/v/release/SnowLuma/SnowLuma?label=release&style=flat-square"></a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/actions"><img alt="Build" src="https://img.shields.io/github/actions/workflow/status/SnowLuma/SnowLuma/release.yml?branch=main&style=flat-square&label=build"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/sdk"><img alt="@snowluma/sdk" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=%40snowluma%2Fsdk&color=cb3837"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/ui"><img alt="@snowluma/ui" src="https://img.shields.io/npm/v/%40snowluma%2Fui?style=flat-square&label=%40snowluma%2Fui&color=cb3837"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/sdk"><img alt="NPM" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=sdk&color=cb3837"></a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/stargazers"><img alt="Stars" src="https://img.shields.io/github/stars/SnowLuma/SnowLuma?style=flat-square"></a>
|
||||
</p>
|
||||
|
||||
@@ -21,111 +22,29 @@
|
||||
|
||||
---
|
||||
|
||||
## 简介
|
||||
|
||||
SnowLuma 在 QQ 客户端与生态侧之间承担协议转换工作,向上以 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准协议暴露能力。Bridge 层负责会话与事件枢纽,再通过 WebSocket / HTTP / WebUI 等多种适配器对外提供接入。
|
||||
|
||||
项目持续迭代中,稳定版本通过 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 发布。
|
||||
SnowLuma 是一个基于 TypeScript 的协议转换框架,旨在为 QQ 客户端提供 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准接口,支持 WebSocket/HTTP 适配、多账号并行及 WebUI 管理。
|
||||
|
||||
## 特性
|
||||
|
||||
- **OneBot v11 兼容** —— 涵盖文本、图片、视频、语音、合并转发、戳一戳、Markdown、JSON、XML 等常用消息段。
|
||||
- **多账号并行** —— 同一进程可同时托管多个 QQ 账号,会话彼此独立。
|
||||
- **多种适配器** —— WebSocket Server / WebSocket Client / HTTP Server / HTTP Post,HTTP 服务端同时支持 `application/json` 与 `application/x-www-form-urlencoded`。
|
||||
- **WebUI 管理面板** —— 浏览器登录、密码强度校验、登录限流、SSE 实时日志、配置热更新。
|
||||
- **TypeScript 全链路** —— Bridge / OneBot / SDK / UI 均使用 TypeScript,发布到 npm 的 `@snowluma/sdk` 与 `@snowluma/ui` 可直接供下游应用消费。
|
||||
- **数据持久化** —— 好友、群、群成员等关系数据落 SQLite,跨重启可用。
|
||||
- **OneBot v11 兼容**:支持文本、音视频、Markdown、JSON 等消息格式。
|
||||
- **高性能架构**:TypeScript 全栈,基于 pnpm monorepo 管理,核心逻辑分离。
|
||||
- **现代化管理**:内置 WebUI 面板,支持实时日志、密码热更、多账号管理。
|
||||
- **多适配器支持**:WebSocket (Server/Client)、HTTP (Server/Post)。
|
||||
- **数据持久化**:使用 SQLite 存储好友、群组等关系数据。
|
||||
|
||||
## 快速开始
|
||||
|
||||
下载预构建发布包:
|
||||
|
||||
```bash
|
||||
# 从 Releases 下载 zip,解压到任意目录
|
||||
./launcher.bat # Windows
|
||||
```
|
||||
|
||||
或从源码开发:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/SnowLuma/SnowLuma.git
|
||||
cd SnowLuma
|
||||
pnpm install
|
||||
pnpm build
|
||||
pnpm start
|
||||
```
|
||||
|
||||
WebUI 默认监听 `5099` 端口。首次启动会在控制台打印 `initial credentials: user=admin password=<...>`,登录后请立即修改。
|
||||
若未完成首次改密就关闭进程,下次启动会自动重新生成一个新的随机密码。
|
||||
|
||||
## 工作区
|
||||
|
||||
本仓库使用 pnpm monorepo 管理,各包职责如下:
|
||||
|
||||
| 包 | 说明 |
|
||||
| --- | --- |
|
||||
| [`@snowluma/core`](packages/core) | 核心:协议层 / Bridge / OneBot / WebUI 全部在此。 |
|
||||
| [`@snowluma/sdk`](packages/sdk) | OneBot HTTP & WebSocket TypeScript SDK,发布到 npm。 |
|
||||
| [`@snowluma/ui`](packages/ui) | Tailwind 4 共享组件库(shadcn 风格),发布到 npm。 |
|
||||
| [`@snowluma/websocket`](packages/websocket) | OneBot WebSocket 适配器底层。 |
|
||||
| [`@snowluma/proton`](packages/proton) | 编译期 protobuf 编/解码器生成器:TS interface 标注 `pb<N, T>`,Vite 插件在构建时把 `protobuf_encode<T>` / `protobuf_decode<T>` 替换为内联 codec,零运行时反射。 |
|
||||
| [`@snowluma/runtime`](packages/runtime) | 运行时清单与发布包资源。 |
|
||||
| [`webui`](packages/webui) | Web 管理面板前端。 |
|
||||
|
||||
## 架构
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A([QQ 客户端])
|
||||
B["协议层<br/><sub>packet pipeline · cmd 分派</sub>"]
|
||||
C["Bridge 层<br/><sub>会话调度 · 花名册缓存 · 消息发送</sub>"]
|
||||
D["OneBot 层<br/><sub>Event Converter · Action Handler</sub>"]
|
||||
E([WS / HTTP / WebUI])
|
||||
|
||||
A --> B --> C --> D --> E
|
||||
```
|
||||
|
||||
## 文档
|
||||
|
||||
- [路线图](RoadMap.md)
|
||||
- [贡献指南](CONTRIBUTING.md)
|
||||
- [行为准则](CODE_OF_CONDUCT.md)
|
||||
|
||||
## 开发命令
|
||||
|
||||
```bash
|
||||
pnpm dev # 启动 core dev server
|
||||
pnpm dev:web # 启动 webui dev server
|
||||
pnpm test # 运行 core 测试
|
||||
pnpm typecheck # 全仓库 type check
|
||||
pnpm build:all # 构建 core + sdk + webui
|
||||
```
|
||||
1. 从 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载最新发布包并解压。
|
||||
2. 运行 `./launcher.bat` (Windows) 或 `./launcher.sh` (Linux)。
|
||||
3. 访问 `http://localhost:5099` (初始账号 `admin`,密码见控制台输出)。
|
||||
|
||||
## 鸣谢
|
||||
|
||||
- [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) —— Proto 定义参考。
|
||||
- [NapCatQQ](https://github.com/NapNeko/NapCatQQ) —— Scanner 与 Packet 处理实现参考。
|
||||
参考了 [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) 的协议定义与 [NapCatQQ](https://github.com/NapNeko/NapCatQQ) 的实现思路。
|
||||
|
||||
## 贡献者
|
||||
---
|
||||
|
||||
感谢每一位为 SnowLuma 提交过代码的伙伴。
|
||||
<p align="center">
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors"><img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" /></a>
|
||||
</p>
|
||||
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" alt="Contributors" />
|
||||
</a>
|
||||
|
||||
## Star 趋势
|
||||
|
||||
<a href="https://star-history.com/#SnowLuma/SnowLuma&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
## 社区
|
||||
|
||||
- QQ 群:[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
|
||||
- Telegram:[SnowLuma-TG](https://t.me/napcatqq)
|
||||
- 问题反馈:[GitHub Issues](https://github.com/SnowLuma/SnowLuma/issues)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.3",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.3",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/common",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.3",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/core",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.3",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -46,7 +46,6 @@
|
||||
"@snowluma/protocol": "workspace:*",
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@snowluma/sqlite": "workspace:*",
|
||||
"@snowluma/websocket": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -9,6 +9,7 @@ import type { BridgeContext } from '../bridge-context';
|
||||
import { ClickInlineKeyboardButton } from '@snowluma/protocol/oidb-services/misc/click-inline-keyboard-button';
|
||||
import { SendGroupSign } from '@snowluma/protocol/oidb-services/misc/send-group-sign';
|
||||
import { TranslateEnToZh } from '@snowluma/protocol/oidb-services/misc/translate-en-to-zh';
|
||||
import { RequestDbKey } from '@snowluma/protocol/oidb-services/misc/request-decrypt-key';
|
||||
|
||||
export class MiscApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
@@ -75,4 +76,15 @@ export class MiscApi {
|
||||
sendGroupSign(groupId: number): Promise<void> {
|
||||
return SendGroupSign.invoke(this.ctx, { groupId });
|
||||
}
|
||||
|
||||
async getDecryptKey(dbSalt: string): Promise<string> {
|
||||
const result = await RequestDbKey.invoke(this.ctx, { db_salt: dbSalt });
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMsg || `Failed to get decrypt key (code: ${result.errorCode})`);
|
||||
}
|
||||
if (!result.dbKey) {
|
||||
throw new Error('Decrypt key is empty');
|
||||
}
|
||||
return result.dbKey;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key';
|
||||
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
|
||||
import { getGroupEssenceMsg, getGroupEssenceMsgAll, type GroupEssenceMsgRet } from '@snowluma/protocol/web/group-essence';
|
||||
@@ -247,16 +248,11 @@ export class WebApi {
|
||||
let imgHeight = 300;
|
||||
|
||||
if (options?.image) {
|
||||
let imageBuffer: Buffer;
|
||||
|
||||
if (options.image.startsWith('http://') || options.image.startsWith('https://')) {
|
||||
const response = await fetch(options.image);
|
||||
if (!response.ok) throw new Error(`Failed to download image: ${response.status}`);
|
||||
imageBuffer = Buffer.from(await response.arrayBuffer());
|
||||
} else {
|
||||
const { readFileSync } = await import('fs');
|
||||
imageBuffer = readFileSync(options.image);
|
||||
}
|
||||
// Route through loadBinarySource so the group-notice image download
|
||||
// gets the same browser-UA + Referer-retry hardening as every other
|
||||
// media fetch — and http/file/base64 source handling for free.
|
||||
const loaded = await loadBinarySource(options.image, 'group-notice image');
|
||||
const imageBuffer = Buffer.from(loaded.bytes);
|
||||
|
||||
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
|
||||
if (picInfo) {
|
||||
|
||||
@@ -355,6 +355,12 @@ export async function initWebUI(
|
||||
return c.json({ list });
|
||||
});
|
||||
|
||||
// Live OneBot adapter health per account (listening / connected / client
|
||||
// counts / last-delivery), powering the dashboard's connection card.
|
||||
app.get('/api/connections', (c) => {
|
||||
return c.json({ list: oneBotManager.getConnectionStatuses() });
|
||||
});
|
||||
|
||||
app.get('/api/logs', (c) => {
|
||||
const limit = Number(c.req.query('limit') ?? 300);
|
||||
return c.json({ list: getRecentLogs(limit) });
|
||||
|
||||
@@ -99,3 +99,81 @@ describe('loadBinarySource maxBytes enforcement', () => {
|
||||
).rejects.toThrow(/too large: 128 > 64/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadBinarySource HTTP header hardening', () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('sends a browser User-Agent on the first attempt, without a Referer', async () => {
|
||||
const calls: Array<Record<string, string>> = [];
|
||||
globalThis.fetch = vi.fn(async (_url: unknown, init?: RequestInit) => {
|
||||
calls.push((init?.headers ?? {}) as Record<string, string>);
|
||||
return new Response(new Uint8Array([1, 2, 3]), { status: 200 });
|
||||
}) as typeof fetch;
|
||||
|
||||
await loadBinarySource('https://example.test/a.png', 'image');
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]['User-Agent']).toMatch(/Mozilla\/5\.0/);
|
||||
expect(calls[0]['Referer']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('retries with a Referer when the first fetch fails at the network level', async () => {
|
||||
// Reproduces the reported bug: an anti-bot front-end resets the
|
||||
// header-less request → undici `TypeError: fetch failed`. The retry
|
||||
// carries a Referer pointing at the resource itself and succeeds.
|
||||
const calls: Array<Record<string, string>> = [];
|
||||
globalThis.fetch = vi.fn(async (_url: unknown, init?: RequestInit) => {
|
||||
calls.push((init?.headers ?? {}) as Record<string, string>);
|
||||
if (calls.length === 1) throw new TypeError('fetch failed');
|
||||
return new Response(new Uint8Array([9, 9]), { status: 200 });
|
||||
}) as typeof fetch;
|
||||
|
||||
const loaded = await loadBinarySource('https://img.example.test/x.gif', 'image');
|
||||
expect(Array.from(loaded.bytes)).toEqual([9, 9]);
|
||||
expect(calls).toHaveLength(2);
|
||||
expect(calls[0]['Referer']).toBeUndefined();
|
||||
expect(calls[1]['Referer']).toBe('https://img.example.test/x.gif');
|
||||
});
|
||||
|
||||
it('retries with a Referer on a 403 (anti-hotlink)', async () => {
|
||||
let n = 0;
|
||||
globalThis.fetch = vi.fn(async () => {
|
||||
n++;
|
||||
if (n === 1) return new Response(new Uint8Array(0), { status: 403 });
|
||||
return new Response(new Uint8Array([7]), { status: 200 });
|
||||
}) as typeof fetch;
|
||||
|
||||
const loaded = await loadBinarySource('https://cdn.example.test/y.jpg', 'image');
|
||||
expect(Array.from(loaded.bytes)).toEqual([7]);
|
||||
expect(n).toBe(2);
|
||||
});
|
||||
|
||||
it('does not retry a size-limit rejection (deterministic, no second download)', async () => {
|
||||
const fetchMock = vi.fn(async () => new Response(new Uint8Array(0), {
|
||||
status: 200,
|
||||
headers: { 'content-length': String(10 * 1024 * 1024) },
|
||||
}));
|
||||
globalThis.fetch = fetchMock as typeof fetch;
|
||||
|
||||
await expect(
|
||||
loadBinarySource('https://example.test/big.bin', 'image', 1024),
|
||||
).rejects.toThrow(/too large/);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('surfaces the first error when the Referer retry also fails', async () => {
|
||||
let n = 0;
|
||||
globalThis.fetch = vi.fn(async () => {
|
||||
n++;
|
||||
throw new TypeError('fetch failed');
|
||||
}) as typeof fetch;
|
||||
|
||||
await expect(
|
||||
loadBinarySource('https://example.test/z.png', 'image'),
|
||||
).rejects.toThrow(/fetch failed/);
|
||||
expect(n).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { defineConfig, PluginOption, UserConfig } from 'vite';
|
||||
import { fileURLToPath } from 'url';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { builtinModules } from 'module';
|
||||
import cp from 'vite-plugin-cp';
|
||||
import protobufVitePlugin from '@snowluma/proton/vite';
|
||||
import fs from 'fs';
|
||||
import { builtinModules } from 'module';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { defineConfig, PluginOption, UserConfig } from 'vite';
|
||||
import cp from 'vite-plugin-cp';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = path.resolve(__dirname, '..', '..');
|
||||
@@ -20,12 +20,16 @@ const rootPkg = JSON.parse(
|
||||
// vite-plugin-cp consumes globs through globby; on Windows we must use POSIX-style separators.
|
||||
const toPosix = (p: string) => p.replace(/\\/g, '/');
|
||||
|
||||
// `@snowluma/websocket` and `@snowluma/sqlite` are bundled — they're
|
||||
// in-tree TS workspace wrappers that route their native `.node`
|
||||
// addons through `dist/native/`. Only Node builtins stay external;
|
||||
// the actual `better-sqlite3` JS wrapper is pulled in via the
|
||||
// `@snowluma/sqlite` re-export and bundled into `index.mjs`.
|
||||
const external: string[] = [];
|
||||
// `@snowluma/websocket` is bundled — it's an
|
||||
// in-tree TS workspace wrapper that routes its native `.node`
|
||||
// addon through `dist/native/`. Only Node builtins stay external.
|
||||
//
|
||||
// `node:sqlite` is an experimental builtin that Node 22.x lines don't
|
||||
// list in `builtinModules`, so the `nodeModules` sweep below misses it.
|
||||
// Externalise it explicitly — otherwise Vite bundles it and swaps in a
|
||||
// browser shell, crashing the hook with `DatabaseSync is not a
|
||||
// constructor` (the bug PR #68 set out to fix).
|
||||
const external: string[] = ['node:sqlite', 'sqlite'];
|
||||
|
||||
const nodeModules = [...builtinModules, ...builtinModules.map((m) => `node:${m}`)].flat();
|
||||
|
||||
@@ -46,20 +50,8 @@ const runtimeDistFiles = ['package.json',
|
||||
// Native binaries shipped for the selected target:
|
||||
// * `snowluma-*.{dll,node,so}` – NTQQ hook (Windows + Linux).
|
||||
// * `websocket-*.node` – RFC 6455 framing/mask addon (all platforms).
|
||||
// * `better-sqlite3-v<abi>-*.node` – SQLite native binding consumed
|
||||
// by @snowluma/sqlite. Two ABIs
|
||||
// vendored side-by-side
|
||||
// (v127 = Node 22 LTS, v137 =
|
||||
// Node 24) so the runtime can
|
||||
// pick whichever matches the
|
||||
// host's `process.versions.modules`.
|
||||
// Vendored via
|
||||
// `tools/fetch-sqlite-prebuilts.mjs`
|
||||
// from WiseLibs's prebuild releases.
|
||||
const SQLITE_ABIS = ['v127', 'v137'];
|
||||
const nativeFiles = [
|
||||
`websocket-${targetTriple}.node`,
|
||||
...SQLITE_ABIS.map((abi) => `better-sqlite3-${abi}-${targetTriple}.node`),
|
||||
...(targetPlatform === 'win32'
|
||||
? [`snowluma-${targetTriple}.dll`, `snowluma-${targetTriple}.node`]
|
||||
: []),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/onebot",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.3",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis.<area>.method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",
|
||||
@@ -91,7 +91,6 @@
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@snowluma/protocol": "workspace:*",
|
||||
"@snowluma/sqlite": "workspace:*",
|
||||
"@snowluma/websocket": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import type { ApiActionContext, ApiHandler } from '../api-handler';
|
||||
import { asBoolean, asMessage, asNumber, asString } from '../api-handler';
|
||||
import type { ForwardPreviewMeta } from '../modules/message-actions';
|
||||
@@ -1175,6 +1176,35 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('request_decrypt_key', async (params) => {
|
||||
const dbPath = asString(params.db_path);
|
||||
if (!dbPath) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'db_path is required');
|
||||
}
|
||||
|
||||
try {
|
||||
const buffer = Buffer.alloc(128);
|
||||
const fileHandle = await readFile(dbPath);
|
||||
|
||||
if (fileHandle.length < 0xaf) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'Database file too short');
|
||||
}
|
||||
|
||||
fileHandle.copy(buffer, 0, 0x2f, 0xaf);
|
||||
const dbSalt = buffer.toString('utf8');
|
||||
|
||||
if (!/^[0-9a-fA-F]{128}$/.test(dbSalt)) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'Invalid db_salt: not a valid 128-character hex string');
|
||||
}
|
||||
|
||||
const dbKey = await ctx.bridge.apis.misc.getDecryptKey(dbSalt.toLowerCase());
|
||||
|
||||
return okResponse({ db_key: dbKey });
|
||||
} catch (err) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function hexToBytes(hex: string): Uint8Array {
|
||||
|
||||
@@ -3,6 +3,35 @@ import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asNumber, asString, asBoolean, asMessage } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
/**
|
||||
* Re-sign image URLs in a stored message event at read time. `get_msg`
|
||||
* returns a copy persisted when the message first arrived, and image rkeys
|
||||
* expire — so walk the segment array and refresh each image URL through
|
||||
* `ctx.getImageInfo`, which mints a current rkey. Best-effort and in-place;
|
||||
* `findEvent` returns a fresh parse, so mutating the array is safe.
|
||||
*/
|
||||
async function refreshStoredImageUrls(event: JsonObject, ctx: ApiActionContext): Promise<void> {
|
||||
const segments = event.message;
|
||||
if (!Array.isArray(segments)) return;
|
||||
for (const seg of segments) {
|
||||
if (!seg || typeof seg !== 'object') continue;
|
||||
const segment = seg as { type?: unknown; data?: Record<string, JsonValue> };
|
||||
if (segment.type !== 'image') continue;
|
||||
const data = segment.data;
|
||||
if (!data || typeof data !== 'object') continue;
|
||||
const file = typeof data.file === 'string' ? data.file
|
||||
: typeof data.file_id === 'string' ? data.file_id
|
||||
: '';
|
||||
if (!file) continue;
|
||||
try {
|
||||
const info = await ctx.getImageInfo(file);
|
||||
if (info && typeof info.url === 'string' && info.url) data.url = info.url;
|
||||
} catch {
|
||||
// Keep the stored URL when the refresh fails.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('send_msg', async (params) => {
|
||||
const messageType = asString(params.message_type);
|
||||
@@ -77,6 +106,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
delete result.post_type;
|
||||
delete result.self_id;
|
||||
result.real_id = (result.message_id ?? messageId) as JsonValue;
|
||||
await refreshStoredImageUrls(result, ctx);
|
||||
return okResponse(result);
|
||||
});
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
} from './to-request';
|
||||
import { elementsToJson } from './to-segment';
|
||||
|
||||
export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string;
|
||||
export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string | Promise<string>;
|
||||
export type MediaUrlResolver = (element: MessageElement, isGroup: boolean, sessionId: number) => Promise<string>;
|
||||
export type MessageIdResolver = (isGroup: boolean, sessionId: number, sequence: number, eventName: string) => number;
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ async function elementToSegment(
|
||||
}
|
||||
|
||||
if (element.type === 'image') {
|
||||
const url = imageUrlResolver ? imageUrlResolver(element, isGroup) : (element.imageUrl ?? '');
|
||||
const url = imageUrlResolver ? await imageUrlResolver(element, isGroup) : (element.imageUrl ?? '');
|
||||
const data: JsonObject = {
|
||||
url,
|
||||
file: element.fileId ?? '',
|
||||
|
||||
@@ -114,7 +114,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
complete: cachedCount >= serverCount,
|
||||
};
|
||||
},
|
||||
getImageInfo: (file) => getCachedImageInfo(mediaStore, file),
|
||||
getImageInfo: (file) => getCachedImageInfo(mediaStore, file, ref.converterCtx.imageUrlResolver),
|
||||
getRecordInfo: (file) => getCachedRecordInfo(bridge, mediaStore, file),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -15,6 +15,10 @@ interface CachedRKey {
|
||||
|
||||
const RKEY_REFRESH_SKEW = 60;
|
||||
const RKEY_REFRESH_COOLDOWN = 30;
|
||||
// Upper bound on how long URL resolution may block on a refresh round-trip.
|
||||
// A stuck packet send must never wedge message conversion — past this we
|
||||
// fall back to whatever the cache holds (possibly nothing).
|
||||
const RKEY_REFRESH_TIMEOUT_MS = 5000;
|
||||
const PRIVATE_IMAGE_RKEY_TYPE = 10;
|
||||
const GROUP_IMAGE_RKEY_TYPE = 20;
|
||||
const PRIVATE_VIDEO_RKEY_TYPE = 12;
|
||||
@@ -26,31 +30,28 @@ const FALLBACK_IMAGE_RKEY_TYPE = 2;
|
||||
export class RKeyCache {
|
||||
private cache = new Map<number, CachedRKey>();
|
||||
private lastRefreshAttempt = 0;
|
||||
private refreshInflight: Promise<void> | null = null;
|
||||
|
||||
warmUp(bridge: BridgeInterface, uin: string): void {
|
||||
bridge.apis.contacts.fetchDownloadRKeys().then(
|
||||
(rkeys) => {
|
||||
this.updateCache(rkeys);
|
||||
log.info('rkeys loaded: UIN=%s count=%d', uin, rkeys.length);
|
||||
},
|
||||
(err) => {
|
||||
log.warn('failed to load rkeys for UIN %s: %s', uin, err instanceof Error ? err.message : String(err));
|
||||
},
|
||||
this.ensureFresh(bridge).then(
|
||||
() => log.info('rkeys loaded: UIN=%s count=%d', uin, this.cache.size),
|
||||
(err) => log.warn('failed to load rkeys for UIN %s: %s', uin, err instanceof Error ? err.message : String(err)),
|
||||
);
|
||||
}
|
||||
|
||||
resolveImageUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string {
|
||||
async resolveImageUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): Promise<string> {
|
||||
const url = element.imageUrl ?? '';
|
||||
if (!urlNeedsRKey(url)) return url;
|
||||
|
||||
const rkey = this.findRKey(bridge, isGroup);
|
||||
const rkey = await this.findRKey(bridge, isGroup);
|
||||
if (!rkey) return url;
|
||||
|
||||
const cleanRKey = stripRKeyPrefix(rkey);
|
||||
const separator = url.includes('?') ? '&rkey=' : '?rkey=';
|
||||
return url + separator + encodeURIComponent(cleanRKey);
|
||||
}
|
||||
resolveMediaUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string {
|
||||
|
||||
async resolveMediaUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): Promise<string> {
|
||||
const url = element.url ?? '';
|
||||
if (!url || !urlNeedsRKey(url)) return url;
|
||||
|
||||
@@ -65,7 +66,7 @@ export class RKeyCache {
|
||||
primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
|
||||
}
|
||||
|
||||
const rkey = this.findRKeyForType(bridge, primaryType);
|
||||
const rkey = await this.findRKeyForType(bridge, primaryType);
|
||||
if (!rkey) return url;
|
||||
|
||||
const cleanRKey = stripRKeyPrefix(rkey);
|
||||
@@ -89,32 +90,66 @@ export class RKeyCache {
|
||||
}
|
||||
}
|
||||
|
||||
private findRKey(bridge: BridgeInterface, isGroup: boolean): string | null {
|
||||
private findRKey(bridge: BridgeInterface, isGroup: boolean): Promise<string | null> {
|
||||
const primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
|
||||
return this.findRKeyForType(bridge, primaryType);
|
||||
}
|
||||
|
||||
private findRKeyForType(bridge: BridgeInterface, primaryType: number): string | null {
|
||||
/** Pull a still-valid rkey out of the cache, or null if missing/expiring. */
|
||||
private findInCache(primaryType: number): string | null {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
|
||||
const tryFind = (type: number): string | null => {
|
||||
const cached = this.cache.get(type);
|
||||
if (!cached || !cached.value) return null;
|
||||
if (cached.expiresAt !== 0 && now + RKEY_REFRESH_SKEW >= cached.expiresAt) return null;
|
||||
return cached.value;
|
||||
};
|
||||
return tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
|
||||
}
|
||||
|
||||
let result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
|
||||
if (result) return result;
|
||||
if (now - this.lastRefreshAttempt < RKEY_REFRESH_COOLDOWN) return null;
|
||||
this.lastRefreshAttempt = now;
|
||||
bridge.apis.contacts.fetchDownloadRKeys().then(
|
||||
(rkeys) => this.updateCache(rkeys),
|
||||
() => { /* ignore */ },
|
||||
);
|
||||
private async findRKeyForType(bridge: BridgeInterface, primaryType: number): Promise<string | null> {
|
||||
const cached = this.findInCache(primaryType);
|
||||
if (cached) return cached;
|
||||
|
||||
result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
|
||||
return result;
|
||||
// Cache miss or inside the expiry skew: block on a fresh fetch rather
|
||||
// than hand back a URL with a stale/absent rkey — the CDN rejects those
|
||||
// with `{"retcode":-5503010,"retmsg":"invalid rkey"}`. Mirrors NapCat's
|
||||
// getImageUrl path, which does `if (isExpired()) await refreshRkey()`
|
||||
// before building the URL instead of refreshing in the background.
|
||||
await this.ensureFresh(bridge);
|
||||
return this.findInCache(primaryType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh the rkey cache via OIDB 0x9067_202, coalescing concurrent
|
||||
* callers onto one in-flight request and backing off for
|
||||
* RKEY_REFRESH_COOLDOWN after a failed attempt so a persistently
|
||||
* unreachable server isn't hammered once per inbound image. The await is
|
||||
* bounded by RKEY_REFRESH_TIMEOUT_MS.
|
||||
*/
|
||||
private async ensureFresh(bridge: BridgeInterface): Promise<void> {
|
||||
if (!this.refreshInflight) {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
if (now - this.lastRefreshAttempt < RKEY_REFRESH_COOLDOWN) return;
|
||||
this.lastRefreshAttempt = now;
|
||||
this.refreshInflight = bridge.apis.contacts.fetchDownloadRKeys()
|
||||
.then((rkeys) => { this.updateCache(rkeys); })
|
||||
.catch((err) => {
|
||||
log.warn('rkey refresh failed: %s', err instanceof Error ? err.message : String(err));
|
||||
})
|
||||
.finally(() => { this.refreshInflight = null; });
|
||||
}
|
||||
|
||||
const inflight = this.refreshInflight;
|
||||
if (!inflight) return;
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const timeout = new Promise<void>((resolve) => { timer = setTimeout(resolve, RKEY_REFRESH_TIMEOUT_MS); });
|
||||
try {
|
||||
await Promise.race([inflight, timeout]);
|
||||
} finally {
|
||||
if (timer) clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
OneBotNetworkManager,
|
||||
WsClientAdapter,
|
||||
WsServerAdapter,
|
||||
type AdapterStatus,
|
||||
type NetworkAdapterContext,
|
||||
} from './network';
|
||||
import { ReactionStore } from './reaction-store';
|
||||
@@ -46,6 +47,11 @@ export class OneBotInstance {
|
||||
|
||||
get nickname(): string { return this.bridge.identity.nickname; }
|
||||
|
||||
/** Live status of this account's OneBot network adapters. */
|
||||
getConnectionStatuses(): AdapterStatus[] {
|
||||
return this.networkManager.describeStatuses();
|
||||
}
|
||||
|
||||
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) {
|
||||
this.uin = uin;
|
||||
this.bridge = bridge;
|
||||
|
||||
@@ -3,10 +3,18 @@ import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { BridgeManager } from '@snowluma/core/manager';
|
||||
import { loadOneBotConfig } from './config';
|
||||
import { OneBotInstance } from './instance';
|
||||
import type { AdapterStatus } from './network';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1';
|
||||
|
||||
/** Per-account OneBot connection health, surfaced to the WebUI dashboard. */
|
||||
export interface AccountConnections {
|
||||
uin: string;
|
||||
nickname: string;
|
||||
adapters: AdapterStatus[];
|
||||
}
|
||||
|
||||
export class OneBotManager {
|
||||
private readonly instances = new Map<string, OneBotInstance>();
|
||||
|
||||
@@ -28,6 +36,15 @@ export class OneBotManager {
|
||||
return [...this.instances.values()];
|
||||
}
|
||||
|
||||
/** Live OneBot adapter status for every account, for the WebUI dashboard. */
|
||||
getConnectionStatuses(): AccountConnections[] {
|
||||
return this.getInstances().map((i) => ({
|
||||
uin: i.uin,
|
||||
nickname: i.nickname,
|
||||
adapters: i.getConnectionStatuses(),
|
||||
}));
|
||||
}
|
||||
|
||||
reloadConfig(uin: string): boolean {
|
||||
const instance = this.instances.get(uin);
|
||||
if (!instance) return false;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
|
||||
import fs from 'fs';
|
||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import path from 'path';
|
||||
|
||||
export interface CachedImage {
|
||||
@@ -62,17 +62,17 @@ const TYPE_VIDEO = 'video';
|
||||
const DEFAULT_KEEP_ENTRIES = 4096;
|
||||
|
||||
export class MediaStore {
|
||||
private readonly db: DatabaseType;
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly maxEntriesPerType: number;
|
||||
|
||||
// Prepared statements (pay the parsing cost once at startup).
|
||||
private readonly upsertEntry: Statement;
|
||||
private readonly upsertKey: Statement;
|
||||
private readonly findEntryByKey: Statement;
|
||||
private readonly findEntryByPrimary: Statement;
|
||||
private readonly evictByType: Statement;
|
||||
private readonly purgeOrphanKeys: Statement;
|
||||
private readonly countByType: Statement;
|
||||
private readonly upsertEntry: StatementSync;
|
||||
private readonly upsertKey: StatementSync;
|
||||
private readonly findEntryByKey: StatementSync;
|
||||
private readonly findEntryByPrimary: StatementSync;
|
||||
private readonly evictByType: StatementSync;
|
||||
private readonly purgeOrphanKeys: StatementSync;
|
||||
private readonly countByType: StatementSync;
|
||||
|
||||
constructor(dbPath: string, maxEntriesPerType = DEFAULT_KEEP_ENTRIES) {
|
||||
this.maxEntriesPerType = Math.max(64, maxEntriesPerType);
|
||||
@@ -80,9 +80,9 @@ export class MediaStore {
|
||||
const dir = path.dirname(dbPath);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
|
||||
this.db = new Database(dbPath);
|
||||
this.db.pragma('journal_mode = WAL');
|
||||
this.db.pragma('synchronous = NORMAL');
|
||||
this.db = new DatabaseSync(dbPath);
|
||||
this.db.exec('PRAGMA journal_mode = WAL');
|
||||
this.db.exec('PRAGMA synchronous = NORMAL');
|
||||
this.initSchema();
|
||||
|
||||
this.upsertEntry = this.db.prepare(
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
|
||||
import fs from 'fs';
|
||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import path from 'path';
|
||||
import type { JsonObject, MessageMeta } from './types';
|
||||
|
||||
export class MessageStore {
|
||||
private readonly db: DatabaseType;
|
||||
private readonly stmtStoreEvent: Statement;
|
||||
private readonly stmtStoreMeta: Statement;
|
||||
private readonly stmtFindEvent: Statement;
|
||||
private readonly stmtFindMeta: Statement;
|
||||
private readonly stmtResolveReplyGroup: Statement;
|
||||
private readonly stmtResolveReplyPrivate: Statement;
|
||||
private readonly stmtListEventsAnchored: Statement;
|
||||
private readonly stmtListEventsLatest: Statement;
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly stmtStoreEvent: StatementSync;
|
||||
private readonly stmtStoreMeta: StatementSync;
|
||||
private readonly stmtFindEvent: StatementSync;
|
||||
private readonly stmtFindMeta: StatementSync;
|
||||
private readonly stmtResolveReplyGroup: StatementSync;
|
||||
private readonly stmtResolveReplyPrivate: StatementSync;
|
||||
private readonly stmtListEventsAnchored: StatementSync;
|
||||
private readonly stmtListEventsLatest: StatementSync;
|
||||
|
||||
constructor(dbPath: string) {
|
||||
const dir = path.dirname(dbPath);
|
||||
@@ -20,9 +20,9 @@ export class MessageStore {
|
||||
|
||||
// Replace .json extension with .db if present
|
||||
const finalPath = dbPath.replace(/\.json$/, '.db');
|
||||
this.db = new Database(finalPath);
|
||||
this.db.pragma('journal_mode = WAL');
|
||||
this.db.pragma('synchronous = NORMAL');
|
||||
this.db = new DatabaseSync(finalPath);
|
||||
this.db.exec('PRAGMA journal_mode = WAL');
|
||||
this.db.exec('PRAGMA synchronous = NORMAL');
|
||||
this.initSchema();
|
||||
|
||||
// Prepare once. Statements survive for the lifetime of the
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import type { ImageUrlResolver } from '../event-converter';
|
||||
import type { MediaStore } from '../media-store';
|
||||
import type { JsonObject } from '../types';
|
||||
|
||||
@@ -8,10 +10,29 @@ const log = createLogger('OneBot');
|
||||
export async function getImageInfo(
|
||||
mediaStore: MediaStore,
|
||||
file: string,
|
||||
imageUrlResolver?: ImageUrlResolver | null,
|
||||
): Promise<JsonObject | null> {
|
||||
const cached = mediaStore.findImage(file);
|
||||
if (!cached) return null;
|
||||
const url = cached.url || cached.imageUrl || '';
|
||||
|
||||
let url = cached.url || cached.imageUrl || '';
|
||||
|
||||
// Re-sign with a current rkey at lookup time. The stored `url` was signed
|
||||
// when the message first arrived and its rkey may have since expired — the
|
||||
// CDN then rejects the download with
|
||||
// `{"retcode":-5503010,"retmsg":"invalid rkey"}`. Resolving from the raw
|
||||
// (unsigned) `imageUrl` mints a fresh rkey, mirroring NapCat which
|
||||
// re-signs on every getImageUrl call instead of handing back a baked URL.
|
||||
if (imageUrlResolver && cached.imageUrl) {
|
||||
try {
|
||||
const element: MessageElement = { type: 'image', imageUrl: cached.imageUrl, subType: cached.subType };
|
||||
const fresh = await imageUrlResolver(element, cached.isGroup);
|
||||
if (fresh) url = fresh;
|
||||
} catch {
|
||||
// Best-effort: fall back to the stored URL on any resolver failure.
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
file: url || cached.file,
|
||||
url,
|
||||
|
||||
@@ -16,6 +16,19 @@ export enum NetworkReloadType {
|
||||
Opened = 3,
|
||||
}
|
||||
|
||||
export type AdapterStatusLevel = 'ok' | 'warn' | 'down' | 'disabled';
|
||||
|
||||
/** Live runtime status of a single network adapter, surfaced to the WebUI
|
||||
* dashboard (and the per-node config cards) so the gateway's own
|
||||
* connection health is visible. `detail` is a short human string, e.g.
|
||||
* "3 个客户端" / "重连中" / "上次推送失败 14:53:01". */
|
||||
export interface AdapterStatus {
|
||||
name: string;
|
||||
kind: 'httpServer' | 'httpClient' | 'wsServer' | 'wsClient';
|
||||
status: AdapterStatusLevel;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
|
||||
readonly name: string;
|
||||
protected config: C;
|
||||
@@ -37,4 +50,7 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
|
||||
abstract reload(config: C): NetworkReloadType | Promise<NetworkReloadType>;
|
||||
|
||||
abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise<void>;
|
||||
|
||||
/** Report live connection health for the WebUI dashboard. */
|
||||
abstract describeStatus(): AdapterStatus;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import type { HttpClientNetwork, JsonObject } from '../types';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
|
||||
import { executeQuickOperation } from './quick-operation';
|
||||
|
||||
const moduleLog = createLogger('OneBot.POST');
|
||||
@@ -15,6 +15,7 @@ const DEFAULT_TIMEOUT_MS = 5000;
|
||||
export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
private options: EventReportOptions;
|
||||
private signature_: string;
|
||||
private lastDelivery: { at: number; ok: boolean } | null = null;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) {
|
||||
@@ -39,6 +40,15 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
this.isEnabled = false;
|
||||
}
|
||||
|
||||
override describeStatus(): AdapterStatus {
|
||||
if (!this.isEnabled) return { name: this.name, kind: 'httpClient', status: 'disabled', detail: '未启用' };
|
||||
if (!this.lastDelivery) return { name: this.name, kind: 'httpClient', status: 'ok', detail: '已启用' };
|
||||
const at = new Date(this.lastDelivery.at).toTimeString().slice(0, 8);
|
||||
return this.lastDelivery.ok
|
||||
? { name: this.name, kind: 'httpClient', status: 'ok', detail: `上次推送成功 ${at}` }
|
||||
: { name: this.name, kind: 'httpClient', status: 'warn', detail: `上次推送失败 ${at}` };
|
||||
}
|
||||
|
||||
async reload(next: HttpClientNetwork): Promise<NetworkReloadType> {
|
||||
const wasEnabled = this.isEnabled;
|
||||
const willEnable = next.enabled !== false && !!next.url;
|
||||
@@ -98,6 +108,7 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
if (response.ok) {
|
||||
this.lastDelivery = { at: Date.now(), ok: true };
|
||||
const contentType = response.headers.get('content-type') ?? '';
|
||||
if (contentType.includes('application/json')) {
|
||||
const body = await response.text();
|
||||
@@ -106,9 +117,11 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.lastDelivery = { at: Date.now(), ok: false };
|
||||
this.log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status);
|
||||
}
|
||||
} catch (error) {
|
||||
this.lastDelivery = { at: Date.now(), ok: false };
|
||||
if (this.isEnabled) {
|
||||
this.log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
|
||||
@@ -7,13 +7,14 @@ import {
|
||||
} from 'http';
|
||||
import type { DispatchPayload } from '../event-filter';
|
||||
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
|
||||
import { isAuthorized, normalizePath } from './utils';
|
||||
|
||||
const moduleLog = createLogger('OneBot.HTTP');
|
||||
|
||||
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
|
||||
private server: Server | null = null;
|
||||
private listening = false;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
|
||||
@@ -36,10 +37,17 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
close(): void {
|
||||
if (!this.isEnabled && !this.server) return;
|
||||
this.isEnabled = false;
|
||||
this.listening = false;
|
||||
this.server?.close();
|
||||
this.server = null;
|
||||
}
|
||||
|
||||
override describeStatus(): AdapterStatus {
|
||||
if (!this.isEnabled) return { name: this.name, kind: 'httpServer', status: 'disabled', detail: '未启用' };
|
||||
if (!this.listening) return { name: this.name, kind: 'httpServer', status: 'down', detail: '未监听(端口被占用?)' };
|
||||
return { name: this.name, kind: 'httpServer', status: 'ok', detail: '监听中' };
|
||||
}
|
||||
|
||||
async reload(next: HttpServerNetwork): Promise<NetworkReloadType> {
|
||||
const prevSig = bindingSignature(this.config);
|
||||
const wasEnabled = this.isEnabled;
|
||||
@@ -76,6 +84,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
this.server = server;
|
||||
|
||||
server.on('listening', () => {
|
||||
this.listening = true;
|
||||
this.log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
this.name,
|
||||
@@ -85,6 +94,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
);
|
||||
});
|
||||
server.on('error', (err) => {
|
||||
this.listening = false;
|
||||
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
export { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
export {
|
||||
IOneBotNetworkAdapter,
|
||||
NetworkReloadType,
|
||||
type AdapterStatus,
|
||||
type AdapterStatusLevel,
|
||||
type NetworkAdapterContext,
|
||||
} from './adapter';
|
||||
export { HttpPostAdapter } from './http-post-adapter';
|
||||
export { HttpServerAdapter } from './http-server-adapter';
|
||||
export { OneBotNetworkManager } from './network-manager';
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { buildDispatchPayload } from '../event-filter';
|
||||
import type { JsonObject, NetworkBase } from '../types';
|
||||
import { IOneBotNetworkAdapter } from './adapter';
|
||||
import { IOneBotNetworkAdapter, type AdapterStatus } from './adapter';
|
||||
|
||||
const log = createLogger('OneBot.Network');
|
||||
|
||||
@@ -30,6 +30,11 @@ export class OneBotNetworkManager {
|
||||
|
||||
list(): AnyAdapter[] { return [...this.adapters.values()]; }
|
||||
|
||||
/** Live status of every registered adapter, for the WebUI dashboard. */
|
||||
describeStatuses(): AdapterStatus[] {
|
||||
return this.list().map((a) => a.describeStatus());
|
||||
}
|
||||
|
||||
hasActiveAdapters(): boolean {
|
||||
for (const a of this.adapters.values()) if (a.isActive) return true;
|
||||
return false;
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import type { JsonObject, WsClientNetwork, WsRole } from '../types';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
|
||||
import { rawDataToString, safeClose, safeSend } from './utils';
|
||||
|
||||
const moduleLog = createLogger('OneBot.WS-Client');
|
||||
@@ -16,6 +16,7 @@ const DEFAULT_RECONNECT_INTERVAL_MS = 5000;
|
||||
|
||||
export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
private socket: WebSocket | null = null;
|
||||
private connected = false;
|
||||
private reconnectTimer: NodeJS.Timeout | null = null;
|
||||
private options: EventReportOptions;
|
||||
private role: WsRole;
|
||||
@@ -46,6 +47,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
close(): void {
|
||||
this.explicitlyClosed = true;
|
||||
this.isEnabled = false;
|
||||
this.connected = false;
|
||||
this.cancelReconnect();
|
||||
if (this.socket) {
|
||||
safeClose(this.socket);
|
||||
@@ -53,6 +55,12 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
}
|
||||
}
|
||||
|
||||
override describeStatus(): AdapterStatus {
|
||||
if (!this.isEnabled) return { name: this.name, kind: 'wsClient', status: 'disabled', detail: '未启用' };
|
||||
if (this.connected) return { name: this.name, kind: 'wsClient', status: 'ok', detail: '已连接' };
|
||||
return { name: this.name, kind: 'wsClient', status: 'warn', detail: this.reconnectTimer ? '重连中' : '连接中' };
|
||||
}
|
||||
|
||||
async reload(next: WsClientNetwork): Promise<NetworkReloadType> {
|
||||
const prevSig = bindingSignature(this.config);
|
||||
const wasEnabled = this.isEnabled;
|
||||
@@ -108,6 +116,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
this.socket = socket;
|
||||
|
||||
socket.on('open', () => {
|
||||
this.connected = true;
|
||||
this.log.info('[%s] connected %s', this.name, this.config.url);
|
||||
this.sendBootstrapMetaEvents(socket);
|
||||
});
|
||||
@@ -120,6 +129,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
|
||||
socket.on('close', () => {
|
||||
this.socket = null;
|
||||
this.connected = false;
|
||||
if (this.explicitlyClosed || !this.isEnabled) return;
|
||||
this.scheduleReconnect();
|
||||
});
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import type { JsonObject, WsRole, WsServerNetwork } from '../types';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
|
||||
import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend } from './utils';
|
||||
|
||||
const moduleLog = createLogger('OneBot.WS-Server');
|
||||
@@ -22,6 +22,7 @@ interface ForwardConn {
|
||||
|
||||
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
private wss: WebSocketServer | null = null;
|
||||
private listening = false;
|
||||
private connections = new Map<WebSocket, ForwardConn>();
|
||||
private options: EventReportOptions;
|
||||
private readonly log: Logger;
|
||||
@@ -57,12 +58,19 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
}
|
||||
|
||||
this.isEnabled = false;
|
||||
this.listening = false;
|
||||
for (const ws of [...this.connections.keys()]) safeClose(ws);
|
||||
this.connections.clear();
|
||||
this.wss?.close();
|
||||
this.wss = null;
|
||||
}
|
||||
|
||||
override describeStatus(): AdapterStatus {
|
||||
if (!this.isEnabled) return { name: this.name, kind: 'wsServer', status: 'disabled', detail: '未启用' };
|
||||
if (!this.listening) return { name: this.name, kind: 'wsServer', status: 'down', detail: '未监听(端口被占用?)' };
|
||||
return { name: this.name, kind: 'wsServer', status: 'ok', detail: `${this.connections.size} 个客户端` };
|
||||
}
|
||||
|
||||
async reload(next: WsServerNetwork): Promise<NetworkReloadType> {
|
||||
const prevSig = bindingSignature(this.config);
|
||||
const wasEnabled = this.isEnabled;
|
||||
@@ -111,6 +119,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
this.wss = wss;
|
||||
|
||||
wss.on('listening', () => {
|
||||
this.listening = true;
|
||||
this.log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
this.name,
|
||||
@@ -121,6 +130,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
});
|
||||
|
||||
wss.on('error', (err: Error) => {
|
||||
this.listening = false;
|
||||
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
|
||||
import fs from 'fs';
|
||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import path from 'path';
|
||||
|
||||
export class ReactionStore {
|
||||
private readonly db: DatabaseType;
|
||||
private readonly stmtUpsert: Statement;
|
||||
private readonly stmtRemove: Statement;
|
||||
private readonly stmtList: Statement;
|
||||
private readonly stmtCount: Statement;
|
||||
private readonly stmtCountByEmoji: Statement;
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly stmtUpsert: StatementSync;
|
||||
private readonly stmtRemove: StatementSync;
|
||||
private readonly stmtList: StatementSync;
|
||||
private readonly stmtCount: StatementSync;
|
||||
private readonly stmtCountByEmoji: StatementSync;
|
||||
|
||||
constructor(dbPath: string) {
|
||||
const dir = path.dirname(dbPath);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
this.db = new Database(dbPath);
|
||||
this.db.pragma('journal_mode = WAL');
|
||||
this.db.pragma('synchronous = NORMAL');
|
||||
this.db = new DatabaseSync(dbPath);
|
||||
this.db.exec('PRAGMA journal_mode = WAL');
|
||||
this.db.exec('PRAGMA synchronous = NORMAL');
|
||||
this.initSchema();
|
||||
|
||||
this.stmtUpsert = this.db.prepare(
|
||||
|
||||
94
packages/onebot/tests/instance-rkey.test.ts
Normal file
94
packages/onebot/tests/instance-rkey.test.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { RKeyCache } from '../src/instance-rkey';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
|
||||
// The screenshot URL: a raw QQ-NT multimedia download link with no rkey yet.
|
||||
const NT_IMAGE_URL = 'https://multimedia.nt.qq.com.cn/download?appid=1407&fileid=ABC';
|
||||
const GROUP_IMAGE_TYPE = 20;
|
||||
const PRIVATE_IMAGE_TYPE = 10;
|
||||
|
||||
function nowSec(): number {
|
||||
return Math.floor(Date.now() / 1000);
|
||||
}
|
||||
|
||||
function makeBridge(fetchImpl: () => Promise<unknown[]>) {
|
||||
const fetchDownloadRKeys = vi.fn(fetchImpl);
|
||||
return { bridge: { apis: { contacts: { fetchDownloadRKeys } } }, fetchDownloadRKeys };
|
||||
}
|
||||
|
||||
function freshGroupRkey(value = 'GROUPKEY') {
|
||||
return [{ rkey: value, type: GROUP_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 }];
|
||||
}
|
||||
|
||||
function imageEl(): MessageElement {
|
||||
return { type: 'image', imageUrl: NT_IMAGE_URL };
|
||||
}
|
||||
|
||||
describe('RKeyCache.resolveImageUrl', () => {
|
||||
it('awaits a refresh on a cold cache and appends the rkey', async () => {
|
||||
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
|
||||
const cache = new RKeyCache();
|
||||
|
||||
const url = await cache.resolveImageUrl(bridge as never, imageEl(), true);
|
||||
|
||||
expect(url).toBe(`${NT_IMAGE_URL}&rkey=GROUPKEY`);
|
||||
expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('coalesces concurrent cold-cache lookups into a single fetch', async () => {
|
||||
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
|
||||
const cache = new RKeyCache();
|
||||
|
||||
const urls = await Promise.all([
|
||||
cache.resolveImageUrl(bridge as never, imageEl(), true),
|
||||
cache.resolveImageUrl(bridge as never, imageEl(), true),
|
||||
cache.resolveImageUrl(bridge as never, imageEl(), true),
|
||||
]);
|
||||
|
||||
expect(urls).toEqual(Array(3).fill(`${NT_IMAGE_URL}&rkey=GROUPKEY`));
|
||||
expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('serves a still-valid rkey from cache without re-fetching', async () => {
|
||||
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
|
||||
const cache = new RKeyCache();
|
||||
|
||||
await cache.resolveImageUrl(bridge as never, imageEl(), true);
|
||||
await cache.resolveImageUrl(bridge as never, imageEl(), true);
|
||||
|
||||
expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('falls back to the unsigned URL (no throw) when the refresh fails', async () => {
|
||||
const { bridge, fetchDownloadRKeys } = makeBridge(async () => { throw new Error('oidb down'); });
|
||||
const cache = new RKeyCache();
|
||||
|
||||
const url = await cache.resolveImageUrl(bridge as never, imageEl(), true);
|
||||
|
||||
expect(url).toBe(NT_IMAGE_URL);
|
||||
expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('uses the private rkey type for c2c images', async () => {
|
||||
const { bridge } = makeBridge(async () => [
|
||||
{ rkey: 'PRIVATEKEY', type: PRIVATE_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 },
|
||||
{ rkey: 'GROUPKEY', type: GROUP_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 },
|
||||
]);
|
||||
const cache = new RKeyCache();
|
||||
|
||||
const url = await cache.resolveImageUrl(bridge as never, imageEl(), false);
|
||||
|
||||
expect(url).toBe(`${NT_IMAGE_URL}&rkey=PRIVATEKEY`);
|
||||
});
|
||||
|
||||
it('leaves non-NT URLs untouched and never fetches', async () => {
|
||||
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
|
||||
const cache = new RKeyCache();
|
||||
const el: MessageElement = { type: 'image', imageUrl: 'https://gchat.qpic.cn/foo.jpg' };
|
||||
|
||||
const url = await cache.resolveImageUrl(bridge as never, el, true);
|
||||
|
||||
expect(url).toBe('https://gchat.qpic.cn/foo.jpg');
|
||||
expect(fetchDownloadRKeys).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
63
packages/onebot/tests/media-actions.test.ts
Normal file
63
packages/onebot/tests/media-actions.test.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import { getImageInfo } from '../src/modules/media-actions';
|
||||
import type { CachedImage, MediaStore } from '../src/media-store';
|
||||
|
||||
const RAW = 'https://multimedia.nt.qq.com.cn/download?appid=1407&fileid=ABC';
|
||||
|
||||
function fakeStore(image: CachedImage | null): MediaStore {
|
||||
return { findImage: () => image } as unknown as MediaStore;
|
||||
}
|
||||
|
||||
function cachedImage(overrides: Partial<CachedImage> = {}): CachedImage {
|
||||
return {
|
||||
file: 'ABC.jpg',
|
||||
url: `${RAW}&rkey=STALE`, // signed when the message arrived; now expired
|
||||
fileSize: 100,
|
||||
fileName: 'ABC.jpg',
|
||||
subType: 0,
|
||||
summary: '',
|
||||
isGroup: true,
|
||||
sessionId: 123,
|
||||
imageUrl: RAW, // raw, unsigned — the basis for re-signing
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('getImageInfo — rkey re-signing at lookup time', () => {
|
||||
it('re-signs from the raw imageUrl via the resolver', async () => {
|
||||
const resolver = vi.fn(async (el: MessageElement) => `${el.imageUrl}&rkey=FRESH`);
|
||||
|
||||
const info = await getImageInfo(fakeStore(cachedImage()), 'ABC.jpg', resolver);
|
||||
|
||||
expect(info?.url).toBe(`${RAW}&rkey=FRESH`);
|
||||
expect(info?.file).toBe(`${RAW}&rkey=FRESH`);
|
||||
expect(resolver).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ type: 'image', imageUrl: RAW }),
|
||||
true, // isGroup carried through
|
||||
);
|
||||
});
|
||||
|
||||
it('returns the stored URL when no resolver is wired', async () => {
|
||||
const info = await getImageInfo(fakeStore(cachedImage()), 'ABC.jpg');
|
||||
expect(info?.url).toBe(`${RAW}&rkey=STALE`);
|
||||
});
|
||||
|
||||
it('falls back to the stored URL when the resolver throws', async () => {
|
||||
const resolver = vi.fn(async () => { throw new Error('rkey fetch failed'); });
|
||||
const info = await getImageInfo(fakeStore(cachedImage()), 'ABC.jpg', resolver);
|
||||
expect(info?.url).toBe(`${RAW}&rkey=STALE`);
|
||||
});
|
||||
|
||||
it('skips re-signing when no raw imageUrl is stored', async () => {
|
||||
const resolver = vi.fn(async () => 'should-not-be-used');
|
||||
const info = await getImageInfo(fakeStore(cachedImage({ imageUrl: '' })), 'ABC.jpg', resolver);
|
||||
expect(resolver).not.toHaveBeenCalled();
|
||||
expect(info?.url).toBe(`${RAW}&rkey=STALE`);
|
||||
});
|
||||
|
||||
it('returns null when the image is not cached', async () => {
|
||||
const info = await getImageInfo(fakeStore(null), 'missing.jpg');
|
||||
expect(info).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/proto-defs",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.3",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb<N, T>` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton';
|
||||
import type { pb, pb_optional, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton';
|
||||
|
||||
// Re-exported from the legacy oidb-action module while large protocol groups
|
||||
// are split into focused files.
|
||||
@@ -13,7 +13,11 @@ export interface OidbMuteMember {
|
||||
body?: pb<3, OidbMuteMemberBody>;
|
||||
}
|
||||
export interface OidbMuteAllState {
|
||||
state?: pb<17, uint_32>;
|
||||
// Explicit presence: the unmute request sends state=0, which proto3 would
|
||||
// otherwise omit — leaving an empty `muteState` the server can't tell apart
|
||||
// from the other commands sharing OIDB (0x89A, 0) (SetSearch / SetAddOption,
|
||||
// disambiguated by body shape). pb_optional forces the 0 onto the wire.
|
||||
state?: pb_optional<17, uint_32>;
|
||||
}
|
||||
export interface OidbMuteAll {
|
||||
groupUin?: pb<1, uint_32>;
|
||||
@@ -90,13 +94,19 @@ export interface OidbSetAdmin {
|
||||
uid?: pb<2, string>;
|
||||
isAdmin?: pb<3, bool>;
|
||||
}
|
||||
// 0x8FC_3 (set member card) shares its wire shape with 0x8FC_2 (special
|
||||
// title): the body wrapper sits at tag 3, and the card name at tag 8 —
|
||||
// NOT tags 2/2. Sending body@2 / targetName@2 makes the server miss both
|
||||
// and reject with `OIDB error 1007`. Cross-checked byte-for-byte against:
|
||||
// dev/Lagrange.Core/…/Request/OidbSvcTrpcTcp0x8FC.cs (Body=3, TargetName=8)
|
||||
// dev/napcatQQInside/…/proto/oidb/Oidb.0x8FC_2.ts (body=3, targetName=8)
|
||||
export interface OidbRenameMemberBody {
|
||||
targetUid?: pb<1, string>;
|
||||
targetName?: pb<2, string>;
|
||||
targetName?: pb<8, string>;
|
||||
}
|
||||
export interface OidbRenameMember {
|
||||
groupUin?: pb<1, uint_32>;
|
||||
body?: pb<2, OidbRenameMemberBody>;
|
||||
body?: pb<3, OidbRenameMemberBody>;
|
||||
}
|
||||
export interface OidbRenameGroupBody {
|
||||
targetName?: pb<1, string>;
|
||||
@@ -112,7 +122,8 @@ export interface OidbSpecialTitleBody {
|
||||
}
|
||||
export interface OidbSpecialTitle {
|
||||
groupUin?: pb<1, uint_32>;
|
||||
body?: pb<2, OidbSpecialTitleBody>;
|
||||
// Same family as 0x8FC_3 above — body wrapper is tag 3, not 2.
|
||||
body?: pb<3, OidbSpecialTitleBody>;
|
||||
}
|
||||
// 0x7E5_104 (FriendLike) request body. Field numbers 11/12/13 (NOT
|
||||
// 1/2/3) — the server reads `targetUid` from tag 11 and rejects with
|
||||
@@ -657,4 +668,22 @@ export interface GroupAvatarExtra {
|
||||
field3?: pb<3, GroupAvatarExtraField3>;
|
||||
field5?: pb<5, uint_32>;
|
||||
field6?: pb<6, uint_32>;
|
||||
}
|
||||
}
|
||||
|
||||
export interface Oidb0xcdeReqBodyInfo {
|
||||
db_salt?: pb<1, string>;
|
||||
}
|
||||
|
||||
export interface Oidb0xcdeReq {
|
||||
info?: pb<2, Oidb0xcdeReqBodyInfo>;
|
||||
sessionData?: pb<10, bytes>;
|
||||
}
|
||||
|
||||
export interface Oidb0xcdeRespBodyInfo {
|
||||
dbKey?: pb<1, string>;
|
||||
}
|
||||
|
||||
export interface Oidb0xcdeResp {
|
||||
info?: pb<2, Oidb0xcdeRespBodyInfo>;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/protocol",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.3",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/<x>'` collapses to `import { … } from '@snowluma/protocol/<x>'`.",
|
||||
@@ -107,6 +107,10 @@
|
||||
"types": "./src/oidb-services/misc/send-group-sign.ts",
|
||||
"default": "./src/oidb-services/misc/send-group-sign.ts"
|
||||
},
|
||||
"./oidb-services/misc/request-decrypt-key": {
|
||||
"types": "./src/oidb-services/misc/request-decrypt-key.ts",
|
||||
"default": "./src/oidb-services/misc/request-decrypt-key.ts"
|
||||
},
|
||||
"./oidb-services/web/force-fetch-client-key": {
|
||||
"types": "./src/oidb-services/web/force-fetch-client-key.ts",
|
||||
"default": "./src/oidb-services/web/force-fetch-client-key.ts"
|
||||
@@ -368,8 +372,7 @@
|
||||
"dependencies": {
|
||||
"@snowluma/common": "workspace:*",
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@snowluma/sqlite": "workspace:*"
|
||||
"@snowluma/proton": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
|
||||
@@ -22,6 +22,19 @@ const DEFAULT_MAX_BINARY_SIZE = 1024 * 1024 * 1024; // 1 GiB
|
||||
export const FILE_UPLOAD_MAX_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB
|
||||
const FETCH_TIMEOUT_MS = 60_000;
|
||||
|
||||
/**
|
||||
* Browser-like User-Agent for remote media downloads. Many image / CDN
|
||||
* hosts (and anti-hotlink front-ends) reject or RST a header-less,
|
||||
* non-browser request — which surfaces as undici `TypeError: fetch
|
||||
* failed` rather than a clean 403. Sending a normal browser UA on every
|
||||
* request (and retrying with a Referer when the first try is refused) is
|
||||
* what lets NapCat fetch sources our bare `fetch(source)` couldn't.
|
||||
* Cross-checked against
|
||||
* `dev/napcatQQInside/packages/napcat-common/src/file.ts:101-142,359-369`.
|
||||
*/
|
||||
const DOWNLOAD_USER_AGENT =
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36';
|
||||
|
||||
export interface ImageHashes {
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
@@ -65,6 +78,14 @@ export function resolveLocalFilePath(source: string): string | null {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tag a size-limit error so the HTTP retry path leaves it alone — retrying
|
||||
* a too-large response just re-downloads the same oversized body.
|
||||
*/
|
||||
function tooLarge(message: string): Error {
|
||||
return Object.assign(new Error(message), { noRetry: true });
|
||||
}
|
||||
|
||||
export async function loadBinarySource(
|
||||
source: string,
|
||||
resourceName: string,
|
||||
@@ -81,49 +102,79 @@ export async function loadBinarySource(
|
||||
}
|
||||
|
||||
if (/^https?:\/\//i.test(source)) {
|
||||
const resp = await fetch(source, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
|
||||
const declared = Number(resp.headers.get('content-length') ?? '0');
|
||||
if (Number.isFinite(declared) && declared > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${declared} > ${maxBytes}`);
|
||||
}
|
||||
const fileName = guessFileNameFromUrl(source);
|
||||
// Stream the body incrementally so a server that omits or
|
||||
// understates Content-Length can't make us buffer a chunked response
|
||||
// past maxBytes — `await resp.arrayBuffer()` would happily allocate
|
||||
// the entire payload before we get a chance to length-check it.
|
||||
const reader = resp.body?.getReader();
|
||||
if (!reader) {
|
||||
const bytes = new Uint8Array(await resp.arrayBuffer());
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
|
||||
|
||||
// A single fetch attempt with the given headers. Streams the body
|
||||
// incrementally so a server that omits or understates Content-Length
|
||||
// can't make us buffer a chunked response past maxBytes — `await
|
||||
// resp.arrayBuffer()` would happily allocate the entire payload before
|
||||
// we get a chance to length-check it. Size-limit rejections are tagged
|
||||
// `noRetry` so the outer retry doesn't re-download an oversized body.
|
||||
const attempt = async (headers: Record<string, string>): Promise<LoadedBinary> => {
|
||||
const resp = await fetch(source, {
|
||||
headers,
|
||||
redirect: 'follow',
|
||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||
});
|
||||
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
|
||||
const declared = Number(resp.headers.get('content-length') ?? '0');
|
||||
if (Number.isFinite(declared) && declared > maxBytes) {
|
||||
throw tooLarge(`${resourceName} too large: ${declared} > ${maxBytes}`);
|
||||
}
|
||||
const reader = resp.body?.getReader();
|
||||
if (!reader) {
|
||||
const bytes = new Uint8Array(await resp.arrayBuffer());
|
||||
if (bytes.length > maxBytes) {
|
||||
throw tooLarge(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
|
||||
}
|
||||
return { bytes, fileName };
|
||||
}
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (!value) continue;
|
||||
total += value.byteLength;
|
||||
if (total > maxBytes) {
|
||||
await reader.cancel().catch(() => { /* ignore */ });
|
||||
throw tooLarge(`${resourceName} too large: > ${maxBytes}`);
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
const bytes = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
bytes.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return { bytes, fileName };
|
||||
}
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
};
|
||||
|
||||
// First try with a browser UA only. On any non-size failure — a
|
||||
// network-level `fetch failed` (connection reset by an anti-bot
|
||||
// front-end) or a 403/4xx from anti-hotlink — retry once with a
|
||||
// Referer pointing at the resource itself, the common bypass for
|
||||
// same-origin hotlink checks. Mirrors NapCat's with/without-Referer
|
||||
// strategy.
|
||||
const baseHeaders: Record<string, string> = {
|
||||
'User-Agent': DOWNLOAD_USER_AGENT,
|
||||
Accept: '*/*',
|
||||
};
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (!value) continue;
|
||||
total += value.byteLength;
|
||||
if (total > maxBytes) {
|
||||
await reader.cancel().catch(() => { /* ignore */ });
|
||||
throw new Error(`${resourceName} too large: > ${maxBytes}`);
|
||||
}
|
||||
chunks.push(value);
|
||||
return await attempt(baseHeaders);
|
||||
} catch (err) {
|
||||
if ((err as { noRetry?: boolean } | null)?.noRetry) throw err;
|
||||
try {
|
||||
return await attempt({ ...baseHeaders, Referer: source });
|
||||
} catch {
|
||||
throw err;
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
const bytes = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
bytes.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return { bytes, fileName };
|
||||
}
|
||||
|
||||
const filePath = resolveLocalFilePath(source);
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import fs from 'fs';
|
||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import path from 'path';
|
||||
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
|
||||
|
||||
import type {
|
||||
FriendInfo, GroupMemberInfo, QQGroupInfo,
|
||||
UserProfileInfo, GroupRequestInfo,
|
||||
} from './qq-info';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import type {
|
||||
FriendInfo, GroupMemberInfo,
|
||||
GroupRequestInfo,
|
||||
QQGroupInfo,
|
||||
UserProfileInfo,
|
||||
} from './qq-info';
|
||||
|
||||
const moduleLogger = createLogger('Identity');
|
||||
|
||||
@@ -109,14 +111,14 @@ export class IdentityService {
|
||||
private readonly uidByUin = new Map<number, string>();
|
||||
|
||||
// ─── Persistence + fetcher ───
|
||||
private readonly db: DatabaseType | null;
|
||||
private readonly db: DatabaseSync | null;
|
||||
// Prepared-statement cache. Every `.prepare(sql)` call in this
|
||||
// service re-parses the SQL — that's the SQLite anti-pattern
|
||||
// RoadMap #5 is fixing. We memoize by the SQL string itself so the
|
||||
// call sites stay readable (no need to enumerate 20+ named fields
|
||||
// upfront); the Map lookup is O(1) hash + string-eq, which is
|
||||
// negligible next to the SQL parse it replaces.
|
||||
private readonly stmtCache_ = new Map<string, Statement>();
|
||||
private readonly stmtCache_ = new Map<string, StatementSync>();
|
||||
private inTransaction = false;
|
||||
private fetcher: IdentityFetcher | null = null;
|
||||
private readonly log: Logger;
|
||||
@@ -134,16 +136,16 @@ export class IdentityService {
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
this.db = new Database(dbPath);
|
||||
this.db.pragma('journal_mode = WAL');
|
||||
this.db.pragma('synchronous = NORMAL');
|
||||
this.db = new DatabaseSync(dbPath);
|
||||
this.db.exec('PRAGMA journal_mode = WAL');
|
||||
this.db.exec('PRAGMA synchronous = NORMAL');
|
||||
this.initSchema();
|
||||
this.loadSnapshot();
|
||||
}
|
||||
|
||||
/** Cached `prepare(sql)`. First call per unique SQL parses; later
|
||||
* calls reuse the same `Statement` object. See `stmtCache_`. */
|
||||
private pstmt(sql: string): Statement {
|
||||
private pstmt(sql: string): StatementSync {
|
||||
let cached = this.stmtCache_.get(sql);
|
||||
if (cached !== undefined) return cached;
|
||||
cached = this.db!.prepare(sql);
|
||||
|
||||
@@ -117,9 +117,19 @@ export async function invokeOidb<TCtx extends OidbSender, TReq, TResp, TParams,
|
||||
: `OidbSvcTrpcTcp.0x${spec.command.toString(16)}_${subCommand}`;
|
||||
|
||||
const result = await ctx.sendRawPacket(wireName, reqBytes, timeoutMs);
|
||||
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
|
||||
if (!result.gotResponse) throw new Error(result.errorMessage || 'no response');
|
||||
|
||||
if (!result.success) {
|
||||
if (result.errorCode && result.errorCode !== 0) {
|
||||
throw new OidbError(
|
||||
result.errorCode,
|
||||
result.errorMessage || '',
|
||||
spec.command,
|
||||
subCommand
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const respBytes = result.responseData ?? new Uint8Array(0);
|
||||
if (respBytes.length > 0) {
|
||||
const meta = protobuf_decode<OidbBaseMeta>(respBytes);
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { Oidb0xcdeReq, Oidb0xcdeResp } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { invokeOidb, type OidbSender } from '../../oidb-service';
|
||||
|
||||
export namespace RequestDbKey {
|
||||
export const command = 0xcde;
|
||||
export const subCommand = 2;
|
||||
|
||||
export interface Params {
|
||||
db_salt: string;
|
||||
sessionData?: Uint8Array;
|
||||
}
|
||||
|
||||
export interface Result {
|
||||
success: boolean;
|
||||
dbKey?: string;
|
||||
errorCode?: number;
|
||||
errorMsg?: string;
|
||||
}
|
||||
|
||||
export type Deps = OidbSender;
|
||||
|
||||
export const serialize = (_ctx: Deps, p: Params): Oidb0xcdeReq => {
|
||||
const req: Oidb0xcdeReq = {
|
||||
info: {
|
||||
db_salt: p.db_salt,
|
||||
}
|
||||
};
|
||||
if (p.sessionData) {
|
||||
req.sessionData = p.sessionData;
|
||||
}
|
||||
return req;
|
||||
};
|
||||
|
||||
export const deserialize = (_ctx: Deps, body: Oidb0xcdeResp): string => {
|
||||
const dbKey = body.info?.dbKey;
|
||||
|
||||
if (!dbKey) {
|
||||
throw new Error('Oidb 0xcde_2 payload empty (Missing dbKey)');
|
||||
}
|
||||
return dbKey;
|
||||
};
|
||||
|
||||
export const encode = (env: OidbBase<Oidb0xcdeReq>): Uint8Array =>
|
||||
protobuf_encode<OidbBase<Oidb0xcdeReq>>(env);
|
||||
|
||||
export const decode = (bytes: Uint8Array): OidbBase<Oidb0xcdeResp> =>
|
||||
protobuf_decode<OidbBase<Oidb0xcdeResp>>(bytes);
|
||||
|
||||
export const invoke = async (deps: Deps, params: Params): Promise<Result> => {
|
||||
try {
|
||||
const key = await invokeOidb(deps, RequestDbKey, params);
|
||||
return {
|
||||
success: true,
|
||||
dbKey: key,
|
||||
};
|
||||
} catch (error: any) {
|
||||
const code = error?.code ?? -1;
|
||||
|
||||
return {
|
||||
success: false,
|
||||
errorCode: code,
|
||||
errorMsg: code === 1006
|
||||
? "数据库不匹配!检查数据库是否属于当前帐号"
|
||||
: (error?.serverMsg || error?.message || "网络或包结构解析失败"),
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -26,12 +26,18 @@ describe('MuteAll namespace', () => {
|
||||
expect(env.body).toMatchObject({ groupUin: 12345, muteState: { state: 0xFFFFFFFF } });
|
||||
});
|
||||
|
||||
it('enable=false emits state=0', async () => {
|
||||
it('enable=false forces state=0 ONTO the wire (so the server can disambiguate)', async () => {
|
||||
const deps = makeDeps();
|
||||
await MuteAll.invoke(deps, { groupId: 12345, enable: false });
|
||||
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
|
||||
const env = protobuf_decode<OidbBase<OidbMuteAll>>(bytes);
|
||||
// proto3 default 0 fields are omitted on the wire.
|
||||
expect(env.body?.muteState?.state ?? 0).toBe(0);
|
||||
expect(env.body?.muteState?.state).toBe(0);
|
||||
// The fix (issue #70): state=0 is a `pb_optional<>` field, so it must be
|
||||
// PRESENT on the wire — field 17 (varint tag 0x88 0x01) + value 0x00 — not
|
||||
// omitted. An empty `muteState` is indistinguishable from the other
|
||||
// commands sharing OIDB (0x89A, 0), so the server rejects unmute with 1007.
|
||||
const arr = Array.from(bytes);
|
||||
const hasStateField = arr.some((_, i) => arr[i] === 0x88 && arr[i + 1] === 0x01 && arr[i + 2] === 0x00);
|
||||
expect(hasStateField).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/proton",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.3",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.",
|
||||
|
||||
8
packages/proton/protobuf.d.ts
vendored
8
packages/proton/protobuf.d.ts
vendored
@@ -3,6 +3,14 @@
|
||||
export type pb<_ProtoNumber extends number, Type> = Type;
|
||||
/** Marks a repeated protobuf field: `ids: pb_repeated<fieldNumber, Type>` → Type[] */
|
||||
export type pb_repeated<_ProtoNumber extends number, Type> = Type[];
|
||||
/**
|
||||
* Marks a singular field with **explicit presence** (proto3 `optional`): it
|
||||
* serialises whenever the value is present, INCLUDING its zero/default value
|
||||
* — unlike `pb<>`, which omits zeros. Use when the wire peer needs the field
|
||||
* present to disambiguate, e.g. an OIDB sub-command keyed on body shape where
|
||||
* a zero must still appear on the wire. `name: pb_optional<fieldNumber, Type>`.
|
||||
*/
|
||||
export type pb_optional<_ProtoNumber extends number, Type> = Type;
|
||||
|
||||
// ── Protobuf primitive types ──────────────────────────────────────────
|
||||
export type uint_32 = number;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import ts from 'typescript';
|
||||
import {
|
||||
WireType,
|
||||
PB_MARKER, PB_REPEATED_MARKER,
|
||||
PB_MARKER, PB_REPEATED_MARKER, PB_OPTIONAL_MARKER,
|
||||
type ProtobufField, type ProtobufMessage,
|
||||
type GenericProtobufTemplate, type GenericFieldTemplate,
|
||||
} from './types.js';
|
||||
@@ -85,7 +85,7 @@ function parsePbTypeRef(
|
||||
// Resolve the marker name through aliased imports so `import { pb as P }`
|
||||
// / `import { pb_repeated as PR }` still match the marker constants.
|
||||
const marker = resolveImportedTypeName(t.typeName.text);
|
||||
if (marker !== PB_MARKER && marker !== PB_REPEATED_MARKER) return null;
|
||||
if (marker !== PB_MARKER && marker !== PB_REPEATED_MARKER && marker !== PB_OPTIONAL_MARKER) return null;
|
||||
const ta = t.typeArguments;
|
||||
if (!ta || ta.length !== 2) return null;
|
||||
const fnNode = ta[0];
|
||||
@@ -129,6 +129,7 @@ function extractField(
|
||||
isMessage: false, // placeholder
|
||||
isOptional: member.questionToken != null,
|
||||
isRepeated: parsed.marker === PB_REPEATED_MARKER,
|
||||
explicitPresence: parsed.marker === PB_OPTIONAL_MARKER,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -149,6 +150,7 @@ function extractGenericField(
|
||||
isTypeParam: tpSet.has(raw),
|
||||
isOptional: member.questionToken != null,
|
||||
isRepeated: parsed.marker === PB_REPEATED_MARKER,
|
||||
explicitPresence: parsed.marker === PB_OPTIONAL_MARKER,
|
||||
};
|
||||
// If the field's type-arg is itself a generic instantiation (`Wrapper<U>`,
|
||||
// where U is a type param of the enclosing template), capture the original
|
||||
|
||||
@@ -89,6 +89,7 @@ export function monomorphizeTypeNode(
|
||||
isMessage: false,
|
||||
isOptional: f.isOptional,
|
||||
isRepeated: f.isRepeated,
|
||||
explicitPresence: f.explicitPresence,
|
||||
};
|
||||
}
|
||||
return {
|
||||
@@ -99,6 +100,7 @@ export function monomorphizeTypeNode(
|
||||
isMessage: false,
|
||||
isOptional: f.isOptional,
|
||||
isRepeated: f.isRepeated,
|
||||
explicitPresence: f.explicitPresence,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -13,6 +13,14 @@ export interface ProtobufField {
|
||||
isMessage: boolean;
|
||||
isOptional: boolean;
|
||||
isRepeated: boolean;
|
||||
/**
|
||||
* Explicit presence (proto3 `optional`), set only by the `pb_optional<>`
|
||||
* marker. When true, a scalar field serialises even at its zero/default
|
||||
* value. Distinct from `isOptional` (which merely tracks the TS `?` and is
|
||||
* true for almost every field) — the encoder keys off THIS flag, never
|
||||
* `isOptional`, so existing `pb<>` fields are unaffected.
|
||||
*/
|
||||
explicitPresence: boolean;
|
||||
}
|
||||
|
||||
export interface ProtobufMessage {
|
||||
@@ -34,6 +42,8 @@ export interface GenericFieldTemplate {
|
||||
isTypeParam: boolean;
|
||||
isOptional: boolean;
|
||||
isRepeated: boolean;
|
||||
/** Explicit presence (proto3 `optional`); see ProtobufField.explicitPresence. */
|
||||
explicitPresence: boolean;
|
||||
/**
|
||||
* For fields whose type-arg is itself a generic instantiation
|
||||
* (e.g. `wrapped: pb<5, Wrapper<U>>` where `U` is a template type
|
||||
@@ -70,3 +80,4 @@ export const PRIMITIVE_TYPE_MAP: Record<string, { wireType: WireType; defaultVal
|
||||
/** Marker identifiers recognised in type references */
|
||||
export const PB_MARKER = 'pb';
|
||||
export const PB_REPEATED_MARKER = 'pb_repeated';
|
||||
export const PB_OPTIONAL_MARKER = 'pb_optional';
|
||||
|
||||
@@ -91,6 +91,14 @@ export function generateEncoder(msg: ProtobufMessage, _registry: MessageRegistry
|
||||
|
||||
function buildSingularBlock(field: ProtobufField, index: number): EncoderBlock {
|
||||
const { name, fieldNumber, typeName, wireType, isMessage } = field;
|
||||
// `pb_optional<>` scalar → serialise even at the zero value (proto3 explicit
|
||||
// presence). Message fields already emit on `!= null`, so they stay on the
|
||||
// default path; only scalars need the dedicated guard. Every `pb<>` /
|
||||
// `pb_repeated<>` field has `explicitPresence === false` and so takes the
|
||||
// untouched branches below — their generated code is byte-for-byte unchanged.
|
||||
if (field.explicitPresence && !isMessage) {
|
||||
return buildExplicitPresenceScalarBlock(field, index);
|
||||
}
|
||||
const valueVar = `_f${index}`;
|
||||
const cacheVar = `_c${index}`;
|
||||
const tagLength = computeTagBytes(fieldNumber, isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType).length;
|
||||
@@ -318,6 +326,221 @@ function buildSingularBlock(field: ProtobufField, index: number): EncoderBlock {
|
||||
return { declare: [], size: [], write: [] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Encoder block for a singular scalar field marked `pb_optional<>` (proto3
|
||||
* explicit presence). Identical to the default scalar paths EXCEPT the guard
|
||||
* is `!= null` instead of `!= null && !== <default>`, so the field — and a
|
||||
* `bool`'s real value — is written even when zero/false/empty. Reached only
|
||||
* when `field.explicitPresence === true`, so default `pb<>` fields never run
|
||||
* this code.
|
||||
*/
|
||||
function buildExplicitPresenceScalarBlock(field: ProtobufField, index: number): EncoderBlock {
|
||||
const { name, fieldNumber, typeName, wireType } = field;
|
||||
const valueVar = `_f${index}`;
|
||||
const cacheVar = `_c${index}`;
|
||||
const isLenDelim = typeName === 'string' || typeName === 'bytes';
|
||||
const tagLength = computeTagBytes(fieldNumber, isLenDelim ? 2 : wireType).length;
|
||||
const declareVal = ` const ${valueVar} = obj.${name};`;
|
||||
const present = `${valueVar} != null`;
|
||||
|
||||
if (typeName === 'string') {
|
||||
return {
|
||||
declare: [declareVal, ` let ${cacheVar};`],
|
||||
size: [
|
||||
` if (${present}) {`,
|
||||
` ${cacheVar} = __utf8Len(${valueVar});`,
|
||||
` const _len = ${cacheVar};`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_len', ' '),
|
||||
` size += _len;`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
writeTag(fieldNumber, 2, ' '),
|
||||
` const _len = ${cacheVar};`,
|
||||
writeVarint('_len', ' '),
|
||||
` offset = __utf8Write(buf, offset, ${valueVar});`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'bytes') {
|
||||
return {
|
||||
declare: [declareVal],
|
||||
size: [
|
||||
` if (${present}) {`,
|
||||
` const _len = ${valueVar}.length;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_len', ' '),
|
||||
` size += _len;`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
writeTag(fieldNumber, 2, ' '),
|
||||
` const _len = ${valueVar}.length;`,
|
||||
writeVarint('_len', ' '),
|
||||
` buf.set(${valueVar}, offset);`,
|
||||
` offset += _len;`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'bool') {
|
||||
return {
|
||||
declare: [declareVal],
|
||||
size: [` if (${present}) size += ${tagLength + 1};`],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
` buf[offset++] = ${valueVar} ? 1 : 0;`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (isVarint64(typeName)) {
|
||||
const bigintExpr = bigintVarintExpr(typeName, valueVar);
|
||||
return {
|
||||
declare: [declareVal],
|
||||
size: [
|
||||
` if (${present}) {`,
|
||||
` const _val = ${bigintExpr};`,
|
||||
` size += ${tagLength};`,
|
||||
` size += __varint64Size(_val);`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
` const _val = ${bigintExpr};`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
` offset = __writeVarint64(buf, offset, _val);`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'sint_32') {
|
||||
return {
|
||||
declare: [declareVal],
|
||||
size: [
|
||||
` if (${present}) {`,
|
||||
` const _val = ((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_val', ' '),
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
writeVarint(`((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0`, ' '),
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (wireType === WireType.Varint) {
|
||||
return {
|
||||
declare: [declareVal],
|
||||
size: [
|
||||
` if (${present}) {`,
|
||||
` const _val = ${valueVar} >>> 0;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_val', ' '),
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
writeVarint(`${valueVar} >>> 0`, ' '),
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'float') {
|
||||
return {
|
||||
declare: [declareVal],
|
||||
size: [` if (${present}) size += ${tagLength + 4};`],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
writeTag(fieldNumber, 5, ' '),
|
||||
` offset = __writeFloat32(buf, offset, ${valueVar});`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (wireType === WireType.Bit32) {
|
||||
return {
|
||||
declare: [declareVal],
|
||||
size: [` if (${present}) size += ${tagLength + 4};`],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
writeTag(fieldNumber, 5, ' '),
|
||||
` const _val = ${valueVar};`,
|
||||
` buf[offset++] = _val & 0xff;`,
|
||||
` buf[offset++] = (_val >> 8) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 16) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 24) & 0xff;`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'double') {
|
||||
return {
|
||||
declare: [declareVal],
|
||||
size: [` if (${present}) size += ${tagLength + 8};`],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
writeTag(fieldNumber, 1, ' '),
|
||||
` offset = __writeFloat64(buf, offset, ${valueVar});`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (isFixed64BigInt(typeName)) {
|
||||
return {
|
||||
declare: [declareVal],
|
||||
size: [` if (${present}) size += ${tagLength + 8};`],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
writeTag(fieldNumber, 1, ' '),
|
||||
` offset = __writeFixed64(buf, offset, ${valueVar});`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (wireType === WireType.Bit64) {
|
||||
return {
|
||||
declare: [declareVal],
|
||||
size: [` if (${present}) size += ${tagLength + 8};`],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
writeTag(fieldNumber, 1, ' '),
|
||||
` const _val = ${valueVar};`,
|
||||
` buf[offset++] = _val & 0xff;`,
|
||||
` buf[offset++] = (_val >> 8) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 16) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 24) & 0xff;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
return { declare: [], size: [], write: [] };
|
||||
}
|
||||
|
||||
function buildRepeatedBlock(field: ProtobufField, index: number): EncoderBlock {
|
||||
const { name, fieldNumber, typeName, wireType, isMessage } = field;
|
||||
const arrayVar = `_f${index}`;
|
||||
|
||||
@@ -25,6 +25,7 @@ function cloneField(field: ProtobufField): ProtobufField {
|
||||
isMessage: field.isMessage,
|
||||
isOptional: field.isOptional,
|
||||
isRepeated: field.isRepeated,
|
||||
explicitPresence: field.explicitPresence ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -139,3 +139,43 @@ interface DoubleMsg {
|
||||
expect(result.values[1]).toBeCloseTo(-0.5);
|
||||
});
|
||||
});
|
||||
|
||||
describe('pb_optional explicit presence', () => {
|
||||
it('serialises a zero scalar (where pb<> would omit it)', () => {
|
||||
const { enc, dec } = makeRoundTripFromSchema(
|
||||
`interface OptMsg { forced: pb_optional<1, uint_32>; }`,
|
||||
'OptMsg',
|
||||
);
|
||||
// field 1, varint, value 0 → tag 0x08 then payload 0x00 (NOT empty).
|
||||
expect(Array.from(enc({ forced: 0 }))).toEqual([0x08, 0x00]);
|
||||
expect(dec(enc({ forced: 0 })).forced).toBe(0);
|
||||
});
|
||||
|
||||
it('still omits the field when the value is absent (undefined)', () => {
|
||||
const { enc } = makeRoundTripFromSchema(
|
||||
`interface OptMsg2 { forced: pb_optional<1, uint_32>; }`,
|
||||
'OptMsg2',
|
||||
);
|
||||
expect(enc({}).length).toBe(0);
|
||||
});
|
||||
|
||||
it('does not change a sibling plain pb<> field (it still omits its zero)', () => {
|
||||
const { enc, dec } = makeRoundTripFromSchema(
|
||||
`interface MixMsg { plain: pb<1, uint_32>; forced: pb_optional<2, uint_32>; }`,
|
||||
'MixMsg',
|
||||
);
|
||||
// plain=0 omitted (unchanged); only forced=0 is emitted (field 2 → tag 0x10).
|
||||
expect(Array.from(enc({ plain: 0, forced: 0 }))).toEqual([0x10, 0x00]);
|
||||
expect(dec(enc({ plain: 7, forced: 9 }))).toEqual({ plain: 7, forced: 9 });
|
||||
});
|
||||
|
||||
it('forces a false bool onto the wire', () => {
|
||||
const { enc, dec } = makeRoundTripFromSchema(
|
||||
`interface BoolOpt { flag: pb_optional<1, bool>; }`,
|
||||
'BoolOpt',
|
||||
);
|
||||
expect(Array.from(enc({ flag: false }))).toEqual([0x08, 0x00]);
|
||||
expect(dec(enc({ flag: false })).flag).toBe(false);
|
||||
expect(Array.from(enc({ flag: true }))).toEqual([0x08, 0x01]);
|
||||
});
|
||||
});
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/runtime",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.3",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.mjs",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"name": "MotricSeven",
|
||||
"email": "motricseven@gmail.com"
|
||||
},
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.3",
|
||||
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
|
||||
"keywords": [
|
||||
"snowluma",
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
{
|
||||
"name": "@snowluma/sqlite",
|
||||
"version": "1.9.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma SQLite wrapper. Exposes the `better-sqlite3` Database constructor + Statement type, but loads the native `.node` binding from `dist/native/sqlite/<platform>-<arch>/` at runtime instead of going through `bindings('better_sqlite3.node')` + `node_modules/.../build/Release/`. The vendored prebuilds under `packages/runtime/native/sqlite/` get copied into the dist tree by `vite-plugin-cp` during the @snowluma/core build, mirroring how `websocket-*.node` and `ffmpegAddon.*.node` are handled. The end result: production artifacts ship as a single self-contained dist/ directory with no `dist/node_modules/` and no install step at runtime.",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"default": "./src/index.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/node": "^24.12.2",
|
||||
"better-sqlite3": "12.10.0",
|
||||
"typescript": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
import BetterSqlite3 from 'better-sqlite3';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
// Re-export the public types/classes consumers need. `Database` and
|
||||
// `Statement` come straight from better-sqlite3 — we only intercept
|
||||
// the constructor at call time, not the class shape.
|
||||
export type { Database, Options, RunResult, Statement } from 'better-sqlite3';
|
||||
|
||||
function triplet(): string {
|
||||
return `${process.platform}-${process.arch}`;
|
||||
}
|
||||
|
||||
function abi(): string {
|
||||
// `process.versions.modules` is the NODE_MODULE_VERSION the running
|
||||
// Node binary expects — e.g. "127" for Node 22, "137" for Node 24.
|
||||
// Stays in sync with whatever the host actually does at load time.
|
||||
return `v${process.versions.modules}`;
|
||||
}
|
||||
|
||||
function locateBinding(): string {
|
||||
const tri = triplet();
|
||||
const fileName = `better-sqlite3-${abi()}-${tri}.node`;
|
||||
// Two candidate locations, tried in order:
|
||||
// 1. Production: dist/native/better-sqlite3-<triplet>.node
|
||||
// — `import.meta.url` resolves to dist/ at runtime (the wrapper
|
||||
// is bundled into index.mjs alongside it).
|
||||
// 2. Dev: <repo>/packages/runtime/native/better-sqlite3-<triplet>.node
|
||||
// — `import.meta.url` resolves to packages/sqlite/src/index.ts;
|
||||
// walk up to repo root + into runtime/native.
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const distCandidate = join(here, 'native', fileName);
|
||||
if (existsSync(distCandidate)) return distCandidate;
|
||||
|
||||
// From packages/sqlite/src ⇢ go up to packages/, then into
|
||||
// runtime/native. (Two `..` segments, not three — `src` → `sqlite/`
|
||||
// → `packages/`, then descend into `runtime/native`.)
|
||||
const devCandidate = resolve(here, '..', '..', 'runtime', 'native', fileName);
|
||||
if (existsSync(devCandidate)) return devCandidate;
|
||||
|
||||
throw new Error(
|
||||
`@snowluma/sqlite: could not locate ${fileName}. ` +
|
||||
`Tried:\n ${distCandidate}\n ${devCandidate}\n` +
|
||||
`Run \`node tools/fetch-sqlite-prebuilts.mjs\` to vendor the missing platform binary.`,
|
||||
);
|
||||
}
|
||||
|
||||
// Load the native addon once at module import — keeping it module-
|
||||
// scoped so the require() cost is paid exactly once per process.
|
||||
let addon: unknown | null = null;
|
||||
function loadAddon(): unknown {
|
||||
if (addon) return addon;
|
||||
const bindingPath = locateBinding();
|
||||
// better-sqlite3 expects the addon to be loaded via the CJS
|
||||
// require() mechanism (N-API init runs through it). createRequire
|
||||
// is the ESM-safe way to do that with an absolute path.
|
||||
const req = createRequire(import.meta.url);
|
||||
addon = req(bindingPath);
|
||||
return addon;
|
||||
}
|
||||
|
||||
// Drop-in `Database` factory. Matches the better-sqlite3 default-
|
||||
// export signature exactly: `new Database(filename[, options])` →
|
||||
// `Database` instance.
|
||||
//
|
||||
// We can't just `class extends BetterSqlite3` because better-sqlite3's
|
||||
// default export is a function that returns the instance (the `new
|
||||
// Database(...)` shape works through that function's `new.target`
|
||||
// check). Wrapping at the function-call boundary keeps that contract
|
||||
// intact.
|
||||
type BetterSqlite3Type = typeof BetterSqlite3;
|
||||
type DatabaseInstance = InstanceType<BetterSqlite3Type>;
|
||||
type DatabaseOptions = ConstructorParameters<BetterSqlite3Type>[1];
|
||||
type BetterSqlite3Constructor = new (filename?: string | Buffer, options?: DatabaseOptions) => DatabaseInstance;
|
||||
|
||||
const Database = function Database(filename?: string | Buffer, options?: DatabaseOptions): DatabaseInstance {
|
||||
const opts = { ...(options ?? {}), nativeBinding: loadAddon() } as DatabaseOptions;
|
||||
// better-sqlite3 的默认导出同时支持函数调用和 new 调用;这里只需要构造器形态。
|
||||
return new (BetterSqlite3 as unknown as BetterSqlite3Constructor)(filename, opts);
|
||||
} as unknown as BetterSqlite3Type;
|
||||
|
||||
export default Database;
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
"name": "MotricSeven",
|
||||
"email": "motricseven@gmail.com"
|
||||
},
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.3",
|
||||
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
|
||||
"keywords": [
|
||||
"snowluma",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/websocket",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.3",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "webui",
|
||||
"private": true,
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.3",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -21,6 +21,11 @@ function AuthBoundary() {
|
||||
const [authed, setAuthed] = useState(false);
|
||||
const [mustChange, setMustChange] = useState(false);
|
||||
const [status, setStatus] = useState('未连接');
|
||||
// The password from *this* session's login, carried into the forced
|
||||
// change-password gate so it doesn't have to render an old-password field
|
||||
// (which browsers autofill, misleading users on upgrade). Stays undefined
|
||||
// for a returning session that's already authed but still must change.
|
||||
const [loginPassword, setLoginPassword] = useState<string | undefined>(undefined);
|
||||
|
||||
const client = useMemo<ApiClient>(
|
||||
() =>
|
||||
@@ -63,14 +68,21 @@ function AuthBoundary() {
|
||||
</div>
|
||||
) : !authed ? (
|
||||
<LoginGate
|
||||
onAuthed={(needsChange) => {
|
||||
onAuthed={(needsChange, password) => {
|
||||
setAuthed(true);
|
||||
setStatus('已连接');
|
||||
setMustChange(needsChange);
|
||||
setLoginPassword(password);
|
||||
}}
|
||||
/>
|
||||
) : mustChange ? (
|
||||
<ForcedChangePasswordGate onSuccess={() => setMustChange(false)} />
|
||||
<ForcedChangePasswordGate
|
||||
knownOldPassword={loginPassword}
|
||||
onSuccess={() => {
|
||||
setMustChange(false);
|
||||
setLoginPassword(undefined);
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<SessionProvider value={{ status, onLogoutComplete: handleLogoutComplete }}>
|
||||
<RouterProvider router={appRouter} />
|
||||
@@ -81,13 +93,13 @@ function AuthBoundary() {
|
||||
);
|
||||
}
|
||||
|
||||
function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean) => void }) {
|
||||
function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean, password: string) => void }) {
|
||||
const api = useApi();
|
||||
const handleLogin = useCallback(
|
||||
async (password: string) => {
|
||||
const result = await api.login(password);
|
||||
if (!result.ok) return { success: false, error: result.message };
|
||||
onAuthed(result.mustChangePassword);
|
||||
onAuthed(result.mustChangePassword, password);
|
||||
return { success: true };
|
||||
},
|
||||
[api, onAuthed],
|
||||
@@ -95,11 +107,17 @@ function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean) => void }) {
|
||||
return <LoginPage onLogin={handleLogin} />;
|
||||
}
|
||||
|
||||
function ForcedChangePasswordGate({ onSuccess }: { onSuccess: () => void }) {
|
||||
function ForcedChangePasswordGate({
|
||||
knownOldPassword,
|
||||
onSuccess,
|
||||
}: {
|
||||
knownOldPassword?: string;
|
||||
onSuccess: () => void;
|
||||
}) {
|
||||
const api = useApi();
|
||||
return (
|
||||
<ChangePasswordPage
|
||||
forced
|
||||
knownOldPassword={knownOldPassword}
|
||||
checkStrength={(p) => api.checkPasswordStrength(p)}
|
||||
submit={(o, n) => api.changePassword(o, n)}
|
||||
onSuccess={onSuccess}
|
||||
|
||||
48
packages/webui/src/components/change-password-dialog.tsx
Normal file
48
packages/webui/src/components/change-password-dialog.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { ChangePasswordForm } from '@/components/pages/change-password-form';
|
||||
import { useApi } from '@/lib/api';
|
||||
|
||||
interface ChangePasswordDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/** Fired after the password is changed successfully (dialog closes itself). */
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* In-app "修改访问密码" modal. The forced first-time flow uses the full-screen
|
||||
* ChangePasswordPage; this is the voluntary change a logged-in admin triggers
|
||||
* from 设置 → 账号安全. Both share ChangePasswordForm, so behaviour is identical.
|
||||
*/
|
||||
export function ChangePasswordDialog({ open, onOpenChange, onSuccess }: ChangePasswordDialogProps) {
|
||||
const api = useApi();
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>修改访问密码</DialogTitle>
|
||||
<DialogDescription>
|
||||
设置一个全新的强密码后,其它会话将被立即下线,需要重新登录。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<ChangePasswordForm
|
||||
checkStrength={(p) => api.checkPasswordStrength(p)}
|
||||
submit={(o, n) => api.changePassword(o, n)}
|
||||
onSuccess={() => {
|
||||
onSuccess();
|
||||
onOpenChange(false);
|
||||
}}
|
||||
onCancel={() => onOpenChange(false)}
|
||||
idPrefix="dialog-cpw"
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -9,11 +9,27 @@ import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { AdapterCommon } from './defaults';
|
||||
import type { AdapterStatus } from '@/types';
|
||||
|
||||
const LIVE_STYLE: Record<AdapterStatus['status'], string> = {
|
||||
ok: 'bg-success/10 text-success',
|
||||
warn: 'bg-warning/10 text-warning',
|
||||
down: 'bg-destructive/10 text-destructive',
|
||||
disabled: 'bg-muted text-muted-foreground',
|
||||
};
|
||||
const LIVE_LABEL: Record<AdapterStatus['status'], string> = {
|
||||
ok: '正常',
|
||||
warn: '注意',
|
||||
down: '异常',
|
||||
disabled: '未启用',
|
||||
};
|
||||
|
||||
interface NodeSummaryCardProps<T extends AdapterCommon> {
|
||||
item: T;
|
||||
summary: string;
|
||||
duplicateName: boolean;
|
||||
/** Live runtime status from the OneBot manager, matched by adapter name. */
|
||||
liveStatus?: AdapterStatus;
|
||||
onToggleEnabled: (next: boolean) => void;
|
||||
onEdit: () => void;
|
||||
onDelete: () => void;
|
||||
@@ -23,6 +39,7 @@ export function NodeSummaryCard<T extends AdapterCommon>({
|
||||
item,
|
||||
summary,
|
||||
duplicateName,
|
||||
liveStatus,
|
||||
onToggleEnabled,
|
||||
onEdit,
|
||||
onDelete,
|
||||
@@ -51,6 +68,14 @@ export function NodeSummaryCard<T extends AdapterCommon>({
|
||||
{!enabled && (
|
||||
<Badge variant="secondary" className="font-normal">已停用</Badge>
|
||||
)}
|
||||
{liveStatus && (
|
||||
<span
|
||||
className={cn('rounded px-1.5 py-0.5 text-[10px] font-medium', LIVE_STYLE[liveStatus.status])}
|
||||
title={liveStatus.detail}
|
||||
>
|
||||
{LIVE_LABEL[liveStatus.status]} · {liveStatus.detail}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-0.5 truncate font-mono text-xs text-muted-foreground tabular-nums">{summary}</div>
|
||||
<div className="mt-1.5 flex flex-wrap items-center gap-1.5">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState, type ReactNode } from 'react';
|
||||
import { motion, AnimatePresence } from 'motion/react';
|
||||
import { useRouterState } from '@tanstack/react-router';
|
||||
import { Sheet, SheetContent } from '@/components/ui/sheet';
|
||||
import { Sheet, SheetContent, SheetDescription, SheetTitle } from '@/components/ui/sheet';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Sidebar } from '@/components/layout/sidebar';
|
||||
import { TopBar } from '@/components/layout/top-bar';
|
||||
@@ -44,6 +44,11 @@ export function MainLayout({ status, onLogout, children }: MainLayoutProps) {
|
||||
{isMobile && (
|
||||
<Sheet open={mobileOpen} onOpenChange={setMobileOpen}>
|
||||
<SheetContent side="left" className="w-64 max-w-[80vw] p-0">
|
||||
{/* Radix Dialog (the Sheet primitive) requires an accessible name +
|
||||
description; the nav itself is the visible content, so these are
|
||||
screen-reader-only. */}
|
||||
<SheetTitle className="sr-only">导航菜单</SheetTitle>
|
||||
<SheetDescription className="sr-only">切换 SnowLuma 控制台的页面。</SheetDescription>
|
||||
<Sidebar onItemClick={() => setMobileOpen(false)} />
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
@@ -62,7 +67,7 @@ export function MainLayout({ status, onLogout, children }: MainLayoutProps) {
|
||||
|
||||
<main className={cn('flex min-h-0 flex-1 flex-col')}>
|
||||
<ScrollArea className="flex-1 min-h-0" viewportClassName="[&>div]:!block">
|
||||
<div className="mx-auto w-full max-w-7xl px-4 py-5 sm:px-6 sm:py-6 lg:px-8">
|
||||
<div className="mx-auto w-full max-w-7xl px-4 py-5 sm:px-6 sm:py-6 lg:px-8 2xl:max-w-[1600px]">
|
||||
<AnimatePresence mode="wait">
|
||||
<motion.div
|
||||
key={pathname}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { LayoutDashboard, Settings, SlidersHorizontal, Terminal } from 'lucide-react';
|
||||
import { LayoutDashboard, PlugZap, Settings, SlidersHorizontal, Terminal } from 'lucide-react';
|
||||
import { motion } from 'motion/react';
|
||||
import { Link, useRouterState } from '@tanstack/react-router';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
@@ -16,6 +16,7 @@ export interface NavItem {
|
||||
|
||||
export const NAV_ITEMS: NavItem[] = [
|
||||
{ to: '/', label: '总览', icon: LayoutDashboard, description: '主机与服务状态' },
|
||||
{ to: '/processes', label: '进程注入', icon: PlugZap, description: '加载 / 卸载 / 登录' },
|
||||
{ to: '/config', label: '节点配置', icon: Settings, description: 'OneBot 协议端点' },
|
||||
{ to: '/logs', label: '日志', icon: Terminal, description: '实时事件流' },
|
||||
{ to: '/settings', label: '系统设置', icon: SlidersHorizontal, description: '主题与账号' },
|
||||
|
||||
262
packages/webui/src/components/pages/change-password-form.tsx
Normal file
262
packages/webui/src/components/pages/change-password-form.tsx
Normal file
@@ -0,0 +1,262 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { motion, AnimatePresence } from 'motion/react';
|
||||
import { Check, Eye, EyeOff, Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export interface PasswordRule {
|
||||
id: string;
|
||||
label: string;
|
||||
ok: boolean;
|
||||
}
|
||||
|
||||
export interface ChangePasswordFormProps {
|
||||
/**
|
||||
* When provided, the "current password" field is omitted entirely and this
|
||||
* value is used as the old password.
|
||||
*
|
||||
* Used by the forced first-time flow: the old password is *exactly* what
|
||||
* the user just logged in with, so we fill it ourselves. Rendering the
|
||||
* field at all let Edge/Chrome password-managers autofill it on upgrade —
|
||||
* users saw it pre-filled, assumed it was correct, and could never save
|
||||
* (the autofilled value was stale / not the temp password). Dropping the
|
||||
* field removes the trap entirely.
|
||||
*/
|
||||
knownOldPassword?: string;
|
||||
/** Sends `{ password }`; returns the rule list + valid flag. */
|
||||
checkStrength: (password: string) => Promise<{ rules: PasswordRule[]; valid: boolean }>;
|
||||
/** Sends `{ oldPassword, newPassword }`. Returns success or error message. */
|
||||
submit: (oldPassword: string, newPassword: string) => Promise<{ success: boolean; message?: string }>;
|
||||
/** Called after a successful submit. */
|
||||
onSuccess: () => void;
|
||||
/** When provided, a cancel button is shown (used by the settings dialog). */
|
||||
onCancel?: () => void;
|
||||
/** Disambiguates input ids if two instances ever mount at once. */
|
||||
idPrefix?: string;
|
||||
submitLabel?: string;
|
||||
}
|
||||
|
||||
export function ChangePasswordForm({
|
||||
knownOldPassword,
|
||||
checkStrength,
|
||||
submit,
|
||||
onSuccess,
|
||||
onCancel,
|
||||
idPrefix = 'cpw',
|
||||
submitLabel = '保存新密码',
|
||||
}: ChangePasswordFormProps) {
|
||||
const carriesOld = knownOldPassword !== undefined;
|
||||
|
||||
const [oldPassword, setOldPassword] = useState('');
|
||||
const [newPassword, setNewPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [showOld, setShowOld] = useState(false);
|
||||
const [showNew, setShowNew] = useState(false);
|
||||
const [rules, setRules] = useState<PasswordRule[]>([]);
|
||||
const [valid, setValid] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const effectiveOld = carriesOld ? (knownOldPassword as string) : oldPassword;
|
||||
const confirmMatches = newPassword.length > 0 && newPassword === confirmPassword;
|
||||
const canSubmit =
|
||||
!submitting && effectiveOld.length > 0 && valid && confirmMatches && effectiveOld !== newPassword;
|
||||
|
||||
// Debounce the strength check so we don't slam the API on every keystroke.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const handle = window.setTimeout(async () => {
|
||||
try {
|
||||
const res = await checkStrength(newPassword);
|
||||
if (cancelled) return;
|
||||
setRules(res.rules);
|
||||
setValid(res.valid);
|
||||
} catch {
|
||||
/* ignore – the form will just stay disabled */
|
||||
}
|
||||
}, 180);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.clearTimeout(handle);
|
||||
};
|
||||
}, [newPassword, checkStrength]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!canSubmit) return;
|
||||
setSubmitting(true);
|
||||
setError('');
|
||||
try {
|
||||
const res = await submit(effectiveOld, newPassword);
|
||||
if (res.success) {
|
||||
onSuccess();
|
||||
} else {
|
||||
setError(res.message || '修改失败');
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : '网络错误');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
|
||||
{!carriesOld && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor={`${idPrefix}-old`}>当前密码</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id={`${idPrefix}-old`}
|
||||
type={showOld ? 'text' : 'password'}
|
||||
autoComplete="current-password"
|
||||
value={oldPassword}
|
||||
onChange={(e) => setOldPassword(e.target.value)}
|
||||
placeholder="输入当前访问密码"
|
||||
className="h-10 pr-10 text-sm"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowOld((v) => !v)}
|
||||
aria-label={showOld ? '隐藏密码' : '显示密码'}
|
||||
tabIndex={-1}
|
||||
className="absolute right-2 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
{showOld ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor={`${idPrefix}-new`}>新密码</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id={`${idPrefix}-new`}
|
||||
type={showNew ? 'text' : 'password'}
|
||||
autoComplete="new-password"
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
placeholder="设置新的强密码"
|
||||
className="h-10 pr-10 text-sm"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowNew((v) => !v)}
|
||||
aria-label={showNew ? '隐藏密码' : '显示密码'}
|
||||
tabIndex={-1}
|
||||
className="absolute right-2 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
{showNew ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor={`${idPrefix}-confirm`}>确认新密码</Label>
|
||||
<Input
|
||||
id={`${idPrefix}-confirm`}
|
||||
type={showNew ? 'text' : 'password'}
|
||||
autoComplete="new-password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
placeholder="再次输入新密码"
|
||||
className="h-10 text-sm"
|
||||
/>
|
||||
{confirmPassword.length > 0 && !confirmMatches && (
|
||||
<span className="text-[11px] text-destructive">两次输入的密码不一致</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<RuleList rules={rules} />
|
||||
|
||||
<AnimatePresence>
|
||||
{error && (
|
||||
<motion.p
|
||||
initial={{ opacity: 0, y: -4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0 }}
|
||||
className="rounded-md bg-destructive/10 px-3 py-2 text-center text-xs text-destructive"
|
||||
>
|
||||
{error}
|
||||
</motion.p>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{onCancel && (
|
||||
<Button type="button" variant="ghost" onClick={onCancel} className="h-10">
|
||||
取消
|
||||
</Button>
|
||||
)}
|
||||
<Button type="submit" disabled={!canSubmit} className="ml-auto h-10">
|
||||
{submitting ? (
|
||||
<>
|
||||
<Loader2 className="size-4 animate-spin" /> 提交中…
|
||||
</>
|
||||
) : (
|
||||
submitLabel
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function RuleList({ rules }: { rules: PasswordRule[] }) {
|
||||
// Initial empty state: show a placeholder set so the user knows the rules
|
||||
// exist even before any input.
|
||||
const display = useMemo<PasswordRule[]>(() => {
|
||||
if (rules.length > 0) return rules;
|
||||
return [
|
||||
{ id: 'length', label: '长度不少于 10 位', ok: false },
|
||||
{ id: 'lower', label: '至少包含一个小写字母', ok: false },
|
||||
{ id: 'upper', label: '至少包含一个大写字母', ok: false },
|
||||
{ id: 'special', label: '至少包含一个特殊字符', ok: false },
|
||||
{ id: 'no-space', label: '不得包含空格', ok: false },
|
||||
];
|
||||
}, [rules]);
|
||||
|
||||
return (
|
||||
<ul className="grid gap-1.5 rounded-lg border bg-muted/30 p-3">
|
||||
{display.map((rule) => (
|
||||
<li key={rule.id} className="flex items-center gap-2">
|
||||
<motion.span
|
||||
initial={false}
|
||||
animate={{
|
||||
backgroundColor: rule.ok ? 'color-mix(in oklab, var(--primary) 20%, transparent)' : 'transparent',
|
||||
borderColor: rule.ok ? 'var(--primary)' : 'var(--border)',
|
||||
scale: rule.ok ? [1, 1.18, 1] : 1,
|
||||
}}
|
||||
transition={{ duration: 0.25 }}
|
||||
className={cn('flex size-4 items-center justify-center rounded-full border')}
|
||||
>
|
||||
<AnimatePresence>
|
||||
{rule.ok && (
|
||||
<motion.span
|
||||
key="check"
|
||||
initial={{ opacity: 0, scale: 0.4 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.4 }}
|
||||
transition={{ duration: 0.18 }}
|
||||
>
|
||||
<Check className="size-3 text-primary" strokeWidth={3} />
|
||||
</motion.span>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</motion.span>
|
||||
<motion.span
|
||||
initial={false}
|
||||
animate={{ color: rule.ok ? 'var(--foreground)' : 'var(--muted-foreground)' }}
|
||||
transition={{ duration: 0.2 }}
|
||||
className="text-xs"
|
||||
>
|
||||
{rule.label}
|
||||
</motion.span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
@@ -1,104 +1,40 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { motion, AnimatePresence } from 'motion/react';
|
||||
import { Check, Eye, EyeOff, KeyRound, Loader2, ShieldAlert } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { motion } from 'motion/react';
|
||||
import { ShieldAlert } from 'lucide-react';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { ThemeToggle } from '@/components/theme-toggle';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ChangePasswordForm, type PasswordRule } from '@/components/pages/change-password-form';
|
||||
|
||||
export interface PasswordRule {
|
||||
id: string;
|
||||
label: string;
|
||||
ok: boolean;
|
||||
}
|
||||
// Re-exported so existing importers (e.g. the API client) keep resolving
|
||||
// `PasswordRule` from this module after the form was extracted.
|
||||
export type { PasswordRule };
|
||||
|
||||
interface ChangePasswordPageProps {
|
||||
/** When true, this is the forced first-time change flow. */
|
||||
forced?: boolean;
|
||||
/** Heading shown above the form. */
|
||||
/**
|
||||
* The password the user just logged in with. Passed straight through to the
|
||||
* form as `knownOldPassword`, so the forced flow never renders an
|
||||
* old-password field for a browser to autofill. See change-password-form.
|
||||
*/
|
||||
knownOldPassword?: string;
|
||||
title?: string;
|
||||
/** Subheading. */
|
||||
description?: string;
|
||||
/** Sends `{ password }` and returns the rule list + valid flag. */
|
||||
checkStrength: (password: string) => Promise<{ rules: PasswordRule[]; valid: boolean }>;
|
||||
/** Sends `{ oldPassword, newPassword }`. Returns success or error message. */
|
||||
submit: (oldPassword: string, newPassword: string) => Promise<{ success: boolean; message?: string }>;
|
||||
/** Called after a successful submit. */
|
||||
onSuccess: () => void;
|
||||
/** Called when user cancels (only available when not forced). */
|
||||
onCancel?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Full-screen "you must set a new password before continuing" gate, shown
|
||||
* once right after the first login with a generated temp password. The
|
||||
* in-app "修改访问密码" action uses ChangePasswordDialog instead.
|
||||
*/
|
||||
export function ChangePasswordPage({
|
||||
forced = false,
|
||||
title,
|
||||
description,
|
||||
knownOldPassword,
|
||||
title = '请先设置新的访问密码',
|
||||
description = '为了保护你的实例,必须将首次启动生成的临时密码替换为符合下列要求的强密码。',
|
||||
checkStrength,
|
||||
submit,
|
||||
onSuccess,
|
||||
onCancel,
|
||||
}: ChangePasswordPageProps) {
|
||||
const [oldPassword, setOldPassword] = useState('');
|
||||
const [newPassword, setNewPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [showOld, setShowOld] = useState(false);
|
||||
const [showNew, setShowNew] = useState(false);
|
||||
const [rules, setRules] = useState<PasswordRule[]>([]);
|
||||
const [valid, setValid] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const confirmMatches = newPassword.length > 0 && newPassword === confirmPassword;
|
||||
const canSubmit =
|
||||
!submitting && oldPassword.length > 0 && valid && confirmMatches && oldPassword !== newPassword;
|
||||
|
||||
// Debounce the strength check so we don't slam the API on every keystroke.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const handle = window.setTimeout(async () => {
|
||||
try {
|
||||
const res = await checkStrength(newPassword);
|
||||
if (cancelled) return;
|
||||
setRules(res.rules);
|
||||
setValid(res.valid);
|
||||
} catch {
|
||||
/* ignore – the form will just stay disabled */
|
||||
}
|
||||
}, 180);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.clearTimeout(handle);
|
||||
};
|
||||
}, [newPassword, checkStrength]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!canSubmit) return;
|
||||
setSubmitting(true);
|
||||
setError('');
|
||||
try {
|
||||
const res = await submit(oldPassword, newPassword);
|
||||
if (res.success) {
|
||||
onSuccess();
|
||||
} else {
|
||||
setError(res.message || '修改失败');
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : '网络错误');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const computedTitle = title ?? (forced ? '请先设置新的访问密码' : '修改访问密码');
|
||||
const computedDescription =
|
||||
description ??
|
||||
(forced
|
||||
? '为了保护你的实例,必须将首次启动生成的临时密码替换为符合下列要求的强密码。'
|
||||
: '设置一个全新的强密码后,其他会话将被立即下线,需要重新登录。');
|
||||
|
||||
return (
|
||||
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-8">
|
||||
<div
|
||||
@@ -128,176 +64,26 @@ export function ChangePasswordPage({
|
||||
<CardContent className="p-7 sm:p-9">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex size-12 shrink-0 items-center justify-center rounded-2xl bg-primary/10 ring-1 ring-primary/20">
|
||||
{forced ? (
|
||||
<ShieldAlert className="size-6 text-primary" />
|
||||
) : (
|
||||
<KeyRound className="size-6 text-primary" />
|
||||
)}
|
||||
<ShieldAlert className="size-6 text-primary" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<h1 className="text-lg font-semibold tracking-tight">{computedTitle}</h1>
|
||||
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">{computedDescription}</p>
|
||||
<h1 className="text-lg font-semibold tracking-tight">{title}</h1>
|
||||
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">{description}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="mt-6 flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="old">当前密码</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="old"
|
||||
type={showOld ? 'text' : 'password'}
|
||||
autoComplete="current-password"
|
||||
value={oldPassword}
|
||||
onChange={(e) => setOldPassword(e.target.value)}
|
||||
placeholder="输入当前访问密码"
|
||||
className="h-10 pr-10 text-sm"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowOld((v) => !v)}
|
||||
aria-label={showOld ? '隐藏密码' : '显示密码'}
|
||||
tabIndex={-1}
|
||||
className="absolute right-2 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
{showOld ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="new">新密码</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="new"
|
||||
type={showNew ? 'text' : 'password'}
|
||||
autoComplete="new-password"
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
placeholder="设置新的强密码"
|
||||
className="h-10 pr-10 text-sm"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowNew((v) => !v)}
|
||||
aria-label={showNew ? '隐藏密码' : '显示密码'}
|
||||
tabIndex={-1}
|
||||
className="absolute right-2 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
{showNew ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="confirm">确认新密码</Label>
|
||||
<Input
|
||||
id="confirm"
|
||||
type={showNew ? 'text' : 'password'}
|
||||
autoComplete="new-password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
placeholder="再次输入新密码"
|
||||
className="h-10 text-sm"
|
||||
/>
|
||||
{confirmPassword.length > 0 && !confirmMatches && (
|
||||
<span className="text-[11px] text-destructive">两次输入的密码不一致</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<RuleList rules={rules} />
|
||||
|
||||
<AnimatePresence>
|
||||
{error && (
|
||||
<motion.p
|
||||
initial={{ opacity: 0, y: -4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0 }}
|
||||
className="rounded-md bg-destructive/10 px-3 py-2 text-center text-xs text-destructive"
|
||||
>
|
||||
{error}
|
||||
</motion.p>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{!forced && onCancel && (
|
||||
<Button type="button" variant="ghost" onClick={onCancel} className="h-10">
|
||||
取消
|
||||
</Button>
|
||||
)}
|
||||
<Button type="submit" disabled={!canSubmit} className="ml-auto h-10">
|
||||
{submitting ? (
|
||||
<>
|
||||
<Loader2 className="size-4 animate-spin" /> 提交中…
|
||||
</>
|
||||
) : (
|
||||
'保存新密码'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
<div className="mt-6">
|
||||
<ChangePasswordForm
|
||||
knownOldPassword={knownOldPassword}
|
||||
checkStrength={checkStrength}
|
||||
submit={submit}
|
||||
onSuccess={onSuccess}
|
||||
idPrefix="forced-cpw"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RuleList({ rules }: { rules: PasswordRule[] }) {
|
||||
// Initial empty state: show a placeholder set so the user knows the rules
|
||||
// exist even before any input.
|
||||
const display = useMemo<PasswordRule[]>(() => {
|
||||
if (rules.length > 0) return rules;
|
||||
return [
|
||||
{ id: 'length', label: '长度不少于 10 位', ok: false },
|
||||
{ id: 'lower', label: '至少包含一个小写字母', ok: false },
|
||||
{ id: 'upper', label: '至少包含一个大写字母', ok: false },
|
||||
{ id: 'special', label: '至少包含一个特殊字符', ok: false },
|
||||
{ id: 'no-space', label: '不得包含空格', ok: false },
|
||||
];
|
||||
}, [rules]);
|
||||
|
||||
return (
|
||||
<ul className="grid gap-1.5 rounded-lg border bg-muted/30 p-3">
|
||||
{display.map((rule) => (
|
||||
<li key={rule.id} className="flex items-center gap-2">
|
||||
<motion.span
|
||||
initial={false}
|
||||
animate={{
|
||||
backgroundColor: rule.ok ? 'color-mix(in oklab, var(--primary) 20%, transparent)' : 'transparent',
|
||||
borderColor: rule.ok ? 'var(--primary)' : 'var(--border)',
|
||||
scale: rule.ok ? [1, 1.18, 1] : 1,
|
||||
}}
|
||||
transition={{ duration: 0.25 }}
|
||||
className={cn(
|
||||
'flex size-4 items-center justify-center rounded-full border',
|
||||
)}
|
||||
>
|
||||
<AnimatePresence>
|
||||
{rule.ok && (
|
||||
<motion.span
|
||||
key="check"
|
||||
initial={{ opacity: 0, scale: 0.4 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.4 }}
|
||||
transition={{ duration: 0.18 }}
|
||||
>
|
||||
<Check className="size-3 text-primary" strokeWidth={3} />
|
||||
</motion.span>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</motion.span>
|
||||
<motion.span
|
||||
initial={false}
|
||||
animate={{ color: rule.ok ? 'var(--foreground)' : 'var(--muted-foreground)' }}
|
||||
transition={{ duration: 0.2 }}
|
||||
className="text-xs"
|
||||
>
|
||||
{rule.label}
|
||||
</motion.span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import { Badge } from '@/components/ui/badge';
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type {
|
||||
AdapterStatus,
|
||||
NetworkKind,
|
||||
OneBotConfig,
|
||||
OneBotNetworks,
|
||||
@@ -39,7 +40,7 @@ type DialogState =
|
||||
// index: null → create with `seed`, otherwise edit the item at that position.
|
||||
|
||||
export function ConfigPage() {
|
||||
const { qqList, selectedUin, setSelectedUin } = useAppState();
|
||||
const { qqList, connections, selectedUin, setSelectedUin } = useAppState();
|
||||
const {
|
||||
config,
|
||||
setConfig,
|
||||
@@ -56,7 +57,11 @@ export function ConfigPage() {
|
||||
});
|
||||
|
||||
const [activeTab, setActiveTab] = useState<TabKey>('general');
|
||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
|
||||
// Default the account strip to its 56px avatar-only form on narrow screens
|
||||
// (≤lg) so the editor pane isn't squeezed; the user can still expand it.
|
||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(
|
||||
() => typeof window !== 'undefined' && window.matchMedia('(max-width: 1024px)').matches,
|
||||
);
|
||||
const [confirmSave, setConfirmSave] = useState(false);
|
||||
// The edit dialog is modal and blocks every other click in the page,
|
||||
// so `selectedUin` cannot change while it's open — no defensive close
|
||||
@@ -68,40 +73,56 @@ export function ConfigPage() {
|
||||
[pendingSwitchUin, qqList],
|
||||
);
|
||||
|
||||
// Per-kind helpers (typed at the call site so the dialog's onSubmit
|
||||
// payload is exactly the kind's adapter shape).
|
||||
function updateKind<K extends NetworkKind>(kind: K, next: OneBotNetworks[K]): void {
|
||||
// Live adapter status for the selected account, keyed by adapter name so
|
||||
// each summary card can light up its real connection state.
|
||||
const liveStatusByName = useMemo(() => {
|
||||
const acc = connections.find((c) => c.uin === selectedUin);
|
||||
const map = new Map<string, AdapterStatus>();
|
||||
for (const a of acc?.adapters ?? []) map.set(a.name, a);
|
||||
return map;
|
||||
}, [connections, selectedUin]);
|
||||
|
||||
// A discrete node mutation (create / edit / delete / enable-toggle) is
|
||||
// persisted the moment it happens — clicking 保存 inside the editor dialog
|
||||
// (or flipping the enable switch) IS the save. This removes the old
|
||||
// two-step trap where editing a token in the dialog only marked the config
|
||||
// "dirty" until you also pressed the top-right 保存, which silently cost
|
||||
// many users their token edits. The general-settings tab keeps its explicit
|
||||
// top-right save (it's a continuously-edited free-form surface).
|
||||
function commitKind<K extends NetworkKind>(kind: K, nextList: OneBotNetworks[K]): void {
|
||||
if (!config) return;
|
||||
setConfig({ ...config, networks: { ...config.networks, [kind]: next } });
|
||||
const next = { ...config, networks: { ...config.networks, [kind]: nextList } };
|
||||
setConfig(next);
|
||||
void save(next);
|
||||
}
|
||||
|
||||
function handleCreate<K extends NetworkKind>(kind: K, item: OneBotNetworks[K][number]): void {
|
||||
if (!config) return;
|
||||
const list = config.networks[kind] as OneBotNetworks[K];
|
||||
updateKind(kind, [...list, item] as OneBotNetworks[K]);
|
||||
commitKind(kind, [...list, item] as OneBotNetworks[K]);
|
||||
}
|
||||
|
||||
function handleEdit<K extends NetworkKind>(kind: K, index: number, item: OneBotNetworks[K][number]): void {
|
||||
if (!config) return;
|
||||
const list = config.networks[kind] as OneBotNetworks[K];
|
||||
const next = list.map((it, i) => (i === index ? item : it)) as OneBotNetworks[K];
|
||||
updateKind(kind, next);
|
||||
commitKind(kind, list.map((it, i) => (i === index ? item : it)) as OneBotNetworks[K]);
|
||||
}
|
||||
|
||||
function handleDelete<K extends NetworkKind>(kind: K, index: number): void {
|
||||
if (!config) return;
|
||||
const list = config.networks[kind] as OneBotNetworks[K];
|
||||
const next = list.filter((_, i) => i !== index) as OneBotNetworks[K];
|
||||
updateKind(kind, next);
|
||||
commitKind(kind, list.filter((_, i) => i !== index) as OneBotNetworks[K]);
|
||||
}
|
||||
|
||||
function handleToggleEnabled<K extends NetworkKind>(kind: K, index: number, enabled: boolean): void {
|
||||
if (!config) return;
|
||||
const list = config.networks[kind] as OneBotNetworks[K];
|
||||
const next = list.map((it, i) =>
|
||||
i === index ? ({ ...it, enabled: enabled ? undefined : false } as OneBotNetworks[K][number]) : it,
|
||||
) as OneBotNetworks[K];
|
||||
updateKind(kind, next);
|
||||
commitKind(
|
||||
kind,
|
||||
list.map((it, i) =>
|
||||
i === index ? ({ ...it, enabled: enabled ? undefined : false } as OneBotNetworks[K][number]) : it,
|
||||
) as OneBotNetworks[K],
|
||||
);
|
||||
}
|
||||
|
||||
const openCreate = (kind: NetworkKind) => {
|
||||
@@ -159,6 +180,7 @@ export function ConfigPage() {
|
||||
<NetworkTabView
|
||||
kind={activeTab}
|
||||
config={config}
|
||||
statusByName={liveStatusByName}
|
||||
onCreateClick={() => openCreate(activeTab)}
|
||||
onEdit={(idx) => openEdit(activeTab, idx)}
|
||||
onDelete={(idx) => handleDelete(activeTab, idx)}
|
||||
@@ -237,7 +259,7 @@ function HeaderBar({ selectedUin, dirty, saveStatus, onSave, activeTab, onCreate
|
||||
UIN {selectedUin}
|
||||
</code>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{saveStatus && (
|
||||
<span
|
||||
className={cn(
|
||||
@@ -281,7 +303,7 @@ interface TabStripProps {
|
||||
|
||||
function TabStrip({ activeTab, onChange, counts }: TabStripProps) {
|
||||
return (
|
||||
<div className="flex flex-wrap gap-1 border-b">
|
||||
<div className="flex gap-1 overflow-x-auto border-b [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
{ALL_TABS.map((key) => {
|
||||
const label = key === 'general' ? '通用设置' : NETWORK_TABS[key].title;
|
||||
const count = key === 'general' ? null : counts[key];
|
||||
@@ -292,7 +314,7 @@ function TabStrip({ activeTab, onChange, counts }: TabStripProps) {
|
||||
type="button"
|
||||
onClick={() => onChange(key)}
|
||||
className={cn(
|
||||
'group relative inline-flex items-center gap-1.5 px-3 py-2 text-sm transition-colors cursor-pointer',
|
||||
'group relative inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap px-3 py-2 text-sm transition-colors cursor-pointer',
|
||||
active ? 'text-foreground' : 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
@@ -333,6 +355,7 @@ function countMap(networks: OneBotNetworks): Record<NetworkKind, number> {
|
||||
interface NetworkTabViewProps {
|
||||
kind: NetworkKind;
|
||||
config: OneBotConfig;
|
||||
statusByName: Map<string, AdapterStatus>;
|
||||
onCreateClick: () => void;
|
||||
onEdit: (index: number) => void;
|
||||
onDelete: (index: number) => void;
|
||||
@@ -342,6 +365,7 @@ interface NetworkTabViewProps {
|
||||
function NetworkTabView({
|
||||
kind,
|
||||
config,
|
||||
statusByName,
|
||||
onCreateClick,
|
||||
onEdit,
|
||||
onDelete,
|
||||
@@ -390,6 +414,7 @@ function NetworkTabView({
|
||||
item={item}
|
||||
summary={summarize(item)}
|
||||
duplicateName={duplicate}
|
||||
liveStatus={statusByName.get(item.name)}
|
||||
onToggleEnabled={(v) => onToggleEnabled(idx, v)}
|
||||
onEdit={() => onEdit(idx)}
|
||||
onDelete={() => onDelete(idx)}
|
||||
|
||||
@@ -21,6 +21,13 @@ const levelClass: Record<LogLevel, string> = {
|
||||
|
||||
const LEVELS: LogLevel[] = ['debug', 'info', 'success', 'warn', 'error'];
|
||||
|
||||
/** Show a locale time when the backend sends an ISO timestamp (it does);
|
||||
* fall back to the raw string otherwise so we never render "Invalid Date". */
|
||||
function formatTime(t: string): string {
|
||||
const d = new Date(t);
|
||||
return Number.isNaN(d.getTime()) ? t : d.toLocaleTimeString();
|
||||
}
|
||||
|
||||
export function LogsPage() {
|
||||
const api = useApi();
|
||||
const [logs, setLogs] = useState<LogEntry[]>([]);
|
||||
@@ -205,16 +212,19 @@ export function LogsPage() {
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
transition={{ duration: 0.12 }}
|
||||
className="flex gap-2 whitespace-pre-wrap px-3 py-0.5 leading-5 hover:bg-accent/30"
|
||||
className="flex flex-col gap-0.5 px-3 py-1 leading-5 hover:bg-accent/30 sm:flex-row sm:gap-2 sm:py-0.5"
|
||||
>
|
||||
<span className="shrink-0 text-muted-foreground tabular-nums">
|
||||
{new Date(log.time).toLocaleTimeString()}
|
||||
</span>
|
||||
<span className={cn('w-14 shrink-0 font-semibold', levelClass[log.level])}>
|
||||
{log.level.toUpperCase()}
|
||||
</span>
|
||||
<span className="w-28 shrink-0 truncate text-muted-foreground">[{log.scope}]</span>
|
||||
<span className="break-all">{log.message}</span>
|
||||
{/* Meta drops to its own line on phones so the message gets
|
||||
the full width instead of a ~40px column that breaks
|
||||
every few characters. On sm+ it's the dense single row. */}
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<span className="shrink-0 text-muted-foreground tabular-nums">{formatTime(log.time)}</span>
|
||||
<span className={cn('shrink-0 font-semibold sm:w-14', levelClass[log.level])}>
|
||||
{log.level.toUpperCase()}
|
||||
</span>
|
||||
<span className="min-w-0 truncate text-muted-foreground sm:w-28">[{log.scope}]</span>
|
||||
</div>
|
||||
<span className="min-w-0 whitespace-pre-wrap break-all">{log.message}</span>
|
||||
</motion.div>
|
||||
))
|
||||
)}
|
||||
|
||||
@@ -1,51 +1,32 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import {
|
||||
Activity,
|
||||
AlertCircle,
|
||||
CheckCircle2,
|
||||
ArrowRight,
|
||||
Bell,
|
||||
Cable,
|
||||
Cpu,
|
||||
Eye,
|
||||
Loader2,
|
||||
MemoryStick,
|
||||
MonitorCog,
|
||||
PlugZap,
|
||||
RefreshCw,
|
||||
Server,
|
||||
Unplug,
|
||||
Users,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||
import { ProcessProbeDialog } from '@/components/process-probe-dialog';
|
||||
import { cn, formatBytes, formatUptime } from '@/lib/utils';
|
||||
import type { HookProcessInfo } from '@/types';
|
||||
import type { AppPath } from '@/router';
|
||||
import type { AccountConnections, AdapterStatus, AdapterStatusLevel, LogEntry } from '@/types';
|
||||
import { useApi } from '@/lib/api';
|
||||
import { useAppState } from '@/contexts/AppStateContext';
|
||||
import { useSession } from '@/contexts/SessionContext';
|
||||
|
||||
const processStatusLabel: Record<HookProcessInfo['status'], string> = {
|
||||
available: '可加载',
|
||||
loading: '加载中',
|
||||
connecting: '等待连接',
|
||||
loaded: '等待登录',
|
||||
online: '已在线',
|
||||
error: '错误',
|
||||
disconnected: '已断开',
|
||||
};
|
||||
|
||||
function processBadgeVariant(status: HookProcessInfo['status']) {
|
||||
if (status === 'online') return 'success' as const;
|
||||
if (status === 'error') return 'destructive' as const;
|
||||
if (status === 'disconnected') return 'destructive' as const;
|
||||
if (status === 'loading' || status === 'connecting' || status === 'loaded') return 'default' as const;
|
||||
return 'secondary' as const;
|
||||
}
|
||||
|
||||
function qqAvatarUrl(uin: string) {
|
||||
return `/avatar/${encodeURIComponent(uin)}`;
|
||||
}
|
||||
@@ -56,44 +37,48 @@ function StatTile({
|
||||
value,
|
||||
subtext,
|
||||
accent = false,
|
||||
to,
|
||||
}: {
|
||||
icon: React.ReactNode;
|
||||
label: string;
|
||||
value: React.ReactNode;
|
||||
subtext?: React.ReactNode;
|
||||
accent?: boolean;
|
||||
/** When set, the whole tile becomes a link to this route. */
|
||||
to?: AppPath;
|
||||
}) {
|
||||
return (
|
||||
<Card className="overflow-hidden">
|
||||
<CardContent className="flex items-center gap-3 p-4">
|
||||
<div
|
||||
className={cn(
|
||||
'flex size-10 shrink-0 items-center justify-center rounded-xl',
|
||||
accent ? 'bg-primary text-primary-foreground' : 'bg-primary/10 text-primary'
|
||||
)}
|
||||
>
|
||||
{icon}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">{label}</p>
|
||||
<div className="mt-0.5 truncate text-base font-semibold tabular-nums">{value}</div>
|
||||
{subtext && <p className="mt-0.5 truncate text-[11px] text-muted-foreground">{subtext}</p>}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
const body = (
|
||||
<CardContent className="flex items-center gap-3 p-4">
|
||||
<div
|
||||
className={cn(
|
||||
'flex size-10 shrink-0 items-center justify-center rounded-xl',
|
||||
accent ? 'bg-primary text-primary-foreground' : 'bg-primary/10 text-primary'
|
||||
)}
|
||||
>
|
||||
{icon}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">{label}</p>
|
||||
<div className="mt-0.5 truncate text-base font-semibold tabular-nums">{value}</div>
|
||||
{subtext && <p className="mt-0.5 truncate text-[11px] text-muted-foreground">{subtext}</p>}
|
||||
</div>
|
||||
{to && <ArrowRight className="size-4 shrink-0 text-muted-foreground/60" />}
|
||||
</CardContent>
|
||||
);
|
||||
|
||||
if (to) {
|
||||
return (
|
||||
<Link to={to} className="block rounded-xl outline-none">
|
||||
<Card className="overflow-hidden transition-colors hover:border-primary/40 hover:bg-accent/30">{body}</Card>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
return <Card className="overflow-hidden">{body}</Card>;
|
||||
}
|
||||
|
||||
export function OverviewPage() {
|
||||
const { qqList, processList, systemInfo, processOps, refreshProcesses, refreshSystem } =
|
||||
useAppState();
|
||||
const { qqList, processList, systemInfo, connections, refreshSystem } = useAppState();
|
||||
const { status } = useSession();
|
||||
const { statusOf, banner: processActionStatus, load, unload, refresh } = processOps;
|
||||
const [confirm, setConfirm] = useState<
|
||||
| { kind: 'load' | 'unload'; pid: number; name: string }
|
||||
| null
|
||||
>(null);
|
||||
const [probeDialog, setProbeDialog] = useState<{ pid: number; name: string } | null>(null);
|
||||
|
||||
// Lightweight tick to refresh "uptime" pretty-print every 30s
|
||||
const [, force] = useState(0);
|
||||
@@ -103,11 +88,14 @@ export function OverviewPage() {
|
||||
}, []);
|
||||
|
||||
const online = status === '已连接';
|
||||
// Read-only injection health for the dashboard. Control lives on /processes.
|
||||
const onlineProcs = processList.filter((p) => p.status === 'online').length;
|
||||
const loadableProcs = processList.filter((p) => !p.injected).length;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
{/* Top stats */}
|
||||
<div className="grid grid-cols-2 gap-3 sm:gap-4 md:grid-cols-4">
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 sm:gap-4 lg:grid-cols-5">
|
||||
<StatTile
|
||||
icon={<Activity className="size-5" />}
|
||||
label="服务状态"
|
||||
@@ -121,6 +109,13 @@ export function OverviewPage() {
|
||||
value={qqList.length}
|
||||
subtext={`已接入 ${qqList.length} 个会话`}
|
||||
/>
|
||||
<StatTile
|
||||
icon={<PlugZap className="size-5" />}
|
||||
label="进程注入"
|
||||
value={`${onlineProcs} 在线`}
|
||||
subtext={`${processList.length} 进程 · ${loadableProcs} 可注入`}
|
||||
to="/processes"
|
||||
/>
|
||||
<StatTile
|
||||
icon={<Server className="size-5" />}
|
||||
label="主机名"
|
||||
@@ -135,6 +130,35 @@ export function OverviewPage() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* First-run nudge: nothing online yet → point at the injection page. */}
|
||||
{qqList.length === 0 && (
|
||||
<motion.div initial={{ opacity: 0, y: -4 }} animate={{ opacity: 1, y: 0 }}>
|
||||
<Link
|
||||
to="/processes"
|
||||
className="flex items-center gap-3 rounded-xl border border-primary/30 bg-primary/5 px-4 py-3 transition-colors hover:bg-primary/10"
|
||||
>
|
||||
<div className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-primary/15 text-primary">
|
||||
<PlugZap className="size-5" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium">
|
||||
{loadableProcs > 0 ? `检测到 ${loadableProcs} 个可加载 QQ 进程` : '尚未接入任何账号'}
|
||||
</p>
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
前往「进程注入」加载 QQ,登录后会自动接入 OneBot 流程。
|
||||
</p>
|
||||
</div>
|
||||
<ArrowRight className="size-4 shrink-0 text-primary" />
|
||||
</Link>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* Operational health — connection status + recent alerts (side by side on wide screens) */}
|
||||
<div className="grid gap-6 xl:grid-cols-2">
|
||||
<ConnectionsCard connections={connections} />
|
||||
<RecentAlertsCard />
|
||||
</div>
|
||||
|
||||
{/* System metrics */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">
|
||||
@@ -240,147 +264,6 @@ export function OverviewPage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* QQ Processes */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">
|
||||
<div>
|
||||
<CardTitle>QQ 进程</CardTitle>
|
||||
<CardDescription>
|
||||
加载 SnowLuma 后会监听登录状态,登录后自动接入 OneBot 流程
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={refreshProcesses}>
|
||||
<RefreshCw className="size-3.5" /> 刷新
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{processActionStatus && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: -4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="mb-3 rounded-md border border-primary/20 bg-primary/5 px-3 py-2 text-xs text-primary"
|
||||
>
|
||||
{processActionStatus}
|
||||
</motion.div>
|
||||
)}
|
||||
{processList.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed py-10 text-muted-foreground">
|
||||
<Cpu className="size-7" strokeWidth={1.5} />
|
||||
<p className="text-sm">未检测到可加载 QQ 主进程</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 gap-3 xl:grid-cols-2">
|
||||
{processList.map((proc, idx) => {
|
||||
const op = statusOf(proc.pid);
|
||||
const loading = op === 'load' || proc.status === 'loading';
|
||||
const unloading = op === 'unload';
|
||||
const refreshing = op === 'refresh';
|
||||
const busy = op != null || proc.status === 'loading';
|
||||
const isOnline = proc.status === 'online';
|
||||
const canUnload = proc.injected;
|
||||
// Refresh is meaningful whenever a hook may exist (so the user
|
||||
// can re-check the pipe and trigger a reconnect on demand).
|
||||
const showRefresh = proc.injected || proc.status === 'connecting' || proc.status === 'disconnected';
|
||||
return (
|
||||
<motion.div
|
||||
key={proc.pid}
|
||||
initial={{ opacity: 0, y: 6 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.03 + idx * 0.025, duration: 0.22 }}
|
||||
className="flex items-center gap-3 rounded-lg border bg-card/50 p-3"
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'flex size-10 shrink-0 items-center justify-center rounded-lg',
|
||||
isOnline
|
||||
? 'bg-success/15 text-success'
|
||||
: proc.status === 'error'
|
||||
? 'bg-destructive/15 text-destructive'
|
||||
: 'bg-primary/10 text-primary'
|
||||
)}
|
||||
>
|
||||
{isOnline ? (
|
||||
<CheckCircle2 className="size-5" />
|
||||
) : proc.status === 'error' ? (
|
||||
<AlertCircle className="size-5" />
|
||||
) : (
|
||||
<Cpu className="size-5" />
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate text-sm font-semibold">{proc.name || 'QQ.exe'}</span>
|
||||
<Badge variant={processBadgeVariant(proc.status)}>{processStatusLabel[proc.status]}</Badge>
|
||||
</div>
|
||||
<div className="mt-0.5 truncate font-mono text-[11px] text-muted-foreground tabular-nums">
|
||||
PID {proc.pid}
|
||||
{proc.uin && proc.uin !== '0' ? ` · UIN ${proc.uin}` : ''}
|
||||
</div>
|
||||
{proc.path && (
|
||||
<div className="truncate text-[11px] text-muted-foreground/80" title={proc.path}>
|
||||
{proc.path}
|
||||
</div>
|
||||
)}
|
||||
{proc.error && (
|
||||
<div className="mt-0.5 truncate text-[11px] text-destructive" title={proc.error}>
|
||||
{proc.error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1.5">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busy}
|
||||
onClick={() => setProbeDialog({ pid: proc.pid, name: proc.name || `PID ${proc.pid}` })}
|
||||
>
|
||||
<Eye className="size-3.5" /> 探测登录
|
||||
</Button>
|
||||
{showRefresh && (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
aria-label={`刷新进程 ${proc.pid} 管道状态`}
|
||||
title="刷新管道状态 / 重连"
|
||||
onClick={() => refresh(proc.pid)}
|
||||
className="size-8 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{refreshing ? (
|
||||
<Loader2 className="size-3.5 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="size-3.5" />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant={canUnload ? 'outline' : 'default'}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
setConfirm({
|
||||
kind: canUnload ? 'unload' : 'load',
|
||||
pid: proc.pid,
|
||||
name: proc.name || `PID ${proc.pid}`,
|
||||
})
|
||||
}
|
||||
className={cn(
|
||||
canUnload && 'text-destructive hover:bg-destructive/10 hover:text-destructive'
|
||||
)}
|
||||
>
|
||||
{(loading || unloading) && <Loader2 className="size-3.5 animate-spin" />}
|
||||
{!loading && !unloading && canUnload && <Unplug className="size-3.5" />}
|
||||
{canUnload ? (unloading ? '卸载中' : '卸载') : loading ? '加载中' : '加载'}
|
||||
</Button>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Online accounts */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@@ -395,7 +278,7 @@ export function OverviewPage() {
|
||||
</div>
|
||||
) : (
|
||||
<ScrollArea className="max-h-[420px]" viewportClassName="[&>div]:!block">
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3">
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
|
||||
{qqList.map((q, idx) => (
|
||||
<motion.div
|
||||
key={q.uin}
|
||||
@@ -421,35 +304,160 @@ export function OverviewPage() {
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<ConfirmDialog
|
||||
open={!!confirm}
|
||||
onOpenChange={(o) => !o && setConfirm(null)}
|
||||
title={confirm?.kind === 'unload' ? '确认卸载 SnowLuma?' : '确认加载 SnowLuma?'}
|
||||
description={
|
||||
confirm
|
||||
? confirm.kind === 'unload'
|
||||
? `将从进程 ${confirm.name} 卸载 SnowLuma 注入,可能导致当前会话断开。`
|
||||
: `将向进程 ${confirm.name} 注入 SnowLuma,并开始监听登录状态。`
|
||||
: ''
|
||||
}
|
||||
confirmText={confirm?.kind === 'unload' ? '卸载' : '加载'}
|
||||
destructive={confirm?.kind === 'unload'}
|
||||
onConfirm={async () => {
|
||||
if (!confirm) return;
|
||||
if (confirm.kind === 'unload') await unload(confirm.pid);
|
||||
else await load(confirm.pid);
|
||||
}}
|
||||
/>
|
||||
|
||||
{probeDialog && (
|
||||
<ProcessProbeDialog
|
||||
pid={probeDialog.pid}
|
||||
processName={probeDialog.name}
|
||||
open={!!probeDialog}
|
||||
onOpenChange={(open) => !open && setProbeDialog(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── connection health ───────────────
|
||||
|
||||
const CONN_STATUS_STYLE: Record<AdapterStatusLevel, string> = {
|
||||
ok: 'bg-success/10 text-success',
|
||||
warn: 'bg-warning/10 text-warning',
|
||||
down: 'bg-destructive/10 text-destructive',
|
||||
disabled: 'bg-muted text-muted-foreground',
|
||||
};
|
||||
const CONN_STATUS_LABEL: Record<AdapterStatusLevel, string> = {
|
||||
ok: '正常',
|
||||
warn: '注意',
|
||||
down: '异常',
|
||||
disabled: '未启用',
|
||||
};
|
||||
const ADAPTER_KIND_LABEL: Record<AdapterStatus['kind'], string> = {
|
||||
httpServer: 'HTTP 服务端',
|
||||
httpClient: 'HTTP 上报',
|
||||
wsServer: 'WS 服务端',
|
||||
wsClient: 'WS 客户端',
|
||||
};
|
||||
|
||||
function ConnectionsCard({ connections }: { connections: AccountConnections[] }) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Cable className="size-4 text-primary" /> OneBot 连接
|
||||
</CardTitle>
|
||||
<CardDescription>各账号协议端点的实时连接状态</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{connections.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed py-10 text-muted-foreground">
|
||||
<Cable className="size-7" strokeWidth={1.5} />
|
||||
<p className="text-sm">暂无已接入的账号实例</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-4">
|
||||
{connections.map((acc) => (
|
||||
<div key={acc.uin} className="flex flex-col gap-2">
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-sm font-semibold">{acc.nickname || acc.uin}</span>
|
||||
<span className="font-mono text-[11px] text-muted-foreground tabular-nums">{acc.uin}</span>
|
||||
</div>
|
||||
{acc.adapters.length === 0 ? (
|
||||
<p className="rounded-md border border-dashed px-3 py-2 text-[11px] text-muted-foreground">
|
||||
未配置任何协议端点
|
||||
</p>
|
||||
) : (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{acc.adapters.map((a) => (
|
||||
<div key={a.name} className="flex items-center gap-2 rounded-lg border bg-card/40 px-3 py-2">
|
||||
<span
|
||||
className={cn(
|
||||
'shrink-0 rounded px-1.5 py-0.5 text-[10px] font-medium',
|
||||
CONN_STATUS_STYLE[a.status],
|
||||
)}
|
||||
>
|
||||
{CONN_STATUS_LABEL[a.status]}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="truncate text-sm font-medium">{a.name}</span>
|
||||
<span className="shrink-0 text-[10px] text-muted-foreground">{ADAPTER_KIND_LABEL[a.kind]}</span>
|
||||
</div>
|
||||
<div className="truncate text-[11px] text-muted-foreground">{a.detail}</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── recent alerts ───────────────
|
||||
|
||||
function alertClock(t: string): string {
|
||||
const d = new Date(t);
|
||||
return Number.isNaN(d.getTime()) ? t : d.toLocaleTimeString();
|
||||
}
|
||||
|
||||
function RecentAlertsCard() {
|
||||
const api = useApi();
|
||||
const [alerts, setAlerts] = useState<LogEntry[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
api.logs
|
||||
.list(200)
|
||||
.then((list) => {
|
||||
if (!active) return;
|
||||
setAlerts(list.filter((l) => l.level === 'warn' || l.level === 'error').slice(-5));
|
||||
})
|
||||
.catch(() => { /* ignore */ });
|
||||
const stop = api.logs.stream({
|
||||
onLine: (entry) => {
|
||||
if (entry.level !== 'warn' && entry.level !== 'error') return;
|
||||
setAlerts((prev) => [...prev.filter((a) => a.id !== entry.id), entry].slice(-5));
|
||||
},
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
stop();
|
||||
};
|
||||
}, [api]);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">
|
||||
<div>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Bell className="size-4 text-primary" /> 最近告警
|
||||
</CardTitle>
|
||||
<CardDescription>最近的 warn / error 级别日志</CardDescription>
|
||||
</div>
|
||||
<Link
|
||||
to="/logs"
|
||||
className="inline-flex shrink-0 items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
查看日志 <ArrowRight className="size-3" />
|
||||
</Link>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{alerts.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed py-10 text-muted-foreground">
|
||||
<Bell className="size-7" strokeWidth={1.5} />
|
||||
<p className="text-sm">暂无告警</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-1 font-mono text-[11px]">
|
||||
{alerts.map((a) => (
|
||||
<div key={a.id} className="flex gap-2 rounded px-2 py-1 hover:bg-accent/30">
|
||||
<span className="shrink-0 text-muted-foreground tabular-nums">{alertClock(a.time)}</span>
|
||||
<span className={cn('shrink-0 font-semibold', a.level === 'error' ? 'text-destructive' : 'text-warning')}>
|
||||
{a.level.toUpperCase()}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate" title={a.message}>
|
||||
[{a.scope}] {a.message}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
222
packages/webui/src/components/pages/processes-page.tsx
Normal file
222
packages/webui/src/components/pages/processes-page.tsx
Normal file
@@ -0,0 +1,222 @@
|
||||
import { useState } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { AlertCircle, CheckCircle2, Cpu, Eye, Loader2, RefreshCw, Unplug } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||
import { ProcessProbeDialog } from '@/components/process-probe-dialog';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { HookProcessInfo } from '@/types';
|
||||
import { useAppState } from '@/contexts/AppStateContext';
|
||||
|
||||
const processStatusLabel: Record<HookProcessInfo['status'], string> = {
|
||||
available: '可加载',
|
||||
loading: '加载中',
|
||||
connecting: '等待连接',
|
||||
loaded: '等待登录',
|
||||
online: '已在线',
|
||||
error: '错误',
|
||||
disconnected: '已断开',
|
||||
};
|
||||
|
||||
function processBadgeVariant(status: HookProcessInfo['status']) {
|
||||
if (status === 'online') return 'success' as const;
|
||||
if (status === 'error') return 'destructive' as const;
|
||||
if (status === 'disconnected') return 'destructive' as const;
|
||||
if (status === 'loading' || status === 'connecting' || status === 'loaded') return 'default' as const;
|
||||
return 'secondary' as const;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process / injection control surface. Split out of the overview page so the
|
||||
* homepage stays a read-only monitoring dashboard. State (processList,
|
||||
* processOps) is owned by AppLayout and read from context, so this page needs
|
||||
* no plumbing of its own; the layout keeps polling and the unload-failed alert
|
||||
* regardless of which page is mounted.
|
||||
*/
|
||||
export function ProcessesPage() {
|
||||
const { processList, processOps, refreshProcesses } = useAppState();
|
||||
const { statusOf, banner: processActionStatus, load, unload, refresh } = processOps;
|
||||
const [confirm, setConfirm] = useState<{ kind: 'load' | 'unload'; pid: number; name: string } | null>(null);
|
||||
const [probeDialog, setProbeDialog] = useState<{ pid: number; name: string } | null>(null);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">
|
||||
<div>
|
||||
<CardTitle>进程注入</CardTitle>
|
||||
<CardDescription>加载 SnowLuma 后会监听登录状态,登录后自动接入 OneBot 流程</CardDescription>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={refreshProcesses}>
|
||||
<RefreshCw className="size-3.5" /> 刷新
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{processActionStatus && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: -4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="mb-3 rounded-md border border-primary/20 bg-primary/5 px-3 py-2 text-xs text-primary"
|
||||
>
|
||||
{processActionStatus}
|
||||
</motion.div>
|
||||
)}
|
||||
{processList.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed py-16 text-muted-foreground">
|
||||
<Cpu className="size-7" strokeWidth={1.5} />
|
||||
<p className="text-sm">未检测到可加载 QQ 主进程</p>
|
||||
<p className="text-[11px] text-muted-foreground/80">请确认 QQ 已启动后点击右上角刷新</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 gap-3 xl:grid-cols-2 2xl:grid-cols-3">
|
||||
{processList.map((proc, idx) => {
|
||||
const op = statusOf(proc.pid);
|
||||
const loading = op === 'load' || proc.status === 'loading';
|
||||
const unloading = op === 'unload';
|
||||
const refreshing = op === 'refresh';
|
||||
const busy = op != null || proc.status === 'loading';
|
||||
const isOnline = proc.status === 'online';
|
||||
const canUnload = proc.injected;
|
||||
// Refresh is meaningful whenever a hook may exist (so the user
|
||||
// can re-check the pipe and trigger a reconnect on demand).
|
||||
const showRefresh = proc.injected || proc.status === 'connecting' || proc.status === 'disconnected';
|
||||
return (
|
||||
<motion.div
|
||||
key={proc.pid}
|
||||
initial={{ opacity: 0, y: 6 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.03 + idx * 0.025, duration: 0.22 }}
|
||||
className="flex flex-col gap-3 rounded-lg border bg-card/50 p-3 sm:flex-row sm:items-center"
|
||||
>
|
||||
{/* icon + info stay horizontal; on phones the actions drop to
|
||||
a second row so name / PID / path get the full width
|
||||
instead of collapsing to "Q..". */}
|
||||
<div className="flex min-w-0 flex-1 items-center gap-3">
|
||||
<div
|
||||
className={cn(
|
||||
'flex size-10 shrink-0 items-center justify-center rounded-lg',
|
||||
isOnline
|
||||
? 'bg-success/15 text-success'
|
||||
: proc.status === 'error'
|
||||
? 'bg-destructive/15 text-destructive'
|
||||
: 'bg-primary/10 text-primary'
|
||||
)}
|
||||
>
|
||||
{isOnline ? (
|
||||
<CheckCircle2 className="size-5" />
|
||||
) : proc.status === 'error' ? (
|
||||
<AlertCircle className="size-5" />
|
||||
) : (
|
||||
<Cpu className="size-5" />
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="min-w-0 truncate text-sm font-semibold">{proc.name || 'QQ.exe'}</span>
|
||||
<Badge variant={processBadgeVariant(proc.status)} className="shrink-0 whitespace-nowrap">
|
||||
{processStatusLabel[proc.status]}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="mt-0.5 truncate font-mono text-[11px] text-muted-foreground tabular-nums">
|
||||
PID {proc.pid}
|
||||
{proc.uin && proc.uin !== '0' ? ` · UIN ${proc.uin}` : ''}
|
||||
</div>
|
||||
{proc.path && (
|
||||
<div className="truncate text-[11px] text-muted-foreground/80" title={proc.path}>
|
||||
{proc.path}
|
||||
</div>
|
||||
)}
|
||||
{proc.error && (
|
||||
<div className="mt-0.5 truncate text-[11px] text-destructive" title={proc.error}>
|
||||
{proc.error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 flex-wrap items-center gap-1.5">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busy}
|
||||
onClick={() => setProbeDialog({ pid: proc.pid, name: proc.name || `PID ${proc.pid}` })}
|
||||
>
|
||||
<Eye className="size-3.5" /> 探测登录
|
||||
</Button>
|
||||
{showRefresh && (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
aria-label={`刷新进程 ${proc.pid} 管道状态`}
|
||||
title="刷新管道状态 / 重连"
|
||||
onClick={() => refresh(proc.pid)}
|
||||
className="size-8 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{refreshing ? (
|
||||
<Loader2 className="size-3.5 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="size-3.5" />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant={canUnload ? 'outline' : 'default'}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
setConfirm({
|
||||
kind: canUnload ? 'unload' : 'load',
|
||||
pid: proc.pid,
|
||||
name: proc.name || `PID ${proc.pid}`,
|
||||
})
|
||||
}
|
||||
className={cn(
|
||||
canUnload && 'text-destructive hover:bg-destructive/10 hover:text-destructive'
|
||||
)}
|
||||
>
|
||||
{(loading || unloading) && <Loader2 className="size-3.5 animate-spin" />}
|
||||
{!loading && !unloading && canUnload && <Unplug className="size-3.5" />}
|
||||
{canUnload ? (unloading ? '卸载中' : '卸载') : loading ? '加载中' : '加载'}
|
||||
</Button>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<ConfirmDialog
|
||||
open={!!confirm}
|
||||
onOpenChange={(o) => !o && setConfirm(null)}
|
||||
title={confirm?.kind === 'unload' ? '确认卸载 SnowLuma?' : '确认加载 SnowLuma?'}
|
||||
description={
|
||||
confirm
|
||||
? confirm.kind === 'unload'
|
||||
? `将从进程 ${confirm.name} 卸载 SnowLuma 注入,可能导致当前会话断开。`
|
||||
: `将向进程 ${confirm.name} 注入 SnowLuma,并开始监听登录状态。`
|
||||
: ''
|
||||
}
|
||||
confirmText={confirm?.kind === 'unload' ? '卸载' : '加载'}
|
||||
destructive={confirm?.kind === 'unload'}
|
||||
onConfirm={async () => {
|
||||
if (!confirm) return;
|
||||
if (confirm.kind === 'unload') await unload(confirm.pid);
|
||||
else await load(confirm.pid);
|
||||
}}
|
||||
/>
|
||||
|
||||
{probeDialog && (
|
||||
<ProcessProbeDialog
|
||||
pid={probeDialog.pid}
|
||||
processName={probeDialog.name}
|
||||
open={!!probeDialog}
|
||||
onOpenChange={(open) => !open && setProbeDialog(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { Check, KeyRound, Loader2, Monitor, Moon, Sun } from 'lucide-react';
|
||||
import { Check, KeyRound, Monitor, Moon, Palette, RefreshCw, ShieldCheck, Sun } from 'lucide-react';
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
@@ -14,8 +14,7 @@ import {
|
||||
type Density,
|
||||
type ThemeMode,
|
||||
} from '@/contexts/ThemeContext';
|
||||
import { ChangePasswordPage } from '@/components/pages/change-password-page';
|
||||
import { useApi } from '@/lib/api';
|
||||
import { ChangePasswordDialog } from '@/components/change-password-dialog';
|
||||
import { useAppState } from '@/contexts/AppStateContext';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
@@ -30,233 +29,279 @@ const DENSITY_OPTIONS: { value: Density; label: string; description: string }[]
|
||||
{ value: 'compact', label: '紧凑', description: '更小的字号与行距,单屏放更多内容' },
|
||||
];
|
||||
|
||||
type SettingsTab = 'appearance' | 'data' | 'account';
|
||||
|
||||
const TABS: { key: SettingsTab; label: string; icon: typeof Sun }[] = [
|
||||
{ key: 'appearance', label: '外观', icon: Palette },
|
||||
{ key: 'data', label: '数据刷新', icon: RefreshCw },
|
||||
{ key: 'account', label: '账号安全', icon: ShieldCheck },
|
||||
];
|
||||
|
||||
export function SettingsPage() {
|
||||
const api = useApi();
|
||||
const { onLogout } = useAppState();
|
||||
const {
|
||||
mode, setMode,
|
||||
accent, setAccent,
|
||||
radius, setRadius,
|
||||
density, setDensity,
|
||||
pollInterval, setPollInterval,
|
||||
} = useTheme();
|
||||
|
||||
const [showChangePwd, setShowChangePwd] = useState(false);
|
||||
const [pwdSavedAt, setPwdSavedAt] = useState<number | null>(null);
|
||||
|
||||
if (showChangePwd) {
|
||||
return (
|
||||
<ChangePasswordPage
|
||||
forced={false}
|
||||
checkStrength={(p) => api.checkPasswordStrength(p)}
|
||||
submit={(o, n) => api.changePassword(o, n)}
|
||||
onSuccess={() => {
|
||||
setShowChangePwd(false);
|
||||
setPwdSavedAt(Date.now());
|
||||
}}
|
||||
onCancel={() => setShowChangePwd(false)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const [tab, setTab] = useState<SettingsTab>('appearance');
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
{/* Appearance */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>外观</CardTitle>
|
||||
<CardDescription>调整界面的明暗模式、强调色、圆角与密度。所有改动会立即应用并保存到本地。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-6">
|
||||
{/* Mode */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>显示模式</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{MODE_OPTIONS.map((opt) => {
|
||||
const Icon = opt.icon;
|
||||
const active = mode === opt.value;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => setMode(opt.value)}
|
||||
className={cn(
|
||||
'flex items-center gap-2 rounded-lg border px-3 py-2 text-sm transition-colors cursor-pointer',
|
||||
active
|
||||
? 'border-primary bg-primary/10 text-primary'
|
||||
: 'border-border bg-background hover:bg-accent/40',
|
||||
)}
|
||||
>
|
||||
<Icon className="size-4" />
|
||||
{opt.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-5">
|
||||
<MiniTabs tab={tab} onChange={setTab} />
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Accent color */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>强调色</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{ACCENTS.map((spec) => {
|
||||
const active = accent === spec.id;
|
||||
return (
|
||||
<button
|
||||
key={spec.id}
|
||||
type="button"
|
||||
onClick={() => setAccent(spec.id as AccentColor)}
|
||||
title={spec.label}
|
||||
aria-label={spec.label}
|
||||
className={cn(
|
||||
'group relative flex h-9 w-9 items-center justify-center rounded-full border transition-transform cursor-pointer hover:scale-105',
|
||||
active ? 'border-foreground/30 ring-2 ring-primary' : 'border-border',
|
||||
)}
|
||||
style={{ backgroundColor: spec.swatch }}
|
||||
>
|
||||
{active && (
|
||||
<motion.span
|
||||
initial={{ scale: 0.4, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
className="text-white drop-shadow-sm"
|
||||
>
|
||||
<Check className="size-4" strokeWidth={3} />
|
||||
</motion.span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<p className="text-[11px] text-muted-foreground">当前:{ACCENTS.find((a) => a.id === accent)?.label}</p>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Radius */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>圆角</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{RADIUS_OPTIONS.map((opt) => {
|
||||
const active = Math.abs(radius - opt.value) < 1e-6;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => setRadius(opt.value)}
|
||||
className={cn(
|
||||
'rounded-md border px-3 py-2 text-sm transition-colors cursor-pointer',
|
||||
active
|
||||
? 'border-primary bg-primary/10 text-primary'
|
||||
: 'border-border bg-background hover:bg-accent/40',
|
||||
)}
|
||||
style={{ borderRadius: `${opt.value}rem` }}
|
||||
>
|
||||
{opt.label}({opt.value}rem)
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Density */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>显示密度</Label>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{DENSITY_OPTIONS.map((opt) => {
|
||||
const active = density === opt.value;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => setDensity(opt.value)}
|
||||
className={cn(
|
||||
'flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors cursor-pointer',
|
||||
active
|
||||
? 'border-primary bg-primary/10'
|
||||
: 'border-border bg-background hover:bg-accent/40',
|
||||
)}
|
||||
>
|
||||
<span className="text-sm font-medium">{opt.label}</span>
|
||||
<span className="text-[11px] text-muted-foreground">{opt.description}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Behavior */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>数据刷新</CardTitle>
|
||||
<CardDescription>控制总览页轮询刷新 QQ 列表、进程列表与系统状态的间隔。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>轮询间隔</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{POLL_INTERVAL_OPTIONS.map((opt) => {
|
||||
const active = pollInterval === opt.value;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => setPollInterval(opt.value)}
|
||||
className={cn(
|
||||
'rounded-md border px-3 py-2 text-sm transition-colors cursor-pointer',
|
||||
active
|
||||
? 'border-primary bg-primary/10 text-primary'
|
||||
: 'border-border bg-background hover:bg-accent/40',
|
||||
)}
|
||||
>
|
||||
{opt.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<p className="text-[11px] text-muted-foreground">当前生效值:{pollInterval === 0 ? '已暂停轮询' : `${pollInterval} 毫秒`}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Account */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>账号安全</CardTitle>
|
||||
<CardDescription>WebUI 仅有 admin 一个账号,密码会以 scrypt 哈希形式持久化到 config/webui.json。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setShowChangePwd(true)}
|
||||
className="w-fit"
|
||||
>
|
||||
<KeyRound className="size-4" />
|
||||
修改访问密码
|
||||
</Button>
|
||||
{pwdSavedAt && (
|
||||
<span className="text-[11px] text-success">
|
||||
密码已更新({new Date(pwdSavedAt).toLocaleTimeString()})— 其他设备的会话已失效。
|
||||
</span>
|
||||
)}
|
||||
|
||||
<Separator />
|
||||
|
||||
<div>
|
||||
<p className="text-sm font-medium">退出登录</p>
|
||||
<p className="mt-1 text-[11px] text-muted-foreground">立即清除当前浏览器的会话令牌。</p>
|
||||
<Button variant="ghost" onClick={onLogout} className="mt-2 text-destructive hover:text-destructive">
|
||||
<Loader2 className="size-4 hidden" />
|
||||
退出登录
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{tab === 'appearance' && <AppearancePanel />}
|
||||
{tab === 'data' && <DataPanel />}
|
||||
{tab === 'account' && <AccountPanel />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── mini tab strip ───────────────
|
||||
|
||||
function MiniTabs({ tab, onChange }: { tab: SettingsTab; onChange: (t: SettingsTab) => void }) {
|
||||
return (
|
||||
<div className="inline-flex w-fit items-center gap-1 rounded-lg border bg-muted/40 p-1">
|
||||
{TABS.map((t) => {
|
||||
const Icon = t.icon;
|
||||
const active = tab === t.key;
|
||||
return (
|
||||
<button
|
||||
key={t.key}
|
||||
type="button"
|
||||
onClick={() => onChange(t.key)}
|
||||
className={cn(
|
||||
'relative inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm transition-colors cursor-pointer',
|
||||
active ? 'text-foreground' : 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{active && (
|
||||
<motion.span
|
||||
layoutId="settings-tab-pill"
|
||||
className="absolute inset-0 rounded-md bg-background shadow-sm"
|
||||
transition={{ type: 'spring', stiffness: 350, damping: 30 }}
|
||||
/>
|
||||
)}
|
||||
<span className="relative z-10 inline-flex items-center gap-1.5">
|
||||
<Icon className="size-4" />
|
||||
{t.label}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── 外观 ───────────────
|
||||
|
||||
function AppearancePanel() {
|
||||
const { mode, setMode, accent, setAccent, radius, setRadius, density, setDensity } = useTheme();
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>外观</CardTitle>
|
||||
<CardDescription>调整界面的明暗模式、强调色、圆角与密度。所有改动会立即应用并保存到本地。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-6">
|
||||
{/* Mode */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>显示模式</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{MODE_OPTIONS.map((opt) => {
|
||||
const Icon = opt.icon;
|
||||
const active = mode === opt.value;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => setMode(opt.value)}
|
||||
className={cn(
|
||||
'flex items-center gap-2 rounded-lg border px-3 py-2 text-sm transition-colors cursor-pointer',
|
||||
active
|
||||
? 'border-primary bg-primary/10 text-primary'
|
||||
: 'border-border bg-background hover:bg-accent/40',
|
||||
)}
|
||||
>
|
||||
<Icon className="size-4" />
|
||||
{opt.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Accent color */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>强调色</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{ACCENTS.map((spec) => {
|
||||
const active = accent === spec.id;
|
||||
return (
|
||||
<button
|
||||
key={spec.id}
|
||||
type="button"
|
||||
onClick={() => setAccent(spec.id as AccentColor)}
|
||||
title={spec.label}
|
||||
aria-label={spec.label}
|
||||
className={cn(
|
||||
'group relative flex h-9 w-9 items-center justify-center rounded-full border transition-transform cursor-pointer hover:scale-105',
|
||||
active ? 'border-foreground/30 ring-2 ring-primary' : 'border-border',
|
||||
)}
|
||||
style={{ backgroundColor: spec.swatch }}
|
||||
>
|
||||
{active && (
|
||||
<motion.span
|
||||
initial={{ scale: 0.4, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
className="text-white drop-shadow-sm"
|
||||
>
|
||||
<Check className="size-4" strokeWidth={3} />
|
||||
</motion.span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<p className="text-[11px] text-muted-foreground">当前:{ACCENTS.find((a) => a.id === accent)?.label}</p>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Radius */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>圆角</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{RADIUS_OPTIONS.map((opt) => {
|
||||
const active = Math.abs(radius - opt.value) < 1e-6;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => setRadius(opt.value)}
|
||||
className={cn(
|
||||
'rounded-md border px-3 py-2 text-sm transition-colors cursor-pointer',
|
||||
active
|
||||
? 'border-primary bg-primary/10 text-primary'
|
||||
: 'border-border bg-background hover:bg-accent/40',
|
||||
)}
|
||||
style={{ borderRadius: `${opt.value}rem` }}
|
||||
>
|
||||
{opt.label}({opt.value}rem)
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Density */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>显示密度</Label>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{DENSITY_OPTIONS.map((opt) => {
|
||||
const active = density === opt.value;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => setDensity(opt.value)}
|
||||
className={cn(
|
||||
'flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors cursor-pointer',
|
||||
active ? 'border-primary bg-primary/10' : 'border-border bg-background hover:bg-accent/40',
|
||||
)}
|
||||
>
|
||||
<span className="text-sm font-medium">{opt.label}</span>
|
||||
<span className="text-[11px] text-muted-foreground">{opt.description}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── 数据刷新 ───────────────
|
||||
|
||||
function DataPanel() {
|
||||
const { pollInterval, setPollInterval } = useTheme();
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>数据刷新</CardTitle>
|
||||
<CardDescription>控制总览页轮询刷新 QQ 列表、进程列表与系统状态的间隔。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>轮询间隔</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{POLL_INTERVAL_OPTIONS.map((opt) => {
|
||||
const active = pollInterval === opt.value;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => setPollInterval(opt.value)}
|
||||
className={cn(
|
||||
'rounded-md border px-3 py-2 text-sm transition-colors cursor-pointer',
|
||||
active
|
||||
? 'border-primary bg-primary/10 text-primary'
|
||||
: 'border-border bg-background hover:bg-accent/40',
|
||||
)}
|
||||
>
|
||||
{opt.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
当前生效值:{pollInterval === 0 ? '已暂停轮询' : `${pollInterval} 毫秒`}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── 账号安全 ───────────────
|
||||
|
||||
function AccountPanel() {
|
||||
const { onLogout } = useAppState();
|
||||
const [showChangePwd, setShowChangePwd] = useState(false);
|
||||
const [pwdSavedAt, setPwdSavedAt] = useState<number | null>(null);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>账号安全</CardTitle>
|
||||
<CardDescription>WebUI 仅有 admin 一个账号,密码会以 scrypt 哈希形式持久化到 config/webui.json。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<Button variant="outline" onClick={() => setShowChangePwd(true)} className="w-fit">
|
||||
<KeyRound className="size-4" />
|
||||
修改访问密码
|
||||
</Button>
|
||||
{pwdSavedAt && (
|
||||
<span className="text-[11px] text-success">
|
||||
密码已更新({new Date(pwdSavedAt).toLocaleTimeString()})— 其他设备的会话已失效。
|
||||
</span>
|
||||
)}
|
||||
|
||||
<Separator />
|
||||
|
||||
<div>
|
||||
<p className="text-sm font-medium">退出登录</p>
|
||||
<p className="mt-1 text-[11px] text-muted-foreground">立即清除当前浏览器的会话令牌。</p>
|
||||
<Button variant="ghost" onClick={onLogout} className="mt-2 text-destructive hover:text-destructive">
|
||||
退出登录
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<ChangePasswordDialog
|
||||
open={showChangePwd}
|
||||
onOpenChange={setShowChangePwd}
|
||||
onSuccess={() => setPwdSavedAt(Date.now())}
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
95
packages/webui/src/components/pages/status-screens.tsx
Normal file
95
packages/webui/src/components/pages/status-screens.tsx
Normal file
@@ -0,0 +1,95 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { AlertTriangle, Compass, Home, RotateCw } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
type Tone = 'primary' | 'destructive';
|
||||
|
||||
function StatusShell({
|
||||
tone,
|
||||
icon,
|
||||
code,
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
}: {
|
||||
tone: Tone;
|
||||
icon: ReactNode;
|
||||
code?: string;
|
||||
title: string;
|
||||
description: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex min-h-[60vh] w-full flex-col items-center justify-center px-4 text-center">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 16, scale: 0.98 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
transition={{ duration: 0.4, ease: [0.16, 1, 0.3, 1] }}
|
||||
className="flex w-full max-w-md flex-col items-center"
|
||||
>
|
||||
<div
|
||||
className={
|
||||
tone === 'destructive'
|
||||
? 'flex size-14 items-center justify-center rounded-2xl bg-destructive/10 ring-1 ring-destructive/20'
|
||||
: 'flex size-14 items-center justify-center rounded-2xl bg-primary/10 ring-1 ring-primary/20'
|
||||
}
|
||||
>
|
||||
{icon}
|
||||
</div>
|
||||
{code && (
|
||||
<span className="mt-4 font-mono text-4xl font-bold tracking-tight tabular-nums text-muted-foreground/60">
|
||||
{code}
|
||||
</span>
|
||||
)}
|
||||
<h1 className="mt-2 text-xl font-semibold tracking-tight">{title}</h1>
|
||||
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">{description}</p>
|
||||
<div className="mt-6 flex flex-wrap items-center justify-center gap-2">{children}</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Rendered by the router for any unmatched path. */
|
||||
export function NotFoundPage() {
|
||||
return (
|
||||
<StatusShell
|
||||
tone="primary"
|
||||
icon={<Compass className="size-7 text-primary" strokeWidth={1.75} />}
|
||||
code="404"
|
||||
title="页面不存在"
|
||||
description="你访问的地址没有对应的页面,可能链接已失效或输入有误。"
|
||||
>
|
||||
<Button onClick={() => window.location.assign('/')}>
|
||||
<Home className="size-4" /> 返回首页
|
||||
</Button>
|
||||
</StatusShell>
|
||||
);
|
||||
}
|
||||
|
||||
/** Rendered by the router when a route component throws while rendering. */
|
||||
export function ErrorPage({ error, reset }: { error?: Error; reset?: () => void }) {
|
||||
const message = error?.message?.trim();
|
||||
return (
|
||||
<StatusShell
|
||||
tone="destructive"
|
||||
icon={<AlertTriangle className="size-7 text-destructive" strokeWidth={1.75} />}
|
||||
title="页面出错了"
|
||||
description="渲染该页面时发生了意外错误。可以重试,或返回首页继续操作。"
|
||||
>
|
||||
{reset && (
|
||||
<Button variant="outline" onClick={reset}>
|
||||
<RotateCw className="size-4" /> 重试
|
||||
</Button>
|
||||
)}
|
||||
<Button onClick={() => window.location.assign('/')}>
|
||||
<Home className="size-4" /> 返回首页
|
||||
</Button>
|
||||
{message && (
|
||||
<pre className="mt-3 max-h-32 w-full overflow-auto rounded-md border bg-muted/40 px-3 py-2 text-left text-[11px] leading-relaxed text-muted-foreground whitespace-pre-wrap">
|
||||
{message}
|
||||
</pre>
|
||||
)}
|
||||
</StatusShell>
|
||||
);
|
||||
}
|
||||
@@ -32,7 +32,11 @@ const DialogContent = React.forwardRef<
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl border bg-card p-6 shadow-lg outline-none',
|
||||
// `w-[calc(100vw-2rem)]` keeps a 1rem gutter on every side on small
|
||||
// phones (plain `w-full` made the dialog touch both edges). Callers
|
||||
// only ever override `max-w-*` (the desktop cap), so the width floor
|
||||
// here survives those overrides — width and max-width are distinct.
|
||||
'fixed left-1/2 top-1/2 z-50 grid w-[calc(100vw_-_2rem)] max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl border bg-card p-6 shadow-lg outline-none',
|
||||
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
|
||||
className
|
||||
|
||||
@@ -63,4 +63,29 @@ const SheetContent = React.forwardRef<React.ElementRef<typeof DialogPrimitive.Co
|
||||
);
|
||||
SheetContent.displayName = 'SheetContent';
|
||||
|
||||
export { Sheet, SheetTrigger, SheetClose, SheetContent, SheetPortal, SheetOverlay };
|
||||
const SheetTitle = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Title ref={ref} className={cn('text-lg font-semibold tracking-tight', className)} {...props} />
|
||||
));
|
||||
SheetTitle.displayName = 'SheetTitle';
|
||||
|
||||
const SheetDescription = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Description ref={ref} className={cn('text-sm text-muted-foreground', className)} {...props} />
|
||||
));
|
||||
SheetDescription.displayName = 'SheetDescription';
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
SheetTrigger,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetPortal,
|
||||
SheetOverlay,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createContext, useContext, type ReactNode } from 'react';
|
||||
import type { HookProcessInfo, QQInfo, SystemInfo } from '@/types';
|
||||
import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo } from '@/types';
|
||||
import type { HookProcessOps } from '@/hooks/use-hook-process-ops';
|
||||
|
||||
/**
|
||||
@@ -12,11 +12,13 @@ export interface AppStateValue {
|
||||
qqList: QQInfo[];
|
||||
processList: HookProcessInfo[];
|
||||
systemInfo: SystemInfo | null;
|
||||
connections: AccountConnections[];
|
||||
selectedUin: string | null;
|
||||
setSelectedUin: (uin: string | null) => void;
|
||||
processOps: HookProcessOps;
|
||||
refreshProcesses: () => void;
|
||||
refreshSystem: () => void;
|
||||
refreshConnections: () => void;
|
||||
/** Triggered from the topbar logout button. */
|
||||
onLogout: () => void;
|
||||
}
|
||||
|
||||
@@ -25,7 +25,13 @@ export interface UseOneBotInstanceConfig {
|
||||
pendingSwitchUin: string | null;
|
||||
confirmSwitch: () => void;
|
||||
cancelSwitch: () => void;
|
||||
save: () => Promise<void>;
|
||||
/**
|
||||
* Persist to the backend. Pass an explicit config to save it directly —
|
||||
* the node dialog / enable-toggle / delete persist their freshly-computed
|
||||
* config in the same tick, before React has flushed `setConfig`, so they
|
||||
* can't rely on the (still-stale) closed-over `config`.
|
||||
*/
|
||||
save: (override?: OneBotConfig) => Promise<void>;
|
||||
saveStatus: string;
|
||||
}
|
||||
|
||||
@@ -117,11 +123,12 @@ export function useOneBotInstanceConfig(
|
||||
}, CLEAR_SAVE_STATUS_MS);
|
||||
}, []);
|
||||
|
||||
const save = useCallback(async () => {
|
||||
if (!selectedUin || !config) return;
|
||||
const save = useCallback(async (override?: OneBotConfig) => {
|
||||
const target = override ?? config;
|
||||
if (!selectedUin || !target) return;
|
||||
setSaveStatus('保存中...');
|
||||
try {
|
||||
const serverView = await api.config.save(selectedUin, config);
|
||||
const serverView = await api.config.save(selectedUin, target);
|
||||
setConfigState(serverView);
|
||||
setSavedSnapshot(JSON.stringify(serverView));
|
||||
setSaveStatus('保存成功');
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { HookProcessInfo, LogEntry, LogLevel, QQInfo, SystemInfo } from '@/types';
|
||||
import type { AccountConnections, HookProcessInfo, LogEntry, LogLevel, QQInfo, SystemInfo } from '@/types';
|
||||
import type { PasswordRule } from '@/components/pages/change-password-page';
|
||||
import { normalizeOneBotConfig } from '@/lib/onebot-config';
|
||||
import {
|
||||
@@ -222,6 +222,10 @@ class HttpApiClient implements ApiClient {
|
||||
return this.getJson<SystemInfo>('/api/system');
|
||||
}
|
||||
|
||||
connections(): Promise<AccountConnections[]> {
|
||||
return this.getJson<{ list: AccountConnections[] }>('/api/connections').then((d) => d.list ?? []);
|
||||
}
|
||||
|
||||
// ---------- SSE ----------
|
||||
|
||||
private openLogStream(options: LogsStreamOptions): () => void {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type {
|
||||
AccountConnections,
|
||||
HookProcessInfo,
|
||||
LogEntry,
|
||||
LogLevel,
|
||||
@@ -50,6 +51,8 @@ export interface ApiClient {
|
||||
// ---- system ----
|
||||
qqList(): Promise<QQInfo[]>;
|
||||
system(): Promise<SystemInfo>;
|
||||
/** Live OneBot adapter health per account. */
|
||||
connections(): Promise<AccountConnections[]>;
|
||||
|
||||
// ---- hook processes ----
|
||||
processes: {
|
||||
|
||||
@@ -8,7 +8,7 @@ import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { AppStateProvider } from '@/contexts/AppStateContext';
|
||||
import { useSession } from '@/contexts/SessionContext';
|
||||
import type { HookProcessInfo, QQInfo, SystemInfo } from '@/types';
|
||||
import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo } from '@/types';
|
||||
|
||||
/**
|
||||
* The layout route. Owns the live state shared across the four pages
|
||||
@@ -24,6 +24,7 @@ export function AppLayout() {
|
||||
const [qqList, setQqList] = useState<QQInfo[]>([]);
|
||||
const [processList, setProcessList] = useState<HookProcessInfo[]>([]);
|
||||
const [systemInfo, setSystemInfo] = useState<SystemInfo | null>(null);
|
||||
const [connections, setConnections] = useState<AccountConnections[]>([]);
|
||||
const [selectedUin, setSelectedUin] = useState<string | null>(null);
|
||||
|
||||
const refreshQqList = useCallback(async () => {
|
||||
@@ -50,6 +51,14 @@ export function AppLayout() {
|
||||
}
|
||||
}, [api]);
|
||||
|
||||
const refreshConnections = useCallback(async () => {
|
||||
try {
|
||||
setConnections(await api.connections());
|
||||
} catch (e) {
|
||||
console.error('connections', e);
|
||||
}
|
||||
}, [api]);
|
||||
|
||||
const { ops: processOps, unloadFailedAlert, dismissUnloadFailedAlert } = useHookProcessOps({
|
||||
onAfterOp: refreshProcesses,
|
||||
});
|
||||
@@ -59,7 +68,7 @@ export function AppLayout() {
|
||||
let cancelled = false;
|
||||
const tick = async () => {
|
||||
if (cancelled) return;
|
||||
await Promise.all([refreshQqList(), refreshProcesses(), refreshSystem()]);
|
||||
await Promise.all([refreshQqList(), refreshProcesses(), refreshSystem(), refreshConnections()]);
|
||||
};
|
||||
tick();
|
||||
const interval = setInterval(tick, pollInterval);
|
||||
@@ -67,13 +76,14 @@ export function AppLayout() {
|
||||
cancelled = true;
|
||||
clearInterval(interval);
|
||||
};
|
||||
}, [pollInterval, refreshQqList, refreshProcesses, refreshSystem]);
|
||||
}, [pollInterval, refreshQqList, refreshProcesses, refreshSystem, refreshConnections]);
|
||||
|
||||
const handleLogout = useCallback(async () => {
|
||||
await api.logout();
|
||||
setQqList([]);
|
||||
setProcessList([]);
|
||||
setSystemInfo(null);
|
||||
setConnections([]);
|
||||
setSelectedUin(null);
|
||||
session.onLogoutComplete();
|
||||
}, [api, session]);
|
||||
@@ -84,11 +94,13 @@ export function AppLayout() {
|
||||
qqList,
|
||||
processList,
|
||||
systemInfo,
|
||||
connections,
|
||||
selectedUin,
|
||||
setSelectedUin,
|
||||
processOps,
|
||||
refreshProcesses,
|
||||
refreshSystem,
|
||||
refreshConnections,
|
||||
onLogout: handleLogout,
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -6,6 +6,9 @@ import {
|
||||
Outlet,
|
||||
} from '@tanstack/react-router';
|
||||
import { AppLayout } from './app-layout';
|
||||
// Imported eagerly (not lazy): the error / not-found fallbacks must render
|
||||
// even when a route's own chunk failed to load.
|
||||
import { ErrorPage, NotFoundPage } from '@/components/pages/status-screens';
|
||||
|
||||
// Page components are loaded on demand so the initial paint only ships
|
||||
// the auth surface + layout shell. With `defaultPreload: 'intent'` set
|
||||
@@ -34,6 +37,15 @@ const overviewRoute = createRoute({
|
||||
),
|
||||
});
|
||||
|
||||
const processesRoute = createRoute({
|
||||
path: '/processes',
|
||||
getParentRoute: () => appLayoutRoute,
|
||||
component: lazyRouteComponent(
|
||||
() => import('@/components/pages/processes-page'),
|
||||
'ProcessesPage',
|
||||
),
|
||||
});
|
||||
|
||||
const configRoute = createRoute({
|
||||
path: '/config',
|
||||
getParentRoute: () => appLayoutRoute,
|
||||
@@ -62,12 +74,14 @@ const settingsRoute = createRoute({
|
||||
});
|
||||
|
||||
const routeTree = rootRoute.addChildren([
|
||||
appLayoutRoute.addChildren([overviewRoute, configRoute, logsRoute, settingsRoute]),
|
||||
appLayoutRoute.addChildren([overviewRoute, processesRoute, configRoute, logsRoute, settingsRoute]),
|
||||
]);
|
||||
|
||||
export const appRouter = createRouter({
|
||||
routeTree,
|
||||
defaultPreload: 'intent',
|
||||
defaultNotFoundComponent: () => <NotFoundPage />,
|
||||
defaultErrorComponent: ({ error, reset }) => <ErrorPage error={error} reset={reset} />,
|
||||
});
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
@@ -77,4 +91,4 @@ declare module '@tanstack/react-router' {
|
||||
}
|
||||
|
||||
/** Paths registered on the layout — single source of truth for nav metadata. */
|
||||
export type AppPath = '/' | '/config' | '/logs' | '/settings';
|
||||
export type AppPath = '/' | '/processes' | '/config' | '/logs' | '/settings';
|
||||
|
||||
@@ -7,6 +7,21 @@ export interface QQInfo {
|
||||
nickname: string;
|
||||
}
|
||||
|
||||
export type AdapterStatusLevel = 'ok' | 'warn' | 'down' | 'disabled';
|
||||
|
||||
export interface AdapterStatus {
|
||||
name: string;
|
||||
kind: 'httpServer' | 'httpClient' | 'wsServer' | 'wsClient';
|
||||
status: AdapterStatusLevel;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
export interface AccountConnections {
|
||||
uin: string;
|
||||
nickname: string;
|
||||
adapters: AdapterStatus[];
|
||||
}
|
||||
|
||||
export interface HookProcessInfo {
|
||||
pid: number;
|
||||
name: string;
|
||||
|
||||
288
pnpm-lock.yaml
generated
288
pnpm-lock.yaml
generated
@@ -102,9 +102,6 @@ importers:
|
||||
'@snowluma/proton':
|
||||
specifier: workspace:*
|
||||
version: link:../proton
|
||||
'@snowluma/sqlite':
|
||||
specifier: workspace:*
|
||||
version: link:../sqlite
|
||||
'@snowluma/websocket':
|
||||
specifier: workspace:*
|
||||
version: link:../websocket
|
||||
@@ -157,9 +154,6 @@ importers:
|
||||
'@snowluma/proton':
|
||||
specifier: workspace:*
|
||||
version: link:../proton
|
||||
'@snowluma/sqlite':
|
||||
specifier: workspace:*
|
||||
version: link:../sqlite
|
||||
'@snowluma/websocket':
|
||||
specifier: workspace:*
|
||||
version: link:../websocket
|
||||
@@ -201,9 +195,6 @@ importers:
|
||||
'@snowluma/proton':
|
||||
specifier: workspace:*
|
||||
version: link:../proton
|
||||
'@snowluma/sqlite':
|
||||
specifier: workspace:*
|
||||
version: link:../sqlite
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^24.12.2
|
||||
@@ -251,21 +242,6 @@ importers:
|
||||
specifier: ^4.1.4
|
||||
version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
|
||||
|
||||
packages/sqlite:
|
||||
devDependencies:
|
||||
'@types/better-sqlite3':
|
||||
specifier: ^7.6.13
|
||||
version: 7.6.13
|
||||
'@types/node':
|
||||
specifier: ^24.12.2
|
||||
version: 24.12.2
|
||||
better-sqlite3:
|
||||
specifier: 12.10.0
|
||||
version: 12.10.0
|
||||
typescript:
|
||||
specifier: 'catalog:'
|
||||
version: 6.0.2
|
||||
|
||||
packages/ui:
|
||||
dependencies:
|
||||
'@radix-ui/react-alert-dialog':
|
||||
@@ -1695,9 +1671,6 @@ packages:
|
||||
'@tybys/wasm-util@0.10.1':
|
||||
resolution: {integrity: sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==}
|
||||
|
||||
'@types/better-sqlite3@7.6.13':
|
||||
resolution: {integrity: sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==}
|
||||
|
||||
'@types/chai@5.2.3':
|
||||
resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
|
||||
|
||||
@@ -1891,24 +1864,11 @@ packages:
|
||||
base-log-factory@2.1.4:
|
||||
resolution: {integrity: sha512-FK1tHOB+rXvlBcGYYhSNR2QS2juEG4SZ1ekXQRQ2XscYNtDxllzqkzfgBFr12EVrKb2/07NLdbr0cSwVoc378A==}
|
||||
|
||||
base64-js@1.5.1:
|
||||
resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}
|
||||
|
||||
baseline-browser-mapping@2.10.19:
|
||||
resolution: {integrity: sha512-qCkNLi2sfBOn8XhZQ0FXsT1Ki/Yo5P90hrkRamVFRS7/KV9hpfA4HkoWNU152+8w0zPjnxo5psx5NL3PSGgv5g==}
|
||||
engines: {node: '>=6.0.0'}
|
||||
hasBin: true
|
||||
|
||||
better-sqlite3@12.10.0:
|
||||
resolution: {integrity: sha512-CyzaZRQKyHkB2ZInfTTl2nvT33EbDpjkLEbE8/Zck3Ll6O0qqvuGdrJ45HgtH+HykRg88ITY3AdreBGN70aBSQ==}
|
||||
engines: {node: 20.x || 22.x || 23.x || 24.x || 25.x || 26.x}
|
||||
|
||||
bindings@1.5.0:
|
||||
resolution: {integrity: sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==}
|
||||
|
||||
bl@4.1.0:
|
||||
resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==}
|
||||
|
||||
blf-colorful-appender@1.0.6:
|
||||
resolution: {integrity: sha512-MdwOI17J8iOC2XKi5b4VagAJg308R4QesRoCAPw/w7ihzwkTst91LvkTAF3GvPJCEaHXptiUS2UsFkCNiBIEGg==}
|
||||
|
||||
@@ -1924,9 +1884,6 @@ packages:
|
||||
engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
|
||||
hasBin: true
|
||||
|
||||
buffer@5.7.1:
|
||||
resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==}
|
||||
|
||||
bundle-require@5.1.0:
|
||||
resolution: {integrity: sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==}
|
||||
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
|
||||
@@ -1948,9 +1905,6 @@ packages:
|
||||
resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==}
|
||||
engines: {node: '>= 14.16.0'}
|
||||
|
||||
chownr@1.1.4:
|
||||
resolution: {integrity: sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==}
|
||||
|
||||
class-variance-authority@0.7.1:
|
||||
resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==}
|
||||
|
||||
@@ -2003,14 +1957,6 @@ packages:
|
||||
supports-color:
|
||||
optional: true
|
||||
|
||||
decompress-response@6.0.0:
|
||||
resolution: {integrity: sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==}
|
||||
engines: {node: '>=10'}
|
||||
|
||||
deep-extend@0.6.0:
|
||||
resolution: {integrity: sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==}
|
||||
engines: {node: '>=4.0.0'}
|
||||
|
||||
deep-is@0.1.4:
|
||||
resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==}
|
||||
|
||||
@@ -2028,9 +1974,6 @@ packages:
|
||||
electron-to-chromium@1.5.339:
|
||||
resolution: {integrity: sha512-Is+0BBHJ4NrdpAYiperrmp53pLywG/yV/6lIMTAnhxvzj/Cmn5Q/ogSHC6AKe7X+8kPLxxFk0cs5oc/3j/fxIg==}
|
||||
|
||||
end-of-stream@1.4.5:
|
||||
resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==}
|
||||
|
||||
enhanced-resolve@5.20.1:
|
||||
resolution: {integrity: sha512-Qohcme7V1inbAfvjItgw0EaxVX5q2rdVEZHRBrEQdRZTssLDGsL8Lwrznl8oQ/6kuTJONLaDcGjkNP247XEhcA==}
|
||||
engines: {node: '>=10.13.0'}
|
||||
@@ -2114,10 +2057,6 @@ packages:
|
||||
resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
expand-template@2.0.3:
|
||||
resolution: {integrity: sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
expect-type@1.3.0:
|
||||
resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==}
|
||||
engines: {node: '>=12.0.0'}
|
||||
@@ -2149,9 +2088,6 @@ packages:
|
||||
resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==}
|
||||
engines: {node: '>=16.0.0'}
|
||||
|
||||
file-uri-to-path@1.0.0:
|
||||
resolution: {integrity: sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==}
|
||||
|
||||
find-up@5.0.0:
|
||||
resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==}
|
||||
engines: {node: '>=10'}
|
||||
@@ -2180,9 +2116,6 @@ packages:
|
||||
react-dom:
|
||||
optional: true
|
||||
|
||||
fs-constants@1.0.0:
|
||||
resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==}
|
||||
|
||||
fs-extra@11.3.4:
|
||||
resolution: {integrity: sha512-CTXd6rk/M3/ULNQj8FBqBWHYBVYybQ3VPBw0xGKFe3tuH7ytT6ACnvzpIQ3UZtB8yvUKC2cXn1a+x+5EVQLovA==}
|
||||
engines: {node: '>=14.14'}
|
||||
@@ -2206,9 +2139,6 @@ packages:
|
||||
get-tsconfig@4.14.0:
|
||||
resolution: {integrity: sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==}
|
||||
|
||||
github-from-package@0.0.0:
|
||||
resolution: {integrity: sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==}
|
||||
|
||||
glob-parent@6.0.2:
|
||||
resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==}
|
||||
engines: {node: '>=10.13.0'}
|
||||
@@ -2241,9 +2171,6 @@ packages:
|
||||
html-escaper@2.0.2:
|
||||
resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}
|
||||
|
||||
ieee754@1.2.1:
|
||||
resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==}
|
||||
|
||||
ignore@5.3.2:
|
||||
resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==}
|
||||
engines: {node: '>= 4'}
|
||||
@@ -2259,12 +2186,6 @@ packages:
|
||||
resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==}
|
||||
engines: {node: '>=0.8.19'}
|
||||
|
||||
inherits@2.0.4:
|
||||
resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
|
||||
|
||||
ini@1.3.8:
|
||||
resolution: {integrity: sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==}
|
||||
|
||||
is-core-module@2.16.1:
|
||||
resolution: {integrity: sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -2452,20 +2373,10 @@ packages:
|
||||
resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==}
|
||||
engines: {node: '>=10'}
|
||||
|
||||
mimic-response@3.1.0:
|
||||
resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==}
|
||||
engines: {node: '>=10'}
|
||||
|
||||
minimatch@10.2.5:
|
||||
resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==}
|
||||
engines: {node: 18 || 20 || >=22}
|
||||
|
||||
minimist@1.2.8:
|
||||
resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==}
|
||||
|
||||
mkdirp-classic@0.5.3:
|
||||
resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==}
|
||||
|
||||
mlly@1.8.2:
|
||||
resolution: {integrity: sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==}
|
||||
|
||||
@@ -2500,16 +2411,9 @@ packages:
|
||||
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
|
||||
hasBin: true
|
||||
|
||||
napi-build-utils@2.0.0:
|
||||
resolution: {integrity: sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==}
|
||||
|
||||
natural-compare@1.4.0:
|
||||
resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==}
|
||||
|
||||
node-abi@3.92.0:
|
||||
resolution: {integrity: sha512-KdHvFWZjEKDf0cakgFjebl371GPsISX2oZHcuyKqM7DtogIsHrqKeLTo8wBHxaXRAQlY2PsPlZmfo+9ZCxEREQ==}
|
||||
engines: {node: '>=10'}
|
||||
|
||||
node-addon-api@7.1.1:
|
||||
resolution: {integrity: sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==}
|
||||
|
||||
@@ -2523,9 +2427,6 @@ packages:
|
||||
obug@2.1.1:
|
||||
resolution: {integrity: sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==}
|
||||
|
||||
once@1.4.0:
|
||||
resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}
|
||||
|
||||
optionator@0.9.4:
|
||||
resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==}
|
||||
engines: {node: '>= 0.8.0'}
|
||||
@@ -2588,27 +2489,14 @@ packages:
|
||||
resolution: {integrity: sha512-pMMHxBOZKFU6HgAZ4eyGnwXF/EvPGGqUr0MnZ5+99485wwW41kW91A4LOGxSHhgugZmSChL5AlElNdwlNgcnLQ==}
|
||||
engines: {node: ^10 || ^12 || >=14}
|
||||
|
||||
prebuild-install@7.1.3:
|
||||
resolution: {integrity: sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==}
|
||||
engines: {node: '>=10'}
|
||||
deprecated: No longer maintained. Please contact the author of the relevant native addon; alternatives are available.
|
||||
hasBin: true
|
||||
|
||||
prelude-ls@1.2.1:
|
||||
resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==}
|
||||
engines: {node: '>= 0.8.0'}
|
||||
|
||||
pump@3.0.4:
|
||||
resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==}
|
||||
|
||||
punycode@2.3.1:
|
||||
resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
rc@1.2.8:
|
||||
resolution: {integrity: sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==}
|
||||
hasBin: true
|
||||
|
||||
react-dom@19.2.5:
|
||||
resolution: {integrity: sha512-J5bAZz+DXMMwW/wV3xzKke59Af6CHY7G4uYLN1OvBcKEsWOs4pQExj86BBKamxl/Ik5bx9whOrvBlSDfWzgSag==}
|
||||
peerDependencies:
|
||||
@@ -2648,10 +2536,6 @@ packages:
|
||||
resolution: {integrity: sha512-llUJLzz1zTUBrskt2pwZgLq59AemifIftw4aB7JxOqf1HY2FDaGDxgwpAPVzHU1kdWabH7FauP4i1oEeer2WCA==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
readable-stream@3.6.2:
|
||||
resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==}
|
||||
engines: {node: '>= 6'}
|
||||
|
||||
readdirp@4.1.2:
|
||||
resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==}
|
||||
engines: {node: '>= 14.18.0'}
|
||||
@@ -2678,9 +2562,6 @@ packages:
|
||||
engines: {node: '>=18.0.0', npm: '>=8.0.0'}
|
||||
hasBin: true
|
||||
|
||||
safe-buffer@5.2.1:
|
||||
resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==}
|
||||
|
||||
sass@1.99.0:
|
||||
resolution: {integrity: sha512-kgW13M54DUB7IsIRM5LvJkNlpH+WhMpooUcaWGFARkF1Tc82v9mIWkCbCYf+MBvpIUBSeSOTilpZjEPr2VYE6Q==}
|
||||
engines: {node: '>=14.0.0'}
|
||||
@@ -2719,12 +2600,6 @@ packages:
|
||||
siginfo@2.0.0:
|
||||
resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
|
||||
|
||||
simple-concat@1.0.1:
|
||||
resolution: {integrity: sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==}
|
||||
|
||||
simple-get@4.0.1:
|
||||
resolution: {integrity: sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==}
|
||||
|
||||
sonner@2.0.7:
|
||||
resolution: {integrity: sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w==}
|
||||
peerDependencies:
|
||||
@@ -2745,13 +2620,6 @@ packages:
|
||||
std-env@4.1.0:
|
||||
resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==}
|
||||
|
||||
string_decoder@1.3.0:
|
||||
resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==}
|
||||
|
||||
strip-json-comments@2.0.1:
|
||||
resolution: {integrity: sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
sucrase@3.35.1:
|
||||
resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==}
|
||||
engines: {node: '>=16 || 14 >=14.17'}
|
||||
@@ -2775,13 +2643,6 @@ packages:
|
||||
resolution: {integrity: sha512-1MOpMXuhGzGL5TTCZFItxCc0AARf1EZFQkGqMm7ERKj8+Hgr5oLvJOVFcC+lRmR8hCe2S3jC4T5D7Vg/d7/fhA==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
tar-fs@2.1.4:
|
||||
resolution: {integrity: sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==}
|
||||
|
||||
tar-stream@2.2.0:
|
||||
resolution: {integrity: sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
thenify-all@1.6.0:
|
||||
resolution: {integrity: sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==}
|
||||
engines: {node: '>=0.8'}
|
||||
@@ -2847,9 +2708,6 @@ packages:
|
||||
engines: {node: '>=18.0.0'}
|
||||
hasBin: true
|
||||
|
||||
tunnel-agent@0.6.0:
|
||||
resolution: {integrity: sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==}
|
||||
|
||||
tw-animate-css@1.4.0:
|
||||
resolution: {integrity: sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ==}
|
||||
|
||||
@@ -2916,9 +2774,6 @@ packages:
|
||||
peerDependencies:
|
||||
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
|
||||
|
||||
util-deprecate@1.0.2:
|
||||
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
|
||||
|
||||
vite-plugin-cp@6.0.3:
|
||||
resolution: {integrity: sha512-qxKGH3v9wPwUDbDchJf4IH4mRE1zkLWgzZSxwrl8LapwUWm48IFS7SlbRmcF4NquC/fESA5cHFge9E2Ps+woxg==}
|
||||
engines: {node: '>=14.18.0', vite: '>=3.1.0'}
|
||||
@@ -3025,9 +2880,6 @@ packages:
|
||||
resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
wrappy@1.0.2:
|
||||
resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}
|
||||
|
||||
yallist@3.1.1:
|
||||
resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}
|
||||
|
||||
@@ -4075,10 +3927,6 @@ snapshots:
|
||||
tslib: 2.8.1
|
||||
optional: true
|
||||
|
||||
'@types/better-sqlite3@7.6.13':
|
||||
dependencies:
|
||||
'@types/node': 25.6.0
|
||||
|
||||
'@types/chai@5.2.3':
|
||||
dependencies:
|
||||
'@types/deep-eql': 4.0.2
|
||||
@@ -4326,25 +4174,8 @@ snapshots:
|
||||
date-manip: 2.0.6
|
||||
is-what-type: 1.1.4
|
||||
|
||||
base64-js@1.5.1: {}
|
||||
|
||||
baseline-browser-mapping@2.10.19: {}
|
||||
|
||||
better-sqlite3@12.10.0:
|
||||
dependencies:
|
||||
bindings: 1.5.0
|
||||
prebuild-install: 7.1.3
|
||||
|
||||
bindings@1.5.0:
|
||||
dependencies:
|
||||
file-uri-to-path: 1.0.0
|
||||
|
||||
bl@4.1.0:
|
||||
dependencies:
|
||||
buffer: 5.7.1
|
||||
inherits: 2.0.4
|
||||
readable-stream: 3.6.2
|
||||
|
||||
blf-colorful-appender@1.0.6:
|
||||
dependencies:
|
||||
base-log-factory: 2.1.4
|
||||
@@ -4372,11 +4203,6 @@ snapshots:
|
||||
node-releases: 2.0.37
|
||||
update-browserslist-db: 1.2.3(browserslist@4.28.2)
|
||||
|
||||
buffer@5.7.1:
|
||||
dependencies:
|
||||
base64-js: 1.5.1
|
||||
ieee754: 1.2.1
|
||||
|
||||
bundle-require@5.1.0(esbuild@0.27.7):
|
||||
dependencies:
|
||||
esbuild: 0.27.7
|
||||
@@ -4392,8 +4218,6 @@ snapshots:
|
||||
dependencies:
|
||||
readdirp: 4.1.2
|
||||
|
||||
chownr@1.1.4: {}
|
||||
|
||||
class-variance-authority@0.7.1:
|
||||
dependencies:
|
||||
clsx: 2.1.1
|
||||
@@ -4431,12 +4255,6 @@ snapshots:
|
||||
dependencies:
|
||||
ms: 2.1.3
|
||||
|
||||
decompress-response@6.0.0:
|
||||
dependencies:
|
||||
mimic-response: 3.1.0
|
||||
|
||||
deep-extend@0.6.0: {}
|
||||
|
||||
deep-is@0.1.4: {}
|
||||
|
||||
deepmerge@4.3.1: {}
|
||||
@@ -4447,10 +4265,6 @@ snapshots:
|
||||
|
||||
electron-to-chromium@1.5.339: {}
|
||||
|
||||
end-of-stream@1.4.5:
|
||||
dependencies:
|
||||
once: 1.4.0
|
||||
|
||||
enhanced-resolve@5.20.1:
|
||||
dependencies:
|
||||
graceful-fs: 4.2.11
|
||||
@@ -4580,8 +4394,6 @@ snapshots:
|
||||
|
||||
esutils@2.0.3: {}
|
||||
|
||||
expand-template@2.0.3: {}
|
||||
|
||||
expect-type@1.3.0: {}
|
||||
|
||||
fast-deep-equal@3.1.3: {}
|
||||
@@ -4602,8 +4414,6 @@ snapshots:
|
||||
dependencies:
|
||||
flat-cache: 4.0.1
|
||||
|
||||
file-uri-to-path@1.0.0: {}
|
||||
|
||||
find-up@5.0.0:
|
||||
dependencies:
|
||||
locate-path: 6.0.0
|
||||
@@ -4631,8 +4441,6 @@ snapshots:
|
||||
react: 19.2.5
|
||||
react-dom: 19.2.5(react@19.2.5)
|
||||
|
||||
fs-constants@1.0.0: {}
|
||||
|
||||
fs-extra@11.3.4:
|
||||
dependencies:
|
||||
graceful-fs: 4.2.11
|
||||
@@ -4652,8 +4460,6 @@ snapshots:
|
||||
dependencies:
|
||||
resolve-pkg-maps: 1.0.0
|
||||
|
||||
github-from-package@0.0.0: {}
|
||||
|
||||
glob-parent@6.0.2:
|
||||
dependencies:
|
||||
is-glob: 4.0.3
|
||||
@@ -4678,8 +4484,6 @@ snapshots:
|
||||
|
||||
html-escaper@2.0.2: {}
|
||||
|
||||
ieee754@1.2.1: {}
|
||||
|
||||
ignore@5.3.2: {}
|
||||
|
||||
ignore@7.0.5: {}
|
||||
@@ -4689,10 +4493,6 @@ snapshots:
|
||||
|
||||
imurmurhash@0.1.4: {}
|
||||
|
||||
inherits@2.0.4: {}
|
||||
|
||||
ini@1.3.8: {}
|
||||
|
||||
is-core-module@2.16.1:
|
||||
dependencies:
|
||||
hasown: 2.0.2
|
||||
@@ -4838,16 +4638,10 @@ snapshots:
|
||||
dependencies:
|
||||
semver: 7.7.4
|
||||
|
||||
mimic-response@3.1.0: {}
|
||||
|
||||
minimatch@10.2.5:
|
||||
dependencies:
|
||||
brace-expansion: 5.0.5
|
||||
|
||||
minimist@1.2.8: {}
|
||||
|
||||
mkdirp-classic@0.5.3: {}
|
||||
|
||||
mlly@1.8.2:
|
||||
dependencies:
|
||||
acorn: 8.16.0
|
||||
@@ -4879,14 +4673,8 @@ snapshots:
|
||||
|
||||
nanoid@3.3.11: {}
|
||||
|
||||
napi-build-utils@2.0.0: {}
|
||||
|
||||
natural-compare@1.4.0: {}
|
||||
|
||||
node-abi@3.92.0:
|
||||
dependencies:
|
||||
semver: 7.7.4
|
||||
|
||||
node-addon-api@7.1.1:
|
||||
optional: true
|
||||
|
||||
@@ -4896,10 +4684,6 @@ snapshots:
|
||||
|
||||
obug@2.1.1: {}
|
||||
|
||||
once@1.4.0:
|
||||
dependencies:
|
||||
wrappy: 1.0.2
|
||||
|
||||
optionator@0.9.4:
|
||||
dependencies:
|
||||
deep-is: 0.1.4
|
||||
@@ -4951,37 +4735,10 @@ snapshots:
|
||||
picocolors: 1.1.1
|
||||
source-map-js: 1.2.1
|
||||
|
||||
prebuild-install@7.1.3:
|
||||
dependencies:
|
||||
detect-libc: 2.1.2
|
||||
expand-template: 2.0.3
|
||||
github-from-package: 0.0.0
|
||||
minimist: 1.2.8
|
||||
mkdirp-classic: 0.5.3
|
||||
napi-build-utils: 2.0.0
|
||||
node-abi: 3.92.0
|
||||
pump: 3.0.4
|
||||
rc: 1.2.8
|
||||
simple-get: 4.0.1
|
||||
tar-fs: 2.1.4
|
||||
tunnel-agent: 0.6.0
|
||||
|
||||
prelude-ls@1.2.1: {}
|
||||
|
||||
pump@3.0.4:
|
||||
dependencies:
|
||||
end-of-stream: 1.4.5
|
||||
once: 1.4.0
|
||||
|
||||
punycode@2.3.1: {}
|
||||
|
||||
rc@1.2.8:
|
||||
dependencies:
|
||||
deep-extend: 0.6.0
|
||||
ini: 1.3.8
|
||||
minimist: 1.2.8
|
||||
strip-json-comments: 2.0.1
|
||||
|
||||
react-dom@19.2.5(react@19.2.5):
|
||||
dependencies:
|
||||
react: 19.2.5
|
||||
@@ -5016,12 +4773,6 @@ snapshots:
|
||||
|
||||
react@19.2.5: {}
|
||||
|
||||
readable-stream@3.6.2:
|
||||
dependencies:
|
||||
inherits: 2.0.4
|
||||
string_decoder: 1.3.0
|
||||
util-deprecate: 1.0.2
|
||||
|
||||
readdirp@4.1.2: {}
|
||||
|
||||
resolve-from@5.0.0: {}
|
||||
@@ -5087,8 +4838,6 @@ snapshots:
|
||||
'@rollup/rollup-win32-x64-msvc': 4.60.4
|
||||
fsevents: 2.3.3
|
||||
|
||||
safe-buffer@5.2.1: {}
|
||||
|
||||
sass@1.99.0:
|
||||
dependencies:
|
||||
chokidar: 4.0.3
|
||||
@@ -5118,14 +4867,6 @@ snapshots:
|
||||
|
||||
siginfo@2.0.0: {}
|
||||
|
||||
simple-concat@1.0.1: {}
|
||||
|
||||
simple-get@4.0.1:
|
||||
dependencies:
|
||||
decompress-response: 6.0.0
|
||||
once: 1.4.0
|
||||
simple-concat: 1.0.1
|
||||
|
||||
sonner@2.0.7(react-dom@19.2.5(react@19.2.5))(react@19.2.5):
|
||||
dependencies:
|
||||
react: 19.2.5
|
||||
@@ -5139,12 +4880,6 @@ snapshots:
|
||||
|
||||
std-env@4.1.0: {}
|
||||
|
||||
string_decoder@1.3.0:
|
||||
dependencies:
|
||||
safe-buffer: 5.2.1
|
||||
|
||||
strip-json-comments@2.0.1: {}
|
||||
|
||||
sucrase@3.35.1:
|
||||
dependencies:
|
||||
'@jridgewell/gen-mapping': 0.3.13
|
||||
@@ -5167,21 +4902,6 @@ snapshots:
|
||||
|
||||
tapable@2.3.2: {}
|
||||
|
||||
tar-fs@2.1.4:
|
||||
dependencies:
|
||||
chownr: 1.1.4
|
||||
mkdirp-classic: 0.5.3
|
||||
pump: 3.0.4
|
||||
tar-stream: 2.2.0
|
||||
|
||||
tar-stream@2.2.0:
|
||||
dependencies:
|
||||
bl: 4.1.0
|
||||
end-of-stream: 1.4.5
|
||||
fs-constants: 1.0.0
|
||||
inherits: 2.0.4
|
||||
readable-stream: 3.6.2
|
||||
|
||||
thenify-all@1.6.0:
|
||||
dependencies:
|
||||
thenify: 3.3.1
|
||||
@@ -5248,10 +4968,6 @@ snapshots:
|
||||
optionalDependencies:
|
||||
fsevents: 2.3.3
|
||||
|
||||
tunnel-agent@0.6.0:
|
||||
dependencies:
|
||||
safe-buffer: 5.2.1
|
||||
|
||||
tw-animate-css@1.4.0: {}
|
||||
|
||||
type-check@0.4.0:
|
||||
@@ -5308,8 +5024,6 @@ snapshots:
|
||||
dependencies:
|
||||
react: 19.2.5
|
||||
|
||||
util-deprecate@1.0.2: {}
|
||||
|
||||
vite-plugin-cp@6.0.3:
|
||||
dependencies:
|
||||
fs-extra: 11.3.4
|
||||
@@ -5400,8 +5114,6 @@ snapshots:
|
||||
|
||||
word-wrap@1.2.5: {}
|
||||
|
||||
wrappy@1.0.2: {}
|
||||
|
||||
yallist@3.1.1: {}
|
||||
|
||||
yocto-queue@0.1.0: {}
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
// Downloads better-sqlite3 prebuilt native bindings for all SnowLuma
|
||||
// CI matrix targets (win32-x64, linux-x64, linux-arm64) plus the
|
||||
// developer host (darwin-arm64 / darwin-x64) and vendors them into
|
||||
// `packages/runtime/native/better-sqlite3-<platform>-<arch>.node`.
|
||||
//
|
||||
// vite-plugin-cp picks the matching binary for `SNOWLUMA_TARGET`
|
||||
// during `pnpm build` and copies it into `dist/native/`, where
|
||||
// `@snowluma/sqlite/index.ts` finds it at runtime. Naming + layout
|
||||
// mirror the existing `websocket-<platform>-<arch>.node` convention
|
||||
// (flat dir, dash-separated triplet) so SnowLuma's existing
|
||||
// per-target packaging step doesn't need a new code path.
|
||||
//
|
||||
// Usage:
|
||||
// node tools/fetch-sqlite-prebuilts.mjs # default version
|
||||
// node tools/fetch-sqlite-prebuilts.mjs 11.10.0 # explicit version
|
||||
//
|
||||
// Re-run when bumping the better-sqlite3 pin in
|
||||
// `packages/sqlite/package.json`. The script is idempotent —
|
||||
// existing binaries with the same SHA256 are left alone.
|
||||
|
||||
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = join(__dirname, '..');
|
||||
const nativeRoot = join(repoRoot, 'packages', 'runtime', 'native');
|
||||
|
||||
// Default NODE_MODULE_VERSIONs to vendor. v127 = Node 22 LTS (matches
|
||||
// the CI matrix + `engines.node: ">=22"`). v137 = Node 24 (covers dev
|
||||
// boxes already on the newer release). Pass extra versions positionally
|
||||
// after the better-sqlite3 version to add more:
|
||||
// node tools/fetch-sqlite-prebuilts.mjs 11.10.0 v127 v137 v115
|
||||
const DEFAULT_NODE_ABIS = ['v127', 'v137'];
|
||||
|
||||
// The targets vendored into the repo. linuxmusl-* variants are
|
||||
// available too (for Alpine-based Docker images) but SnowLuma's
|
||||
// existing native vendoring (websocket / ffmpeg) only ships glibc
|
||||
// Linux, so we follow that lead. Add musl entries here if/when a
|
||||
// downstream Alpine consumer asks.
|
||||
const TARGETS = [
|
||||
{ triplet: 'darwin-arm64', prebuildName: 'darwin-arm64' },
|
||||
{ triplet: 'darwin-x64', prebuildName: 'darwin-x64' },
|
||||
{ triplet: 'linux-arm64', prebuildName: 'linux-arm64' },
|
||||
{ triplet: 'linux-x64', prebuildName: 'linux-x64' },
|
||||
{ triplet: 'win32-x64', prebuildName: 'win32-x64' },
|
||||
];
|
||||
|
||||
async function main() {
|
||||
const version = process.argv[2] ?? readVersionFromPin();
|
||||
const abis = process.argv.slice(3).filter(a => a.startsWith('v'));
|
||||
const targetAbis = abis.length > 0 ? abis : DEFAULT_NODE_ABIS;
|
||||
console.log(`fetching better-sqlite3 v${version} prebuilds (ABIs: ${targetAbis.join(', ')})`);
|
||||
|
||||
mkdirSync(nativeRoot, { recursive: true });
|
||||
for (const abi of targetAbis) {
|
||||
for (const target of TARGETS) {
|
||||
const destBin = join(nativeRoot, `better-sqlite3-${abi}-${target.triplet}.node`);
|
||||
if (existsSync(destBin)) {
|
||||
console.log(` ✓ ${abi} ${target.triplet} (already vendored, skipping)`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const url = `https://github.com/WiseLibs/better-sqlite3/releases/download/v${version}/better-sqlite3-v${version}-node-${abi}-${target.prebuildName}.tar.gz`;
|
||||
console.log(` ↓ ${abi} ${target.triplet}: ${url}`);
|
||||
|
||||
const tarPath = join(tmpdir(), `better-sqlite3-${version}-${abi}-${target.triplet}.tar.gz`);
|
||||
await downloadTo(url, tarPath);
|
||||
extractBinding(tarPath, destBin);
|
||||
console.log(` → ${destBin}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('done.');
|
||||
}
|
||||
|
||||
function readVersionFromPin() {
|
||||
const pkg = JSON.parse(readFileSync(join(repoRoot, 'packages', 'sqlite', 'package.json'), 'utf8'));
|
||||
const raw = pkg.devDependencies?.['better-sqlite3'];
|
||||
if (!raw) {
|
||||
throw new Error('cannot find better-sqlite3 pin in packages/sqlite/package.json');
|
||||
}
|
||||
// strip the `^` / `~` / `>=` etc prefix.
|
||||
return raw.replace(/^[\^~>=<]+/, '');
|
||||
}
|
||||
|
||||
async function downloadTo(url, dest) {
|
||||
// curl is in every CI image SnowLuma cares about (and on every
|
||||
// dev mac/linux), so we just shell out — keeps this script free
|
||||
// of npm dependencies, which matters because pnpm install hasn't
|
||||
// necessarily run yet when someone clones the repo fresh.
|
||||
const result = spawnSync('curl', ['-fsSL', '--retry', '3', '-o', dest, url], { stdio: 'inherit' });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`curl failed for ${url} (exit ${result.status})`);
|
||||
}
|
||||
}
|
||||
|
||||
function extractBinding(tarPath, destBin) {
|
||||
// The prebuild archive is `build/Release/better_sqlite3.node`
|
||||
// wrapped in the standard better-sqlite3 layout. We capture tar's
|
||||
// stdout as a buffer (spawnSync's `stdio: 'pipe'` + `encoding: null`)
|
||||
// and write that buffer to the destination — simpler than wiring
|
||||
// a Node WriteStream which spawnSync's stdio doesn't accept.
|
||||
const result = spawnSync(
|
||||
'tar',
|
||||
['-xzOf', tarPath, '--strip-components=2', 'build/Release/better_sqlite3.node'],
|
||||
{ stdio: ['ignore', 'pipe', 'inherit'], encoding: null, maxBuffer: 64 * 1024 * 1024 },
|
||||
);
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`tar failed for ${tarPath} (exit ${result.status})`);
|
||||
}
|
||||
writeFileSync(destBin, result.stdout);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in New Issue
Block a user