koishi-plugin-newapi-status 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +31 -0
- package/lib/api/index.d.ts +10 -0
- package/lib/api/index.js +26 -0
- package/lib/api/models.d.ts +9 -0
- package/lib/api/models.js +20 -0
- package/lib/api/network.d.ts +20 -0
- package/lib/api/network.js +42 -0
- package/lib/api/notice.d.ts +8 -0
- package/lib/api/notice.js +17 -0
- package/lib/api/perf.d.ts +31 -0
- package/lib/api/perf.js +52 -0
- package/lib/api/pricing.d.ts +9 -0
- package/lib/api/pricing.js +24 -0
- package/lib/api/ratio.d.ts +10 -0
- package/lib/api/ratio.js +29 -0
- package/lib/api/relay.d.ts +43 -0
- package/lib/api/relay.js +178 -0
- package/lib/api/shared.d.ts +60 -0
- package/lib/api/shared.js +123 -0
- package/lib/api/status.d.ts +12 -0
- package/lib/api/status.js +13 -0
- package/lib/api/uptime.d.ts +9 -0
- package/lib/api/uptime.js +18 -0
- package/lib/config.d.ts +59 -0
- package/lib/config.js +112 -0
- package/lib/format.d.ts +76 -0
- package/lib/format.js +242 -0
- package/lib/index.d.ts +11 -0
- package/lib/index.js +567 -0
- package/lib/log.d.ts +39 -0
- package/lib/log.js +39 -0
- package/lib/monitor.d.ts +39 -0
- package/lib/monitor.js +186 -0
- package/lib/render/ChannelCard.d.ts +6 -0
- package/lib/render/ChannelCard.js +12 -0
- package/lib/render/StatusCard.d.ts +6 -0
- package/lib/render/StatusCard.js +18 -0
- package/lib/render/index.d.ts +12 -0
- package/lib/render/index.js +71 -0
- package/lib/render/styles.d.ts +23 -0
- package/lib/render/styles.js +192 -0
- package/lib/text.d.ts +10 -0
- package/lib/text.js +107 -0
- package/lib/types.d.ts +201 -0
- package/lib/types.js +6 -0
- package/lib/view.d.ts +149 -0
- package/lib/view.js +360 -0
- package/package.json +73 -4
- package/readme.md +225 -0
- package/README.md +0 -3
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.NewApiError = void 0;
|
|
4
|
+
exports.resolveBaseUrl = resolveBaseUrl;
|
|
5
|
+
exports.sanitize = sanitize;
|
|
6
|
+
exports.request = request;
|
|
7
|
+
exports.probe = probe;
|
|
8
|
+
/**
|
|
9
|
+
* 站点 URL 归一化:补全协议、去掉尾部斜杠,并剥掉误粘进来的 /v1、/api 后缀。
|
|
10
|
+
* 插件自己会拼 /api/status、/v1/chat/completions,用户多写一段就会变成
|
|
11
|
+
* /v1/v1/chat/completions 这类 404 —— 这是最常见的配置错误,直接在这里吃掉。
|
|
12
|
+
*/
|
|
13
|
+
function resolveBaseUrl(input) {
|
|
14
|
+
let url = (input || '').trim();
|
|
15
|
+
if (!url)
|
|
16
|
+
throw new NewApiError('未配置 baseUrl:请在插件配置里填写 New API 站点地址');
|
|
17
|
+
if (!/^https?:\/\//i.test(url))
|
|
18
|
+
url = 'https://' + url;
|
|
19
|
+
url = url.replace(/\/+$/, '');
|
|
20
|
+
// 只剥末尾那一段,保留 /newapi 这类真实子路径
|
|
21
|
+
for (;;) {
|
|
22
|
+
const matched = url.match(/\/(v1|api)$/i);
|
|
23
|
+
if (!matched)
|
|
24
|
+
break;
|
|
25
|
+
url = url.slice(0, -matched[0].length);
|
|
26
|
+
}
|
|
27
|
+
return url;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* 把令牌从任意文本里抹掉。所有对外报错、日志、卡片都必须先过这一层,
|
|
31
|
+
* 保证 access_token / PAT / sk- 调用令牌不会泄漏。
|
|
32
|
+
*/
|
|
33
|
+
function sanitize(message, ...secrets) {
|
|
34
|
+
let text = message ?? '';
|
|
35
|
+
for (const secret of secrets) {
|
|
36
|
+
if (!secret || secret.length < 4)
|
|
37
|
+
continue;
|
|
38
|
+
text = text.split(secret).join(`${secret.slice(0, 3)}***${secret.slice(-2)}`);
|
|
39
|
+
}
|
|
40
|
+
return text.replace(/Bearer\s+[^\s"',;]+/gi, 'Bearer ***');
|
|
41
|
+
}
|
|
42
|
+
class NewApiError extends Error {
|
|
43
|
+
status;
|
|
44
|
+
code;
|
|
45
|
+
constructor(message, status, code) {
|
|
46
|
+
super(message);
|
|
47
|
+
this.status = status;
|
|
48
|
+
this.code = code;
|
|
49
|
+
this.name = 'NewApiError';
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
exports.NewApiError = NewApiError;
|
|
53
|
+
const STATUS_HINT = {
|
|
54
|
+
401: '鉴权失败:access_token / PAT 无效或已过期',
|
|
55
|
+
403: '权限不足:该接口未对外开放,或令牌缺少对应 scope',
|
|
56
|
+
404: '接口不存在:请确认 baseUrl 指向 New API 站点根路径',
|
|
57
|
+
429: '请求过于频繁:站点限流中',
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* 统一请求入口。所有 New API 面板接口都走这里:
|
|
61
|
+
* 强制 JSON、记录耗时、把 HTTP 状态映射成人能看懂的中文提示,且不泄漏令牌。
|
|
62
|
+
*/
|
|
63
|
+
async function request(ctx, options, path, req = {}) {
|
|
64
|
+
const url = resolveBaseUrl(options.baseUrl) + path;
|
|
65
|
+
const headers = { Accept: 'application/json' };
|
|
66
|
+
const token = req.authorization === null ? undefined : (req.authorization ?? options.token);
|
|
67
|
+
if (token)
|
|
68
|
+
headers.Authorization = `Bearer ${token}`;
|
|
69
|
+
// 老版本 New API 的鉴权中间件会校验这个头,缺失直接 401
|
|
70
|
+
if (options.userId && options.userId > 0)
|
|
71
|
+
headers['New-Api-User'] = String(options.userId);
|
|
72
|
+
const started = Date.now();
|
|
73
|
+
try {
|
|
74
|
+
const response = await ctx.http(url, {
|
|
75
|
+
method: req.method ?? 'GET',
|
|
76
|
+
params: req.query,
|
|
77
|
+
headers,
|
|
78
|
+
data: req.body,
|
|
79
|
+
responseType: req.stream ? 'stream' : undefined,
|
|
80
|
+
timeout: req.timeout ?? options.timeout ?? 10000,
|
|
81
|
+
});
|
|
82
|
+
const latencyMs = Date.now() - started;
|
|
83
|
+
if (req.stream) {
|
|
84
|
+
return { data: response.data, latencyMs, status: response.status };
|
|
85
|
+
}
|
|
86
|
+
const payload = response.data;
|
|
87
|
+
if (payload && typeof payload === 'object' && 'success' in payload && payload.success === false) {
|
|
88
|
+
throw new NewApiError(sanitize(payload.message || '接口返回失败', options.token), response.status);
|
|
89
|
+
}
|
|
90
|
+
if (req.raw)
|
|
91
|
+
return { data: payload, latencyMs, status: response.status };
|
|
92
|
+
const data = payload && typeof payload === 'object' && 'data' in payload ? payload.data : payload;
|
|
93
|
+
return { data, latencyMs, status: response.status };
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
if (error instanceof NewApiError)
|
|
97
|
+
throw error;
|
|
98
|
+
const status = error?.response?.status;
|
|
99
|
+
const body = error?.response?.data;
|
|
100
|
+
const serverMessage = typeof body === 'string'
|
|
101
|
+
? body
|
|
102
|
+
: (body && typeof body === 'object' ? (body.message || body.error?.message) : undefined);
|
|
103
|
+
const hint = status ? STATUS_HINT[status] : undefined;
|
|
104
|
+
const detail = serverMessage ? String(serverMessage) : error?.message;
|
|
105
|
+
const message = [hint, detail].filter(Boolean).join(' | ') || '请求失败';
|
|
106
|
+
throw new NewApiError(sanitize(message, options.token), status);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/** 探测某个接口的可达性与耗时,不抛错(status 指令用) */
|
|
110
|
+
async function probe(ctx, options, path) {
|
|
111
|
+
const started = Date.now();
|
|
112
|
+
try {
|
|
113
|
+
await request(ctx, options, path, { authorization: null });
|
|
114
|
+
return { ok: true, latencyMs: Date.now() - started };
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
return {
|
|
118
|
+
ok: false,
|
|
119
|
+
latencyMs: Date.now() - started,
|
|
120
|
+
error: error instanceof NewApiError ? error.message : sanitize(String(error), options.token),
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
import type { SiteStatus } from '../types';
|
|
3
|
+
import { ApiResponse, ApiClientOptions } from './shared';
|
|
4
|
+
/** GET /api/status —— 无鉴权,站点基础信息与启用的模块开关 */
|
|
5
|
+
export declare function getSiteStatus(ctx: Context, options: ApiClientOptions): Promise<ApiResponse<SiteStatus>>;
|
|
6
|
+
/** 探测站点可达性(不抛错) */
|
|
7
|
+
export declare function probeSite(ctx: Context, options: ApiClientOptions): Promise<{
|
|
8
|
+
ok: boolean;
|
|
9
|
+
latencyMs: number;
|
|
10
|
+
error?: string;
|
|
11
|
+
}>;
|
|
12
|
+
export type SiteStatusResult = ApiResponse<SiteStatus>;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getSiteStatus = getSiteStatus;
|
|
4
|
+
exports.probeSite = probeSite;
|
|
5
|
+
const shared_1 = require("./shared");
|
|
6
|
+
/** GET /api/status —— 无鉴权,站点基础信息与启用的模块开关 */
|
|
7
|
+
function getSiteStatus(ctx, options) {
|
|
8
|
+
return (0, shared_1.request)(ctx, options, '/api/status', { authorization: null });
|
|
9
|
+
}
|
|
10
|
+
/** 探测站点可达性(不抛错) */
|
|
11
|
+
function probeSite(ctx, options) {
|
|
12
|
+
return (0, shared_1.probe)(ctx, options, '/api/status');
|
|
13
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
import type { UptimeGroup } from '../types';
|
|
3
|
+
import { ApiClientOptions } from './shared';
|
|
4
|
+
/**
|
|
5
|
+
* GET /api/uptime/status —— 无鉴权。
|
|
6
|
+
* data 是 [{ categoryName, monitors: [{ name, uptime, status, group? }] }],
|
|
7
|
+
* status: 1 = up,0 = down;uptime 是 24h 可用率百分比。
|
|
8
|
+
*/
|
|
9
|
+
export declare function getUptimeStatus(ctx: Context, options: ApiClientOptions): Promise<UptimeGroup[]>;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getUptimeStatus = getUptimeStatus;
|
|
4
|
+
const shared_1 = require("./shared");
|
|
5
|
+
/**
|
|
6
|
+
* GET /api/uptime/status —— 无鉴权。
|
|
7
|
+
* data 是 [{ categoryName, monitors: [{ name, uptime, status, group? }] }],
|
|
8
|
+
* status: 1 = up,0 = down;uptime 是 24h 可用率百分比。
|
|
9
|
+
*/
|
|
10
|
+
async function getUptimeStatus(ctx, options) {
|
|
11
|
+
const { data } = await (0, shared_1.request)(ctx, options, '/api/uptime/status', { authorization: null });
|
|
12
|
+
if (!Array.isArray(data))
|
|
13
|
+
return [];
|
|
14
|
+
return data.map((group) => ({
|
|
15
|
+
categoryName: group?.categoryName ?? '未分组',
|
|
16
|
+
monitors: Array.isArray(group?.monitors) ? group.monitors : [],
|
|
17
|
+
}));
|
|
18
|
+
}
|
package/lib/config.d.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { Schema } from 'koishi';
|
|
2
|
+
import type { LogLevelName } from './log';
|
|
3
|
+
/** 系统配置里预设的测试凭据 */
|
|
4
|
+
export interface TestPreset {
|
|
5
|
+
/** 展示用的名称,指令里通过 -k/第二个参数引用 */
|
|
6
|
+
keyId: string;
|
|
7
|
+
/** 上游调用令牌,必须是 sk- 开头的 relay key,不能填面板 access_token */
|
|
8
|
+
key: string;
|
|
9
|
+
model: string;
|
|
10
|
+
group?: string;
|
|
11
|
+
}
|
|
12
|
+
export interface MonitorConfig {
|
|
13
|
+
enabled: boolean;
|
|
14
|
+
/** 巡检间隔(秒) */
|
|
15
|
+
interval: number;
|
|
16
|
+
/** 若填写且宿主装有 koishi-plugin-cron,则改用 cron 表达式调度 */
|
|
17
|
+
cron: string;
|
|
18
|
+
/** 接收告警的频道,形如 onebot:123456789 */
|
|
19
|
+
channels: string[];
|
|
20
|
+
/**
|
|
21
|
+
* 盯模型用的 sk- 调用令牌。
|
|
22
|
+
* 面板的 /api/channel 全部要求管理员权限,普通 access_token 拿不到渠道状态;
|
|
23
|
+
* 但 relay 的 GET /v1/models 用 sk- 令牌就能读,渠道被禁用后模型会从清单里消失,
|
|
24
|
+
* 所以「渠道级告警」用这份清单做差集轮询,不需要 AdminAuth。
|
|
25
|
+
* 留空则只巡检站点可用性。
|
|
26
|
+
*/
|
|
27
|
+
apiKey: string;
|
|
28
|
+
/** 需要重点盯的模型名;留空则监控整份 /v1/models 清单的任何变化 */
|
|
29
|
+
models: string[];
|
|
30
|
+
/** 连续失败多少次才告警,避免抖动 */
|
|
31
|
+
threshold: number;
|
|
32
|
+
}
|
|
33
|
+
export interface TestConfig {
|
|
34
|
+
enabled: boolean;
|
|
35
|
+
model: string;
|
|
36
|
+
prompt: string;
|
|
37
|
+
maxTokens: number;
|
|
38
|
+
timeout: number;
|
|
39
|
+
presets: Record<string, Omit<TestPreset, 'keyId'>>;
|
|
40
|
+
}
|
|
41
|
+
export interface Config {
|
|
42
|
+
baseUrl: string;
|
|
43
|
+
accessToken: string;
|
|
44
|
+
userId: number;
|
|
45
|
+
commandPrefix: string;
|
|
46
|
+
timeout: number;
|
|
47
|
+
render: 'auto' | 'image' | 'text';
|
|
48
|
+
noticeLimit: number;
|
|
49
|
+
perfHours: number;
|
|
50
|
+
healthHours: number;
|
|
51
|
+
healthThreshold: number;
|
|
52
|
+
/** 日志过滤档位:silent / error / info / debug(对应 reggol 的 0/1/2/3) */
|
|
53
|
+
logLevel: LogLevelName;
|
|
54
|
+
/** 追加在 /newapi help 底部的自定义文本,留空则不追加 */
|
|
55
|
+
helpText: string;
|
|
56
|
+
monitor: MonitorConfig;
|
|
57
|
+
test: TestConfig;
|
|
58
|
+
}
|
|
59
|
+
export declare const Config: Schema<Config>;
|
package/lib/config.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Config = void 0;
|
|
4
|
+
const koishi_1 = require("koishi");
|
|
5
|
+
exports.Config = koishi_1.Schema.intersect([
|
|
6
|
+
koishi_1.Schema.object({
|
|
7
|
+
baseUrl: koishi_1.Schema.string()
|
|
8
|
+
.description('New API 站点地址,例如 https://api.example.com。只填到站点根即可;末尾误带的 /v1、/api 会被自动剥掉')
|
|
9
|
+
.required(),
|
|
10
|
+
accessToken: koishi_1.Schema.string()
|
|
11
|
+
.role('secret')
|
|
12
|
+
.description('面板 access_token 或 PAT。仅 group ratio、模型列表等需要登录的接口使用;**不要填 sk- 调用令牌**。')
|
|
13
|
+
.default(''),
|
|
14
|
+
userId: koishi_1.Schema.natural()
|
|
15
|
+
.description('面板用户 ID,填了才会带上 New-Api-User 头。老版本 New API(v0.13 及以前)的鉴权接口要求这个头,不填会 401;v1.0 起可留 0。')
|
|
16
|
+
.default(0),
|
|
17
|
+
commandPrefix: koishi_1.Schema.string()
|
|
18
|
+
.description('指令前缀,默认 newapi(即 /newapi status)。改成 api 就是 /api status。')
|
|
19
|
+
.default('newapi'),
|
|
20
|
+
timeout: koishi_1.Schema.natural()
|
|
21
|
+
.description('单次 HTTP 请求超时(毫秒)')
|
|
22
|
+
.default(10000),
|
|
23
|
+
logLevel: koishi_1.Schema.union([
|
|
24
|
+
koishi_1.Schema.const('silent').description('完全不输出'),
|
|
25
|
+
koishi_1.Schema.const('error').description('只输出 success / error'),
|
|
26
|
+
koishi_1.Schema.const('info').description('输出 success / error / info / warn(默认)'),
|
|
27
|
+
koishi_1.Schema.const('debug').description('全部输出,含请求耗时等诊断细节'),
|
|
28
|
+
])
|
|
29
|
+
.description('日志等级过滤。日志命名空间固定为 newapi-status,在 Koishi 控制台「日志」页按此过滤')
|
|
30
|
+
.default('info'),
|
|
31
|
+
}).description('基础设置'),
|
|
32
|
+
koishi_1.Schema.object({
|
|
33
|
+
render: koishi_1.Schema.union([
|
|
34
|
+
koishi_1.Schema.const('auto').description('装有 puppeteer 就出图,否则出文本'),
|
|
35
|
+
koishi_1.Schema.const('image').description('强制出图,缺 puppeteer 时报错'),
|
|
36
|
+
koishi_1.Schema.const('text').description('强制纯文本'),
|
|
37
|
+
])
|
|
38
|
+
.description('卡片渲染方式')
|
|
39
|
+
.default('auto'),
|
|
40
|
+
noticeLimit: koishi_1.Schema.natural()
|
|
41
|
+
.description('公告 / 时间线最多展示条数')
|
|
42
|
+
.default(3),
|
|
43
|
+
perfHours: koishi_1.Schema.natural()
|
|
44
|
+
.description('模型表现默认统计窗口(小时),上限 720')
|
|
45
|
+
.default(24),
|
|
46
|
+
healthHours: koishi_1.Schema.natural()
|
|
47
|
+
.description('model health 使用的统计窗口(小时)。注意:New API 的 perf-metrics 只有小时级桶,拿不到分钟级')
|
|
48
|
+
.default(1),
|
|
49
|
+
healthThreshold: koishi_1.Schema.natural()
|
|
50
|
+
.description('model health 的成功率阈值(0-100)')
|
|
51
|
+
.default(95),
|
|
52
|
+
helpText: koishi_1.Schema.string()
|
|
53
|
+
.role('textarea')
|
|
54
|
+
.description('追加在 /newapi help 输出底部的自定义文本,支持换行。留空则不追加')
|
|
55
|
+
.default(''),
|
|
56
|
+
}).description('展示设置'),
|
|
57
|
+
koishi_1.Schema.object({
|
|
58
|
+
monitor: koishi_1.Schema.object({
|
|
59
|
+
enabled: koishi_1.Schema.boolean()
|
|
60
|
+
.description('开启定时巡检:站点点不通会告警;配了 apiKey 还会对 /v1/models 做差集轮询,模型消失即告警')
|
|
61
|
+
.default(false),
|
|
62
|
+
interval: koishi_1.Schema.natural()
|
|
63
|
+
.description('巡检间隔(秒),最小 30。想验证告警链路可以先改 60')
|
|
64
|
+
.default(300),
|
|
65
|
+
cron: koishi_1.Schema.string()
|
|
66
|
+
.description('改用 cron 表达式调度(需安装 koishi-plugin-cron),留空则用固定间隔')
|
|
67
|
+
.default(''),
|
|
68
|
+
channels: koishi_1.Schema.array(koishi_1.Schema.string())
|
|
69
|
+
.description('接收告警的频道,形如 onebot:123456789(需先在 Koishi 数据库里给频道设置 assignee)')
|
|
70
|
+
.default([]),
|
|
71
|
+
apiKey: koishi_1.Schema.string()
|
|
72
|
+
.role('secret')
|
|
73
|
+
.description('巡检用的 sk- 调用令牌(relay key)。填了才会做模型清单轮询;不能填面板 access_token')
|
|
74
|
+
.default(''),
|
|
75
|
+
models: koishi_1.Schema.array(koishi_1.Schema.string())
|
|
76
|
+
.description('重点盯的模型名;留空则监控整份 /v1/models 清单,任何模型消失都告警')
|
|
77
|
+
.default([]),
|
|
78
|
+
threshold: koishi_1.Schema.natural()
|
|
79
|
+
.description('连续异常多少次才发告警')
|
|
80
|
+
.default(2),
|
|
81
|
+
}).description('定时巡检'),
|
|
82
|
+
}).description('巡检设置'),
|
|
83
|
+
koishi_1.Schema.object({
|
|
84
|
+
test: koishi_1.Schema.object({
|
|
85
|
+
enabled: koishi_1.Schema.boolean()
|
|
86
|
+
.description('开启 /newapi test 连通性测试。默认关闭,避免未配置 key 的站点误触')
|
|
87
|
+
.default(false),
|
|
88
|
+
model: koishi_1.Schema.string()
|
|
89
|
+
.description('未指定模型时使用的默认模型')
|
|
90
|
+
.default('gpt-4o-mini'),
|
|
91
|
+
prompt: koishi_1.Schema.string()
|
|
92
|
+
.description('测试用最短提示词')
|
|
93
|
+
.default('hi'),
|
|
94
|
+
maxTokens: koishi_1.Schema.natural()
|
|
95
|
+
.description('测试请求的 max_tokens')
|
|
96
|
+
.default(16),
|
|
97
|
+
timeout: koishi_1.Schema.natural()
|
|
98
|
+
.description('测试请求超时(毫秒)')
|
|
99
|
+
.default(30000),
|
|
100
|
+
presets: koishi_1.Schema.dict(koishi_1.Schema.object({
|
|
101
|
+
key: koishi_1.Schema.string()
|
|
102
|
+
.role('secret')
|
|
103
|
+
.description('sk- 开头的调用令牌(relay key),不是面板 access_token')
|
|
104
|
+
.required(),
|
|
105
|
+
model: koishi_1.Schema.string().description('该 key 默认使用的模型'),
|
|
106
|
+
group: koishi_1.Schema.string().description('备注用分组名'),
|
|
107
|
+
}))
|
|
108
|
+
.description('预设凭据:keyId → { key, model, group }。指令里用 keyId 引用,避免把 key 打在聊天记录里。')
|
|
109
|
+
.default({}),
|
|
110
|
+
}).description('连通性测试'),
|
|
111
|
+
}).description('测试设置'),
|
|
112
|
+
]);
|
package/lib/format.d.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 纯函数格式化工具。所有函数无副作用,便于 vitest 单测。
|
|
3
|
+
*/
|
|
4
|
+
export type Level = 'ok' | 'warn' | 'fail' | 'unknown';
|
|
5
|
+
/** 延迟分档阈值(毫秒):< 1500 绿,1500 ~ 5000 黄,> 5000 或缺失 红/灰 */
|
|
6
|
+
export declare const LATENCY_FAST = 1500;
|
|
7
|
+
export declare const LATENCY_SLOW = 5000;
|
|
8
|
+
/**
|
|
9
|
+
* 延迟分档。
|
|
10
|
+
* - 非有限数字或 <= 0 → unknown(灰)
|
|
11
|
+
* - < 1500 → ok
|
|
12
|
+
* - <= 5000 → warn
|
|
13
|
+
* - > 5000 → fail
|
|
14
|
+
*/
|
|
15
|
+
export declare function classifyLatency(ms?: number | null): Level;
|
|
16
|
+
/** 延迟文本,形如 `412ms` / `1.42s` / `--` */
|
|
17
|
+
export declare function formatLatency(ms?: number | null): string;
|
|
18
|
+
/**
|
|
19
|
+
* 把秒数格式化成中文时长。
|
|
20
|
+
* @param compact true 时只保留最大的两级单位(卡片用),false 时补零到分钟(文本用)。
|
|
21
|
+
*/
|
|
22
|
+
export declare function formatDuration(seconds?: number | null, compact?: boolean): string;
|
|
23
|
+
/** 把 unix 秒格式化成 `MM-DD HH:mm`(按调用方时区) */
|
|
24
|
+
export declare function formatTimestamp(unixSeconds?: number | null): string;
|
|
25
|
+
/** 把 unix 秒格式化成 `HH:mm`(色块时间轴用) */
|
|
26
|
+
export declare function formatClock(unixSeconds?: number | null): string;
|
|
27
|
+
/**
|
|
28
|
+
* 额度换算。New API 的 quota 字段是整数额度,除以 quota_per_unit 得到「美元」,
|
|
29
|
+
* 再按 usd_exchange_rate × price 换算成展示货币。display_in_currency 为 false 时只显示额度。
|
|
30
|
+
*/
|
|
31
|
+
export declare function formatQuota(quota: number, options?: {
|
|
32
|
+
quota_per_unit?: number;
|
|
33
|
+
display_in_currency?: boolean;
|
|
34
|
+
usd_exchange_rate?: number;
|
|
35
|
+
price?: number;
|
|
36
|
+
symbol?: string;
|
|
37
|
+
}): string;
|
|
38
|
+
/** 千分位数字,保留最多两位小数且去掉多余的 0 */
|
|
39
|
+
export declare function formatNumber(value?: number | null, digits?: number): string;
|
|
40
|
+
/**
|
|
41
|
+
* 倍率展示。New API 中 model_ratio / group_ratio 为倍数:1 → 1.00×。
|
|
42
|
+
* 按次计费(quota_type === 1)时倍率为 0,需要显示为「按次」。
|
|
43
|
+
*/
|
|
44
|
+
export declare function formatRatio(ratio?: number | null, quotaType?: number): string;
|
|
45
|
+
/** 成功率(0–100)分档 */
|
|
46
|
+
export declare function classifySuccessRate(rate?: number | null): Level;
|
|
47
|
+
/** 成功率文本,形如 `99.94%` */
|
|
48
|
+
export declare function formatSuccessRate(rate?: number | null): string;
|
|
49
|
+
/** Uptime Kuma 监控状态:1 = up,0 = down,其余视为未知 */
|
|
50
|
+
export declare function formatMonitorStatus(status?: number | null): {
|
|
51
|
+
level: Level;
|
|
52
|
+
text: string;
|
|
53
|
+
};
|
|
54
|
+
/** 站点可访问性:能拿到 /api/status 即为可访问 */
|
|
55
|
+
export declare function formatSiteAvailability(reachable: boolean): {
|
|
56
|
+
level: Level;
|
|
57
|
+
text: string;
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* 解析 console_setting.Announcements。它是 JSON 数组字符串(不是数组对象),
|
|
61
|
+
* 也可能直接是普通字符串,两种都要能处理。
|
|
62
|
+
*/
|
|
63
|
+
export declare function parseAnnouncements(raw?: unknown, limit?: number): string[];
|
|
64
|
+
/**
|
|
65
|
+
* 公告是 Markdown 裸文本(实测 /api/notice 返回 "# 欢迎来到\n## 公告请看时间线"),
|
|
66
|
+
* 卡片里不渲染 Markdown,所以去掉标题号、加粗、行内代码与链接语法,只留人话。
|
|
67
|
+
*/
|
|
68
|
+
export declare function stripMarkdown(text?: string | null): string;
|
|
69
|
+
/** 状态色块分档:成功率 → 色块等级 */
|
|
70
|
+
export declare function classifySeries(values: Array<{
|
|
71
|
+
success_rate: number;
|
|
72
|
+
}>, threshold?: number): Level[];
|
|
73
|
+
/** 取最近 n 个点的成功率数组,不足时原样返回 */
|
|
74
|
+
export declare function tail<T>(list: T[] | undefined, n: number): T[];
|
|
75
|
+
/** 计算百分比文本,除零返回 -- */
|
|
76
|
+
export declare function formatPercent(value: number, total: number): string;
|
package/lib/format.js
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* 纯函数格式化工具。所有函数无副作用,便于 vitest 单测。
|
|
4
|
+
*/
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.LATENCY_SLOW = exports.LATENCY_FAST = void 0;
|
|
7
|
+
exports.classifyLatency = classifyLatency;
|
|
8
|
+
exports.formatLatency = formatLatency;
|
|
9
|
+
exports.formatDuration = formatDuration;
|
|
10
|
+
exports.formatTimestamp = formatTimestamp;
|
|
11
|
+
exports.formatClock = formatClock;
|
|
12
|
+
exports.formatQuota = formatQuota;
|
|
13
|
+
exports.formatNumber = formatNumber;
|
|
14
|
+
exports.formatRatio = formatRatio;
|
|
15
|
+
exports.classifySuccessRate = classifySuccessRate;
|
|
16
|
+
exports.formatSuccessRate = formatSuccessRate;
|
|
17
|
+
exports.formatMonitorStatus = formatMonitorStatus;
|
|
18
|
+
exports.formatSiteAvailability = formatSiteAvailability;
|
|
19
|
+
exports.parseAnnouncements = parseAnnouncements;
|
|
20
|
+
exports.stripMarkdown = stripMarkdown;
|
|
21
|
+
exports.classifySeries = classifySeries;
|
|
22
|
+
exports.tail = tail;
|
|
23
|
+
exports.formatPercent = formatPercent;
|
|
24
|
+
/** 延迟分档阈值(毫秒):< 1500 绿,1500 ~ 5000 黄,> 5000 或缺失 红/灰 */
|
|
25
|
+
exports.LATENCY_FAST = 1500;
|
|
26
|
+
exports.LATENCY_SLOW = 5000;
|
|
27
|
+
/**
|
|
28
|
+
* 延迟分档。
|
|
29
|
+
* - 非有限数字或 <= 0 → unknown(灰)
|
|
30
|
+
* - < 1500 → ok
|
|
31
|
+
* - <= 5000 → warn
|
|
32
|
+
* - > 5000 → fail
|
|
33
|
+
*/
|
|
34
|
+
function classifyLatency(ms) {
|
|
35
|
+
if (ms == null || !Number.isFinite(ms) || ms <= 0)
|
|
36
|
+
return 'unknown';
|
|
37
|
+
if (ms < exports.LATENCY_FAST)
|
|
38
|
+
return 'ok';
|
|
39
|
+
if (ms <= exports.LATENCY_SLOW)
|
|
40
|
+
return 'warn';
|
|
41
|
+
return 'fail';
|
|
42
|
+
}
|
|
43
|
+
/** 延迟文本,形如 `412ms` / `1.42s` / `--` */
|
|
44
|
+
function formatLatency(ms) {
|
|
45
|
+
if (ms == null || !Number.isFinite(ms) || ms <= 0)
|
|
46
|
+
return '--';
|
|
47
|
+
if (ms < 1000)
|
|
48
|
+
return `${Math.round(ms)}ms`;
|
|
49
|
+
return `${(ms / 1000).toFixed(2)}s`;
|
|
50
|
+
}
|
|
51
|
+
const UNITS = [
|
|
52
|
+
['天', 86400],
|
|
53
|
+
['时', 3600],
|
|
54
|
+
['分', 60],
|
|
55
|
+
['秒', 1],
|
|
56
|
+
];
|
|
57
|
+
/**
|
|
58
|
+
* 把秒数格式化成中文时长。
|
|
59
|
+
* @param compact true 时只保留最大的两级单位(卡片用),false 时补零到分钟(文本用)。
|
|
60
|
+
*/
|
|
61
|
+
function formatDuration(seconds, compact = false) {
|
|
62
|
+
if (seconds == null || !Number.isFinite(seconds) || seconds < 0)
|
|
63
|
+
return '--';
|
|
64
|
+
let rest = Math.floor(seconds);
|
|
65
|
+
const parts = [];
|
|
66
|
+
for (const [unit, size] of UNITS) {
|
|
67
|
+
const value = Math.floor(rest / size);
|
|
68
|
+
rest -= value * size;
|
|
69
|
+
// 非 compact 时补足到分钟,但整点(如正好 1 天)不补 0 分
|
|
70
|
+
const padMinute = unit === '分' && !compact && parts.length > 0 && rest > 0;
|
|
71
|
+
if (value || padMinute)
|
|
72
|
+
parts.push(`${value}${unit}`);
|
|
73
|
+
if (compact && parts.length >= 2)
|
|
74
|
+
break;
|
|
75
|
+
if (compact && !value && !parts.length && size === 1)
|
|
76
|
+
parts.push('0秒');
|
|
77
|
+
}
|
|
78
|
+
if (!parts.length)
|
|
79
|
+
return compact ? '0秒' : '0分';
|
|
80
|
+
return parts.join('');
|
|
81
|
+
}
|
|
82
|
+
/** 把 unix 秒格式化成 `MM-DD HH:mm`(按调用方时区) */
|
|
83
|
+
function formatTimestamp(unixSeconds) {
|
|
84
|
+
if (unixSeconds == null || !Number.isFinite(unixSeconds) || unixSeconds <= 0)
|
|
85
|
+
return '--';
|
|
86
|
+
const date = new Date(unixSeconds * 1000);
|
|
87
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
88
|
+
return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
|
|
89
|
+
}
|
|
90
|
+
/** 把 unix 秒格式化成 `HH:mm`(色块时间轴用) */
|
|
91
|
+
function formatClock(unixSeconds) {
|
|
92
|
+
if (unixSeconds == null || !Number.isFinite(unixSeconds) || unixSeconds <= 0)
|
|
93
|
+
return '--';
|
|
94
|
+
const date = new Date(unixSeconds * 1000);
|
|
95
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
96
|
+
return `${pad(date.getHours())}:${pad(date.getMinutes())}`;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* 额度换算。New API 的 quota 字段是整数额度,除以 quota_per_unit 得到「美元」,
|
|
100
|
+
* 再按 usd_exchange_rate × price 换算成展示货币。display_in_currency 为 false 时只显示额度。
|
|
101
|
+
*/
|
|
102
|
+
function formatQuota(quota, options = {}) {
|
|
103
|
+
if (!Number.isFinite(quota))
|
|
104
|
+
return '--';
|
|
105
|
+
const perUnit = options.quota_per_unit && options.quota_per_unit > 0 ? options.quota_per_unit : 500000;
|
|
106
|
+
const usd = quota / perUnit;
|
|
107
|
+
if (!options.display_in_currency)
|
|
108
|
+
return `${formatNumber(quota)} 额度`;
|
|
109
|
+
const rate = options.usd_exchange_rate && options.usd_exchange_rate > 0 ? options.usd_exchange_rate : 1;
|
|
110
|
+
const price = options.price && options.price > 0 ? options.price : 1;
|
|
111
|
+
const amount = usd * rate * price;
|
|
112
|
+
const symbol = options.symbol ?? '$';
|
|
113
|
+
return `${symbol}${amount.toFixed(2)}`;
|
|
114
|
+
}
|
|
115
|
+
/** 千分位数字,保留最多两位小数且去掉多余的 0 */
|
|
116
|
+
function formatNumber(value, digits = 2) {
|
|
117
|
+
if (value == null || !Number.isFinite(value))
|
|
118
|
+
return '--';
|
|
119
|
+
const fixed = Number(value.toFixed(digits));
|
|
120
|
+
return fixed.toLocaleString('en-US', { maximumFractionDigits: digits });
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* 倍率展示。New API 中 model_ratio / group_ratio 为倍数:1 → 1.00×。
|
|
124
|
+
* 按次计费(quota_type === 1)时倍率为 0,需要显示为「按次」。
|
|
125
|
+
*/
|
|
126
|
+
function formatRatio(ratio, quotaType) {
|
|
127
|
+
if (quotaType === 1)
|
|
128
|
+
return '按次';
|
|
129
|
+
if (ratio == null || !Number.isFinite(ratio))
|
|
130
|
+
return '--';
|
|
131
|
+
if (ratio === 0)
|
|
132
|
+
return '免费';
|
|
133
|
+
return `${ratio.toFixed(2)}×`;
|
|
134
|
+
}
|
|
135
|
+
/** 成功率(0–100)分档 */
|
|
136
|
+
function classifySuccessRate(rate) {
|
|
137
|
+
if (rate == null || !Number.isFinite(rate) || rate < 0)
|
|
138
|
+
return 'unknown';
|
|
139
|
+
if (rate >= 95)
|
|
140
|
+
return 'ok';
|
|
141
|
+
if (rate >= 80)
|
|
142
|
+
return 'warn';
|
|
143
|
+
return 'fail';
|
|
144
|
+
}
|
|
145
|
+
/** 成功率文本,形如 `99.94%` */
|
|
146
|
+
function formatSuccessRate(rate) {
|
|
147
|
+
if (rate == null || !Number.isFinite(rate) || rate < 0)
|
|
148
|
+
return '--';
|
|
149
|
+
return `${rate.toFixed(2)}%`;
|
|
150
|
+
}
|
|
151
|
+
/** Uptime Kuma 监控状态:1 = up,0 = down,其余视为未知 */
|
|
152
|
+
function formatMonitorStatus(status) {
|
|
153
|
+
if (status === 1)
|
|
154
|
+
return { level: 'ok', text: '正常' };
|
|
155
|
+
if (status === 0)
|
|
156
|
+
return { level: 'fail', text: '离线' };
|
|
157
|
+
return { level: 'unknown', text: '未知' };
|
|
158
|
+
}
|
|
159
|
+
/** 站点可访问性:能拿到 /api/status 即为可访问 */
|
|
160
|
+
function formatSiteAvailability(reachable) {
|
|
161
|
+
return reachable ? { level: 'ok', text: '可访问' } : { level: 'fail', text: '不可访问' };
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* 解析 console_setting.Announcements。它是 JSON 数组字符串(不是数组对象),
|
|
165
|
+
* 也可能直接是普通字符串,两种都要能处理。
|
|
166
|
+
*/
|
|
167
|
+
function parseAnnouncements(raw, limit = 0) {
|
|
168
|
+
if (raw === null || raw === undefined)
|
|
169
|
+
return [];
|
|
170
|
+
let list = raw;
|
|
171
|
+
if (typeof raw === 'string') {
|
|
172
|
+
const trimmed = raw.trim();
|
|
173
|
+
if (!trimmed)
|
|
174
|
+
return [];
|
|
175
|
+
// console_setting.Announcements 是 JSON 数组字符串;新版站点则直接返回数组
|
|
176
|
+
if (trimmed.startsWith('[') || trimmed.startsWith('"')) {
|
|
177
|
+
try {
|
|
178
|
+
list = JSON.parse(trimmed);
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
list = trimmed;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
const result = [];
|
|
186
|
+
const push = (value) => {
|
|
187
|
+
// 新版 /api/status 的 announcements 是对象数组:{ content, extra, id, publishDate, type }
|
|
188
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
189
|
+
push(value.content);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (typeof value !== 'string')
|
|
193
|
+
return;
|
|
194
|
+
// 公告正文可能是 Markdown(/api/notice 是裸 Markdown),卡片里不渲染标记
|
|
195
|
+
const text = stripMarkdown(value);
|
|
196
|
+
if (text)
|
|
197
|
+
result.push(text);
|
|
198
|
+
};
|
|
199
|
+
if (Array.isArray(list))
|
|
200
|
+
list.forEach(push);
|
|
201
|
+
else if (typeof list === 'string') {
|
|
202
|
+
// 兼容纯文本公告:按行或按分号切分
|
|
203
|
+
list.split(/\r?\n|;/).forEach(push);
|
|
204
|
+
}
|
|
205
|
+
else if (list && typeof list === 'object') {
|
|
206
|
+
push(list);
|
|
207
|
+
}
|
|
208
|
+
return limit > 0 ? result.slice(0, limit) : result;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* 公告是 Markdown 裸文本(实测 /api/notice 返回 "# 欢迎来到\n## 公告请看时间线"),
|
|
212
|
+
* 卡片里不渲染 Markdown,所以去掉标题号、加粗、行内代码与链接语法,只留人话。
|
|
213
|
+
*/
|
|
214
|
+
function stripMarkdown(text) {
|
|
215
|
+
if (!text)
|
|
216
|
+
return '';
|
|
217
|
+
return String(text)
|
|
218
|
+
.replace(/!?\[([^\]]*)\]\((https?:[^\s)]+)\)/g, '$1 $2')
|
|
219
|
+
.replace(/^\s{0,3}#{1,6}\s*/gm, '')
|
|
220
|
+
.replace(/\*\*([^*]+)\*\*/g, '$1')
|
|
221
|
+
.replace(/(^|\s)[*_]([^\s*_][^*_]*)[*_](?=\s|$)/g, '$1$2')
|
|
222
|
+
.replace(/\u0060([^\u0060]+)\u0060/g, '$1')
|
|
223
|
+
.replace(/^\s{0,3}>\s?/gm, '')
|
|
224
|
+
.replace(/\s+/g, ' ')
|
|
225
|
+
.trim();
|
|
226
|
+
}
|
|
227
|
+
/** 状态色块分档:成功率 → 色块等级 */
|
|
228
|
+
function classifySeries(values, threshold) {
|
|
229
|
+
return values.map((point) => classifySuccessRate(point.success_rate));
|
|
230
|
+
}
|
|
231
|
+
/** 取最近 n 个点的成功率数组,不足时原样返回 */
|
|
232
|
+
function tail(list, n) {
|
|
233
|
+
if (!list?.length)
|
|
234
|
+
return [];
|
|
235
|
+
return n > 0 ? list.slice(-n) : list.slice();
|
|
236
|
+
}
|
|
237
|
+
/** 计算百分比文本,除零返回 -- */
|
|
238
|
+
function formatPercent(value, total) {
|
|
239
|
+
if (!total)
|
|
240
|
+
return '--';
|
|
241
|
+
return `${((value / total) * 100).toFixed(1)}%`;
|
|
242
|
+
}
|