lint
This commit is contained in:
977 files changed
+198426
-158324
No files matched your search
@@ -1,48 +1,52 @@
|
||||
import { assessAccessToken } from '@snowluma/common/access-token';
|
||||
|
||||
export interface AccessTokenFeedback {
|
||||
valid: boolean;
|
||||
tone: 'success' | 'warning' | 'error';
|
||||
message: string;
|
||||
valid: boolean;
|
||||
tone: 'success' | 'warning' | 'error';
|
||||
message: string;
|
||||
}
|
||||
|
||||
export function accessTokenFeedback(
|
||||
token: string,
|
||||
userInputs: readonly (string | number)[],
|
||||
allowEmpty: boolean,
|
||||
token: string,
|
||||
userInputs: readonly (string | number)[],
|
||||
allowEmpty: boolean,
|
||||
): AccessTokenFeedback {
|
||||
if (!token) {
|
||||
return allowEmpty
|
||||
? {
|
||||
valid: true,
|
||||
tone: 'warning',
|
||||
message: '留空将关闭该服务端的鉴权,仅建议在本机使用。',
|
||||
}
|
||||
: {
|
||||
valid: false,
|
||||
tone: 'error',
|
||||
message: '未绑定本机地址时,远程访问必须填写令牌;请生成令牌或将主机改为 127.0.0.1。',
|
||||
};
|
||||
}
|
||||
if (!token) {
|
||||
return allowEmpty
|
||||
? {
|
||||
valid: true,
|
||||
tone: 'warning',
|
||||
message: '留空将关闭该服务端的鉴权,仅建议在本机使用。',
|
||||
}
|
||||
: {
|
||||
valid: false,
|
||||
tone: 'error',
|
||||
message:
|
||||
'未绑定本机地址时,远程访问必须填写令牌;请生成令牌或将主机改为 127.0.0.1。',
|
||||
};
|
||||
}
|
||||
|
||||
const assessment = assessAccessToken(token, userInputs);
|
||||
|
||||
if (assessment.reason === 'too-short') {
|
||||
return {
|
||||
valid: false,
|
||||
tone: 'error',
|
||||
message: '令牌至少需要 16 个字符,请继续补充或重新生成。',
|
||||
};
|
||||
}
|
||||
|
||||
if (!assessment.acceptable) {
|
||||
return {
|
||||
valid: false,
|
||||
tone: 'error',
|
||||
message: '令牌容易被猜中,请使用右侧按钮生成新的随机令牌。',
|
||||
};
|
||||
}
|
||||
|
||||
const assessment = assessAccessToken(token, userInputs);
|
||||
if (assessment.reason === 'too-short') {
|
||||
return {
|
||||
valid: false,
|
||||
tone: 'error',
|
||||
message: '令牌至少需要 16 个字符,请继续补充或重新生成。',
|
||||
valid: true,
|
||||
tone: 'success',
|
||||
message: '令牌强度符合要求。',
|
||||
};
|
||||
}
|
||||
if (!assessment.acceptable) {
|
||||
return {
|
||||
valid: false,
|
||||
tone: 'error',
|
||||
message: '令牌容易被猜中,请使用右侧按钮生成新的随机令牌。',
|
||||
};
|
||||
}
|
||||
return {
|
||||
valid: true,
|
||||
tone: 'success',
|
||||
message: '令牌强度符合要求。',
|
||||
};
|
||||
}
|
||||
+1188
-875
File diff suppressed because it is too large.
Load diff
@@ -4,11 +4,15 @@ import type { ApiClient } from './types';
|
||||
const ApiContext = createContext<ApiClient | null>(null);
|
||||
|
||||
export function ApiProvider({ client, children }: { client: ApiClient; children: ReactNode }) {
|
||||
return <ApiContext.Provider value={client}>{children}</ApiContext.Provider>;
|
||||
return <ApiContext.Provider value={client}>{children}</ApiContext.Provider>;
|
||||
}
|
||||
|
||||
export function useApi(): ApiClient {
|
||||
const client = useContext(ApiContext);
|
||||
if (!client) throw new Error('useApi must be used inside <ApiProvider>');
|
||||
return client;
|
||||
const client = useContext(ApiContext);
|
||||
|
||||
if (!client) {
|
||||
throw new Error('useApi must be used inside <ApiProvider>');
|
||||
}
|
||||
|
||||
return client;
|
||||
}
|
||||
@@ -2,12 +2,12 @@ export { createApiClient } from './client';
|
||||
export { ApiProvider, useApi } from './context';
|
||||
export { ApiError } from './types';
|
||||
export type {
|
||||
ApiClient,
|
||||
ChangePasswordResult,
|
||||
CreateApiClientOptions,
|
||||
LoginResult,
|
||||
LogsStreamOptions,
|
||||
ProcessActionResult,
|
||||
StreamStatus,
|
||||
TokenStore,
|
||||
ApiClient,
|
||||
ChangePasswordResult,
|
||||
CreateApiClientOptions,
|
||||
LoginResult,
|
||||
LogsStreamOptions,
|
||||
ProcessActionResult,
|
||||
StreamStatus,
|
||||
TokenStore,
|
||||
} from './types';
|
||||
@@ -1,19 +1,24 @@
|
||||
import type { TokenStore } from './types';
|
||||
|
||||
export function localStorageTokenStore(key: string): TokenStore {
|
||||
return {
|
||||
load: () => {
|
||||
try {
|
||||
return localStorage.getItem(key);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
save: (token) => {
|
||||
try {
|
||||
if (token == null) localStorage.removeItem(key);
|
||||
else localStorage.setItem(key, token);
|
||||
} catch { /* private mode / storage blocked */ }
|
||||
},
|
||||
};
|
||||
return {
|
||||
load: () => {
|
||||
try {
|
||||
return localStorage.getItem(key);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
save: (token) => {
|
||||
try {
|
||||
if (token == null) {
|
||||
localStorage.removeItem(key);
|
||||
} else {
|
||||
localStorage.setItem(key, token);
|
||||
}
|
||||
} catch {
|
||||
/* private mode / storage blocked */
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
+252
-230
@@ -1,302 +1,324 @@
|
||||
import type {
|
||||
AccountConnections,
|
||||
BackupBundle,
|
||||
BackupImportResult,
|
||||
DebugActionDoc,
|
||||
DebugInvokeResult,
|
||||
DebugStreamFrame,
|
||||
DebugStreamMessage,
|
||||
DebugUploadResult,
|
||||
GlobalSettings,
|
||||
HookProcessInfo,
|
||||
LogEntry,
|
||||
LogLevel,
|
||||
NotificationDeliveryRecord,
|
||||
NotificationsConfig,
|
||||
OneBotConfig,
|
||||
QQInfo,
|
||||
SystemInfo,
|
||||
LogStorageSettingsPatch,
|
||||
StorageCleanupRequest,
|
||||
StorageCleanupResponse,
|
||||
StorageOverviewResponse,
|
||||
StorageSettingsUpdateResponse,
|
||||
SystemSettings,
|
||||
SystemSettingsPatch,
|
||||
SystemSettingsResponse,
|
||||
UiAppearance,
|
||||
UiConfig,
|
||||
UpdateInfo,
|
||||
AccountConnections,
|
||||
BackupBundle,
|
||||
BackupImportResult,
|
||||
DebugActionDoc,
|
||||
DebugInvokeResult,
|
||||
DebugStreamFrame,
|
||||
DebugStreamMessage,
|
||||
DebugUploadResult,
|
||||
GlobalSettings,
|
||||
HookProcessInfo,
|
||||
LogEntry,
|
||||
LogLevel,
|
||||
NotificationDeliveryRecord,
|
||||
NotificationsConfig,
|
||||
OneBotConfig,
|
||||
QQInfo,
|
||||
SystemInfo,
|
||||
LogStorageSettingsPatch,
|
||||
StorageCleanupRequest,
|
||||
StorageCleanupResponse,
|
||||
StorageOverviewResponse,
|
||||
StorageSettingsUpdateResponse,
|
||||
SystemSettings,
|
||||
SystemSettingsPatch,
|
||||
SystemSettingsResponse,
|
||||
UiAppearance,
|
||||
UiConfig,
|
||||
UpdateInfo,
|
||||
} from '@/types';
|
||||
import type { PasswordRule } from '@/components/pages/change-password-form';
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
code: string | undefined;
|
||||
constructor(status: number, message: string, code?: string) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
}
|
||||
status: number;
|
||||
code: string | undefined;
|
||||
constructor(status: number, message: string, code?: string) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
export type LoginResult =
|
||||
| { ok: true; mustChangePassword: boolean }
|
||||
| { ok: false; needsTotp: true }
|
||||
| { ok: false; message: string };
|
||||
| { ok: true; mustChangePassword: boolean }
|
||||
| { ok: false; needsTotp: true }
|
||||
| { ok: false; message: string };
|
||||
|
||||
export type TotpStatus =
|
||||
| { enabled: false }
|
||||
| { enabled: true; remainingRecoveryCodes: number; label: string };
|
||||
{ enabled: false } | { enabled: true; remainingRecoveryCodes: number; label: string };
|
||||
|
||||
export type TotpEnrollment = {
|
||||
secret: string;
|
||||
otpauthUrl: string;
|
||||
issuer: string;
|
||||
accountName: string;
|
||||
secret: string;
|
||||
otpauthUrl: string;
|
||||
issuer: string;
|
||||
accountName: string;
|
||||
};
|
||||
|
||||
export type TotpBeginResult =
|
||||
| { success: true } & TotpEnrollment
|
||||
| { success: false; message: string };
|
||||
({ success: true } & TotpEnrollment) | { success: false; message: string };
|
||||
|
||||
export type TotpConfirmResult =
|
||||
| { success: true; recoveryCodes: string[] }
|
||||
| { success: false; message: string };
|
||||
{ success: true; recoveryCodes: string[] } | { success: false; message: string };
|
||||
|
||||
export type ChangePasswordResult = { success: boolean; message?: string };
|
||||
|
||||
export interface AgreementDoc {
|
||||
id: 'eula' | 'privacy';
|
||||
title: string;
|
||||
declaredVersion: string;
|
||||
effectiveDate: string;
|
||||
text: string;
|
||||
id: 'eula' | 'privacy';
|
||||
title: string;
|
||||
declaredVersion: string;
|
||||
effectiveDate: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface AgreementsPayload {
|
||||
/** Content-hash version of the current agreement set. */
|
||||
version: string;
|
||||
/** Whether the operator must (re-)accept before using the panel. */
|
||||
consentRequired: boolean;
|
||||
documents: AgreementDoc[];
|
||||
/** Content-hash version of the current agreement set. */
|
||||
version: string;
|
||||
/** Whether the operator must (re-)accept before using the panel. */
|
||||
consentRequired: boolean;
|
||||
documents: AgreementDoc[];
|
||||
}
|
||||
|
||||
export type RecordConsentResult = {
|
||||
success: boolean;
|
||||
message?: string;
|
||||
/** On a 409 version-mismatch, the server's current version to re-fetch. */
|
||||
currentVersion?: string;
|
||||
success: boolean;
|
||||
message?: string;
|
||||
/** On a 409 version-mismatch, the server's current version to re-fetch. */
|
||||
currentVersion?: string;
|
||||
};
|
||||
|
||||
export type ProcessActionResult = {
|
||||
process?: HookProcessInfo & { error?: string };
|
||||
process?: HookProcessInfo & { error?: string };
|
||||
};
|
||||
|
||||
export interface ConfigApplyError {
|
||||
name: string;
|
||||
kind?: 'httpServer' | 'httpClient' | 'wsServer' | 'wsClient';
|
||||
phase: string;
|
||||
message: string;
|
||||
at: number;
|
||||
restored?: boolean;
|
||||
name: string;
|
||||
kind?: 'httpServer' | 'httpClient' | 'wsServer' | 'wsClient';
|
||||
phase: string;
|
||||
message: string;
|
||||
at: number;
|
||||
restored?: boolean;
|
||||
}
|
||||
|
||||
export interface ConfigSaveResult {
|
||||
config: OneBotConfig;
|
||||
saved: boolean;
|
||||
applied: boolean;
|
||||
online: boolean;
|
||||
errors: ConfigApplyError[];
|
||||
message: string;
|
||||
config: OneBotConfig;
|
||||
saved: boolean;
|
||||
applied: boolean;
|
||||
online: boolean;
|
||||
errors: ConfigApplyError[];
|
||||
message: string;
|
||||
}
|
||||
|
||||
export type StreamStatus = 'open' | 'reconnecting' | 'closed';
|
||||
|
||||
export interface LogsStreamOptions {
|
||||
onLine: (line: LogEntry) => void;
|
||||
onStatus?: (status: StreamStatus) => void;
|
||||
onLine: (line: LogEntry) => void;
|
||||
onStatus?: (status: StreamStatus) => void;
|
||||
}
|
||||
|
||||
/** A single frame from /api/state/stream — either a control frame or a
|
||||
* fresh snapshot for one of the three live dashboard resources. */
|
||||
export type StateStreamEvent =
|
||||
| { kind: 'ready' }
|
||||
| { kind: 'dropped'; count: number }
|
||||
| { resource: 'processes'; data: HookProcessInfo[] }
|
||||
| { resource: 'qq-list'; data: QQInfo[] }
|
||||
| { resource: 'connections'; data: AccountConnections[] };
|
||||
| { kind: 'ready' }
|
||||
| { kind: 'dropped'; count: number }
|
||||
| { resource: 'processes'; data: HookProcessInfo[] }
|
||||
| { resource: 'qq-list'; data: QQInfo[] }
|
||||
| { resource: 'connections'; data: AccountConnections[] };
|
||||
|
||||
export interface StateStreamOptions {
|
||||
onEvent: (event: StateStreamEvent) => void;
|
||||
onStatus?: (status: StreamStatus) => void;
|
||||
onEvent: (event: StateStreamEvent) => void;
|
||||
onStatus?: (status: StreamStatus) => void;
|
||||
}
|
||||
|
||||
export interface ApiClient {
|
||||
// ---- auth ----
|
||||
login(password: string, secondFactor?: { totp?: string; recoveryCode?: string }): Promise<LoginResult>;
|
||||
logout(): Promise<void>;
|
||||
/** True if the current token is still valid. */
|
||||
status(): Promise<boolean>;
|
||||
/** Whether the current session must rotate its password before doing anything else. */
|
||||
mustChangePassword(): Promise<boolean>;
|
||||
checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }>;
|
||||
changePassword(oldPassword: string, newPassword: string): Promise<ChangePasswordResult>;
|
||||
totp: {
|
||||
status(): Promise<TotpStatus>;
|
||||
begin(options?: { issuer?: string; accountName?: string }): Promise<TotpBeginResult>;
|
||||
confirm(password: string, code: string): Promise<TotpConfirmResult>;
|
||||
disable(password: string, secondFactor: { totp?: string; recoveryCode?: string }): Promise<{ success: boolean; message?: string }>;
|
||||
regenerateRecoveryCodes(password: string, totp: string): Promise<TotpConfirmResult>;
|
||||
};
|
||||
// ---- auth ----
|
||||
login(
|
||||
password: string,
|
||||
secondFactor?: { totp?: string; recoveryCode?: string },
|
||||
): Promise<LoginResult>;
|
||||
logout(): Promise<void>;
|
||||
/** True if the current token is still valid. */
|
||||
status(): Promise<boolean>;
|
||||
/** Whether the current session must rotate its password before doing anything else. */
|
||||
mustChangePassword(): Promise<boolean>;
|
||||
checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }>;
|
||||
changePassword(oldPassword: string, newPassword: string): Promise<ChangePasswordResult>;
|
||||
totp: {
|
||||
status(): Promise<TotpStatus>;
|
||||
begin(options?: { issuer?: string; accountName?: string }): Promise<TotpBeginResult>;
|
||||
confirm(password: string, code: string): Promise<TotpConfirmResult>;
|
||||
disable(
|
||||
password: string,
|
||||
secondFactor: { totp?: string; recoveryCode?: string },
|
||||
): Promise<{ success: boolean; message?: string }>;
|
||||
regenerateRecoveryCodes(password: string, totp: string): Promise<TotpConfirmResult>;
|
||||
};
|
||||
|
||||
// ---- EULA / PRIVACY consent (shown after login, before set-password) ----
|
||||
agreements: {
|
||||
/** Fetch agreement texts + current version + whether consent is required. */
|
||||
get(): Promise<AgreementsPayload>;
|
||||
/** Record acceptance of `version`. success:false (409) carries currentVersion. */
|
||||
recordConsent(version: string): Promise<RecordConsentResult>;
|
||||
};
|
||||
// ---- EULA / PRIVACY consent (shown after login, before set-password) ----
|
||||
agreements: {
|
||||
/** Fetch agreement texts + current version + whether consent is required. */
|
||||
get(): Promise<AgreementsPayload>;
|
||||
/** Record acceptance of `version`. success:false (409) carries currentVersion. */
|
||||
recordConsent(version: string): Promise<RecordConsentResult>;
|
||||
};
|
||||
|
||||
// ---- system ----
|
||||
qqList(): Promise<QQInfo[]>;
|
||||
system(): Promise<SystemInfo>;
|
||||
/** Live OneBot adapter health per account. */
|
||||
connections(): Promise<AccountConnections[]>;
|
||||
// ---- system ----
|
||||
qqList(): Promise<QQInfo[]>;
|
||||
system(): Promise<SystemInfo>;
|
||||
/** Live OneBot adapter health per account. */
|
||||
connections(): Promise<AccountConnections[]>;
|
||||
|
||||
/** Subscribe to the unified SSE feed pushing fresh snapshots whenever
|
||||
* processes / qq-list / connections change. Initial frames on connect
|
||||
* give the current snapshot for all three resources. Returns a disposer.
|
||||
* REST endpoints above remain for the pre-SSE first paint and the slow
|
||||
* reconcile fallback if the SSE drops. */
|
||||
stateStream(options: StateStreamOptions): () => void;
|
||||
/** Subscribe to the unified SSE feed pushing fresh snapshots whenever
|
||||
* processes / qq-list / connections change. Initial frames on connect
|
||||
* give the current snapshot for all three resources. Returns a disposer.
|
||||
* REST endpoints above remain for the pre-SSE first paint and the slow
|
||||
* reconcile fallback if the SSE drops. */
|
||||
stateStream(options: StateStreamOptions): () => void;
|
||||
|
||||
// ---- hook processes ----
|
||||
processes: {
|
||||
list(): Promise<HookProcessInfo[]>;
|
||||
load(pid: number): Promise<ProcessActionResult>;
|
||||
unload(pid: number): Promise<ProcessActionResult>;
|
||||
refresh(pid: number): Promise<ProcessActionResult>;
|
||||
probeLoginInfo(pid: number, signal?: AbortSignal): Promise<unknown>;
|
||||
};
|
||||
// ---- hook processes ----
|
||||
processes: {
|
||||
list(): Promise<HookProcessInfo[]>;
|
||||
load(pid: number): Promise<ProcessActionResult>;
|
||||
unload(pid: number): Promise<ProcessActionResult>;
|
||||
refresh(pid: number): Promise<ProcessActionResult>;
|
||||
probeLoginInfo(pid: number, signal?: AbortSignal): Promise<unknown>;
|
||||
};
|
||||
|
||||
// ---- OneBotInstance per-UIN config ----
|
||||
config: {
|
||||
get(uin: string): Promise<OneBotConfig>;
|
||||
save(uin: string, config: OneBotConfig): Promise<ConfigSaveResult>;
|
||||
};
|
||||
// ---- OneBotInstance per-UIN config ----
|
||||
config: {
|
||||
get(uin: string): Promise<OneBotConfig>;
|
||||
save(uin: string, config: OneBotConfig): Promise<ConfigSaveResult>;
|
||||
};
|
||||
|
||||
// ---- WebUI listener self-config (port / host / TLS / trust-proxy) ----
|
||||
systemSettings: {
|
||||
get(): Promise<SystemSettingsResponse>;
|
||||
save(patch: SystemSettingsPatch): Promise<{ settings: SystemSettings; restartRequiredToApply: boolean }>;
|
||||
/** Validate + write config/cert.pem + key.pem (restart to apply). */
|
||||
uploadCert(cert: string, key: string): Promise<void>;
|
||||
deleteCert(): Promise<void>;
|
||||
/** Download the config backup bundle (credentials gated). */
|
||||
exportBackup(includeCredentials: boolean): Promise<BackupBundle>;
|
||||
/** Validate + restore a bundle as one process-level transaction. */
|
||||
importBackup(backup: BackupBundle, restoreCredentials: boolean): Promise<BackupImportResult>;
|
||||
};
|
||||
// ---- WebUI listener self-config (port / host / TLS / trust-proxy) ----
|
||||
systemSettings: {
|
||||
get(): Promise<SystemSettingsResponse>;
|
||||
save(
|
||||
patch: SystemSettingsPatch,
|
||||
): Promise<{ settings: SystemSettings; restartRequiredToApply: boolean }>;
|
||||
/** Validate + write config/cert.pem + key.pem (restart to apply). */
|
||||
uploadCert(cert: string, key: string): Promise<void>;
|
||||
deleteCert(): Promise<void>;
|
||||
/** Download the config backup bundle (credentials gated). */
|
||||
exportBackup(includeCredentials: boolean): Promise<BackupBundle>;
|
||||
/** Validate + restore a bundle as one process-level transaction. */
|
||||
importBackup(
|
||||
backup: BackupBundle,
|
||||
restoreCredentials: boolean,
|
||||
): Promise<BackupImportResult>;
|
||||
};
|
||||
|
||||
// ---- managed storage (logs / stream temp / per-account databases) ----
|
||||
storage: {
|
||||
get(): Promise<StorageOverviewResponse>;
|
||||
saveSettings(patch: LogStorageSettingsPatch): Promise<StorageSettingsUpdateResponse>;
|
||||
cleanup(request: StorageCleanupRequest): Promise<StorageCleanupResponse>;
|
||||
};
|
||||
// ---- managed storage (logs / stream temp / per-account databases) ----
|
||||
storage: {
|
||||
get(): Promise<StorageOverviewResponse>;
|
||||
saveSettings(patch: LogStorageSettingsPatch): Promise<StorageSettingsUpdateResponse>;
|
||||
cleanup(request: StorageCleanupRequest): Promise<StorageCleanupResponse>;
|
||||
};
|
||||
|
||||
// ---- debug tools (action tester + live event/action stream) ----
|
||||
debug: {
|
||||
actions(): Promise<{ actions: DebugActionDoc[]; categories: { category: string; count: number }[] }>;
|
||||
invoke(uin: string, action: string, params: Record<string, unknown>): Promise<DebugInvokeResult>;
|
||||
/** Invoke a Stream API action (or any action) and receive every frame.
|
||||
* Resolves when the stream ends; pass a signal to cancel. */
|
||||
invokeStream(
|
||||
uin: string,
|
||||
action: string,
|
||||
params: Record<string, unknown>,
|
||||
onFrame: (frame: DebugStreamFrame) => void,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void>;
|
||||
/** Stream a browser file to a temp path on the server; returns the path to
|
||||
* feed a send action. `onProgress` reports 0..1 of bytes uploaded. */
|
||||
upload(
|
||||
file: File,
|
||||
opts?: { filename?: string; onProgress?: (fraction: number) => void; signal?: AbortSignal },
|
||||
): Promise<DebugUploadResult>;
|
||||
/** Live merged SSE; returns an unsubscribe. */
|
||||
stream(onMessage: (m: DebugStreamMessage) => void, onStatus?: (s: StreamStatus) => void): () => void;
|
||||
};
|
||||
// ---- debug tools (action tester + live event/action stream) ----
|
||||
debug: {
|
||||
actions(): Promise<{
|
||||
actions: DebugActionDoc[];
|
||||
categories: { category: string; count: number }[];
|
||||
}>;
|
||||
invoke(
|
||||
uin: string,
|
||||
action: string,
|
||||
params: Record<string, unknown>,
|
||||
): Promise<DebugInvokeResult>;
|
||||
/** Invoke a Stream API action (or any action) and receive every frame.
|
||||
* Resolves when the stream ends; pass a signal to cancel. */
|
||||
invokeStream(
|
||||
uin: string,
|
||||
action: string,
|
||||
params: Record<string, unknown>,
|
||||
onFrame: (frame: DebugStreamFrame) => void,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void>;
|
||||
/** Stream a browser file to a temp path on the server; returns the path to
|
||||
* feed a send action. `onProgress` reports 0..1 of bytes uploaded. */
|
||||
upload(
|
||||
file: File,
|
||||
opts?: {
|
||||
filename?: string;
|
||||
onProgress?: (fraction: number) => void;
|
||||
signal?: AbortSignal;
|
||||
},
|
||||
): Promise<DebugUploadResult>;
|
||||
/** Live merged SSE; returns an unsubscribe. */
|
||||
stream(
|
||||
onMessage: (m: DebugStreamMessage) => void,
|
||||
onStatus?: (s: StreamStatus) => void,
|
||||
): () => void;
|
||||
};
|
||||
|
||||
// ---- notifications (account up/down webhooks) ----
|
||||
notifications: {
|
||||
/** Global channel store (channels + debounce). Bearer-gated. */
|
||||
getConfig(): Promise<NotificationsConfig>;
|
||||
/** Persist the global store (whole-config; server normalizes). */
|
||||
saveConfig(config: Partial<NotificationsConfig>): Promise<NotificationsConfig>;
|
||||
/** Recent in-memory delivery history, most-recent-first (≤100). */
|
||||
recent(limit?: number): Promise<NotificationDeliveryRecord[]>;
|
||||
/** Fire a one-off test to a single channel by id. */
|
||||
test(channelId: string): Promise<{ success: boolean; message?: string; status?: number }>;
|
||||
};
|
||||
// ---- notifications (account up/down webhooks) ----
|
||||
notifications: {
|
||||
/** Global channel store (channels + debounce). Bearer-gated. */
|
||||
getConfig(): Promise<NotificationsConfig>;
|
||||
/** Persist the global store (whole-config; server normalizes). */
|
||||
saveConfig(config: Partial<NotificationsConfig>): Promise<NotificationsConfig>;
|
||||
/** Recent in-memory delivery history, most-recent-first (≤100). */
|
||||
recent(limit?: number): Promise<NotificationDeliveryRecord[]>;
|
||||
/** Fire a one-off test to a single channel by id. */
|
||||
test(channelId: string): Promise<{ success: boolean; message?: string; status?: number }>;
|
||||
};
|
||||
|
||||
// ---- global deployment config (rkey fallback servers + musicSignUrl) ----
|
||||
globalConfig: {
|
||||
/** Fetch the all-accounts global settings (config/snowluma.json). Bearer-gated. */
|
||||
get(): Promise<GlobalSettings>;
|
||||
/** Persist global settings (section-merged + normalized server-side). */
|
||||
save(config: Partial<GlobalSettings>): Promise<GlobalSettings>;
|
||||
};
|
||||
// ---- global deployment config (rkey fallback servers + musicSignUrl) ----
|
||||
globalConfig: {
|
||||
/** Fetch the all-accounts global settings (config/snowluma.json). Bearer-gated. */
|
||||
get(): Promise<GlobalSettings>;
|
||||
/** Persist global settings (section-merged + normalized server-side). */
|
||||
save(config: Partial<GlobalSettings>): Promise<GlobalSettings>;
|
||||
};
|
||||
|
||||
// ---- update check ----
|
||||
update: {
|
||||
/** Advisory check for a newer stable release. Read-only — never downloads. */
|
||||
check(force?: boolean): Promise<UpdateInfo>;
|
||||
};
|
||||
// ---- update check ----
|
||||
update: {
|
||||
/** Advisory check for a newer stable release. Read-only — never downloads. */
|
||||
check(force?: boolean): Promise<UpdateInfo>;
|
||||
};
|
||||
|
||||
// ---- WebUI customization (config/ui.json) ----
|
||||
ui: {
|
||||
/** Full config (appearance + layout). Bearer-gated. */
|
||||
get(): Promise<UiConfig>;
|
||||
/** Persist config. Section-level merge: a payload with only `appearance`
|
||||
* or only `layout` keeps the other section. Returns the normalized view. */
|
||||
save(config: Partial<UiConfig>): Promise<UiConfig>;
|
||||
/** Cosmetic appearance subset, usable pre-auth (login page theming). */
|
||||
getPublic(): Promise<UiAppearance>;
|
||||
/** Upload a background image (PNG/JPEG/WebP, ≤5MB). Returns updated config. */
|
||||
uploadBackground(file: File): Promise<UiConfig>;
|
||||
/** Remove the background image. Returns updated config. */
|
||||
deleteBackground(): Promise<UiConfig>;
|
||||
};
|
||||
// ---- WebUI customization (config/ui.json) ----
|
||||
ui: {
|
||||
/** Full config (appearance + layout). Bearer-gated. */
|
||||
get(): Promise<UiConfig>;
|
||||
/** Persist config. Section-level merge: a payload with only `appearance`
|
||||
* or only `layout` keeps the other section. Returns the normalized view. */
|
||||
save(config: Partial<UiConfig>): Promise<UiConfig>;
|
||||
/** Cosmetic appearance subset, usable pre-auth (login page theming). */
|
||||
getPublic(): Promise<UiAppearance>;
|
||||
/** Upload a background image (PNG/JPEG/WebP, ≤5MB). Returns updated config. */
|
||||
uploadBackground(file: File): Promise<UiConfig>;
|
||||
/** Remove the background image. Returns updated config. */
|
||||
deleteBackground(): Promise<UiConfig>;
|
||||
};
|
||||
|
||||
// ---- logs ----
|
||||
logs: {
|
||||
list(limit?: number): Promise<LogEntry[]>;
|
||||
/** Subscribe to the SSE log stream. Returns a disposer. */
|
||||
stream(options: LogsStreamOptions): () => void;
|
||||
/** Download the complete server-side snapshot of retained normal and TRACE records. */
|
||||
exportTrace(): Promise<{ text: string; filename: string }>;
|
||||
/** Current console / subscriber level. File logging level is set via
|
||||
* SNOWLUMA_LOG_FILE_LEVEL (default: debug), independent of this method. */
|
||||
getLevel(): Promise<{ level: LogLevel; levels: LogLevel[] }>;
|
||||
/** Change the console / subscriber level at runtime. No restart needed. */
|
||||
setLevel(level: LogLevel): Promise<{ level: LogLevel; levels: LogLevel[] }>;
|
||||
};
|
||||
// ---- logs ----
|
||||
logs: {
|
||||
list(limit?: number): Promise<LogEntry[]>;
|
||||
/** Subscribe to the SSE log stream. Returns a disposer. */
|
||||
stream(options: LogsStreamOptions): () => void;
|
||||
/** Download the complete server-side snapshot of retained normal and TRACE records. */
|
||||
exportTrace(): Promise<{ text: string; filename: string }>;
|
||||
/** Current console / subscriber level. File logging level is set via
|
||||
* SNOWLUMA_LOG_FILE_LEVEL (default: debug), independent of this method. */
|
||||
getLevel(): Promise<{ level: LogLevel; levels: LogLevel[] }>;
|
||||
/** Change the console / subscriber level at runtime. No restart needed. */
|
||||
setLevel(level: LogLevel): Promise<{ level: LogLevel; levels: LogLevel[] }>;
|
||||
};
|
||||
|
||||
/** Escape hatch for endpoints not yet wrapped above. */
|
||||
request(url: string, init?: RequestInit): Promise<Response>;
|
||||
/** Escape hatch for endpoints not yet wrapped above. */
|
||||
request(url: string, init?: RequestInit): Promise<Response>;
|
||||
}
|
||||
|
||||
export interface TokenStore {
|
||||
load(): string | null;
|
||||
save(token: string | null): void;
|
||||
load(): string | null;
|
||||
save(token: string | null): void;
|
||||
}
|
||||
|
||||
export interface CreateApiClientOptions {
|
||||
/** Persists the bearer token across reloads. Defaults to localStorage('snowluma_token'). */
|
||||
tokenStore?: TokenStore;
|
||||
/** Fires whenever a request returns 401, after the token has been cleared. */
|
||||
onUnauthorized?: () => void;
|
||||
/** Persists the bearer token across reloads. Defaults to localStorage('snowluma_token'). */
|
||||
tokenStore?: TokenStore;
|
||||
/** Fires whenever a request returns 401, after the token has been cleared. */
|
||||
onUnauthorized?: () => void;
|
||||
}
|
||||
@@ -14,38 +14,70 @@ export const GRID_CELL_HEIGHT = 108;
|
||||
export const GRID_MARGIN = 8;
|
||||
|
||||
export interface GridWidgetSpec {
|
||||
id: string;
|
||||
label: string;
|
||||
/** Minimum width/height in grid units — prevents the content from collapsing. */
|
||||
minW: number;
|
||||
minH: number;
|
||||
/** Default placement when the operator hasn't positioned it yet. */
|
||||
def: { x: number; y: number; w: number; h: number };
|
||||
/** Whether the widget is shown by default. Static widgets (note/link/account)
|
||||
* start hidden — they're opt-in and need configuring first. Defaults true. */
|
||||
defaultVisible?: boolean;
|
||||
id: string;
|
||||
label: string;
|
||||
/** Minimum width/height in grid units — prevents the content from collapsing. */
|
||||
minW: number;
|
||||
minH: number;
|
||||
/** Default placement when the operator hasn't positioned it yet. */
|
||||
def: { x: number; y: number; w: number; h: number };
|
||||
/** Whether the widget is shown by default. Static widgets (note/link/account)
|
||||
* start hidden — they're opt-in and need configuring first. Defaults true. */
|
||||
defaultVisible?: boolean;
|
||||
}
|
||||
|
||||
/** The five top stat tiles, split out of the legacy single `stats` block. */
|
||||
export const STAT_TILE_IDS = [
|
||||
'stat:status', 'stat:accounts', 'stat:processes', 'stat:host', 'stat:uptime',
|
||||
'stat:status',
|
||||
'stat:accounts',
|
||||
'stat:processes',
|
||||
'stat:host',
|
||||
'stat:uptime',
|
||||
] as const;
|
||||
|
||||
export const GRID_WIDGETS: GridWidgetSpec[] = [
|
||||
{ id: 'stat:status', label: '服务状态', minW: 2, minH: 1, def: { x: 0, y: 0, w: 2, h: 1 } },
|
||||
{ id: 'stat:accounts', label: '在线账号', minW: 2, minH: 1, def: { x: 2, y: 0, w: 2, h: 1 } },
|
||||
{ id: 'stat:processes', label: '进程注入', minW: 2, minH: 1, def: { x: 4, y: 0, w: 2, h: 1 } },
|
||||
{ id: 'stat:host', label: '主机名', minW: 2, minH: 1, def: { x: 6, y: 0, w: 2, h: 1 } },
|
||||
{ id: 'stat:uptime', label: '系统运行', minW: 2, minH: 1, def: { x: 8, y: 0, w: 2, h: 1 } },
|
||||
{ id: 'connections', label: 'OneBot 连接', minW: 3, minH: 3, def: { x: 0, y: 1, w: 6, h: 4 } },
|
||||
{ id: 'alerts', label: '最近告警', minW: 3, minH: 3, def: { x: 6, y: 1, w: 6, h: 4 } },
|
||||
{ id: 'host', label: '主机资源', minW: 4, minH: 3, def: { x: 0, y: 5, w: 12, h: 4 } },
|
||||
{ id: 'sessions', label: '在线会话', minW: 3, minH: 3, def: { x: 0, y: 9, w: 12, h: 5 } },
|
||||
// Static, opt-in widgets — content lives in block.config, hidden by default.
|
||||
{ id: 'note', label: '便签', minW: 2, minH: 2, def: { x: 0, y: 14, w: 4, h: 2 }, defaultVisible: false },
|
||||
{ id: 'link', label: '链接卡', minW: 2, minH: 1, def: { x: 4, y: 14, w: 4, h: 1 }, defaultVisible: false },
|
||||
{ id: 'account', label: '账号快捷卡', minW: 2, minH: 1, def: { x: 8, y: 14, w: 4, h: 1 }, defaultVisible: false },
|
||||
{ id: 'deliveries', label: '最近投递', minW: 3, minH: 3, def: { x: 0, y: 16, w: 6, h: 3 }, defaultVisible: false },
|
||||
{ id: 'stat:status', label: '服务状态', minW: 2, minH: 1, def: { x: 0, y: 0, w: 2, h: 1 } },
|
||||
{ id: 'stat:accounts', label: '在线账号', minW: 2, minH: 1, def: { x: 2, y: 0, w: 2, h: 1 } },
|
||||
{ id: 'stat:processes', label: '进程注入', minW: 2, minH: 1, def: { x: 4, y: 0, w: 2, h: 1 } },
|
||||
{ id: 'stat:host', label: '主机名', minW: 2, minH: 1, def: { x: 6, y: 0, w: 2, h: 1 } },
|
||||
{ id: 'stat:uptime', label: '系统运行', minW: 2, minH: 1, def: { x: 8, y: 0, w: 2, h: 1 } },
|
||||
{ id: 'connections', label: 'OneBot 连接', minW: 3, minH: 3, def: { x: 0, y: 1, w: 6, h: 4 } },
|
||||
{ id: 'alerts', label: '最近告警', minW: 3, minH: 3, def: { x: 6, y: 1, w: 6, h: 4 } },
|
||||
{ id: 'host', label: '主机资源', minW: 4, minH: 3, def: { x: 0, y: 5, w: 12, h: 4 } },
|
||||
{ id: 'sessions', label: '在线会话', minW: 3, minH: 3, def: { x: 0, y: 9, w: 12, h: 5 } },
|
||||
// Static, opt-in widgets — content lives in block.config, hidden by default.
|
||||
{
|
||||
id: 'note',
|
||||
label: '便签',
|
||||
minW: 2,
|
||||
minH: 2,
|
||||
def: { x: 0, y: 14, w: 4, h: 2 },
|
||||
defaultVisible: false,
|
||||
},
|
||||
{
|
||||
id: 'link',
|
||||
label: '链接卡',
|
||||
minW: 2,
|
||||
minH: 1,
|
||||
def: { x: 4, y: 14, w: 4, h: 1 },
|
||||
defaultVisible: false,
|
||||
},
|
||||
{
|
||||
id: 'account',
|
||||
label: '账号快捷卡',
|
||||
minW: 2,
|
||||
minH: 1,
|
||||
def: { x: 8, y: 14, w: 4, h: 1 },
|
||||
defaultVisible: false,
|
||||
},
|
||||
{
|
||||
id: 'deliveries',
|
||||
label: '最近投递',
|
||||
minW: 3,
|
||||
minH: 3,
|
||||
def: { x: 0, y: 16, w: 6, h: 3 },
|
||||
defaultVisible: false,
|
||||
},
|
||||
];
|
||||
|
||||
/** Widgets hidden on first sight (opt-in) — derived from the catalogue's
|
||||
@@ -53,28 +85,32 @@ export const GRID_WIDGETS: GridWidgetSpec[] = [
|
||||
* (migrateOverviewBlocks) and mobile (reconcileLayoutItems) from a single
|
||||
* source of truth — no second registration to forget. */
|
||||
export const HIDDEN_BY_DEFAULT_IDS: ReadonlySet<string> = new Set(
|
||||
GRID_WIDGETS.filter((w) => w.defaultVisible === false).map((w) => w.id),
|
||||
GRID_WIDGETS.filter((w) => w.defaultVisible === false).map((w) => w.id),
|
||||
);
|
||||
|
||||
const WIDGET_BY_ID = new Map(GRID_WIDGETS.map((w) => [w.id, w]));
|
||||
|
||||
export function widgetLabel(id: string): string {
|
||||
return WIDGET_BY_ID.get(id)?.label ?? id;
|
||||
return WIDGET_BY_ID.get(id)?.label ?? id;
|
||||
}
|
||||
|
||||
function isObj(v: unknown): v is Record<string, unknown> {
|
||||
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
||||
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
||||
}
|
||||
|
||||
function validCoords(item: UiLayoutItem | undefined): boolean {
|
||||
return !!item
|
||||
&& typeof item.x === 'number' && typeof item.y === 'number'
|
||||
&& typeof item.w === 'number' && typeof item.h === 'number';
|
||||
return (
|
||||
!!item &&
|
||||
typeof item.x === 'number' &&
|
||||
typeof item.y === 'number' &&
|
||||
typeof item.w === 'number' &&
|
||||
typeof item.h === 'number'
|
||||
);
|
||||
}
|
||||
|
||||
/** A fully-positioned overview block (coords always present). */
|
||||
export function defaultOverviewGrid(): UiLayoutItem[] {
|
||||
return GRID_WIDGETS.map((w) => ({ id: w.id, visible: w.defaultVisible !== false, ...w.def }));
|
||||
return GRID_WIDGETS.map((w) => ({ id: w.id, visible: w.defaultVisible !== false, ...w.def }));
|
||||
}
|
||||
|
||||
/** The widget ids in single-column (mobile) default order — same catalogue as
|
||||
@@ -83,7 +119,7 @@ export const MOBILE_WIDGET_IDS: readonly string[] = GRID_WIDGETS.map((w) => w.id
|
||||
|
||||
/** Default single-column mobile overview (id+visible, no coords). */
|
||||
export function defaultOverviewMobile(): UiLayoutItem[] {
|
||||
return GRID_WIDGETS.map((w) => ({ id: w.id, visible: w.defaultVisible !== false }));
|
||||
return GRID_WIDGETS.map((w) => ({ id: w.id, visible: w.defaultVisible !== false }));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -97,135 +133,191 @@ export function defaultOverviewMobile(): UiLayoutItem[] {
|
||||
* Output items always carry x/y/w/h.
|
||||
*/
|
||||
export function migrateOverviewBlocks(stored: UiLayoutItem[] | undefined): UiLayoutItem[] {
|
||||
const byId = new Map<string, UiLayoutItem>();
|
||||
for (const raw of Array.isArray(stored) ? stored : []) {
|
||||
if (isObj(raw) && typeof raw.id === 'string') byId.set(raw.id, raw as UiLayoutItem);
|
||||
}
|
||||
const byId = new Map<string, UiLayoutItem>();
|
||||
|
||||
// Legacy: a single `stats` block → seed the 5 tiles' visibility from it,
|
||||
// but only when the tiles aren't already individually present.
|
||||
const legacyStats = byId.get('stats');
|
||||
for (const raw of Array.isArray(stored) ? stored : []) {
|
||||
if (isObj(raw) && typeof raw.id === 'string') {
|
||||
byId.set(raw.id, raw as UiLayoutItem);
|
||||
}
|
||||
}
|
||||
|
||||
return GRID_WIDGETS.map((spec) => {
|
||||
const item = byId.get(spec.id);
|
||||
const isStatTile = (STAT_TILE_IDS as readonly string[]).includes(spec.id);
|
||||
const visible = item
|
||||
? item.visible !== false
|
||||
: isStatTile && legacyStats
|
||||
? legacyStats.visible !== false
|
||||
: spec.defaultVisible !== false;
|
||||
const coords = validCoords(item)
|
||||
? { x: item!.x!, y: item!.y!, w: item!.w!, h: item!.h! }
|
||||
: { ...spec.def };
|
||||
const config = isObj(item?.config) ? { config: { ...item.config } } : {};
|
||||
return { id: spec.id, visible, ...coords, ...config };
|
||||
});
|
||||
// Legacy: a single `stats` block → seed the 5 tiles' visibility from it,
|
||||
// but only when the tiles aren't already individually present.
|
||||
const legacyStats = byId.get('stats');
|
||||
|
||||
return GRID_WIDGETS.map((spec) => {
|
||||
const item = byId.get(spec.id);
|
||||
const isStatTile = (STAT_TILE_IDS as readonly string[]).includes(spec.id);
|
||||
const visible = item
|
||||
? item.visible !== false
|
||||
: isStatTile && legacyStats
|
||||
? legacyStats.visible !== false
|
||||
: spec.defaultVisible !== false;
|
||||
const coords = validCoords(item)
|
||||
? { x: item!.x!, y: item!.y!, w: item!.w!, h: item!.h! }
|
||||
: { ...spec.def };
|
||||
const config = isObj(item?.config) ? { config: { ...item.config } } : {};
|
||||
return { id: spec.id, visible, ...coords, ...config };
|
||||
});
|
||||
}
|
||||
|
||||
export function minSizeOf(id: string): { minW: number; minH: number } {
|
||||
const spec = WIDGET_BY_ID.get(id);
|
||||
return { minW: spec?.minW ?? 1, minH: spec?.minH ?? 1 };
|
||||
const spec = WIDGET_BY_ID.get(id);
|
||||
return { minW: spec?.minW ?? 1, minH: spec?.minH ?? 1 };
|
||||
}
|
||||
|
||||
/** A widget's natural height (grid rows) for single-column mobile stacking —
|
||||
* the catalogue default, so phones get sensible per-widget heights without
|
||||
* carrying the desktop grid's stored coords. */
|
||||
export function mobileHeightOf(id: string): number {
|
||||
return WIDGET_BY_ID.get(id)?.def.h ?? 1;
|
||||
return WIDGET_BY_ID.get(id)?.def.h ?? 1;
|
||||
}
|
||||
|
||||
// ─── Per-widget config (interpreted client-side from the opaque block.config) ───
|
||||
|
||||
export const ALL_LOG_LEVELS: LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
|
||||
|
||||
export interface AlertsConfig { count: number; levels: LogLevel[] }
|
||||
export interface SessionsConfig { sort: 'recent' | 'uin' | 'nickname'; filter: string }
|
||||
export interface AlertsConfig {
|
||||
count: number;
|
||||
levels: LogLevel[];
|
||||
}
|
||||
export interface SessionsConfig {
|
||||
sort: 'recent' | 'uin' | 'nickname';
|
||||
filter: string;
|
||||
}
|
||||
/** Host widget: which resource sub-panels to show. */
|
||||
export interface HostConfig { cpu: boolean; memory: boolean; runtime: boolean }
|
||||
export interface HostConfig {
|
||||
cpu: boolean;
|
||||
memory: boolean;
|
||||
runtime: boolean;
|
||||
}
|
||||
/** Connections widget: filter + sort + issues-only. */
|
||||
export interface ConnectionsConfig { filter: string; onlyIssues: boolean; sort: 'default' | 'name' | 'status' }
|
||||
export interface ConnectionsConfig {
|
||||
filter: string;
|
||||
onlyIssues: boolean;
|
||||
sort: 'default' | 'name' | 'status';
|
||||
}
|
||||
|
||||
export const DEFAULT_ALERTS_CONFIG: AlertsConfig = { count: 5, levels: ['warn', 'error'] };
|
||||
export const DEFAULT_SESSIONS_CONFIG: SessionsConfig = { sort: 'recent', filter: '' };
|
||||
export const DEFAULT_HOST_CONFIG: HostConfig = { cpu: true, memory: true, runtime: true };
|
||||
export const DEFAULT_CONNECTIONS_CONFIG: ConnectionsConfig = { filter: '', onlyIssues: false, sort: 'default' };
|
||||
export const DEFAULT_CONNECTIONS_CONFIG: ConnectionsConfig = {
|
||||
filter: '',
|
||||
onlyIssues: false,
|
||||
sort: 'default',
|
||||
};
|
||||
|
||||
/** Static-widget content (stored in block.config). */
|
||||
export interface NoteConfig { text: string }
|
||||
export interface LinkConfig { label: string; url: string; icon: string }
|
||||
export interface AccountConfig { uin: string }
|
||||
export interface NoteConfig {
|
||||
text: string;
|
||||
}
|
||||
export interface LinkConfig {
|
||||
label: string;
|
||||
url: string;
|
||||
icon: string;
|
||||
}
|
||||
export interface AccountConfig {
|
||||
uin: string;
|
||||
}
|
||||
|
||||
/** Allowed link-card icon ids (a curated lucide subset). */
|
||||
export const LINK_ICON_IDS = ['link', 'external', 'github', 'book', 'server', 'globe', 'star', 'bell'] as const;
|
||||
export const LINK_ICON_IDS = [
|
||||
'link',
|
||||
'external',
|
||||
'github',
|
||||
'book',
|
||||
'server',
|
||||
'globe',
|
||||
'star',
|
||||
'bell',
|
||||
] as const;
|
||||
/** Max note length — kept under the server's 4096-byte block.config JSON cap. */
|
||||
export const NOTE_MAX = 4000;
|
||||
|
||||
/** Widgets that expose a config form (gear) in the layout editor. */
|
||||
export const CONFIGURABLE_WIDGETS = new Set([
|
||||
'alerts', 'sessions', 'host', 'connections', 'note', 'link', 'account',
|
||||
'alerts',
|
||||
'sessions',
|
||||
'host',
|
||||
'connections',
|
||||
'note',
|
||||
'link',
|
||||
'account',
|
||||
]);
|
||||
|
||||
export function parseNoteConfig(config: Record<string, unknown> | undefined): NoteConfig {
|
||||
const c = config ?? {};
|
||||
return { text: typeof c.text === 'string' ? c.text.slice(0, NOTE_MAX) : '' };
|
||||
const c = config ?? {};
|
||||
return { text: typeof c.text === 'string' ? c.text.slice(0, NOTE_MAX) : '' };
|
||||
}
|
||||
|
||||
// Only http(s) — never javascript:/data: (the url goes into an <a href>).
|
||||
const SAFE_URL_RE = /^https?:\/\//i;
|
||||
|
||||
export function parseLinkConfig(config: Record<string, unknown> | undefined): LinkConfig {
|
||||
const c = config ?? {};
|
||||
const label = typeof c.label === 'string' ? c.label.slice(0, 60) : '';
|
||||
const url = typeof c.url === 'string' && SAFE_URL_RE.test(c.url.trim()) ? c.url.trim().slice(0, 2048) : '';
|
||||
const icon = typeof c.icon === 'string' && (LINK_ICON_IDS as readonly string[]).includes(c.icon) ? c.icon : 'link';
|
||||
return { label, url, icon };
|
||||
const c = config ?? {};
|
||||
const label = typeof c.label === 'string' ? c.label.slice(0, 60) : '';
|
||||
const url =
|
||||
typeof c.url === 'string' && SAFE_URL_RE.test(c.url.trim())
|
||||
? c.url.trim().slice(0, 2048)
|
||||
: '';
|
||||
const icon =
|
||||
typeof c.icon === 'string' && (LINK_ICON_IDS as readonly string[]).includes(c.icon)
|
||||
? c.icon
|
||||
: 'link';
|
||||
return { label, url, icon };
|
||||
}
|
||||
|
||||
export function parseAccountConfig(config: Record<string, unknown> | undefined): AccountConfig {
|
||||
const c = config ?? {};
|
||||
const uin = typeof c.uin === 'string' ? c.uin.replace(/\D/g, '').slice(0, 15) : '';
|
||||
return { uin };
|
||||
const c = config ?? {};
|
||||
const uin = typeof c.uin === 'string' ? c.uin.replace(/\D/g, '').slice(0, 15) : '';
|
||||
return { uin };
|
||||
}
|
||||
|
||||
export function parseAlertsConfig(config: Record<string, unknown> | undefined): AlertsConfig {
|
||||
const c = config ?? {};
|
||||
const count = typeof c.count === 'number' && Number.isFinite(c.count)
|
||||
? Math.min(50, Math.max(1, Math.trunc(c.count)))
|
||||
: DEFAULT_ALERTS_CONFIG.count;
|
||||
const levels = Array.isArray(c.levels)
|
||||
? ALL_LOG_LEVELS.filter((l) => (c.levels as unknown[]).includes(l))
|
||||
: DEFAULT_ALERTS_CONFIG.levels;
|
||||
return { count, levels: levels.length > 0 ? levels : DEFAULT_ALERTS_CONFIG.levels };
|
||||
const c = config ?? {};
|
||||
const count =
|
||||
typeof c.count === 'number' && Number.isFinite(c.count)
|
||||
? Math.min(50, Math.max(1, Math.trunc(c.count)))
|
||||
: DEFAULT_ALERTS_CONFIG.count;
|
||||
const levels = Array.isArray(c.levels)
|
||||
? ALL_LOG_LEVELS.filter((l) => (c.levels as unknown[]).includes(l))
|
||||
: DEFAULT_ALERTS_CONFIG.levels;
|
||||
return { count, levels: levels.length > 0 ? levels : DEFAULT_ALERTS_CONFIG.levels };
|
||||
}
|
||||
|
||||
export function parseSessionsConfig(config: Record<string, unknown> | undefined): SessionsConfig {
|
||||
const c = config ?? {};
|
||||
const sort = c.sort === 'uin' || c.sort === 'nickname' || c.sort === 'recent'
|
||||
? c.sort
|
||||
: DEFAULT_SESSIONS_CONFIG.sort;
|
||||
const filter = typeof c.filter === 'string' ? c.filter.slice(0, 100) : '';
|
||||
return { sort, filter };
|
||||
const c = config ?? {};
|
||||
const sort =
|
||||
c.sort === 'uin' || c.sort === 'nickname' || c.sort === 'recent'
|
||||
? c.sort
|
||||
: DEFAULT_SESSIONS_CONFIG.sort;
|
||||
const filter = typeof c.filter === 'string' ? c.filter.slice(0, 100) : '';
|
||||
return { sort, filter };
|
||||
}
|
||||
|
||||
export function parseHostConfig(config: Record<string, unknown> | undefined): HostConfig {
|
||||
const c = config ?? {};
|
||||
const bool = (v: unknown, d: boolean) => (typeof v === 'boolean' ? v : d);
|
||||
const cfg = {
|
||||
cpu: bool(c.cpu, true),
|
||||
memory: bool(c.memory, true),
|
||||
runtime: bool(c.runtime, true),
|
||||
};
|
||||
// Never let every panel be hidden — that leaves an empty card; fall back to all.
|
||||
return cfg.cpu || cfg.memory || cfg.runtime ? cfg : { ...DEFAULT_HOST_CONFIG };
|
||||
const c = config ?? {};
|
||||
const bool = (v: unknown, d: boolean) => (typeof v === 'boolean' ? v : d);
|
||||
const cfg = {
|
||||
cpu: bool(c.cpu, true),
|
||||
memory: bool(c.memory, true),
|
||||
runtime: bool(c.runtime, true),
|
||||
};
|
||||
// Never let every panel be hidden — that leaves an empty card; fall back to all.
|
||||
return cfg.cpu || cfg.memory || cfg.runtime ? cfg : { ...DEFAULT_HOST_CONFIG };
|
||||
}
|
||||
|
||||
export function parseConnectionsConfig(config: Record<string, unknown> | undefined): ConnectionsConfig {
|
||||
const c = config ?? {};
|
||||
const sort = c.sort === 'name' || c.sort === 'status' || c.sort === 'default'
|
||||
? c.sort
|
||||
: DEFAULT_CONNECTIONS_CONFIG.sort;
|
||||
return {
|
||||
filter: typeof c.filter === 'string' ? c.filter.slice(0, 100) : '',
|
||||
onlyIssues: typeof c.onlyIssues === 'boolean' ? c.onlyIssues : false,
|
||||
sort,
|
||||
};
|
||||
export function parseConnectionsConfig(
|
||||
config: Record<string, unknown> | undefined,
|
||||
): ConnectionsConfig {
|
||||
const c = config ?? {};
|
||||
const sort =
|
||||
c.sort === 'name' || c.sort === 'status' || c.sort === 'default'
|
||||
? c.sort
|
||||
: DEFAULT_CONNECTIONS_CONFIG.sort;
|
||||
return {
|
||||
filter: typeof c.filter === 'string' ? c.filter.slice(0, 100) : '',
|
||||
onlyIssues: typeof c.onlyIssues === 'boolean' ? c.onlyIssues : false,
|
||||
sort,
|
||||
};
|
||||
}
|
||||
@@ -3,16 +3,16 @@
|
||||
// design: it's a debugging convenience, not a persisted record, so there is no
|
||||
// backend store. Newest first.
|
||||
export interface InvokeRecord {
|
||||
id: string;
|
||||
at: number;
|
||||
uin: string;
|
||||
action: string;
|
||||
params: Record<string, unknown>;
|
||||
ok: boolean;
|
||||
/** wall-clock ms, when known. */
|
||||
ms?: number;
|
||||
/** true if invoked via the streaming transport. */
|
||||
stream?: boolean;
|
||||
id: string;
|
||||
at: number;
|
||||
uin: string;
|
||||
action: string;
|
||||
params: Record<string, unknown>;
|
||||
ok: boolean;
|
||||
/** wall-clock ms, when known. */
|
||||
ms?: number;
|
||||
/** true if invoked via the streaming transport. */
|
||||
stream?: boolean;
|
||||
}
|
||||
|
||||
const LS_KEY = 'snowluma.debug.history.v1';
|
||||
@@ -21,21 +21,37 @@ const CAP = 200;
|
||||
let seq = 0;
|
||||
|
||||
export function loadHistory(): InvokeRecord[] {
|
||||
try {
|
||||
const raw = localStorage.getItem(LS_KEY);
|
||||
if (!raw) return [];
|
||||
const arr = JSON.parse(raw) as InvokeRecord[];
|
||||
return Array.isArray(arr) ? arr : [];
|
||||
} catch { return []; }
|
||||
try {
|
||||
const raw = localStorage.getItem(LS_KEY);
|
||||
|
||||
if (!raw) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const arr = JSON.parse(raw) as InvokeRecord[];
|
||||
return Array.isArray(arr) ? arr : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function pushHistory(rec: Omit<InvokeRecord, 'id'>): InvokeRecord[] {
|
||||
const full: InvokeRecord = { ...rec, id: `h-${rec.at.toString(36)}-${(seq++).toString(36)}` };
|
||||
const next = [full, ...loadHistory()].slice(0, CAP);
|
||||
try { localStorage.setItem(LS_KEY, JSON.stringify(next)); } catch { /* quota — drop silently */ }
|
||||
return next;
|
||||
const full: InvokeRecord = { ...rec, id: `h-${rec.at.toString(36)}-${(seq++).toString(36)}` };
|
||||
const next = [full, ...loadHistory()].slice(0, CAP);
|
||||
|
||||
try {
|
||||
localStorage.setItem(LS_KEY, JSON.stringify(next));
|
||||
} catch {
|
||||
/* quota — drop silently */
|
||||
}
|
||||
|
||||
return next;
|
||||
}
|
||||
|
||||
export function clearHistory(): void {
|
||||
try { localStorage.removeItem(LS_KEY); } catch { /* ignore */ }
|
||||
try {
|
||||
localStorage.removeItem(LS_KEY);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
+233
-194
@@ -12,185 +12,198 @@ import { Fragment, type ReactNode } from 'react';
|
||||
* http/https/mailto; anything else renders as plain text.
|
||||
*/
|
||||
export function Markdown({ content }: { content: string }): ReactNode {
|
||||
const blocks = parseBlocks(content.replace(/\r\n?/g, '\n'));
|
||||
return (
|
||||
<div className="sl-md space-y-3 text-sm leading-relaxed">
|
||||
{blocks.map((block, i) => (
|
||||
<Fragment key={i}>{renderBlock(block)}</Fragment>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
const blocks = parseBlocks(content.replace(/\r\n?/g, '\n'));
|
||||
return (
|
||||
<div className="sl-md space-y-3 text-sm leading-relaxed">
|
||||
{blocks.map((block, i) => (
|
||||
<Fragment key={i}>{renderBlock(block)}</Fragment>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type Block =
|
||||
| { type: 'heading'; level: number; text: string }
|
||||
| { type: 'hr' }
|
||||
| { type: 'quote'; lines: string[] }
|
||||
| { type: 'ul'; items: string[] }
|
||||
| { type: 'ol'; items: string[] }
|
||||
| { type: 'code'; text: string }
|
||||
| { type: 'p'; text: string };
|
||||
| { type: 'heading'; level: number; text: string }
|
||||
| { type: 'hr' }
|
||||
| { type: 'quote'; lines: string[] }
|
||||
| { type: 'ul'; items: string[] }
|
||||
| { type: 'ol'; items: string[] }
|
||||
| { type: 'code'; text: string }
|
||||
| { type: 'p'; text: string };
|
||||
|
||||
function parseBlocks(src: string): Block[] {
|
||||
const lines = src.split('\n');
|
||||
const blocks: Block[] = [];
|
||||
let i = 0;
|
||||
const lines = src.split('\n');
|
||||
const blocks: Block[] = [];
|
||||
let i = 0;
|
||||
|
||||
while (i < lines.length) {
|
||||
const line = lines[i];
|
||||
while (i < lines.length) {
|
||||
const line = lines[i];
|
||||
|
||||
// blank line — skip
|
||||
if (line.trim() === '') {
|
||||
i++;
|
||||
continue;
|
||||
// blank line — skip
|
||||
if (line.trim() === '') {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// fenced code block ``` ... ```
|
||||
if (/^\s*```/.test(line)) {
|
||||
const body: string[] = [];
|
||||
i++;
|
||||
|
||||
while (i < lines.length && !/^\s*```/.test(lines[i])) {
|
||||
body.push(lines[i]);
|
||||
i++;
|
||||
}
|
||||
|
||||
i++; // consume closing fence (or EOF)
|
||||
blocks.push({ type: 'code', text: body.join('\n') });
|
||||
continue;
|
||||
}
|
||||
|
||||
// horizontal rule
|
||||
if (/^\s*([-*_])\s*(\1\s*){2,}$/.test(line)) {
|
||||
blocks.push({ type: 'hr' });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// heading
|
||||
const heading = line.match(/^(#{1,6})\s+(.*)$/);
|
||||
|
||||
if (heading) {
|
||||
blocks.push({ type: 'heading', level: heading[1].length, text: heading[2].trim() });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// blockquote (consecutive `>` lines)
|
||||
if (/^\s*>/.test(line)) {
|
||||
const quote: string[] = [];
|
||||
|
||||
while (i < lines.length && /^\s*>/.test(lines[i])) {
|
||||
quote.push(lines[i].replace(/^\s*>\s?/, ''));
|
||||
i++;
|
||||
}
|
||||
|
||||
blocks.push({ type: 'quote', lines: quote });
|
||||
continue;
|
||||
}
|
||||
|
||||
// unordered list
|
||||
if (/^\s*[-*+]\s+/.test(line)) {
|
||||
const items: string[] = [];
|
||||
|
||||
while (i < lines.length && /^\s*[-*+]\s+/.test(lines[i])) {
|
||||
items.push(lines[i].replace(/^\s*[-*+]\s+/, ''));
|
||||
i++;
|
||||
}
|
||||
|
||||
blocks.push({ type: 'ul', items });
|
||||
continue;
|
||||
}
|
||||
|
||||
// ordered list
|
||||
if (/^\s*\d+[.)]\s+/.test(line)) {
|
||||
const items: string[] = [];
|
||||
|
||||
while (i < lines.length && /^\s*\d+[.)]\s+/.test(lines[i])) {
|
||||
items.push(lines[i].replace(/^\s*\d+[.)]\s+/, ''));
|
||||
i++;
|
||||
}
|
||||
|
||||
blocks.push({ type: 'ol', items });
|
||||
continue;
|
||||
}
|
||||
|
||||
// paragraph — gather until a blank line or a line that starts a new block
|
||||
const para: string[] = [];
|
||||
|
||||
while (i < lines.length && lines[i].trim() !== '' && !startsNewBlock(lines[i])) {
|
||||
para.push(lines[i].trim());
|
||||
i++;
|
||||
}
|
||||
|
||||
blocks.push({ type: 'p', text: para.join(' ') });
|
||||
}
|
||||
|
||||
// fenced code block ``` ... ```
|
||||
if (/^\s*```/.test(line)) {
|
||||
const body: string[] = [];
|
||||
i++;
|
||||
while (i < lines.length && !/^\s*```/.test(lines[i])) {
|
||||
body.push(lines[i]);
|
||||
i++;
|
||||
}
|
||||
i++; // consume closing fence (or EOF)
|
||||
blocks.push({ type: 'code', text: body.join('\n') });
|
||||
continue;
|
||||
}
|
||||
|
||||
// horizontal rule
|
||||
if (/^\s*([-*_])\s*(\1\s*){2,}$/.test(line)) {
|
||||
blocks.push({ type: 'hr' });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// heading
|
||||
const heading = line.match(/^(#{1,6})\s+(.*)$/);
|
||||
if (heading) {
|
||||
blocks.push({ type: 'heading', level: heading[1].length, text: heading[2].trim() });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// blockquote (consecutive `>` lines)
|
||||
if (/^\s*>/.test(line)) {
|
||||
const quote: string[] = [];
|
||||
while (i < lines.length && /^\s*>/.test(lines[i])) {
|
||||
quote.push(lines[i].replace(/^\s*>\s?/, ''));
|
||||
i++;
|
||||
}
|
||||
blocks.push({ type: 'quote', lines: quote });
|
||||
continue;
|
||||
}
|
||||
|
||||
// unordered list
|
||||
if (/^\s*[-*+]\s+/.test(line)) {
|
||||
const items: string[] = [];
|
||||
while (i < lines.length && /^\s*[-*+]\s+/.test(lines[i])) {
|
||||
items.push(lines[i].replace(/^\s*[-*+]\s+/, ''));
|
||||
i++;
|
||||
}
|
||||
blocks.push({ type: 'ul', items });
|
||||
continue;
|
||||
}
|
||||
|
||||
// ordered list
|
||||
if (/^\s*\d+[.)]\s+/.test(line)) {
|
||||
const items: string[] = [];
|
||||
while (i < lines.length && /^\s*\d+[.)]\s+/.test(lines[i])) {
|
||||
items.push(lines[i].replace(/^\s*\d+[.)]\s+/, ''));
|
||||
i++;
|
||||
}
|
||||
blocks.push({ type: 'ol', items });
|
||||
continue;
|
||||
}
|
||||
|
||||
// paragraph — gather until a blank line or a line that starts a new block
|
||||
const para: string[] = [];
|
||||
while (i < lines.length && lines[i].trim() !== '' && !startsNewBlock(lines[i])) {
|
||||
para.push(lines[i].trim());
|
||||
i++;
|
||||
}
|
||||
blocks.push({ type: 'p', text: para.join(' ') });
|
||||
}
|
||||
|
||||
return blocks;
|
||||
return blocks;
|
||||
}
|
||||
|
||||
function startsNewBlock(line: string): boolean {
|
||||
return (
|
||||
/^\s*```/.test(line) ||
|
||||
/^(#{1,6})\s+/.test(line) ||
|
||||
/^\s*>/.test(line) ||
|
||||
/^\s*[-*+]\s+/.test(line) ||
|
||||
/^\s*\d+[.)]\s+/.test(line) ||
|
||||
/^\s*([-*_])\s*(\1\s*){2,}$/.test(line)
|
||||
);
|
||||
return (
|
||||
/^\s*```/.test(line) ||
|
||||
/^(#{1,6})\s+/.test(line) ||
|
||||
/^\s*>/.test(line) ||
|
||||
/^\s*[-*+]\s+/.test(line) ||
|
||||
/^\s*\d+[.)]\s+/.test(line) ||
|
||||
/^\s*([-*_])\s*(\1\s*){2,}$/.test(line)
|
||||
);
|
||||
}
|
||||
|
||||
function renderBlock(block: Block): ReactNode {
|
||||
switch (block.type) {
|
||||
case 'heading': {
|
||||
const cls = [
|
||||
'text-xl font-semibold tracking-tight',
|
||||
'text-lg font-semibold tracking-tight',
|
||||
'text-base font-semibold',
|
||||
'text-sm font-semibold',
|
||||
'text-sm font-semibold text-muted-foreground',
|
||||
'text-xs font-semibold text-muted-foreground',
|
||||
][block.level - 1];
|
||||
const inner = renderInline(block.text);
|
||||
switch (block.level) {
|
||||
case 1:
|
||||
return <h1 className={cls}>{inner}</h1>;
|
||||
case 2:
|
||||
return <h2 className={cls}>{inner}</h2>;
|
||||
case 3:
|
||||
return <h3 className={cls}>{inner}</h3>;
|
||||
case 4:
|
||||
return <h4 className={cls}>{inner}</h4>;
|
||||
case 5:
|
||||
return <h5 className={cls}>{inner}</h5>;
|
||||
default:
|
||||
return <h6 className={cls}>{inner}</h6>;
|
||||
}
|
||||
switch (block.type) {
|
||||
case 'heading': {
|
||||
const cls = [
|
||||
'text-xl font-semibold tracking-tight',
|
||||
'text-lg font-semibold tracking-tight',
|
||||
'text-base font-semibold',
|
||||
'text-sm font-semibold',
|
||||
'text-sm font-semibold text-muted-foreground',
|
||||
'text-xs font-semibold text-muted-foreground',
|
||||
][block.level - 1];
|
||||
const inner = renderInline(block.text);
|
||||
|
||||
switch (block.level) {
|
||||
case 1:
|
||||
return <h1 className={cls}>{inner}</h1>;
|
||||
case 2:
|
||||
return <h2 className={cls}>{inner}</h2>;
|
||||
case 3:
|
||||
return <h3 className={cls}>{inner}</h3>;
|
||||
case 4:
|
||||
return <h4 className={cls}>{inner}</h4>;
|
||||
case 5:
|
||||
return <h5 className={cls}>{inner}</h5>;
|
||||
default:
|
||||
return <h6 className={cls}>{inner}</h6>;
|
||||
}
|
||||
}
|
||||
|
||||
case 'hr':
|
||||
return <hr className="border-border" />;
|
||||
case 'quote':
|
||||
return (
|
||||
<blockquote className="border-l-2 border-primary/40 pl-3 text-muted-foreground">
|
||||
{block.lines.map((l, i) => (
|
||||
<p key={i}>{renderInline(l)}</p>
|
||||
))}
|
||||
</blockquote>
|
||||
);
|
||||
case 'ul':
|
||||
return (
|
||||
<ul className="list-disc space-y-1 pl-5">
|
||||
{block.items.map((it, i) => (
|
||||
<li key={i}>{renderInline(it)}</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
case 'ol':
|
||||
return (
|
||||
<ol className="list-decimal space-y-1 pl-5">
|
||||
{block.items.map((it, i) => (
|
||||
<li key={i}>{renderInline(it)}</li>
|
||||
))}
|
||||
</ol>
|
||||
);
|
||||
case 'code':
|
||||
return (
|
||||
<pre className="overflow-x-auto rounded-md bg-muted p-3 text-xs">
|
||||
<code>{block.text}</code>
|
||||
</pre>
|
||||
);
|
||||
case 'p':
|
||||
return <p>{renderInline(block.text)}</p>;
|
||||
}
|
||||
case 'hr':
|
||||
return <hr className="border-border" />;
|
||||
case 'quote':
|
||||
return (
|
||||
<blockquote className="border-l-2 border-primary/40 pl-3 text-muted-foreground">
|
||||
{block.lines.map((l, i) => (
|
||||
<p key={i}>{renderInline(l)}</p>
|
||||
))}
|
||||
</blockquote>
|
||||
);
|
||||
case 'ul':
|
||||
return (
|
||||
<ul className="list-disc space-y-1 pl-5">
|
||||
{block.items.map((it, i) => (
|
||||
<li key={i}>{renderInline(it)}</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
case 'ol':
|
||||
return (
|
||||
<ol className="list-decimal space-y-1 pl-5">
|
||||
{block.items.map((it, i) => (
|
||||
<li key={i}>{renderInline(it)}</li>
|
||||
))}
|
||||
</ol>
|
||||
);
|
||||
case 'code':
|
||||
return (
|
||||
<pre className="overflow-x-auto rounded-md bg-muted p-3 text-xs">
|
||||
<code>{block.text}</code>
|
||||
</pre>
|
||||
);
|
||||
case 'p':
|
||||
return <p>{renderInline(block.text)}</p>;
|
||||
}
|
||||
}
|
||||
|
||||
// Inline spans: `code`, **bold**, *italic* / _italic_, [text](url).
|
||||
@@ -202,43 +215,69 @@ function renderBlock(block: Block): ReactNode {
|
||||
// doc. The caps are far larger than any real inline span; anything longer
|
||||
// renders literally rather than risking a hang.
|
||||
const INLINE_RE =
|
||||
/`[^`\n]{1,2048}`|\*\*[^*\n]{1,2048}\*\*|\*[^*\n]{1,2048}\*|_[^_\n]{1,2048}_|\[[^\]\n]{1,512}\]\([^)\s]{1,2048}\)/g;
|
||||
/`[^`\n]{1,2048}`|\*\*[^*\n]{1,2048}\*\*|\*[^*\n]{1,2048}\*|_[^_\n]{1,2048}_|\[[^\]\n]{1,512}\]\([^)\s]{1,2048}\)/g;
|
||||
|
||||
function renderInline(text: string): ReactNode[] {
|
||||
const out: ReactNode[] = [];
|
||||
const re = new RegExp(INLINE_RE.source, 'g'); // fresh instance: own lastIndex
|
||||
let last = 0;
|
||||
let key = 0;
|
||||
let m: RegExpExecArray | null;
|
||||
const out: ReactNode[] = [];
|
||||
const re = new RegExp(INLINE_RE.source, 'g'); // fresh instance: own lastIndex
|
||||
let last = 0;
|
||||
let key = 0;
|
||||
let m: RegExpExecArray | null;
|
||||
|
||||
while ((m = re.exec(text)) !== null) {
|
||||
if (m.index > last) out.push(text.slice(last, m.index));
|
||||
const tok = m[0];
|
||||
if (tok.startsWith('`')) {
|
||||
out.push(<code key={key++} className="rounded bg-muted px-1 py-0.5 text-xs">{tok.slice(1, -1)}</code>);
|
||||
} else if (tok.startsWith('**')) {
|
||||
out.push(<strong key={key++}>{renderInline(tok.slice(2, -2))}</strong>);
|
||||
} else if (tok.startsWith('*') || tok.startsWith('_')) {
|
||||
out.push(<em key={key++}>{renderInline(tok.slice(1, -1))}</em>);
|
||||
} else {
|
||||
// [label](href) — tok already matched the bounded link shape.
|
||||
const link = tok.match(/^\[([^\]]*)\]\(([^)\s]+)\)$/);
|
||||
if (link) out.push(safeLink(link[2], link[1], key++));
|
||||
else out.push(tok);
|
||||
while ((m = re.exec(text)) !== null) {
|
||||
if (m.index > last) {
|
||||
out.push(text.slice(last, m.index));
|
||||
}
|
||||
|
||||
const tok = m[0];
|
||||
|
||||
if (tok.startsWith('`')) {
|
||||
out.push(
|
||||
<code key={key++} className="rounded bg-muted px-1 py-0.5 text-xs">
|
||||
{tok.slice(1, -1)}
|
||||
</code>,
|
||||
);
|
||||
} else if (tok.startsWith('**')) {
|
||||
out.push(<strong key={key++}>{renderInline(tok.slice(2, -2))}</strong>);
|
||||
} else if (tok.startsWith('*') || tok.startsWith('_')) {
|
||||
out.push(<em key={key++}>{renderInline(tok.slice(1, -1))}</em>);
|
||||
} else {
|
||||
// [label](href) — tok already matched the bounded link shape.
|
||||
const link = tok.match(/^\[([^\]]*)\]\(([^)\s]+)\)$/);
|
||||
|
||||
if (link) {
|
||||
out.push(safeLink(link[2], link[1], key++));
|
||||
} else {
|
||||
out.push(tok);
|
||||
}
|
||||
}
|
||||
|
||||
last = m.index + tok.length;
|
||||
}
|
||||
last = m.index + tok.length;
|
||||
}
|
||||
if (last < text.length) out.push(text.slice(last));
|
||||
|
||||
return out;
|
||||
if (last < text.length) {
|
||||
out.push(text.slice(last));
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
function safeLink(href: string, label: string, key: number): ReactNode {
|
||||
const ok = /^(https?:|mailto:)/i.test(href);
|
||||
if (!ok) return <Fragment key={key}>{label}</Fragment>;
|
||||
return (
|
||||
<a key={key} href={href} target="_blank" rel="noopener noreferrer" className="text-primary underline underline-offset-2">
|
||||
{label}
|
||||
</a>
|
||||
);
|
||||
const ok = /^(https?:|mailto:)/i.test(href);
|
||||
|
||||
if (!ok) {
|
||||
return <Fragment key={key}>{label}</Fragment>;
|
||||
}
|
||||
|
||||
return (
|
||||
<a
|
||||
key={key}
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary underline underline-offset-2"
|
||||
>
|
||||
{label}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
@@ -1,31 +1,28 @@
|
||||
export interface OnboardingActionResult {
|
||||
success: boolean;
|
||||
message?: string;
|
||||
success: boolean;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface OnboardingActions {
|
||||
acceptAgreements: () => Promise<OnboardingActionResult>;
|
||||
changePassword: (
|
||||
oldPassword: string,
|
||||
newPassword: string,
|
||||
) => Promise<OnboardingActionResult>;
|
||||
acceptAgreements: () => Promise<OnboardingActionResult>;
|
||||
changePassword: (oldPassword: string, newPassword: string) => Promise<OnboardingActionResult>;
|
||||
}
|
||||
|
||||
export interface OnboardingExecution {
|
||||
passwordMode: 'change' | 'rehearsal';
|
||||
actions: OnboardingActions;
|
||||
passwordMode: 'change' | 'rehearsal';
|
||||
actions: OnboardingActions;
|
||||
}
|
||||
|
||||
const REHEARSAL_ACTIONS: OnboardingActions = {
|
||||
acceptAgreements: async () => ({ success: true }),
|
||||
changePassword: async () => ({ success: true }),
|
||||
acceptAgreements: async () => ({ success: true }),
|
||||
changePassword: async () => ({ success: true }),
|
||||
};
|
||||
|
||||
export function onboardingExecution(
|
||||
replaying: boolean,
|
||||
liveActions: OnboardingActions,
|
||||
replaying: boolean,
|
||||
liveActions: OnboardingActions,
|
||||
): OnboardingExecution {
|
||||
return replaying
|
||||
? { passwordMode: 'rehearsal', actions: REHEARSAL_ACTIONS }
|
||||
: { passwordMode: 'change', actions: liveActions };
|
||||
return replaying
|
||||
? { passwordMode: 'rehearsal', actions: REHEARSAL_ACTIONS }
|
||||
: { passwordMode: 'change', actions: liveActions };
|
||||
}
|
||||
@@ -3,25 +3,41 @@ export const DEVELOPER_SETTINGS_URL = '/settings?tab=developer';
|
||||
export const DEVELOPER_ONBOARDING_RETURN_KEY = 'snowlumaOnboardingReturnTo';
|
||||
|
||||
interface LocationLike {
|
||||
pathname: string;
|
||||
search: string;
|
||||
hash?: string;
|
||||
pathname: string;
|
||||
search: string;
|
||||
hash?: string;
|
||||
}
|
||||
|
||||
export function isDeveloperOnboardingLocation(location: LocationLike): boolean {
|
||||
if (location.pathname !== '/onboarding') return false;
|
||||
return new URLSearchParams(location.search).get('mode') === 'developer';
|
||||
if (location.pathname !== '/onboarding') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return new URLSearchParams(location.search).get('mode') === 'developer';
|
||||
}
|
||||
|
||||
export function browserPath(location: LocationLike): string {
|
||||
return `${location.pathname}${location.search}${location.hash ?? ''}`;
|
||||
return `${location.pathname}${location.search}${location.hash ?? ''}`;
|
||||
}
|
||||
|
||||
export function developerOnboardingReturnPath(state: unknown): string | null {
|
||||
if (typeof state !== 'object' || state === null) return null;
|
||||
const candidate = (state as Record<string, unknown>)[DEVELOPER_ONBOARDING_RETURN_KEY];
|
||||
if (typeof candidate !== 'string') return null;
|
||||
if (!candidate.startsWith('/') || candidate.startsWith('//')) return null;
|
||||
if (candidate.startsWith('/onboarding')) return null;
|
||||
return candidate;
|
||||
if (typeof state !== 'object' || state === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const candidate = (state as Record<string, unknown>)[DEVELOPER_ONBOARDING_RETURN_KEY];
|
||||
|
||||
if (typeof candidate !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!candidate.startsWith('/') || candidate.startsWith('//')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (candidate.startsWith('/onboarding')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return candidate;
|
||||
}
|
||||
@@ -1,36 +1,41 @@
|
||||
import type { MessageFormat, OneBotConfig, StatusCommandConfig } from '@/types';
|
||||
|
||||
const DEFAULT_STATUS_COMMAND: StatusCommandConfig = {
|
||||
enabled: true,
|
||||
swallow: false,
|
||||
cooldownSeconds: 5,
|
||||
trigger: '#sl',
|
||||
enabled: true,
|
||||
swallow: false,
|
||||
cooldownSeconds: 5,
|
||||
trigger: '#sl',
|
||||
};
|
||||
|
||||
/** Fill the `statusCommand` block with defaults when the backend omits or
|
||||
* partially supplies it (older configs predate the feature). */
|
||||
function normalizeStatusCommand(raw: unknown): StatusCommandConfig {
|
||||
const src = (raw ?? {}) as Record<string, unknown>;
|
||||
return {
|
||||
enabled: typeof src.enabled === 'boolean' ? src.enabled : DEFAULT_STATUS_COMMAND.enabled,
|
||||
swallow: typeof src.swallow === 'boolean' ? src.swallow : DEFAULT_STATUS_COMMAND.swallow,
|
||||
cooldownSeconds:
|
||||
typeof src.cooldownSeconds === 'number' && Number.isFinite(src.cooldownSeconds) && src.cooldownSeconds >= 0
|
||||
? Math.trunc(src.cooldownSeconds)
|
||||
: DEFAULT_STATUS_COMMAND.cooldownSeconds,
|
||||
trigger: typeof src.trigger === 'string' && src.trigger.trim().length > 0 && !/[\r\n]/.test(src.trigger)
|
||||
? src.trigger.trim().slice(0, 32)
|
||||
: DEFAULT_STATUS_COMMAND.trigger,
|
||||
};
|
||||
const src = (raw ?? {}) as Record<string, unknown>;
|
||||
return {
|
||||
enabled: typeof src.enabled === 'boolean' ? src.enabled : DEFAULT_STATUS_COMMAND.enabled,
|
||||
swallow: typeof src.swallow === 'boolean' ? src.swallow : DEFAULT_STATUS_COMMAND.swallow,
|
||||
cooldownSeconds:
|
||||
typeof src.cooldownSeconds === 'number' &&
|
||||
Number.isFinite(src.cooldownSeconds) &&
|
||||
src.cooldownSeconds >= 0
|
||||
? Math.trunc(src.cooldownSeconds)
|
||||
: DEFAULT_STATUS_COMMAND.cooldownSeconds,
|
||||
trigger:
|
||||
typeof src.trigger === 'string' &&
|
||||
src.trigger.trim().length > 0 &&
|
||||
!/[\r\n]/.test(src.trigger)
|
||||
? src.trigger.trim().slice(0, 32)
|
||||
: DEFAULT_STATUS_COMMAND.trigger,
|
||||
};
|
||||
}
|
||||
|
||||
/** Keep only string channel ids (the server re-validates slugs on save). */
|
||||
function normalizeNotifications(raw: unknown): { channelIds: string[] } {
|
||||
const src = (raw ?? {}) as Record<string, unknown>;
|
||||
const channelIds = Array.isArray(src.channelIds)
|
||||
? src.channelIds.filter((x): x is string => typeof x === 'string')
|
||||
: [];
|
||||
return { channelIds };
|
||||
const src = (raw ?? {}) as Record<string, unknown>;
|
||||
const channelIds = Array.isArray(src.channelIds)
|
||||
? src.channelIds.filter((x): x is string => typeof x === 'string')
|
||||
: [];
|
||||
return { channelIds };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -40,37 +45,40 @@ function normalizeNotifications(raw: unknown): { channelIds: string[] } {
|
||||
* into the canonical {@link OneBotConfig} the editor expects.
|
||||
*/
|
||||
export function normalizeOneBotConfig(raw: unknown): OneBotConfig {
|
||||
const cfg = (raw ?? {}) as Record<string, unknown>;
|
||||
const nets = (cfg.networks as Record<string, unknown> | undefined) ?? {};
|
||||
const legacyFormat: MessageFormat = cfg.messageFormat === 'string' ? 'string' : 'array';
|
||||
const legacyReport = !!cfg.reportSelfMessage;
|
||||
const cfg = (raw ?? {}) as Record<string, unknown>;
|
||||
const nets = (cfg.networks as Record<string, unknown> | undefined) ?? {};
|
||||
const legacyFormat: MessageFormat = cfg.messageFormat === 'string' ? 'string' : 'array';
|
||||
const legacyReport = !!cfg.reportSelfMessage;
|
||||
|
||||
const normalize = (item: Record<string, unknown>): Record<string, unknown> => ({
|
||||
...item,
|
||||
messageFormat: item.messageFormat === 'string' ? 'string' : legacyFormat,
|
||||
reportSelfMessage:
|
||||
typeof item.reportSelfMessage === 'boolean' ? item.reportSelfMessage : legacyReport,
|
||||
});
|
||||
const normalize = (item: Record<string, unknown>): Record<string, unknown> => ({
|
||||
...item,
|
||||
messageFormat: item.messageFormat === 'string' ? 'string' : legacyFormat,
|
||||
reportSelfMessage:
|
||||
typeof item.reportSelfMessage === 'boolean' ? item.reportSelfMessage : legacyReport,
|
||||
});
|
||||
|
||||
const list = (x: unknown): Record<string, unknown>[] =>
|
||||
Array.isArray(x) ? x.map((it) => normalize(it as Record<string, unknown>)) : [];
|
||||
const list = (x: unknown): Record<string, unknown>[] =>
|
||||
Array.isArray(x) ? x.map((it) => normalize(it as Record<string, unknown>)) : [];
|
||||
|
||||
return {
|
||||
networks: {
|
||||
httpServers: list(nets.httpServers) as unknown as OneBotConfig['networks']['httpServers'],
|
||||
httpClients: list(nets.httpClients) as unknown as OneBotConfig['networks']['httpClients'],
|
||||
wsServers: list(nets.wsServers) as unknown as OneBotConfig['networks']['wsServers'],
|
||||
wsClients: list(nets.wsClients) as unknown as OneBotConfig['networks']['wsClients'],
|
||||
},
|
||||
statusCommand: normalizeStatusCommand(cfg.statusCommand),
|
||||
historySync: {
|
||||
enabled: (
|
||||
typeof cfg.historySync === 'object'
|
||||
&& cfg.historySync !== null
|
||||
&& !Array.isArray(cfg.historySync)
|
||||
&& (cfg.historySync as Record<string, unknown>).enabled === true
|
||||
),
|
||||
},
|
||||
notifications: normalizeNotifications(cfg.notifications),
|
||||
};
|
||||
return {
|
||||
networks: {
|
||||
httpServers: list(
|
||||
nets.httpServers,
|
||||
) as unknown as OneBotConfig['networks']['httpServers'],
|
||||
httpClients: list(
|
||||
nets.httpClients,
|
||||
) as unknown as OneBotConfig['networks']['httpClients'],
|
||||
wsServers: list(nets.wsServers) as unknown as OneBotConfig['networks']['wsServers'],
|
||||
wsClients: list(nets.wsClients) as unknown as OneBotConfig['networks']['wsClients'],
|
||||
},
|
||||
statusCommand: normalizeStatusCommand(cfg.statusCommand),
|
||||
historySync: {
|
||||
enabled:
|
||||
typeof cfg.historySync === 'object' &&
|
||||
cfg.historySync !== null &&
|
||||
!Array.isArray(cfg.historySync) &&
|
||||
(cfg.historySync as Record<string, unknown>).enabled === true,
|
||||
},
|
||||
notifications: normalizeNotifications(cfg.notifications),
|
||||
};
|
||||
}
|
||||
@@ -1,29 +1,33 @@
|
||||
import type { LogLevel } from '@/types';
|
||||
|
||||
export const TRACE_CONFIRMATION_WARNINGS = [
|
||||
'TRACE 会产生非常大量的数据。',
|
||||
'TRACE 可能包含未经脱敏的隐私数据和凭据。',
|
||||
'TRACE 不适合长时间开启。',
|
||||
'TRACE 仅用于小规模问题复现和 bug 反馈。',
|
||||
'TRACE 会产生非常大量的数据。',
|
||||
'TRACE 可能包含未经脱敏的隐私数据和凭据。',
|
||||
'TRACE 不适合长时间开启。',
|
||||
'TRACE 仅用于小规模问题复现和 bug 反馈。',
|
||||
] as const;
|
||||
|
||||
interface SelectServerLogLevelOptions {
|
||||
currentLevel: LogLevel | null;
|
||||
nextLevel: LogLevel;
|
||||
applyLevel: (level: LogLevel) => void;
|
||||
requestTraceConfirmation: () => void;
|
||||
currentLevel: LogLevel | null;
|
||||
nextLevel: LogLevel;
|
||||
applyLevel: (level: LogLevel) => void;
|
||||
requestTraceConfirmation: () => void;
|
||||
}
|
||||
|
||||
export function selectServerLogLevel({
|
||||
currentLevel,
|
||||
nextLevel,
|
||||
applyLevel,
|
||||
requestTraceConfirmation,
|
||||
currentLevel,
|
||||
nextLevel,
|
||||
applyLevel,
|
||||
requestTraceConfirmation,
|
||||
}: SelectServerLogLevelOptions): void {
|
||||
if (currentLevel === null || currentLevel === nextLevel) return;
|
||||
if (currentLevel !== 'trace' && nextLevel === 'trace') {
|
||||
requestTraceConfirmation();
|
||||
return;
|
||||
}
|
||||
applyLevel(nextLevel);
|
||||
if (currentLevel === null || currentLevel === nextLevel) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentLevel !== 'trace' && nextLevel === 'trace') {
|
||||
requestTraceConfirmation();
|
||||
return;
|
||||
}
|
||||
|
||||
applyLevel(nextLevel);
|
||||
}
|
||||
@@ -1,75 +1,92 @@
|
||||
import {
|
||||
ALL_ACCOUNTS_CONFIRMATION,
|
||||
type LogStorageSettings,
|
||||
type LogStorageSettingsField,
|
||||
type LogStorageSettingsPatch,
|
||||
type LogStorageState,
|
||||
ALL_ACCOUNTS_CONFIRMATION,
|
||||
type LogStorageSettings,
|
||||
type LogStorageSettingsField,
|
||||
type LogStorageSettingsPatch,
|
||||
type LogStorageState,
|
||||
} from '@/types';
|
||||
|
||||
export type StorageTone = 'neutral' | 'success' | 'warning' | 'danger';
|
||||
|
||||
export interface LogStoragePresentation {
|
||||
label: string;
|
||||
tone: StorageTone;
|
||||
percent: number;
|
||||
label: string;
|
||||
tone: StorageTone;
|
||||
percent: number;
|
||||
}
|
||||
|
||||
export function formatBytes(bytes: number): string {
|
||||
const safeBytes = Number.isFinite(bytes) ? Math.max(0, bytes) : 0;
|
||||
if (safeBytes < 1024) return `${Math.round(safeBytes)} B`;
|
||||
const units = ['KB', 'MB', 'GB', 'TB', 'PB'];
|
||||
let value = safeBytes / 1024;
|
||||
let unitIndex = 0;
|
||||
while (value >= 1024 && unitIndex < units.length - 1) {
|
||||
value /= 1024;
|
||||
unitIndex += 1;
|
||||
}
|
||||
const rounded = value < 10 && !Number.isInteger(value)
|
||||
? Number(value.toFixed(1))
|
||||
: Math.round(value);
|
||||
return `${rounded} ${units[unitIndex]}`;
|
||||
const safeBytes = Number.isFinite(bytes) ? Math.max(0, bytes) : 0;
|
||||
|
||||
if (safeBytes < 1024) {
|
||||
return `${Math.round(safeBytes)} B`;
|
||||
}
|
||||
|
||||
const units = ['KB', 'MB', 'GB', 'TB', 'PB'];
|
||||
let value = safeBytes / 1024;
|
||||
let unitIndex = 0;
|
||||
|
||||
while (value >= 1024 && unitIndex < units.length - 1) {
|
||||
value /= 1024;
|
||||
unitIndex += 1;
|
||||
}
|
||||
|
||||
const rounded =
|
||||
value < 10 && !Number.isInteger(value) ? Number(value.toFixed(1)) : Math.round(value);
|
||||
return `${rounded} ${units[unitIndex]}`;
|
||||
}
|
||||
|
||||
export function buildLogSettingsPatch(
|
||||
current: LogStorageSettings,
|
||||
saved: LogStorageSettings,
|
||||
lockedFields: LogStorageSettingsField[],
|
||||
current: LogStorageSettings,
|
||||
saved: LogStorageSettings,
|
||||
lockedFields: LogStorageSettingsField[],
|
||||
): LogStorageSettingsPatch {
|
||||
const locked = new Set(lockedFields);
|
||||
const patch: LogStorageSettingsPatch = {};
|
||||
if (!locked.has('logMaxTotalMb') && current.logMaxTotalMb !== saved.logMaxTotalMb) {
|
||||
patch.logMaxTotalMb = current.logMaxTotalMb;
|
||||
}
|
||||
if (!locked.has('logRetainDays') && current.logRetainDays !== saved.logRetainDays) {
|
||||
patch.logRetainDays = current.logRetainDays;
|
||||
}
|
||||
if (!locked.has('logPerUin') && current.logPerUin !== saved.logPerUin) {
|
||||
patch.logPerUin = current.logPerUin;
|
||||
}
|
||||
return patch;
|
||||
const locked = new Set(lockedFields);
|
||||
const patch: LogStorageSettingsPatch = {};
|
||||
|
||||
if (!locked.has('logMaxTotalMb') && current.logMaxTotalMb !== saved.logMaxTotalMb) {
|
||||
patch.logMaxTotalMb = current.logMaxTotalMb;
|
||||
}
|
||||
|
||||
if (!locked.has('logRetainDays') && current.logRetainDays !== saved.logRetainDays) {
|
||||
patch.logRetainDays = current.logRetainDays;
|
||||
}
|
||||
|
||||
if (!locked.has('logPerUin') && current.logPerUin !== saved.logPerUin) {
|
||||
patch.logPerUin = current.logPerUin;
|
||||
}
|
||||
|
||||
return patch;
|
||||
}
|
||||
|
||||
export function logStoragePresentation(input: {
|
||||
state: LogStorageState;
|
||||
totalBytes: number;
|
||||
maxTotalBytes: number;
|
||||
state: LogStorageState;
|
||||
totalBytes: number;
|
||||
maxTotalBytes: number;
|
||||
}): LogStoragePresentation {
|
||||
const percent = input.maxTotalBytes > 0
|
||||
? Math.max(0, Math.min(100, (input.totalBytes / input.maxTotalBytes) * 100))
|
||||
: 0;
|
||||
if (input.state === 'degraded') {
|
||||
return { label: '磁盘写入已暂停', tone: 'danger', percent };
|
||||
}
|
||||
if (input.state === 'warning') {
|
||||
return { label: '清理异常', tone: 'warning', percent };
|
||||
}
|
||||
if (input.state === 'disabled') {
|
||||
return { label: '文件日志已关闭', tone: 'neutral', percent };
|
||||
}
|
||||
if (percent >= 80) return { label: '接近上限', tone: 'warning', percent };
|
||||
return { label: '正常', tone: 'success', percent };
|
||||
const percent =
|
||||
input.maxTotalBytes > 0
|
||||
? Math.max(0, Math.min(100, (input.totalBytes / input.maxTotalBytes) * 100))
|
||||
: 0;
|
||||
|
||||
if (input.state === 'degraded') {
|
||||
return { label: '磁盘写入已暂停', tone: 'danger', percent };
|
||||
}
|
||||
|
||||
if (input.state === 'warning') {
|
||||
return { label: '清理异常', tone: 'warning', percent };
|
||||
}
|
||||
|
||||
if (input.state === 'disabled') {
|
||||
return { label: '文件日志已关闭', tone: 'neutral', percent };
|
||||
}
|
||||
|
||||
if (percent >= 80) {
|
||||
return { label: '接近上限', tone: 'warning', percent };
|
||||
}
|
||||
|
||||
return { label: '正常', tone: 'success', percent };
|
||||
}
|
||||
|
||||
export function isAllAccountsConfirmation(value: string): boolean {
|
||||
return value === ALL_ACCOUNTS_CONFIRMATION;
|
||||
return value === ALL_ACCOUNTS_CONFIRMATION;
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
export function parseSecondFactor(value: string): { totp: string } | { recoveryCode: string } {
|
||||
const trimmed = value.trim();
|
||||
const digits = trimmed.replace(/\s/g, '');
|
||||
if (/^\d{6}$/.test(digits)) return { totp: digits };
|
||||
return { recoveryCode: trimmed };
|
||||
const trimmed = value.trim();
|
||||
const digits = trimmed.replace(/\s/g, '');
|
||||
|
||||
if (/^\d{6}$/.test(digits)) {
|
||||
return { totp: digits };
|
||||
}
|
||||
|
||||
return { recoveryCode: trimmed };
|
||||
}
|
||||
@@ -1,18 +1,39 @@
|
||||
const LOOPBACK_V4 = /^127\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/u;
|
||||
|
||||
function isLoopbackIpv4(hostname: string): boolean {
|
||||
const match = LOOPBACK_V4.exec(hostname);
|
||||
if (!match) return false;
|
||||
return match.slice(1).every((part) => Number(part) <= 255);
|
||||
const match = LOOPBACK_V4.exec(hostname);
|
||||
|
||||
if (!match) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return match.slice(1).every((part) => Number(part) <= 255);
|
||||
}
|
||||
|
||||
export function isLoopbackHostname(hostname: string): boolean {
|
||||
const host = hostname.trim().toLowerCase().replace(/^\[|\]$/gu, '').replace(/\.$/u, '');
|
||||
if (host === 'localhost' || host.endsWith('.localhost')) return true;
|
||||
if (isLoopbackIpv4(host)) return true;
|
||||
if (host === '::1' || host === '0:0:0:0:0:0:0:1') return true;
|
||||
if (host.startsWith('::ffff:')) return isLoopbackIpv4(host.slice('::ffff:'.length));
|
||||
return false;
|
||||
const host = hostname
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/^\[|\]$/gu, '')
|
||||
.replace(/\.$/u, '');
|
||||
|
||||
if (host === 'localhost' || host.endsWith('.localhost')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isLoopbackIpv4(host)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (host === '::1' || host === '0:0:0:0:0:0:0:1') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (host.startsWith('::ffff:')) {
|
||||
return isLoopbackIpv4(host.slice('::ffff:'.length));
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Empty inbound OneBot tokens are safe when the listener is loopback, or
|
||||
@@ -20,15 +41,15 @@ export function isLoopbackHostname(hostname: string): boolean {
|
||||
* without a token on purpose). A remote WebUI plus a public bind host
|
||||
* must keep a token. */
|
||||
export function allowEmptyInboundAccessToken(
|
||||
webuiHostname: string,
|
||||
bindHost: string | undefined,
|
||||
webuiHostname: string,
|
||||
bindHost: string | undefined,
|
||||
): boolean {
|
||||
return isLoopbackHostname(webuiHostname) || isLoopbackHostname(bindHost ?? '');
|
||||
return isLoopbackHostname(webuiHostname) || isLoopbackHostname(bindHost ?? '');
|
||||
}
|
||||
|
||||
export function shouldWarnAboutInsecureRemoteAccess(location: {
|
||||
protocol: string;
|
||||
hostname: string;
|
||||
protocol: string;
|
||||
hostname: string;
|
||||
}): boolean {
|
||||
return location.protocol !== 'https:' && !isLoopbackHostname(location.hostname);
|
||||
return location.protocol !== 'https:' && !isLoopbackHostname(location.hostname);
|
||||
}
|
||||
@@ -2,79 +2,103 @@ import { clsx, type ClassValue } from 'clsx';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
export function formatBytes(bytes: number, decimals = 1): string {
|
||||
if (!Number.isFinite(bytes) || bytes <= 0) return '0 B';
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
|
||||
const i = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)));
|
||||
const v = bytes / Math.pow(1024, i);
|
||||
return `${v.toFixed(decimals)} ${units[i]}`;
|
||||
if (!Number.isFinite(bytes) || bytes <= 0) {
|
||||
return '0 B';
|
||||
}
|
||||
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
|
||||
const i = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)));
|
||||
const v = bytes / Math.pow(1024, i);
|
||||
return `${v.toFixed(decimals)} ${units[i]}`;
|
||||
}
|
||||
|
||||
export function formatUptime(seconds: number): string {
|
||||
if (!Number.isFinite(seconds) || seconds <= 0) return '0 秒';
|
||||
const d = Math.floor(seconds / 86400);
|
||||
const h = Math.floor((seconds % 86400) / 3600);
|
||||
const m = Math.floor((seconds % 3600) / 60);
|
||||
const parts: string[] = [];
|
||||
if (d) parts.push(`${d} 天`);
|
||||
if (h) parts.push(`${h} 时`);
|
||||
if (m || (!d && !h)) parts.push(`${m} 分`);
|
||||
return parts.join(' ');
|
||||
if (!Number.isFinite(seconds) || seconds <= 0) {
|
||||
return '0 秒';
|
||||
}
|
||||
|
||||
const d = Math.floor(seconds / 86400);
|
||||
const h = Math.floor((seconds % 86400) / 3600);
|
||||
const m = Math.floor((seconds % 3600) / 60);
|
||||
const parts: string[] = [];
|
||||
|
||||
if (d) {
|
||||
parts.push(`${d} 天`);
|
||||
}
|
||||
|
||||
if (h) {
|
||||
parts.push(`${h} 时`);
|
||||
}
|
||||
|
||||
if (m || (!d && !h)) {
|
||||
parts.push(`${m} 分`);
|
||||
}
|
||||
|
||||
return parts.join(' ');
|
||||
}
|
||||
|
||||
/** Fine desktop pointer only. iPad + mouse still reports `any-pointer: coarse`. */
|
||||
export const FINE_POINTER_QUERY =
|
||||
'(hover: hover) and (pointer: fine) and (not (any-pointer: coarse))';
|
||||
'(hover: hover) and (pointer: fine) and (not (any-pointer: coarse))';
|
||||
|
||||
/** Safari / iOS WebKit need the `<a>` in the document and a delayed revoke. */
|
||||
export function downloadBlob(blob: Blob, filename: string): void {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
|
||||
/** Clipboard write that still works on LAN HTTP and inside a modal focus trap. */
|
||||
/** WebKit `<input type="color">` only accepts `#rrggbb`. */
|
||||
export function toColorInputValue(raw: string, fallback = '#0ea5e9'): string {
|
||||
const v = raw.trim();
|
||||
if (/^#[0-9a-fA-F]{6}$/u.test(v)) return v;
|
||||
if (/^#[0-9a-fA-F]{3}$/u.test(v)) {
|
||||
return `#${v[1]}${v[1]}${v[2]}${v[2]}${v[3]}${v[3]}`;
|
||||
}
|
||||
return fallback;
|
||||
const v = raw.trim();
|
||||
|
||||
if (/^#[0-9a-fA-F]{6}$/u.test(v)) {
|
||||
return v;
|
||||
}
|
||||
|
||||
if (/^#[0-9a-fA-F]{3}$/u.test(v)) {
|
||||
return `#${v[1]}${v[1]}${v[2]}${v[2]}${v[3]}${v[3]}`;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export async function copyText(value: string): Promise<boolean> {
|
||||
try {
|
||||
if (navigator.clipboard?.writeText) {
|
||||
await navigator.clipboard.writeText(value);
|
||||
return true;
|
||||
try {
|
||||
if (navigator.clipboard?.writeText) {
|
||||
await navigator.clipboard.writeText(value);
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
/* insecure origin / permission — fall through */
|
||||
}
|
||||
|
||||
try {
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = value;
|
||||
ta.setAttribute('readonly', '');
|
||||
ta.style.position = 'fixed';
|
||||
ta.style.top = '0';
|
||||
ta.style.left = '-9999px';
|
||||
ta.style.opacity = '0.01';
|
||||
const host = document.querySelector('[role="dialog"]') ?? document.body;
|
||||
host.appendChild(ta);
|
||||
ta.focus();
|
||||
ta.setSelectionRange(0, ta.value.length);
|
||||
const ok = document.execCommand('copy');
|
||||
host.removeChild(ta);
|
||||
return ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
} catch { /* insecure origin / permission — fall through */ }
|
||||
try {
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = value;
|
||||
ta.setAttribute('readonly', '');
|
||||
ta.style.position = 'fixed';
|
||||
ta.style.top = '0';
|
||||
ta.style.left = '-9999px';
|
||||
ta.style.opacity = '0.01';
|
||||
const host = document.querySelector('[role="dialog"]') ?? document.body;
|
||||
host.appendChild(ta);
|
||||
ta.focus();
|
||||
ta.setSelectionRange(0, ta.value.length);
|
||||
const ok = document.execCommand('copy');
|
||||
host.removeChild(ta);
|
||||
return ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user