Skip to content

A modern and elegant dashboard for network traffic visualization and analysis.

feat: Add comprehensive testing infrastructure and refine collector services with minor web UI adjustments.

luolei23027b333704
diff --git a/.env.example b/.env.example
index c76278c..f8ee285 100644
--- a/.env.example
+++ b/.env.example
@@ -28,6 +28,13 @@ WS_EXTERNAL_PORT=3002
# 只有当你需要“直连 API/WS”时才需要改这些外部端口。
# 一般不需要修改容器内部端口(WEB_PORT/API_PORT/COLLECTOR_WS_PORT)。
+# -----------------------------------------------------------------------------
+# 安全配置
+# -----------------------------------------------------------------------------
+# Cookie 签名密钥(生产环境必填,建议 32 位以上随机字符串)
+# 可使用 openssl rand -hex 32 生成
+# COOKIE_SECRET=
+
# -----------------------------------------------------------------------------
# 高级配置(一般不需要修改)
# -----------------------------------------------------------------------------
diff --git a/apps/collector/eslint.config.mjs b/apps/collector/eslint.config.mjs
new file mode 100644
index 0000000..b17a6f8
--- /dev/null
+++ b/apps/collector/eslint.config.mjs
@@ -0,0 +1,28 @@
+import eslint from '@eslint/js';
+import tseslint from 'typescript-eslint';
+
+export default tseslint.config(
+ eslint.configs.recommended,
+ ...tseslint.configs.recommended,
+ {
+ ignores: ['dist/**', 'node_modules/**'],
+ },
+ {
+ rules: {
+ // Allow unused vars prefixed with _
+ '@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }],
+ // Allow explicit any for migration (tighten later)
+ '@typescript-eslint/no-explicit-any': 'warn',
+ // Disallow console.log in source (allow warn/error)
+ 'no-console': ['warn', { allow: ['warn', 'error', 'info'] }],
+ },
+ },
+ {
+ // Relaxed rules for test files
+ files: ['**/*.test.ts', '**/__tests__/**'],
+ rules: {
+ '@typescript-eslint/no-explicit-any': 'off',
+ 'no-console': 'off',
+ },
+ },
+);
diff --git a/apps/collector/package.json b/apps/collector/package.json
index 8cc9f78..879a6bf 100644
--- a/apps/collector/package.json
+++ b/apps/collector/package.json
@@ -5,7 +5,10 @@
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc",
- "start": "node dist/index.js"
+ "start": "node dist/index.js",
+ "lint": "eslint src/",
+ "test": "vitest run",
+ "test:watch": "vitest"
},
"dependencies": {
"@fastify/cookie": "^11.0.2",
@@ -17,10 +20,14 @@
"ws": "^8.19.0"
},
"devDependencies": {
+ "@eslint/js": "^9.39.2",
"@types/better-sqlite3": "^7.6.13",
"@types/node": "^22",
"@types/ws": "^8.18.1",
+ "eslint": "^9",
"tsx": "^4.21.0",
- "typescript": "^5"
+ "typescript": "^5",
+ "typescript-eslint": "^8.55.0",
+ "vitest": "^4.0.18"
}
}
diff --git a/apps/collector/src/__tests__/helpers.ts b/apps/collector/src/__tests__/helpers.ts
new file mode 100644
index 0000000..572f8be
--- /dev/null
+++ b/apps/collector/src/__tests__/helpers.ts
@@ -0,0 +1,35 @@
+import { StatsDatabase } from '../db.js';
+import path from 'path';
+import fs from 'fs';
+import os from 'os';
+
+/**
+ * Create a temporary StatsDatabase backed by a real file (better-sqlite3
+ * does not support :memory: with the full schema init).
+ * Automatically cleaned up via the returned `cleanup` function.
+ */
+export function createTestDatabase(): { db: StatsDatabase; cleanup: () => void } {
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'neko-test-'));
+ const dbPath = path.join(tmpDir, 'test.db');
+ const db = new StatsDatabase(dbPath);
+ return {
+ db,
+ cleanup: () => {
+ db.close();
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ },
+ };
+}
+
+/**
+ * Create a backend and return its ID.
+ */
+export function createTestBackend(
+ db: StatsDatabase,
+ name = 'test-backend',
+ url = 'http://127.0.0.1:9090',
+): number {
+ const id = db.createBackend({ name, url, token: '', type: 'clash' });
+ db.setActiveBackend(id);
+ return id;
+}
diff --git a/apps/collector/src/api.ts b/apps/collector/src/api.ts
deleted file mode 100644
index f80b70c..0000000
--- a/apps/collector/src/api.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-/**
- * Legacy compatibility entry.
- *
- * The API implementation was migrated to `app.ts`.
- * Keep this file as a thin re-export to avoid duplicate route definitions
- * and to preserve old import paths.
- */
-
-export { createApp, APIServer } from './app.js';
-export { default } from './app.js';
diff --git a/apps/collector/src/app.ts b/apps/collector/src/app.ts
index d349dfb..8574f96 100644
--- a/apps/collector/src/app.ts
+++ b/apps/collector/src/app.ts
@@ -4,6 +4,7 @@
* This file registers all controllers and services for the API.
*/
+import crypto from 'crypto';
import Fastify from 'fastify';
import cors from '@fastify/cors';
import cookie from '@fastify/cookie';
@@ -45,10 +46,20 @@ export async function createApp(options: AppOptions) {
credentials: true,
});
- // Register Cookie
+ // Register Cookie — auto-generate a random secret if not configured
+ let cookieSecret = process.env.COOKIE_SECRET;
+ if (!cookieSecret) {
+ cookieSecret = crypto.randomBytes(32).toString('hex');
+ if (process.env.NODE_ENV === 'production') {
+ console.warn(
+ '[Security] COOKIE_SECRET is not set. A random secret has been generated for this session. ' +
+ 'Sessions will be invalidated on restart. Set COOKIE_SECRET in your .env for persistence.',
+ );
+ }
+ }
await app.register(cookie, {
- secret: process.env.COOKIE_SECRET || 'neko-master-secret-change-me', // secure cookie sign
- parseOptions: {}
+ secret: cookieSecret,
+ parseOptions: {},
});
// Create services
@@ -271,7 +282,7 @@ export async function createApp(options: AppOptions) {
if (isSurge) {
// Build response from cache or fetch directly
const providers: Record<string, { proxies: { name: string; type: string; now?: string }[] }> = {};
- let cacheStatus = policySyncService?.getCacheStatus(backendId);
+ const cacheStatus = policySyncService?.getCacheStatus(backendId);
// Try to use cache first
if (cacheStatus?.cached && !forceRefresh) {
diff --git a/apps/collector/src/batch-buffer.ts b/apps/collector/src/batch-buffer.ts
new file mode 100644
index 0000000..a52e42e
--- /dev/null
+++ b/apps/collector/src/batch-buffer.ts
@@ -0,0 +1,181 @@
+/**
+ * Shared Batch Buffer
+ *
+ * Extracts the common BatchBuffer class, TrafficUpdate / GeoIPResult interfaces,
+ * and toMinuteKey helper used by both collector.ts and surge-collector.ts.
+ */
+import type { StatsDatabase } from "./db.js";
+import type { GeoIPService } from "./geo-service.js";
+
+export interface TrafficUpdate {
+ domain: string;
+ ip: string;
+ chain: string;
+ chains: string[];
+ rule: string;
+ rulePayload: string;
+ upload: number;
+ download: number;
+ sourceIP?: string;
+ timestampMs?: number;
+}
+
+export interface GeoIPResult {
+ ip: string;
+ geo: {
+ country: string;
+ country_name: string;
+ continent: string;
+ } | null;
+ upload: number;
+ download: number;
+ timestampMs?: number;
+}
+
+export function toMinuteKey(timestampMs?: number): string {
+ const date = new Date(timestampMs ?? Date.now()).toISOString();
+ return `${date.slice(0, 16)}:00`;
+}
+
+export interface FlushResult {
+ domains: number;
+ rules: number;
+ trafficOk: boolean;
+ countryOk: boolean;
+ hasUpdates: boolean;
+}
+
+export class BatchBuffer {
+ private buffer: Map<string, TrafficUpdate> = new Map();
+ private geoQueue: GeoIPResult[] = [];
+ private lastLogTime = 0;
+ private logCounter = 0;
+
+ add(backendId: number, update: TrafficUpdate) {
+ const minuteKey = toMinuteKey(update.timestampMs);
+ const fullChain = update.chains.join(" > ");
+ const key = [
+ backendId,
+ minuteKey,
+ update.domain,
+ update.ip,
+ update.chain,
+ fullChain,
+ update.rule,
+ update.rulePayload,
+ update.sourceIP || "",
+ ].join(":");
+ const existing = this.buffer.get(key);
+
+ if (existing) {
+ existing.upload += update.upload;
+ existing.download += update.download;
+ if ((update.timestampMs ?? 0) > (existing.timestampMs ?? 0)) {
+ existing.timestampMs = update.timestampMs;
+ }
+ } else {
+ this.buffer.set(key, { ...update });
+ }
+ }
+
+ addGeoResult(result: GeoIPResult) {
+ this.geoQueue.push(result);
+ }
+
+ size(): number {
+ return this.buffer.size;
+ }
+
+ hasPending(): boolean {
+ return this.buffer.size > 0 || this.geoQueue.length > 0;
+ }
+
+ flush(
+ db: StatsDatabase,
+ _geoService: GeoIPService | undefined,
+ backendId: number,
+ logPrefix = "Collector",
+ ): FlushResult {
+ const updates = Array.from(this.buffer.values());
+ const geoResults = [...this.geoQueue];
+
+ // Calculate unique domains and rules for logging
+ const domains = new Set<string>();
+ const rules = new Set<string>();
+
+ for (const update of updates) {
+ if (update.domain) domains.add(update.domain);
+ const initialRule =
+ update.chains.length > 0
+ ? update.chains[update.chains.length - 1]
+ : "DIRECT";
+ rules.add(initialRule);
+ }
+
+ let trafficOk = true;
+ let countryOk = true;
+
+ if (updates.length > 0) {
+ try {
+ db.batchUpdateTrafficStats(backendId, updates);
+ } catch (err) {
+ trafficOk = false;
+ console.error(`[${logPrefix}:${backendId}] Batch write failed:`, err);
+ }
+ }
+
+ if (trafficOk) {
+ this.buffer.clear();
+ }
+
+ if (geoResults.length > 0) {
+ try {
+ const countryUpdates = geoResults
+ .filter(
+ (r): r is GeoIPResult & { geo: NonNullable<GeoIPResult["geo"]> } =>
+ r.geo !== null,
+ )
+ .map((r) => ({
+ country: r.geo.country,
+ countryName: r.geo.country_name,
+ continent: r.geo.continent,
+ upload: r.upload,
+ download: r.download,
+ timestampMs: r.timestampMs,
+ }));
+ db.batchUpdateCountryStats(backendId, countryUpdates);
+ } catch (err) {
+ countryOk = false;
+ console.error(
+ `[${logPrefix}:${backendId}] Country batch write failed:`,
+ err,
+ );
+ }
+ }
+
+ if (countryOk) {
+ this.geoQueue = [];
+ }
+
+ return {
+ domains: domains.size,
+ rules: rules.size,
+ trafficOk,
+ countryOk,
+ hasUpdates: updates.length > 0 || geoResults.length > 0,
+ };
+ }
+
+ shouldLog(): boolean {
+ const now = Date.now();
+ if (now - this.lastLogTime > 10000) {
+ this.lastLogTime = now;
+ return true;
+ }
+ return false;
+ }
+
+ incrementLogCounter(): number {
+ return ++this.logCounter;
+ }
+}
diff --git a/apps/collector/src/collector.ts b/apps/collector/src/collector.ts
index bb99a24..93f670b 100644
--- a/apps/collector/src/collector.ts
+++ b/apps/collector/src/collector.ts
@@ -3,6 +3,11 @@ import type { ConnectionsData } from "@neko-master/shared";
import { StatsDatabase } from "./db.js";
import { GeoIPService } from "./geo-service.js";
import { realtimeStore } from "./realtime.js";
+import { BatchBuffer } from "./batch-buffer.js";
+
+// Stale connection cleanup constants
+const STALE_CONNECTION_TIMEOUT = 5 * 60 * 1000; // 5 minutes
+const CLEANUP_INTERVAL = 2 * 60 * 1000; // 2 minutes
interface CollectorOptions {
url: string;
@@ -12,36 +17,6 @@ interface CollectorOptions {
onError?: (error: Error) => void;
}
-interface TrafficUpdate {
- domain: string;
- ip: string;
- chain: string;
- chains: string[];
- rule: string;
- rulePayload: string;
- upload: number;
- download: number;
- sourceIP?: string;
- timestampMs?: number;
-}
-
-interface GeoIPResult {
- ip: string;
- geo: {
- country: string;
- country_name: string;
- continent: string;
- } | null;
- upload: number;
- download: number;
- timestampMs?: number;
-}
-
-function toMinuteKey(timestampMs?: number): string {
- const date = new Date(timestampMs ?? Date.now()).toISOString();
- return `${date.slice(0, 16)}:00`;
-}
-
export class GatewayCollector {
private ws: WebSocket | null = null;
private url: string;
@@ -141,138 +116,6 @@ export class GatewayCollector {
}
}
-// Batch buffer for traffic updates
-class BatchBuffer {
- private buffer: Map<string, TrafficUpdate> = new Map();
- private geoQueue: GeoIPResult[] = [];
- private lastLogTime = 0;
- private logCounter = 0;
-
- add(backendId: number, update: TrafficUpdate) {
- const minuteKey = toMinuteKey(update.timestampMs);
- const fullChain = update.chains.join(" > ");
- const key = [
- backendId,
- minuteKey,
- update.domain,
- update.ip,
- update.chain,
- fullChain,
- update.rule,
- update.rulePayload,
- update.sourceIP || "",
- ].join(":");
- const existing = this.buffer.get(key);
-
- if (existing) {
- existing.upload += update.upload;
- existing.download += update.download;
- if ((update.timestampMs ?? 0) > (existing.timestampMs ?? 0)) {
- existing.timestampMs = update.timestampMs;
- }
- } else {
- this.buffer.set(key, { ...update });
- }
- }
-
- addGeoResult(result: GeoIPResult) {
- this.geoQueue.push(result);
- }
-
- size(): number {
- return this.buffer.size;
- }
-
- hasPending(): boolean {
- return this.buffer.size > 0 || this.geoQueue.length > 0;
- }
-
- flush(
- db: StatsDatabase,
- _geoService: GeoIPService | undefined,
- backendId: number,
- ): { domains: number; rules: number; trafficOk: boolean; countryOk: boolean; hasUpdates: boolean } {
- const updates = Array.from(this.buffer.values());
- const geoResults = [...this.geoQueue];
-
- // Calculate unique domains and rules for logging
- const domains = new Set<string>();
- const rules = new Set<string>();
-
- for (const update of updates) {
- if (update.domain) domains.add(update.domain);
- const initialRule =
- update.chains.length > 0
- ? update.chains[update.chains.length - 1]
- : "DIRECT";
- rules.add(initialRule);
- }
-
- let trafficOk = true;
- let countryOk = true;
-
- if (updates.length > 0) {
- try {
- db.batchUpdateTrafficStats(backendId, updates);
- } catch (err) {
- trafficOk = false;
- console.error(`[Collector:${backendId}] Batch write failed:`, err);
- }
- }
-
- if (trafficOk) {
- this.buffer.clear();
- }
-
- if (geoResults.length > 0) {
- try {
- const countryUpdates = geoResults
- .filter(
- (r): r is GeoIPResult & { geo: NonNullable<GeoIPResult["geo"]> } =>
- r.geo !== null,
- )
- .map((r) => ({
- country: r.geo.country,
- countryName: r.geo.country_name,
- continent: r.geo.continent,
- upload: r.upload,
- download: r.download,
- timestampMs: r.timestampMs,
- }));
- db.batchUpdateCountryStats(backendId, countryUpdates);
- } catch (err) {
- countryOk = false;
- console.error(`[Collector:${backendId}] Country batch write failed:`, err);
- }
- }
-
- if (countryOk) {
- this.geoQueue = [];
- }
-
- return {
- domains: domains.size,
- rules: rules.size,
- trafficOk,
- countryOk,
- hasUpdates: updates.length > 0 || geoResults.length > 0,
- };
- }
-
- shouldLog(): boolean {
- const now = Date.now();
- if (now - this.lastLogTime > 10000) {
- this.lastLogTime = now;
- return true;
- }
- return false;
- }
-
- incrementLogCounter(): number {
- return ++this.logCounter;
- }
-}
-
// Track connection state with their accumulated traffic
interface TrackedConnection {
id: string;
@@ -286,6 +129,7 @@ interface TrackedConnection {
totalUpload: number;
totalDownload: number;
sourceIP?: string;
+ lastSeen: number;
}
export function createCollector(
@@ -302,11 +146,29 @@ export function createCollector(
let lastBroadcastTime = 0;
const broadcastThrottleMs = 500;
let flushInterval: NodeJS.Timeout | null = null;
+ let cleanupInterval: NodeJS.Timeout | null = null;
const FLUSH_INTERVAL_MS = parseInt(process.env.FLUSH_INTERVAL_MS || "30000");
const FLUSH_MAX_BUFFER_SIZE = parseInt(
process.env.FLUSH_MAX_BUFFER_SIZE || "5000",
);
let isFlushing = false;
+ let lastPruneTime = 0;
+ const PRUNE_INTERVAL_MS = 60_000; // Check memory bounds every 60s
+
+ // Clean up stale connections that haven't been updated for a while
+ const cleanupStaleConnections = () => {
+ const now = Date.now();
+ let cleaned = 0;
+ for (const [connId, conn] of activeConnections) {
+ if (now - conn.lastSeen > STALE_CONNECTION_TIMEOUT) {
+ activeConnections.delete(connId);
+ cleaned++;
+ }
+ }
+ if (cleaned > 0) {
+ console.log(`[Collector:${id}] Cleaned up ${cleaned} stale connections`);
+ }
+ };
const flushBatch = () => {
if (isFlushing || !batchBuffer.hasPending()) {
@@ -315,7 +177,7 @@ export function createCollector(
isFlushing = true;
try {
- const stats = batchBuffer.flush(db, geoService, id);
+ const stats = batchBuffer.flush(db, geoService, id, "Collector");
if (stats.trafficOk) {
realtimeStore.clearTraffic(id);
@@ -332,6 +194,13 @@ export function createCollector(
} finally {
isFlushing = false;
}
+
+ // Periodic memory bounds check on realtime store
+ const now = Date.now();
+ if (now - lastPruneTime > PRUNE_INTERVAL_MS) {
+ lastPruneTime = now;
+ realtimeStore.pruneIfNeeded(id);
+ }
};
// Start batch flush interval
@@ -339,6 +208,11 @@ export function createCollector(
flushBatch();
}, FLUSH_INTERVAL_MS);
+ // Start cleanup interval for stale connections
+ cleanupInterval = setInterval(() => {
+ cleanupStaleConnections();
+ }, CLEANUP_INTERVAL);
+
const collector = new GatewayCollector(id, {
url,
token,
@@ -409,6 +283,7 @@ export function createCollector(
totalUpload: conn.upload,
totalDownload: conn.download,
sourceIP,
+ lastSeen: now,
});
// Record initial traffic for new connection (add to batch buffer)
@@ -513,6 +388,7 @@ export function createCollector(
existing.lastUpload = conn.upload;
existing.lastDownload = conn.download;
+ existing.lastSeen = now;
hasNewTraffic = true;
}
}
@@ -574,7 +450,7 @@ export function createCollector(
},
});
- // Override disconnect to clear interval
+ // Override disconnect to clear intervals
const originalDisconnect = collector.disconnect.bind(collector);
collector.disconnect = () => {
if (flushInterval) {
@@ -583,6 +459,10 @@ export function createCollector(
// Final flush
flushBatch();
}
+ if (cleanupInterval) {
+ clearInterval(cleanupInterval);
+ cleanupInterval = null;
+ }
originalDisconnect();
};
diff --git a/apps/collector/src/database/repositories/traffic-writer.repository.ts b/apps/collector/src/database/repositories/traffic-writer.repository.ts
index 60aa4d6..1e5282a 100644
--- a/apps/collector/src/database/repositories/traffic-writer.repository.ts
+++ b/apps/collector/src/database/repositories/traffic-writer.repository.ts
@@ -21,38 +21,26 @@ export interface TrafficUpdate {
}
export class TrafficWriterRepository extends BaseRepository {
+ // Cached prepared statements for single-write path (avoids re-compilation per call)
+ private _singleStmts: ReturnType<TrafficWriterRepository['prepareSingleStmts']> | null = null;
+
constructor(db: Database.Database) {
super(db);
}
- updateTrafficStats(backendId: number, update: TrafficUpdate) {
- const now = new Date();
- const timestamp = now.toISOString();
- const hour = timestamp.slice(0, 13) + ':00:00';
-
- if (update.upload === 0 && update.download === 0) return;
-
- const ruleName = update.chains.length > 1 ? update.chains[update.chains.length - 1] :
- update.rulePayload ? `${update.rule}(${update.rulePayload})` : update.rule;
- const finalProxy = update.chains.length > 0 ? update.chains[0] : 'DIRECT';
- const fullChain = update.chains.join(' > ') || update.chain || 'DIRECT';
-
- const transaction = this.db.transaction(() => {
- const domainName = update.domain || 'unknown';
- if (domainName !== 'unknown') {
- this.db.prepare(`
- INSERT INTO domain_stats (backend_id, domain, ips, total_upload, total_download, total_connections, last_seen, rules, chains)
- VALUES (@backendId, @domain, @ip, @upload, @download, 1, @timestamp, @rule, @chain)
- ON CONFLICT(backend_id, domain) DO UPDATE SET
- ips = CASE WHEN domain_stats.ips IS NULL THEN @ip WHEN INSTR(domain_stats.ips, @ip) > 0 THEN domain_stats.ips ELSE domain_stats.ips || ',' || @ip END,
- total_upload = total_upload + @upload, total_download = total_download + @download,
- total_connections = total_connections + 1, last_seen = @timestamp,
- rules = CASE WHEN domain_stats.rules IS NULL THEN @rule WHEN INSTR(domain_stats.rules, @rule) > 0 THEN domain_stats.rules ELSE domain_stats.rules || ',' || @rule END,
- chains = CASE WHEN domain_stats.chains IS NULL THEN @chain WHEN INSTR(domain_stats.chains, @chain) > 0 THEN domain_stats.chains ELSE domain_stats.chains || ',' || @chain END
- `).run({ backendId, domain: domainName, ip: update.ip, upload: update.upload, download: update.download, timestamp, rule: ruleName, chain: fullChain });
- }
-
- this.db.prepare(`
+ private prepareSingleStmts() {
+ return {
+ domainUpsert: this.db.prepare(`
+ INSERT INTO domain_stats (backend_id, domain, ips, total_upload, total_download, total_connections, last_seen, rules, chains)
+ VALUES (@backendId, @domain, @ip, @upload, @download, 1, @timestamp, @rule, @chain)
+ ON CONFLICT(backend_id, domain) DO UPDATE SET
+ ips = CASE WHEN domain_stats.ips IS NULL THEN @ip WHEN INSTR(domain_stats.ips, @ip) > 0 THEN domain_stats.ips ELSE domain_stats.ips || ',' || @ip END,
+ total_upload = total_upload + @upload, total_download = total_download + @download,
+ total_connections = total_connections + 1, last_seen = @timestamp,
+ rules = CASE WHEN domain_stats.rules IS NULL THEN @rule WHEN INSTR(domain_stats.rules, @rule) > 0 THEN domain_stats.rules ELSE domain_stats.rules || ',' || @rule END,
+ chains = CASE WHEN domain_stats.chains IS NULL THEN @chain WHEN INSTR(domain_stats.chains, @chain) > 0 THEN domain_stats.chains ELSE domain_stats.chains || ',' || @chain END
+ `),
+ ipUpsert: this.db.prepare(`
INSERT INTO ip_stats (backend_id, ip, domains, total_upload, total_download, total_connections, last_seen, chains, rules)
VALUES (@backendId, @ip, @domain, @upload, @download, 1, @timestamp, @chain, @rule)
ON CONFLICT(backend_id, ip) DO UPDATE SET
@@ -61,77 +49,59 @@ export class TrafficWriterRepository extends BaseRepository {
total_connections = total_connections + 1, last_seen = @timestamp,
chains = CASE WHEN ip_stats.chains IS NULL THEN @chain WHEN INSTR(ip_stats.chains, @chain) > 0 THEN ip_stats.chains ELSE ip_stats.chains || ',' || @chain END,
rules = CASE WHEN ip_stats.rules IS NULL THEN @rule WHEN INSTR(ip_stats.rules, @rule) > 0 THEN ip_stats.rules ELSE ip_stats.rules || ',' || @rule END
- `).run({ backendId, ip: update.ip, domain: update.domain || 'unknown', upload: update.upload, download: update.download, timestamp, chain: fullChain, rule: ruleName });
-
- this.db.prepare(`
+ `),
+ proxyUpsert: this.db.prepare(`
INSERT INTO proxy_stats (backend_id, chain, total_upload, total_download, total_connections, last_seen)
VALUES (@backendId, @chain, @upload, @download, 1, @timestamp)
ON CONFLICT(backend_id, chain) DO UPDATE SET
total_upload = total_upload + @upload, total_download = total_download + @download,
total_connections = total_connections + 1, last_seen = @timestamp
- `).run({ backendId, chain: fullChain, upload: update.upload, download: update.download, timestamp });
-
- this.db.prepare(`
+ `),
+ ruleUpsert: this.db.prepare(`
INSERT INTO rule_stats (backend_id, rule, final_proxy, total_upload, total_download, total_connections, last_seen)
VALUES (@backendId, @rule, @finalProxy, @upload, @download, 1, @timestamp)
ON CONFLICT(backend_id, rule) DO UPDATE SET
final_proxy = @finalProxy, total_upload = total_upload + @upload, total_download = total_download + @download,
total_connections = total_connections + 1, last_seen = @timestamp
- `).run({ backendId, rule: ruleName, finalProxy, upload: update.upload, download: update.download, timestamp });
-
- this.db.prepare(`
+ `),
+ ruleChainUpsert: this.db.prepare(`
INSERT INTO rule_chain_traffic (backend_id, rule, chain, total_upload, total_download, total_connections, last_seen)
VALUES (@backendId, @rule, @chain, @upload, @download, 1, @timestamp)
ON CONFLICT(backend_id, rule, chain) DO UPDATE SET
total_upload = total_upload + @upload, total_download = total_download + @download,
total_connections = total_connections + 1, last_seen = @timestamp
- `).run({ backendId, rule: ruleName, chain: fullChain, upload: update.upload, download: update.download, timestamp });
-
- if (domainName !== 'unknown') {
- this.db.prepare(`
- INSERT INTO rule_domain_traffic (backend_id, rule, domain, total_upload, total_download, total_connections, last_seen)
- VALUES (@backendId, @rule, @domain, @upload, @download, 1, @timestamp)
- ON CONFLICT(backend_id, rule, domain) DO UPDATE SET
- total_upload = total_upload + @upload, total_download = total_download + @download,
- total_connections = total_connections + 1, last_seen = @timestamp
- `).run({ backendId, rule: ruleName, domain: domainName, upload: update.upload, download: update.download, timestamp });
- }
-
- this.db.prepare(`
+ `),
+ ruleDomainUpsert: this.db.prepare(`
+ INSERT INTO rule_domain_traffic (backend_id, rule, domain, total_upload, total_download, total_connections, last_seen)
+ VALUES (@backendId, @rule, @domain, @upload, @download, 1, @timestamp)
+ ON CONFLICT(backend_id, rule, domain) DO UPDATE SET
+ total_upload = total_upload + @upload, total_download = total_download + @download,
+ total_connections = total_connections + 1, last_seen = @timestamp
+ `),
+ ruleIpUpsert: this.db.prepare(`
INSERT INTO rule_ip_traffic (backend_id, rule, ip, total_upload, total_download, total_connections, last_seen)
VALUES (@backendId, @rule, @ip, @upload, @download, 1, @timestamp)
ON CONFLICT(backend_id, rule, ip) DO UPDATE SET
total_upload = total_upload + @upload, total_download = total_download + @download,
total_connections = total_connections + 1, last_seen = @timestamp
- `).run({ backendId, rule: ruleName, ip: update.ip, upload: update.upload, download: update.download, timestamp });
-
- if (update.chains.length > 1) {
- this.db.prepare(`INSERT OR IGNORE INTO rule_proxy_map (backend_id, rule, proxy) VALUES (@backendId, @rule, @proxy)`)
- .run({ backendId, rule: update.chains[update.chains.length - 1], proxy: update.chains[0] });
- }
-
- this.db.prepare(`
+ `),
+ ruleProxyInsert: this.db.prepare(`INSERT OR IGNORE INTO rule_proxy_map (backend_id, rule, proxy) VALUES (@backendId, @rule, @proxy)`),
+ hourlyUpsert: this.db.prepare(`
INSERT INTO hourly_stats (backend_id, hour, upload, download, connections) VALUES (@backendId, @hour, @upload, @download, 1)
ON CONFLICT(backend_id, hour) DO UPDATE SET upload = upload + @upload, download = download + @download, connections = connections + 1
- `).run({ backendId, hour, upload: update.upload, download: update.download });
-
- const minute = timestamp.slice(0, 16) + ':00';
- this.db.prepare(`
+ `),
+ minuteUpsert: this.db.prepare(`
INSERT INTO minute_stats (backend_id, minute, upload, download, connections) VALUES (@backendId, @minute, @upload, @download, 1)
ON CONFLICT(backend_id, minute) DO UPDATE SET upload = upload + @upload, download = download + @download, connections = connections + 1
- `).run({ backendId, minute, upload: update.upload, download: update.download });
-
- if (domainName !== 'unknown') {
- this.db.prepare(`
- INSERT INTO domain_proxy_stats (backend_id, domain, chain, total_upload, total_download, total_connections, last_seen)
- VALUES (@backendId, @domain, @chain, @upload, @download, 1, @timestamp)
- ON CONFLICT(backend_id, domain, chain) DO UPDATE SET
- total_upload = total_upload + @upload, total_download = total_download + @download,
- total_connections = total_connections + 1, last_seen = @timestamp
- `).run({ backendId, domain: domainName, chain: fullChain, upload: update.upload, download: update.download, timestamp });
- }
-
- this.db.prepare(`
+ `),
+ domainProxyUpsert: this.db.prepare(`
+ INSERT INTO domain_proxy_stats (backend_id, domain, chain, total_upload, total_download, total_connections, last_seen)
+ VALUES (@backendId, @domain, @chain, @upload, @download, 1, @timestamp)
+ ON CONFLICT(backend_id, domain, chain) DO UPDATE SET
+ total_upload = total_upload + @upload, total_download = total_download + @download,
+ total_connections = total_connections + 1, last_seen = @timestamp
+ `),
+ ipProxyUpsert: this.db.prepare(`
INSERT INTO ip_proxy_stats (backend_id, ip, chain, total_upload, total_download, total_connections, last_seen, domains)
VALUES (@backendId, @ip, @chain, @upload, @download, 1, @timestamp, @domain)
ON CONFLICT(backend_id, ip, chain) DO UPDATE SET
@@ -139,7 +109,60 @@ export class TrafficWriterRepository extends BaseRepository {
total_connections = total_connections + 1, last_seen = @timestamp,
domains = CASE WHEN ip_proxy_stats.domains IS NULL THEN @domain WHEN @domain = 'unknown' THEN ip_proxy_stats.domains
WHEN INSTR(ip_proxy_stats.domains, @domain) > 0 THEN ip_proxy_stats.domains ELSE ip_proxy_stats.domains || ',' || @domain END
- `).run({ backendId, ip: update.ip, chain: fullChain, upload: update.upload, download: update.download, timestamp, domain: update.domain || 'unknown' });
+ `),
+ };
+ }
+
+ private get singleStmts() {
+ if (!this._singleStmts) {
+ this._singleStmts = this.prepareSingleStmts();
+ }
+ return this._singleStmts;
+ }
+
+ updateTrafficStats(backendId: number, update: TrafficUpdate) {
+ const now = new Date();
+ const timestamp = now.toISOString();
+ const hour = timestamp.slice(0, 13) + ':00:00';
+ const minute = timestamp.slice(0, 16) + ':00';
+
+ if (update.upload === 0 && update.download === 0) return;
+
+ const ruleName = update.chains.length > 1 ? update.chains[update.chains.length - 1] :
+ update.rulePayload ? `${update.rule}(${update.rulePayload})` : update.rule;
+ const finalProxy = update.chains.length > 0 ? update.chains[0] : 'DIRECT';
+ const fullChain = update.chains.join(' > ') || update.chain || 'DIRECT';
+ const s = this.singleStmts;
+
+ const transaction = this.db.transaction(() => {
+ const domainName = update.domain || 'unknown';
+ if (domainName !== 'unknown') {
+ s.domainUpsert.run({ backendId, domain: domainName, ip: update.ip, upload: update.upload, download: update.download, timestamp, rule: ruleName, chain: fullChain });
+ }
+
+ s.ipUpsert.run({ backendId, ip: update.ip, domain: update.domain || 'unknown', upload: update.upload, download: update.download, timestamp, chain: fullChain, rule: ruleName });
+ s.proxyUpsert.run({ backendId, chain: fullChain, upload: update.upload, download: update.download, timestamp });
+ s.ruleUpsert.run({ backendId, rule: ruleName, finalProxy, upload: update.upload, download: update.download, timestamp });
+ s.ruleChainUpsert.run({ backendId, rule: ruleName, chain: fullChain, upload: update.upload, download: update.download, timestamp });
+
+ if (domainName !== 'unknown') {
+ s.ruleDomainUpsert.run({ backendId, rule: ruleName, domain: domainName, upload: update.upload, download: update.download, timestamp });
+ }
+
+ s.ruleIpUpsert.run({ backendId, rule: ruleName, ip: update.ip, upload: update.upload, download: update.download, timestamp });
+
+ if (update.chains.length > 1) {
+ s.ruleProxyInsert.run({ backendId, rule: update.chains[update.chains.length - 1], proxy: update.chains[0] });
+ }
+
+ s.hourlyUpsert.run({ backendId, hour, upload: update.upload, download: update.download });
+ s.minuteUpsert.run({ backendId, minute, upload: update.upload, download: update.download });
+
+ if (domainName !== 'unknown') {
+ s.domainProxyUpsert.run({ backendId, domain: domainName, chain: fullChain, upload: update.upload, download: update.download, timestamp });
+ }
+
+ s.ipProxyUpsert.run({ backendId, ip: update.ip, chain: fullChain, upload: update.upload, download: update.download, timestamp, domain: update.domain || 'unknown' });
});
transaction();
@@ -171,6 +194,18 @@ export class TrafficWriterRepository extends BaseRepository {
const deviceDomainMap = new Map<string, { sourceIP: string; domain: string; upload: number; download: number; count: number }>();
const deviceIPMap = new Map<string, { sourceIP: string; ip: string; upload: number; download: number; count: number }>();
+ // Cache Date→key conversions: many updates share the same timestampMs
+ const timeKeyCache = new Map<number, { hourKey: string; minuteKey: string }>();
+ const getTimeKeys = (tsMs: number) => {
+ let cached = timeKeyCache.get(tsMs);
+ if (!cached) {
+ const d = new Date(tsMs);
+ cached = { hourKey: this.toHourKey(d), minuteKey: this.toMinuteKey(d) };
+ timeKeyCache.set(tsMs, cached);
+ }
+ return cached;
+ };
+
for (const update of updates) {
if (update.upload === 0 && update.download === 0) continue;
@@ -178,9 +213,7 @@ export class TrafficWriterRepository extends BaseRepository {
update.rulePayload ? `${update.rule}(${update.rulePayload})` : update.rule;
const finalProxy = update.chains.length > 0 ? update.chains[0] : 'DIRECT';
const fullChain = update.chains.join(' > ') || update.chain || 'DIRECT';
- const eventDate = new Date(update.timestampMs ?? now.getTime());
- const hourKey = this.toHourKey(eventDate);
- const minuteKey = this.toMinuteKey(eventDate);
+ const { hourKey, minuteKey } = getTimeKeys(update.timestampMs ?? now.getTime());
// Aggregate domain stats
if (update.domain) {
diff --git a/apps/collector/src/database/repositories/traffic-writer.test.ts b/apps/collector/src/database/repositories/traffic-writer.test.ts
new file mode 100644
index 0000000..8d9a132
--- /dev/null
+++ b/apps/collector/src/database/repositories/traffic-writer.test.ts
@@ -0,0 +1,212 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { createTestDatabase, createTestBackend } from '../../__tests__/helpers.js';
+import type { StatsDatabase } from '../../db.js';
+
+describe('TrafficWriterRepository', () => {
+ let db: StatsDatabase;
+ let cleanup: () => void;
+ let backendId: number;
+
+ beforeEach(() => {
+ ({ db, cleanup } = createTestDatabase());
+ backendId = createTestBackend(db);
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ describe('updateTrafficStats (single)', () => {
+ it('should insert domain, IP, proxy, rule, and hourly stats for a single update', () => {
+ db.updateTrafficStats(backendId, {
+ domain: 'example.com',
+ ip: '1.2.3.4',
+ chain: 'ProxyA',
+ chains: ['ProxyA', 'RuleA'],
+ rule: 'DOMAIN-SUFFIX',
+ rulePayload: 'example.com',
+ upload: 100,
+ download: 200,
+ sourceIP: '192.168.1.10',
+ timestampMs: Date.now(),
+ });
+
+ const domains = db.getDomainStats(backendId, 10);
+ expect(domains.length).toBe(1);
+ expect(domains[0].domain).toBe('example.com');
+ expect(domains[0].totalUpload).toBe(100);
+ expect(domains[0].totalDownload).toBe(200);
+
+ const ips = db.getIPStats(backendId, 10);
+ expect(ips.length).toBe(1);
+ expect(ips[0].ip).toBe('1.2.3.4');
+
+ const proxies = db.getProxyStats(backendId);
+ expect(proxies.length).toBeGreaterThanOrEqual(1);
+
+ const rules = db.getRuleStats(backendId);
+ expect(rules.length).toBe(1);
+ });
+
+ it('should skip zero-traffic updates', () => {
+ db.updateTrafficStats(backendId, {
+ domain: 'zero.com',
+ ip: '0.0.0.0',
+ chain: 'DIRECT',
+ chains: ['DIRECT'],
+ rule: 'Match',
+ rulePayload: '',
+ upload: 0,
+ download: 0,
+ });
+
+ const domains = db.getDomainStats(backendId, 10);
+ expect(domains.length).toBe(0);
+ });
+
+ it('should accumulate traffic for the same domain', () => {
+ const base = {
+ domain: 'repeat.com',
+ ip: '1.1.1.1',
+ chain: 'ProxyA',
+ chains: ['ProxyA'],
+ rule: 'Match',
+ rulePayload: '',
+ };
+
+ db.updateTrafficStats(backendId, { ...base, upload: 50, download: 100 });
+ db.updateTrafficStats(backendId, { ...base, upload: 30, download: 70 });
+
+ const domains = db.getDomainStats(backendId, 10);
+ expect(domains.length).toBe(1);
+ expect(domains[0].totalUpload).toBe(80);
+ expect(domains[0].totalDownload).toBe(170);
+ expect(domains[0].totalConnections).toBe(2);
+ });
+ });
+
+ describe('batchUpdateTrafficStats', () => {
+ it('should write all dimensions for a batch of updates', () => {
+ const updates = [
+ {
+ domain: 'a.com',
+ ip: '10.0.0.1',
+ chain: 'ProxyA',
+ chains: ['ProxyA', 'GeoIP'],
+ rule: 'DOMAIN',
+ rulePayload: 'a.com',
+ upload: 100,
+ download: 200,
+ sourceIP: '192.168.1.1',
+ timestampMs: Date.now(),
+ },
+ {
+ domain: 'b.com',
+ ip: '10.0.0.2',
+ chain: 'ProxyB',
+ chains: ['ProxyB', 'Match'],
+ rule: 'Match',
+ rulePayload: '',
+ upload: 50,
+ download: 150,
+ sourceIP: '192.168.1.2',
+ timestampMs: Date.now(),
+ },
+ ];
+
+ db.batchUpdateTrafficStats(backendId, updates);
+
+ // Verify domain stats
+ const domains = db.getDomainStats(backendId, 10);
+ expect(domains.length).toBe(2);
+ const domainNames = domains.map(d => d.domain).sort();
+ expect(domainNames).toEqual(['a.com', 'b.com']);
+
+ // Verify IP stats
+ const ips = db.getIPStats(backendId, 10);
+ expect(ips.length).toBe(2);
+
+ // Verify proxy stats
+ const proxies = db.getProxyStats(backendId);
+ expect(proxies.length).toBeGreaterThanOrEqual(2);
+
+ // Verify device stats
+ const devices = db.getDevices(backendId, 10);
+ expect(devices.length).toBe(2);
+
+ // Verify summary
+ const summary = db.getSummary(backendId);
+ expect(summary.totalUpload).toBe(150);
+ expect(summary.totalDownload).toBe(350);
+ });
+
+ it('should correctly aggregate same-domain updates within a batch', () => {
+ const now = Date.now();
+ const updates = Array.from({ length: 5 }, (_, i) => ({
+ domain: 'same.com',
+ ip: '1.1.1.1',
+ chain: 'ProxyA',
+ chains: ['ProxyA'],
+ rule: 'Match',
+ rulePayload: '',
+ upload: 10,
+ download: 20,
+ sourceIP: '192.168.1.1',
+ timestampMs: now,
+ }));
+
+ db.batchUpdateTrafficStats(backendId, updates);
+
+ const domains = db.getDomainStats(backendId, 10);
+ expect(domains.length).toBe(1);
+ expect(domains[0].totalUpload).toBe(50);
+ expect(domains[0].totalDownload).toBe(100);
+ });
+
+ it('should handle empty batch gracefully', () => {
+ expect(() => db.batchUpdateTrafficStats(backendId, [])).not.toThrow();
+ });
+
+ it('should filter out zero-traffic entries', () => {
+ db.batchUpdateTrafficStats(backendId, [
+ {
+ domain: 'zero.com',
+ ip: '0.0.0.0',
+ chain: 'DIRECT',
+ chains: ['DIRECT'],
+ rule: 'Match',
+ rulePayload: '',
+ upload: 0,
+ download: 0,
+ timestampMs: Date.now(),
+ },
+ ]);
+
+ const summary = db.getSummary(backendId);
+ expect(summary.totalUpload).toBe(0);
+ expect(summary.totalDownload).toBe(0);
+ });
+
+ it('should write minute_stats correctly', () => {
+ const now = Date.now();
+ db.batchUpdateTrafficStats(backendId, [
+ {
+ domain: 'minute.com',
+ ip: '1.1.1.1',
+ chain: 'ProxyA',
+ chains: ['ProxyA'],
+ rule: 'Match',
+ rulePayload: '',
+ upload: 100,
+ download: 200,
+ timestampMs: now,
+ },
+ ]);
+
+ const trend = db.getTrafficTrend(backendId, 60);
+ expect(trend.length).toBeGreaterThanOrEqual(1);
+ const total = trend.reduce((sum, t) => sum + t.upload + t.download, 0);
+ expect(total).toBe(300);
+ });
+ });
+});
diff --git a/apps/collector/src/database/schema.ts b/apps/collector/src/database/schema.ts
index 3c0c30d..25ee0d1 100644
--- a/apps/collector/src/database/schema.ts
+++ b/apps/collector/src/database/schema.ts
@@ -324,6 +324,7 @@ export const SCHEMA = {
name TEXT NOT NULL,
url TEXT NOT NULL,
token TEXT DEFAULT '',
+ type TEXT DEFAULT 'clash',
enabled BOOLEAN DEFAULT 1,
is_active BOOLEAN DEFAULT 0,
listening BOOLEAN DEFAULT 1,
@@ -340,6 +341,29 @@ export const SCHEMA = {
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
`,
+
+ // Surge policy cache
+ SURGE_POLICY_CACHE: `
+ CREATE TABLE IF NOT EXISTS surge_policy_cache (
+ backend_id INTEGER NOT NULL,
+ policy_group TEXT NOT NULL,
+ selected_policy TEXT,
+ policy_type TEXT DEFAULT 'Select',
+ all_policies TEXT,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (backend_id, policy_group),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
+
+ // Auth configuration
+ AUTH_CONFIG: `
+ CREATE TABLE IF NOT EXISTS auth_config (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ `,
} as const;
// Index definitions
@@ -390,6 +414,10 @@ export const INDEXES = [
// Backend configs unique index
`CREATE UNIQUE INDEX IF NOT EXISTS idx_backend_configs_name ON backend_configs(name);`,
+
+ // Surge policy cache indexes
+ `CREATE INDEX IF NOT EXISTS idx_surge_policy_backend ON surge_policy_cache(backend_id);`,
+ `CREATE INDEX IF NOT EXISTS idx_surge_policy_updated ON surge_policy_cache(updated_at);`,
] as const;
// Default app config values
@@ -400,6 +428,13 @@ export const DEFAULT_APP_CONFIG = `
('retention.auto_cleanup', '1');
`;
+// Default auth config values
+export const DEFAULT_AUTH_CONFIG = `
+ INSERT OR IGNORE INTO auth_config (key, value) VALUES
+ ('enabled', '0'),
+ ('token_hash', '');
+`;
+
// Get all schema creation statements in order
export function getAllSchemaStatements(): string[] {
return [
@@ -426,7 +461,10 @@ export function getAllSchemaStatements(): string[] {
SCHEMA.RULE_IP_TRAFFIC,
SCHEMA.BACKEND_CONFIGS,
SCHEMA.APP_CONFIG,
+ SCHEMA.SURGE_POLICY_CACHE,
+ SCHEMA.AUTH_CONFIG,
...INDEXES,
DEFAULT_APP_CONFIG,
+ DEFAULT_AUTH_CONFIG,
];
}
diff --git a/apps/collector/src/db.ts b/apps/collector/src/db.ts
index edfcc54..614e15e 100644
--- a/apps/collector/src/db.ts
+++ b/apps/collector/src/db.ts
@@ -2,6 +2,7 @@ import Database from 'better-sqlite3';
import path from 'path';
import fs from 'fs';
import type { Connection, DomainStats, IPStats, HourlyStats, ProxyStats, RuleStats, ProxyTrafficStats, DeviceStats } from '@neko-master/shared';
+import { getAllSchemaStatements } from './database/schema.js';
import {
AuthRepository,
SurgeRepository,
@@ -47,6 +48,9 @@ export class StatsDatabase {
private db: Database.Database;
private dbPath: string;
+ // Cached prepared statements for getSummary() — avoids re-compilation per call
+ private _summaryStmts: ReturnType<StatsDatabase['prepareSummaryStmts']> | null = null;
+
public readonly repos: {
auth: AuthRepository;
surge: SurgeRepository;
@@ -92,367 +96,10 @@ export class StatsDatabase {
this.db.pragma('cache_size = -16000'); // 16MB page cache
this.db.pragma('busy_timeout = 5000');
- // Domain statistics - aggregated by domain per backend
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS domain_stats (
- backend_id INTEGER NOT NULL,
- domain TEXT NOT NULL,
- ips TEXT,
- total_upload INTEGER DEFAULT 0,
- total_download INTEGER DEFAULT 0,
- total_connections INTEGER DEFAULT 0,
- last_seen DATETIME,
- rules TEXT,
- chains TEXT,
- PRIMARY KEY (backend_id, domain),
- FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
- );
- `);
-
- // IP statistics per backend
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS ip_stats (
- backend_id INTEGER NOT NULL,
- ip TEXT NOT NULL,
- domains TEXT,
- total_upload INTEGER DEFAULT 0,
- total_download INTEGER DEFAULT 0,
- total_connections INTEGER DEFAULT 0,
- last_seen DATETIME,
- asn TEXT,
- geoip TEXT,
- chains TEXT,
- rules TEXT,
- PRIMARY KEY (backend_id, ip),
- FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
- );
- `);
-
- // Proxy/Chain statistics per backend
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS proxy_stats (
- backend_id INTEGER NOT NULL,
- chain TEXT NOT NULL,
- total_upload INTEGER DEFAULT 0,
- total_download INTEGER DEFAULT 0,
- total_connections INTEGER DEFAULT 0,
- last_seen DATETIME,
- PRIMARY KEY (backend_id, chain),
- FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
- );
- `);
-
- // Rule statistics per backend
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS rule_stats (
- backend_id INTEGER NOT NULL,
- rule TEXT NOT NULL,
- final_proxy TEXT,
- total_upload INTEGER DEFAULT 0,
- total_download INTEGER DEFAULT 0,
- total_connections INTEGER DEFAULT 0,
- last_seen DATETIME,
- PRIMARY KEY (backend_id, rule),
- FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
- );
- `);
-
- // Rule to proxy mapping per backend
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS rule_proxy_map (
- backend_id INTEGER NOT NULL,
- rule TEXT,
- proxy TEXT,
- PRIMARY KEY (backend_id, rule, proxy),
- FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
- );
- `);
-
- // ASN cache
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS asn_cache (
- ip TEXT PRIMARY KEY,
- asn TEXT,
- org TEXT,
- queried_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
- `);
-
- // GeoIP cache
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS geoip_cache (
- ip TEXT PRIMARY KEY,
- country TEXT,
- country_name TEXT,
- city TEXT,
- asn TEXT,
- as_name TEXT,
- as_domain TEXT,
- continent TEXT,
- continent_name TEXT,
- queried_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
- `);
-
- // Country traffic statistics per backend
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS country_stats (
- backend_id INTEGER NOT NULL,
- country TEXT NOT NULL,
- country_name TEXT,
- continent TEXT,
- total_upload INTEGER DEFAULT 0,
- total_download INTEGER DEFAULT 0,
- total_connections INTEGER DEFAULT 0,
- last_seen DATETIME,
- PRIMARY KEY (backend_id, country),
- FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
- );
- `);
-
- // Device statistics per backend
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS device_stats (
- backend_id INTEGER NOT NULL,
- source_ip TEXT NOT NULL,
- total_upload INTEGER DEFAULT 0,
- total_download INTEGER DEFAULT 0,
- total_connections INTEGER DEFAULT 0,
- last_seen DATETIME,
- PRIMARY KEY (backend_id, source_ip),
- FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
- );
- `);
-
- // Device×domain traffic aggregation
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS device_domain_stats (
- backend_id INTEGER NOT NULL,
- source_ip TEXT NOT NULL,
- domain TEXT NOT NULL,
- total_upload INTEGER DEFAULT 0,
- total_download INTEGER DEFAULT 0,
- total_connections INTEGER DEFAULT 0,
- last_seen DATETIME,
- PRIMARY KEY (backend_id, source_ip, domain),
- FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
- );
- `);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_device_domain_source_ip ON device_domain_stats(backend_id, source_ip);`);
-
- // Device×IP traffic aggregation
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS device_ip_stats (
- backend_id INTEGER NOT NULL,
- source_ip TEXT NOT NULL,
- ip TEXT NOT NULL,
- total_upload INTEGER DEFAULT 0,
- total_download INTEGER DEFAULT 0,
- total_connections INTEGER DEFAULT 0,
- last_seen DATETIME,
- PRIMARY KEY (backend_id, source_ip, ip),
- FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
- );
- `);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_device_ip_source_ip ON device_ip_stats(backend_id, source_ip);`);
-
- // Hourly aggregation per backend
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS hourly_stats (
- backend_id INTEGER NOT NULL,
- hour TEXT NOT NULL,
- upload INTEGER DEFAULT 0,
- download INTEGER DEFAULT 0,
- connections INTEGER DEFAULT 0,
- PRIMARY KEY (backend_id, hour),
- FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
- );
- `);
-
- // Connection log per backend
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS connection_logs (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- backend_id INTEGER NOT NULL,
- domain TEXT,
- ip TEXT,
- chain TEXT,
- upload INTEGER DEFAULT 0,
- download INTEGER DEFAULT 0,
- timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
- FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
- );
- `);
-
- // Minute-level traffic aggregation (replaces connection_logs for trend queries)
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS minute_stats (
- backend_id INTEGER NOT NULL,
- minute TEXT NOT NULL,
- upload INTEGER DEFAULT 0,
- download INTEGER DEFAULT 0,
- connections INTEGER DEFAULT 0,
- PRIMARY KEY (backend_id, minute),
- FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
- );
- `);
-
- // Minute-level fact table for accurate range queries across domain/ip/rule/proxy/device dimensions
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS minute_dim_stats (
- backend_id INTEGER NOT NULL,
- minute TEXT NOT NULL,
- domain TEXT NOT NULL DEFAULT '',
- ip TEXT NOT NULL DEFAULT '',
- source_ip TEXT NOT NULL DEFAULT '',
- chain TEXT NOT NULL,
- rule TEXT NOT NULL,
- upload INTEGER DEFAULT 0,
- download INTEGER DEFAULT 0,
- connections INTEGER DEFAULT 0,
- PRIMARY KEY (backend_id, minute, domain, ip, source_ip, chain, rule),
- FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
- );
- `);
-
- // Minute-level country facts for range-based country queries
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS minute_country_stats (
- backend_id INTEGER NOT NULL,
- minute TEXT NOT NULL,
- country TEXT NOT NULL,
- country_name TEXT,
- continent TEXT,
- upload INTEGER DEFAULT 0,
- download INTEGER DEFAULT 0,
- connections INTEGER DEFAULT 0,
- PRIMARY KEY (backend_id, minute, country),
- FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
- );
- `);
-
- // Domain×proxy traffic aggregation (replaces connection_logs domain+chain GROUP BY)
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS domain_proxy_stats (
- backend_id INTEGER NOT NULL,
- domain TEXT NOT NULL,
- chain TEXT NOT NULL,
- total_upload INTEGER DEFAULT 0,
- total_download INTEGER DEFAULT 0,
- total_connections INTEGER DEFAULT 0,
- last_seen DATETIME,
- PRIMARY KEY (backend_id, domain, chain),
- FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
- );
- `);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_domain_proxy_chain ON domain_proxy_stats(backend_id, chain);`);
-
- // IP×proxy traffic aggregation (replaces connection_logs ip+chain GROUP BY)
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS ip_proxy_stats (
- backend_id INTEGER NOT NULL,
- ip TEXT NOT NULL,
- chain TEXT NOT NULL,
- total_upload INTEGER DEFAULT 0,
- total_download INTEGER DEFAULT 0,
- total_connections INTEGER DEFAULT 0,
- last_seen DATETIME,
- domains TEXT,
- PRIMARY KEY (backend_id, ip, chain),
- FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
- );
- `);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_ip_proxy_chain ON ip_proxy_stats(backend_id, chain);`);
-
- // Rule-specific cross-reference tables for accurate per-rule traffic
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS rule_chain_traffic (
- backend_id INTEGER NOT NULL,
- rule TEXT NOT NULL,
- chain TEXT NOT NULL,
- total_upload INTEGER DEFAULT 0,
- total_download INTEGER DEFAULT 0,
- total_connections INTEGER DEFAULT 0,
- last_seen DATETIME,
- PRIMARY KEY (backend_id, rule, chain),
- FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
- );
- `);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_rule_chain_traffic ON rule_chain_traffic(backend_id, rule);`);
-
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS rule_domain_traffic (
- backend_id INTEGER NOT NULL,
- rule TEXT NOT NULL,
- domain TEXT NOT NULL,
- total_upload INTEGER DEFAULT 0,
- total_download INTEGER DEFAULT 0,
- total_connections INTEGER DEFAULT 0,
- last_seen DATETIME,
- PRIMARY KEY (backend_id, rule, domain),
- FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
- );
- `);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_rule_domain_traffic ON rule_domain_traffic(backend_id, rule);`);
-
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS rule_ip_traffic (
- backend_id INTEGER NOT NULL,
- rule TEXT NOT NULL,
- ip TEXT NOT NULL,
- total_upload INTEGER DEFAULT 0,
- total_download INTEGER DEFAULT 0,
- total_connections INTEGER DEFAULT 0,
- last_seen DATETIME,
- PRIMARY KEY (backend_id, rule, ip),
- FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
- );
- `);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_rule_ip_traffic ON rule_ip_traffic(backend_id, rule);`);
-
- // Create indexes
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_domain_stats_backend ON domain_stats(backend_id);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_domain_stats_traffic ON domain_stats(total_download + total_upload);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_ip_stats_backend ON ip_stats(backend_id);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_ip_stats_traffic ON ip_stats(total_download + total_upload);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_proxy_stats_backend ON proxy_stats(backend_id);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_proxy_stats_traffic ON proxy_stats(total_download + total_upload);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_rule_stats_backend ON rule_stats(backend_id);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_rule_stats_traffic ON rule_stats(total_download + total_upload);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_rule_proxy_map ON rule_proxy_map(backend_id, rule, proxy);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_country_stats_backend ON country_stats(backend_id);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_hourly_stats_backend ON hourly_stats(backend_id);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_minute_stats_backend_minute ON minute_stats(backend_id, minute);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_minute_dim_backend_minute ON minute_dim_stats(backend_id, minute);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_minute_dim_backend_minute_domain ON minute_dim_stats(backend_id, minute, domain);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_minute_dim_backend_minute_ip ON minute_dim_stats(backend_id, minute, ip);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_minute_dim_backend_minute_chain ON minute_dim_stats(backend_id, minute, chain);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_minute_dim_backend_minute_rule ON minute_dim_stats(backend_id, minute, rule);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_minute_dim_backend_minute_source ON minute_dim_stats(backend_id, minute, source_ip);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_minute_country_backend_minute ON minute_country_stats(backend_id, minute);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_connection_logs_backend ON connection_logs(backend_id);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_connection_logs_timestamp ON connection_logs(timestamp);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_connection_logs_domain ON connection_logs(domain);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_connection_logs_chain ON connection_logs(chain);`);
-
- // Backend configurations - stores Gateway backend connections
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS backend_configs (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- name TEXT NOT NULL,
- url TEXT NOT NULL,
- token TEXT DEFAULT '',
- type TEXT DEFAULT 'clash',
- enabled BOOLEAN DEFAULT 1,
- is_active BOOLEAN DEFAULT 0,
- listening BOOLEAN DEFAULT 1,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
- updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
- `);
-
- // Create unique index on name
- this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_backend_configs_name ON backend_configs(name);`);
+ // Apply all schema statements from the single source of truth
+ for (const stmt of getAllSchemaStatements()) {
+ this.db.exec(stmt);
+ }
// Migration: Add type column if not exists (for older databases)
try {
@@ -462,55 +109,6 @@ export class StatsDatabase {
// Column already exists, ignore
}
- // App configuration - stores app-level settings like retention policy
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS app_config (
- key TEXT PRIMARY KEY,
- value TEXT NOT NULL,
- updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
- `);
-
- // Insert default retention config if not exists
- this.db.exec(`
- INSERT OR IGNORE INTO app_config (key, value) VALUES
- ('retention.connection_logs_days', '7'),
- ('retention.hourly_stats_days', '30'),
- ('retention.auto_cleanup', '1');
- `);
-
- // Surge policy cache - stores Surge policy group selections
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS surge_policy_cache (
- backend_id INTEGER NOT NULL,
- policy_group TEXT NOT NULL,
- selected_policy TEXT,
- policy_type TEXT DEFAULT 'Select',
- all_policies TEXT,
- updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (backend_id, policy_group),
- FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
- );
- `);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_surge_policy_backend ON surge_policy_cache(backend_id);`);
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_surge_policy_updated ON surge_policy_cache(updated_at);`);
-
- // Auth configuration table - stores authentication settings
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS auth_config (
- key TEXT PRIMARY KEY,
- value TEXT NOT NULL,
- updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
- );
- `);
-
- // Insert default auth config if not exists
- this.db.exec(`
- INSERT OR IGNORE INTO auth_config (key, value) VALUES
- ('enabled', '0'),
- ('token_hash', '');
- `);
-
// Migrate existing data if needed (from single-backend schema)
this.migrateIfNeeded();
}
@@ -927,6 +525,31 @@ export class StatsDatabase {
return { startMinute: this.toMinuteKey(startDate), endMinute: this.toMinuteKey(endDate) };
}
+ private prepareSummaryStmts() {
+ return {
+ rangeTraffic: this.db.prepare(`
+ SELECT
+ COALESCE(SUM(connections), 0) as connections,
+ COALESCE(SUM(upload), 0) as upload,
+ COALESCE(SUM(download), 0) as download
+ FROM minute_dim_stats
+ WHERE backend_id = ? AND minute >= ? AND minute <= ?
+ `),
+ rangeDomains: this.db.prepare(`SELECT COUNT(DISTINCT domain) as count FROM minute_dim_stats WHERE backend_id = ? AND minute >= ? AND minute <= ? AND domain != ''`),
+ rangeIPs: this.db.prepare(`SELECT COUNT(DISTINCT ip) as count FROM minute_dim_stats WHERE backend_id = ? AND minute >= ? AND minute <= ? AND ip != ''`),
+ allTraffic: this.db.prepare(`SELECT COALESCE(SUM(total_connections), 0) as connections, COALESCE(SUM(total_upload), 0) as upload, COALESCE(SUM(total_download), 0) as download FROM ip_stats WHERE backend_id = ?`),
+ allDomains: this.db.prepare(`SELECT COUNT(DISTINCT domain) as count FROM domain_stats WHERE backend_id = ?`),
+ allIPs: this.db.prepare(`SELECT COUNT(DISTINCT ip) as count FROM ip_stats WHERE backend_id = ?`),
+ };
+ }
+
+ private get summaryStmts() {
+ if (!this._summaryStmts) {
+ this._summaryStmts = this.prepareSummaryStmts();
+ }
+ return this._summaryStmts;
+ }
+
// ==================== Summary (kept in db.ts - cross-table aggregation) ====================
getSummary(
backendId: number,
@@ -934,29 +557,24 @@ export class StatsDatabase {
end?: string,
): { totalConnections: number; totalUpload: number; totalDownload: number; uniqueDomains: number; uniqueIPs: number } {
const range = this.parseMinuteRange(start, end);
+ const s = this.summaryStmts;
if (range) {
- const trafficStmt = this.db.prepare(`
- SELECT
- COALESCE(SUM(connections), 0) as connections,
- COALESCE(SUM(upload), 0) as upload,
- COALESCE(SUM(download), 0) as download
- FROM minute_dim_stats
- WHERE backend_id = ? AND minute >= ? AND minute <= ?
- `);
- const { connections, upload, download } = trafficStmt.get(backendId, range.startMinute, range.endMinute) as { connections: number; upload: number; download: number };
- const uniqueDomains = (this.db.prepare(`SELECT COUNT(DISTINCT domain) as count FROM minute_dim_stats WHERE backend_id = ? AND minute >= ? AND minute <= ? AND domain != ''`).get(backendId, range.startMinute, range.endMinute) as { count: number }).count;
- const uniqueIPs = (this.db.prepare(`SELECT COUNT(DISTINCT ip) as count FROM minute_dim_stats WHERE backend_id = ? AND minute >= ? AND minute <= ? AND ip != ''`).get(backendId, range.startMinute, range.endMinute) as { count: number }).count;
+ const { connections, upload, download } = s.rangeTraffic.get(backendId, range.startMinute, range.endMinute) as { connections: number; upload: number; download: number };
+ const uniqueDomains = (s.rangeDomains.get(backendId, range.startMinute, range.endMinute) as { count: number }).count;
+ const uniqueIPs = (s.rangeIPs.get(backendId, range.startMinute, range.endMinute) as { count: number }).count;
return { totalConnections: connections, totalUpload: upload, totalDownload: download, uniqueDomains, uniqueIPs };
}
- const { connections, upload, download } = this.db.prepare(`SELECT COALESCE(SUM(total_connections), 0) as connections, COALESCE(SUM(total_upload), 0) as upload, COALESCE(SUM(total_download), 0) as download FROM ip_stats WHERE backend_id = ?`).get(backendId) as { connections: number; upload: number; download: number };
- const uniqueDomains = (this.db.prepare(`SELECT COUNT(DISTINCT domain) as count FROM domain_stats WHERE backend_id = ?`).get(backendId) as { count: number }).count;
- const uniqueIPs = (this.db.prepare(`SELECT COUNT(DISTINCT ip) as count FROM ip_stats WHERE backend_id = ?`).get(backendId) as { count: number }).count;
+ const { connections, upload, download } = s.allTraffic.get(backendId) as { connections: number; upload: number; download: number };
+ const uniqueDomains = (s.allDomains.get(backendId) as { count: number }).count;
+ const uniqueIPs = (s.allIPs.get(backendId) as { count: number }).count;
return { totalConnections: connections, totalUpload: upload, totalDownload: download, uniqueDomains, uniqueIPs };
}
- // Get recent connections for a specific backend
- // Returns empty array - connection_logs is no longer written to (replaced by aggregation tables)
- getRecentConnections(backendId: number, limit = 100): Connection[] {
+ /**
+ * @deprecated connection_logs is no longer written to (replaced by aggregation tables).
+ * Kept for API backward compatibility — always returns [].
+ */
+ getRecentConnections(backendId: number, _limit = 100): Connection[] {
return [];
}
diff --git a/apps/collector/src/geo-service.ts b/apps/collector/src/geo-service.ts
index 3bdfa2c..9418ff4 100644
--- a/apps/collector/src/geo-service.ts
+++ b/apps/collector/src/geo-service.ts
@@ -16,6 +16,7 @@ export class GeoIPService {
private pendingQueries: Map<string, Promise<GeoLocation | null>> = new Map();
private failedIPs: Map<string, number> = new Map(); // IP -> failure timestamp
private lastRequestTime: number = 0;
+ private lastFailedIPsCleanup: number = 0;
private minRequestInterval: number = 100; // Minimum 100ms between requests
private queue: {
ip: string;
@@ -28,6 +29,8 @@ export class GeoIPService {
private static FAIL_COOLDOWN_MS = 30 * 60 * 1000;
// Maximum queue size to prevent unbounded memory growth
private static MAX_QUEUE_SIZE = 100;
+ // Sweep expired failedIPs entries every 10 minutes
+ private static FAILED_IPS_CLEANUP_INTERVAL_MS = 10 * 60 * 1000;
constructor(db: StatsDatabase) {
this.db = db;
@@ -127,6 +130,8 @@ export class GeoIPService {
item.resolve(null);
} finally {
this.isProcessing = false;
+ // Periodically sweep expired failedIPs to prevent unbounded growth
+ this.cleanupFailedIPs();
// Continue processing if more items in queue
if (this.queue.length > 0) {
this.scheduleProcessing();
@@ -134,6 +139,22 @@ export class GeoIPService {
}
}
+ private cleanupFailedIPs() {
+ const now = Date.now();
+ if (now - this.lastFailedIPsCleanup < GeoIPService.FAILED_IPS_CLEANUP_INTERVAL_MS) return;
+ this.lastFailedIPsCleanup = now;
+ let cleaned = 0;
+ for (const [ip, failedAt] of this.failedIPs) {
+ if (now - failedAt > GeoIPService.FAIL_COOLDOWN_MS) {
+ this.failedIPs.delete(ip);
+ cleaned++;
+ }
+ }
+ if (cleaned > 0) {
+ console.log(`[GeoIP] Cleaned ${cleaned} expired failed-IP entries`);
+ }
+ }
+
// Query the API
private async queryAPI(ip: string): Promise<GeoLocation | null> {
try {
diff --git a/apps/collector/src/modules/auth/auth.service.test.ts b/apps/collector/src/modules/auth/auth.service.test.ts
new file mode 100644
index 0000000..c1a808f
--- /dev/null
+++ b/apps/collector/src/modules/auth/auth.service.test.ts
@@ -0,0 +1,92 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { createTestDatabase, createTestBackend } from '../../__tests__/helpers.js';
+import { AuthService } from './auth.service.js';
+import type { StatsDatabase } from '../../db.js';
+
+describe('AuthService', () => {
+ let db: StatsDatabase;
+ let cleanup: () => void;
+ let authService: AuthService;
+
+ beforeEach(() => {
+ ({ db, cleanup } = createTestDatabase());
+ createTestBackend(db);
+ authService = new AuthService(db);
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ describe('getAuthState', () => {
+ it('should return disabled state by default', () => {
+ const state = authService.getAuthState();
+ expect(state.enabled).toBe(false);
+ expect(state.hasToken).toBe(false);
+ });
+ });
+
+ describe('enableAuth / verifyToken', () => {
+ it('should enable auth and verify correct token', async () => {
+ await authService.enableAuth('test123abc');
+
+ expect(authService.isAuthRequired()).toBe(true);
+
+ const result = await authService.verifyToken('test123abc');
+ expect(result.valid).toBe(true);
+ });
+
+ it('should reject incorrect token', async () => {
+ await authService.enableAuth('correct1');
+
+ const result = await authService.verifyToken('wrong-token-1');
+ expect(result.valid).toBe(false);
+ });
+ });
+
+ describe('disableAuth', () => {
+ it('should disable auth and allow all requests', async () => {
+ await authService.enableAuth('myToken1');
+ expect(authService.isAuthRequired()).toBe(true);
+
+ authService.disableAuth();
+ expect(authService.isAuthRequired()).toBe(false);
+
+ // Token verification should succeed when auth is disabled
+ const result = await authService.verifyToken('anything');
+ expect(result.valid).toBe(true);
+ });
+ });
+
+ describe('isValidTokenFormat', () => {
+ it('should reject tokens shorter than 6 characters', () => {
+ expect(authService.isValidTokenFormat('ab1')).toBe(false);
+ });
+
+ it('should reject purely numeric tokens', () => {
+ expect(authService.isValidTokenFormat('123456')).toBe(false);
+ });
+
+ it('should reject purely alphabetic tokens', () => {
+ expect(authService.isValidTokenFormat('abcdef')).toBe(false);
+ });
+
+ it('should accept valid mixed tokens', () => {
+ expect(authService.isValidTokenFormat('abc123')).toBe(true);
+ expect(authService.isValidTokenFormat('MyP4ssw0rd')).toBe(true);
+ });
+ });
+
+ describe('updateToken', () => {
+ it('should update token and verify new one', async () => {
+ await authService.enableAuth('oldToken1');
+ await authService.updateToken('newToken2');
+
+ const oldResult = await authService.verifyToken('oldToken1');
+ expect(oldResult.valid).toBe(false);
+
+ const newResult = await authService.verifyToken('newToken2');
+ expect(newResult.valid).toBe(true);
+ });
+ });
+});
diff --git a/apps/collector/src/modules/backend/backend.service.ts b/apps/collector/src/modules/backend/backend.service.ts
index 4c49c4a..b5c217d 100644
--- a/apps/collector/src/modules/backend/backend.service.ts
+++ b/apps/collector/src/modules/backend/backend.service.ts
@@ -30,7 +30,7 @@ function maskUrl(url: string): string {
} catch {
// If URL parsing fails, use regex fallback
// This regex handles: protocol://[anything-until-slash-or-end]
- return url.replace(/:\/\/[^\/]+/, '://******');
+ return url.replace(/:(\/\/)[^/]+/, '://******');
}
}
diff --git a/apps/collector/src/modules/stats/stats.controller.ts b/apps/collector/src/modules/stats/stats.controller.ts
index 4124c5e..ac7e949 100644
--- a/apps/collector/src/modules/stats/stats.controller.ts
+++ b/apps/collector/src/modules/stats/stats.controller.ts
@@ -29,7 +29,7 @@ function getBackendId(request: FastifyRequest, service: StatsService): number |
// Helper function to parse time range
function getTimeRange(request: FastifyRequest, reply: FastifyReply, isShowcaseMode = false): TimeRange | null {
const query = request.query as Record<string, string | undefined>;
- let { start, end } = query;
+ const { start, end } = query;
if (isShowcaseMode) {
// In showcase mode, we clamp the start time to be no older than 24 hours ago
diff --git a/apps/collector/src/modules/stats/stats.service.test.ts b/apps/collector/src/modules/stats/stats.service.test.ts
new file mode 100644
index 0000000..5cdaeb2
--- /dev/null
+++ b/apps/collector/src/modules/stats/stats.service.test.ts
@@ -0,0 +1,175 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { createTestDatabase, createTestBackend } from '../../__tests__/helpers.js';
+import { StatsService } from './stats.service.js';
+import { realtimeStore } from '../../realtime.js';
+import type { StatsDatabase } from '../../db.js';
+
+describe('StatsService', () => {
+ let db: StatsDatabase;
+ let cleanup: () => void;
+ let backendId: number;
+ let service: StatsService;
+
+ beforeEach(() => {
+ ({ db, cleanup } = createTestDatabase());
+ backendId = createTestBackend(db);
+ service = new StatsService(db, realtimeStore);
+ });
+
+ afterEach(() => {
+ realtimeStore.clearBackend(backendId);
+ cleanup();
+ });
+
+ function seedTraffic() {
+ db.batchUpdateTrafficStats(backendId, [
+ {
+ domain: 'google.com',
+ ip: '142.250.80.46',
+ chain: 'ProxyUS',
+ chains: ['ProxyUS', 'GeoIP'],
+ rule: 'DOMAIN-SUFFIX',
+ rulePayload: 'google.com',
+ upload: 500,
+ download: 3000,
+ sourceIP: '192.168.1.10',
+ timestampMs: Date.now(),
+ },
+ {
+ domain: 'github.com',
+ ip: '140.82.121.3',
+ chain: 'ProxyUS',
+ chains: ['ProxyUS', 'GeoIP'],
+ rule: 'DOMAIN-SUFFIX',
+ rulePayload: 'github.com',
+ upload: 200,
+ download: 1500,
+ sourceIP: '192.168.1.10',
+ timestampMs: Date.now(),
+ },
+ {
+ domain: 'baidu.com',
+ ip: '39.156.66.10',
+ chain: 'DIRECT',
+ chains: ['DIRECT'],
+ rule: 'Match',
+ rulePayload: '',
+ upload: 100,
+ download: 800,
+ sourceIP: '192.168.1.20',
+ timestampMs: Date.now(),
+ },
+ ]);
+ }
+
+ describe('resolveBackendId', () => {
+ it('should return active backend when no ID specified', () => {
+ const id = service.resolveBackendId();
+ expect(id).toBe(backendId);
+ });
+
+ it('should parse string backend ID', () => {
+ const id = service.resolveBackendId(String(backendId));
+ expect(id).toBe(backendId);
+ });
+
+ it('should return null for invalid ID', () => {
+ expect(service.resolveBackendId('abc')).toBeNull();
+ });
+ });
+
+ describe('getSummary', () => {
+ it('should return correct totals', () => {
+ seedTraffic();
+
+ const result = service.getSummary(backendId, { active: false });
+ expect(result.totalUpload).toBe(800);
+ expect(result.totalDownload).toBe(5300);
+ expect(result.totalDomains).toBe(3);
+ expect(result.totalIPs).toBe(3);
+ expect(result.backend.id).toBe(backendId);
+ });
+
+ it('should return empty summary for non-existent backend', () => {
+ expect(() => service.getSummary(99999, { active: false })).toThrow('Backend not found');
+ });
+ });
+
+ describe('getDomainStatsPaginated', () => {
+ it('should return paginated results', () => {
+ seedTraffic();
+
+ const result = service.getDomainStatsPaginated(backendId, { active: false }, {
+ offset: 0,
+ limit: 2,
+ sortBy: 'totalDownload',
+ sortOrder: 'desc',
+ });
+
+ expect(result.data.length).toBeLessThanOrEqual(2);
+ expect(result.total).toBe(3);
+ // Should be sorted by download desc
+ if (result.data.length >= 2) {
+ expect(result.data[0].totalDownload).toBeGreaterThanOrEqual(result.data[1].totalDownload);
+ }
+ });
+
+ it('should support search', () => {
+ seedTraffic();
+
+ const result = service.getDomainStatsPaginated(backendId, { active: false }, {
+ offset: 0,
+ limit: 10,
+ search: 'google',
+ });
+
+ expect(result.data.length).toBe(1);
+ expect(result.data[0].domain).toBe('google.com');
+ });
+ });
+
+ describe('getProxyStats', () => {
+ it('should return proxy stats grouped by chain', () => {
+ seedTraffic();
+
+ const proxies = service.getProxyStats(backendId, { active: false });
+ expect(proxies.length).toBeGreaterThanOrEqual(1);
+ const proxyNames = proxies.map(p => p.chain);
+ expect(proxyNames).toContain('DIRECT');
+ });
+ });
+
+ describe('getDeviceStats', () => {
+ it('should return device stats with source IPs', () => {
+ seedTraffic();
+
+ const devices = service.getDeviceStats(backendId, { active: false }, 10);
+ expect(devices.length).toBe(2);
+ const ips = devices.map(d => d.sourceIP).sort();
+ expect(ips).toEqual(['192.168.1.10', '192.168.1.20']);
+ });
+ });
+
+ describe('shouldIncludeRealtime', () => {
+ it('should return true when no time range is active', () => {
+ expect(service.shouldIncludeRealtime({ active: false })).toBe(true);
+ });
+
+ it('should return true when end is close to now', () => {
+ const now = new Date();
+ expect(service.shouldIncludeRealtime({
+ active: true,
+ start: new Date(now.getTime() - 3600000).toISOString(),
+ end: now.toISOString(),
+ })).toBe(true);
+ });
+
+ it('should return false when end is far in the past', () => {
+ expect(service.shouldIncludeRealtime({
+ active: true,
+ start: '2020-01-01T00:00:00Z',
+ end: '2020-01-02T00:00:00Z',
+ })).toBe(false);
+ });
+ });
+});
diff --git a/apps/collector/src/realtime.ts b/apps/collector/src/realtime.ts
index 2bd36e0..791f203 100644
--- a/apps/collector/src/realtime.ts
+++ b/apps/collector/src/realtime.ts
@@ -219,6 +219,11 @@ export class RealtimeStore {
private countryByBackend = new Map<number, Map<string, CountryDelta>>();
private maxMinutes: number;
+ // Memory bounds: max entries per map before eviction of smallest-traffic entries
+ private static readonly MAX_DOMAIN_ENTRIES = 50_000;
+ private static readonly MAX_IP_ENTRIES = 50_000;
+ private static readonly MAX_DEVICE_DETAIL_ENTRIES = 10_000;
+
constructor(maxMinutes = parseInt(process.env.REALTIME_MAX_MINUTES || '180', 10)) {
this.maxMinutes = Number.isFinite(maxMinutes) ? Math.max(30, maxMinutes) : 180;
}
@@ -1305,6 +1310,55 @@ export class RealtimeStore {
}
}
}
+
+ /**
+ * Evict lowest-traffic entries when a map exceeds its size cap.
+ * Removes the bottom ~25% by total traffic to avoid frequent evictions.
+ */
+ private evictIfNeeded<T extends { totalUpload: number; totalDownload: number }>(
+ map: Map<string, T>,
+ maxEntries: number,
+ ): void {
+ if (map.size <= maxEntries) return;
+
+ const entries = Array.from(map.entries());
+ entries.sort((a, b) =>
+ (a[1].totalUpload + a[1].totalDownload) - (b[1].totalUpload + b[1].totalDownload)
+ );
+
+ // Remove bottom 25%
+ const removeCount = Math.ceil(entries.length * 0.25);
+ for (let i = 0; i < removeCount; i++) {
+ map.delete(entries[i][0]);
+ }
+ }
+
+ /**
+ * Run periodic memory bounds check on all realtime maps.
+ * Called after recordTraffic accumulates data.
+ */
+ pruneIfNeeded(backendId: number): void {
+ const domainMap = this.domainByBackend.get(backendId);
+ if (domainMap) this.evictIfNeeded(domainMap, RealtimeStore.MAX_DOMAIN_ENTRIES);
+
+ const ipMap = this.ipByBackend.get(backendId);
+ if (ipMap) this.evictIfNeeded(ipMap, RealtimeStore.MAX_IP_ENTRIES);
+
+ // Device detail maps (per source IP × domain/IP) can be deeply nested
+ const deviceDomainMap = this.deviceDomainByBackend.get(backendId);
+ if (deviceDomainMap) {
+ for (const [, subMap] of deviceDomainMap) {
+ this.evictIfNeeded(subMap, RealtimeStore.MAX_DEVICE_DETAIL_ENTRIES);
+ }
+ }
+
+ const deviceIPMap = this.deviceIPByBackend.get(backendId);
+ if (deviceIPMap) {
+ for (const [, subMap] of deviceIPMap) {
+ this.evictIfNeeded(subMap, RealtimeStore.MAX_DEVICE_DETAIL_ENTRIES);
+ }
+ }
+ }
}
export const realtimeStore = new RealtimeStore();
diff --git a/apps/collector/src/surge-collector.ts b/apps/collector/src/surge-collector.ts
index e9ac44b..306c452 100644
--- a/apps/collector/src/surge-collector.ts
+++ b/apps/collector/src/surge-collector.ts
@@ -4,6 +4,7 @@ import { GeoIPService } from "./geo-service.js";
import { realtimeStore } from "./realtime.js";
import type { SurgeRequest, SurgeRequestsData } from "@neko-master/shared";
import { calculateBackoffDelay } from "./utils.js";
+import { BatchBuffer } from "./batch-buffer.js";
// Debug configuration
const DEBUG_SURGE = process.env.DEBUG_SURGE === "true";
@@ -18,36 +19,6 @@ interface SurgeCollectorOptions {
onError?: (error: Error) => void;
}
-interface TrafficUpdate {
- domain: string;
- ip: string;
- chain: string;
- chains: string[];
- rule: string;
- rulePayload: string;
- upload: number;
- download: number;
- sourceIP?: string;
- timestampMs?: number;
-}
-
-interface GeoIPResult {
- ip: string;
- geo: {
- country: string;
- country_name: string;
- continent: string;
- } | null;
- upload: number;
- download: number;
- timestampMs?: number;
-}
-
-function toMinuteKey(timestampMs?: number): string {
- const date = new Date(timestampMs ?? Date.now()).toISOString();
- return `${date.slice(0, 16)}:00`;
-}
-
export class SurgeCollector {
private url: string;
private token?: string;
@@ -182,147 +153,6 @@ export class SurgeCollector {
}
}
-// Batch buffer for traffic updates
-class BatchBuffer {
- private buffer: Map<string, TrafficUpdate> = new Map();
- private geoQueue: GeoIPResult[] = [];
- private lastLogTime = 0;
- private logCounter = 0;
-
- add(backendId: number, update: TrafficUpdate) {
- const minuteKey = toMinuteKey(update.timestampMs);
- const fullChain = update.chains.join(" > ");
- const key = [
- backendId,
- minuteKey,
- update.domain,
- update.ip,
- update.chain,
- fullChain,
- update.rule,
- update.rulePayload,
- update.sourceIP || "",
- ].join(":");
- const existing = this.buffer.get(key);
-
- if (existing) {
- existing.upload += update.upload;
- existing.download += update.download;
- if ((update.timestampMs ?? 0) > (existing.timestampMs ?? 0)) {
- existing.timestampMs = update.timestampMs;
- }
- } else {
- this.buffer.set(key, { ...update });
- }
- }
-
- addGeoResult(result: GeoIPResult) {
- this.geoQueue.push(result);
- }
-
- size(): number {
- return this.buffer.size;
- }
-
- hasPending(): boolean {
- return this.buffer.size > 0 || this.geoQueue.length > 0;
- }
-
- flush(
- db: StatsDatabase,
- _geoService: GeoIPService | undefined,
- backendId: number
- ): {
- domains: number;
- rules: number;
- trafficOk: boolean;
- countryOk: boolean;
- hasUpdates: boolean;
- } {
- const updates = Array.from(this.buffer.values());
- const geoResults = [...this.geoQueue];
-
- // Calculate unique domains and rules for logging
- const domains = new Set<string>();
- const rules = new Set<string>();
-
- for (const update of updates) {
- if (update.domain) domains.add(update.domain);
- const initialRule =
- update.chains.length > 0
- ? update.chains[update.chains.length - 1]
- : "DIRECT";
- rules.add(initialRule);
- }
-
- let trafficOk = true;
- let countryOk = true;
-
- if (updates.length > 0) {
- try {
- db.batchUpdateTrafficStats(backendId, updates);
- } catch (err) {
- trafficOk = false;
- console.error(`[SurgeCollector:${backendId}] Batch write failed:`, err);
- }
- }
-
- if (trafficOk) {
- this.buffer.clear();
- }
-
- if (geoResults.length > 0) {
- try {
- const countryUpdates = geoResults
- .filter(
- (r): r is GeoIPResult & { geo: NonNullable<GeoIPResult["geo"]> } =>
- r.geo !== null
- )
- .map((r) => ({
- country: r.geo.country,
- countryName: r.geo.country_name,
- continent: r.geo.continent,
- upload: r.upload,
- download: r.download,
- timestampMs: r.timestampMs,
- }));
- db.batchUpdateCountryStats(backendId, countryUpdates);
- } catch (err) {
- countryOk = false;
- console.error(
- `[SurgeCollector:${backendId}] Country batch write failed:`,
- err
- );
- }
- }
-
- if (countryOk) {
- this.geoQueue = [];
- }
-
- return {
- domains: domains.size,
- rules: rules.size,
- trafficOk,
- countryOk,
- hasUpdates: updates.length > 0 || geoResults.length > 0,
- };
- }
-
- shouldLog(): boolean {
- const now = Date.now();
- if (now - this.lastLogTime > 10000) {
- this.lastLogTime = now;
- return true;
- }
- return false;
- }
-
- incrementLogCounter(): number {
- return ++this.logCounter;
- }
-}
-
// Track request state with their accumulated traffic
interface TrackedRequest {
id: string;
@@ -432,6 +262,8 @@ export function createSurgeCollector(
process.env.FLUSH_MAX_BUFFER_SIZE || "5000"
);
let isFlushing = false;
+ let lastPruneTime = 0;
+ const PRUNE_INTERVAL_MS = 60_000;
let newConnectionsCount = 0;
let completedConnectionsCount = 0;
@@ -467,7 +299,7 @@ export function createSurgeCollector(
isFlushing = true;
try {
- const stats = batchBuffer.flush(db, geoService, id);
+ const stats = batchBuffer.flush(db, geoService, id, "SurgeCollector");
if (stats.trafficOk) {
realtimeStore.clearTraffic(id);
@@ -487,6 +319,13 @@ export function createSurgeCollector(
} finally {
isFlushing = false;
}
+
+ // Periodic memory bounds check on realtime store
+ const pruneNow = Date.now();
+ if (pruneNow - lastPruneTime > PRUNE_INTERVAL_MS) {
+ lastPruneTime = pruneNow;
+ realtimeStore.pruneIfNeeded(id);
+ }
};
flushInterval = setInterval(() => {
@@ -930,7 +769,7 @@ function isDomain(host: string): boolean {
// Remove port if present
const hostWithoutPort = extractHost(host);
if (isIP(hostWithoutPort)) return false;
- return /^[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*$/.test(
+ return /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(
hostWithoutPort
);
}
diff --git a/apps/collector/src/websocket.ts b/apps/collector/src/websocket.ts
index 1813d66..7af05c7 100644
--- a/apps/collector/src/websocket.ts
+++ b/apps/collector/src/websocket.ts
@@ -1,5 +1,5 @@
import { WebSocketServer as WSServer, WebSocket } from 'ws';
-import type { StatsSummary } from '@neko-master/shared';
+import type { StatsSummary, DomainStats, IPStats, ProxyStats, CountryStats, DeviceStats, RuleStats, HourlyStats } from '@neko-master/shared';
import type { StatsDatabase } from './db.js';
import { realtimeStore } from './realtime.js';
import { AuthService } from './modules/auth/auth.service.js';
@@ -108,14 +108,14 @@ export class StatsWebSocketServer {
// Cache for expensive full-summary queries: avoids re-querying all 8 base tables
// when multiple broadcasts fire within a short window.
private baseSummaryCache = new Map<string, {
- summary: any;
- topDomains: any;
- topIPs: any;
- proxyStats: any;
- countryStats: any;
- deviceStats: any;
- ruleStats: any;
- hourlyStats: any;
+ summary: { totalConnections: number; totalUpload: number; totalDownload: number; uniqueDomains: number; uniqueIPs: number };
+ topDomains: DomainStats[];
+ topIPs: IPStats[];
+ proxyStats: ProxyStats[];
+ countryStats: CountryStats[];
+ deviceStats: DeviceStats[];
+ ruleStats: RuleStats[];
+ hourlyStats: HourlyStats[];
ts: number;
}>();
private static BASE_SUMMARY_CACHE_TTL_MS = 2000;
@@ -699,7 +699,7 @@ export class StatsWebSocketServer {
// Use cached base summary data to avoid repeated expensive DB queries
const baseCacheKey = `${resolvedBackendId}|${range.start || ''}|${range.end || ''}`;
- let baseCached = this.baseSummaryCache.get(baseCacheKey);
+ const baseCached = this.baseSummaryCache.get(baseCacheKey);
const baseCacheValid = baseCached && Date.now() - baseCached.ts < StatsWebSocketServer.BASE_SUMMARY_CACHE_TTL_MS;
const dbTopDomains = wantsFullSummary
@@ -1015,6 +1015,7 @@ export class StatsWebSocketServer {
data: stats,
timestamp: new Date().toISOString(),
};
+ // Pre-serialize to avoid repeated JSON.stringify if same payload is reused
ws.send(JSON.stringify(message));
clientInfo.lastSentAt = Date.now();
} catch (err) {
@@ -1033,11 +1034,13 @@ export class StatsWebSocketServer {
if (this.clients.size === 0) return;
- try {
- let sentCount = 0;
- const statsCache = new Map<string, StatsSummary | null>();
+ let sentCount = 0;
+ // Cache serialized JSON per unique query combo to avoid repeated JSON.stringify
+ const jsonCache = new Map<string, string | null>();
+ const ts = new Date().toISOString();
- for (const [ws, clientInfo] of this.clients) {
+ for (const [ws, clientInfo] of this.clients) {
+ try {
if (ws.readyState !== WebSocket.OPEN) continue;
if (!force && clientInfo.minPushIntervalMs > 0) {
@@ -1074,41 +1077,38 @@ export class StatsWebSocketServer {
? `${clientInfo.ipsPage.offset}|${clientInfo.ipsPage.limit}|${clientInfo.ipsPage.sortBy || ''}|${clientInfo.ipsPage.sortOrder || ''}|${clientInfo.ipsPage.search || ''}`
: '';
const cacheKey = `${resolvedBackendId}|${clientInfo.range.start || ''}|${clientInfo.range.end || ''}|${trendKey}|${deviceDetailKey}|${proxyDetailKey}|${ruleDetailKey}|${ruleChainFlowKey}|${domainsPageKey}|${ipsPageKey}`;
- if (!statsCache.has(cacheKey)) {
- statsCache.set(
+ if (!jsonCache.has(cacheKey)) {
+ const stats = this.getStatsForBackend(
+ resolvedBackendId,
+ clientInfo.range,
+ clientInfo.trend,
+ clientInfo.deviceDetail,
+ clientInfo.proxyDetail,
+ clientInfo.ruleDetail,
+ clientInfo.includeRuleChainFlow,
+ clientInfo.domainsPage,
+ clientInfo.ipsPage,
+ );
+ // Serialize once per unique query; reuse for all clients with same params
+ jsonCache.set(
cacheKey,
- this.getStatsForBackend(
- resolvedBackendId,
- clientInfo.range,
- clientInfo.trend,
- clientInfo.deviceDetail,
- clientInfo.proxyDetail,
- clientInfo.ruleDetail,
- clientInfo.includeRuleChainFlow,
- clientInfo.domainsPage,
- clientInfo.ipsPage,
- ),
+ stats ? JSON.stringify({ type: 'stats', data: stats, timestamp: ts }) : null,
);
}
- const stats = statsCache.get(cacheKey);
- if (!stats) continue;
+ const json = jsonCache.get(cacheKey);
+ if (!json) continue;
- const message: WebSocketMessage = {
- type: 'stats',
- data: stats,
- timestamp: new Date().toISOString(),
- };
- ws.send(JSON.stringify(message));
+ ws.send(json);
clientInfo.lastSentAt = now;
sentCount++;
+ } catch (err) {
+ console.error('[WebSocket] Error sending to client:', err);
}
+ }
- if (sentCount > 0) {
- console.log(`[WebSocket] Broadcasted stats to ${sentCount} clients`);
- }
- } catch (err) {
- console.error('[WebSocket] Error broadcasting stats:', err);
+ if (sentCount > 0) {
+ console.log(`[WebSocket] Broadcasted stats to ${sentCount} clients`);
}
}
diff --git a/apps/collector/vitest.config.ts b/apps/collector/vitest.config.ts
new file mode 100644
index 0000000..1be63e0
--- /dev/null
+++ b/apps/collector/vitest.config.ts
@@ -0,0 +1,10 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ globals: true,
+ environment: 'node',
+ include: ['src/**/*.test.ts'],
+ testTimeout: 10000,
+ },
+});
diff --git a/apps/web/components/features/devices/interactive-device-stats.tsx b/apps/web/components/features/devices/interactive-device-stats.tsx
index 9cd1954..521956d 100644
--- a/apps/web/components/features/devices/interactive-device-stats.tsx
+++ b/apps/web/components/features/devices/interactive-device-stats.tsx
@@ -4,7 +4,19 @@ import { useState, useCallback, useMemo, useEffect } from "react";
import { BarChart3, Link2, Smartphone } from "lucide-react";
import { useTranslations } from "next-intl";
import { useQueryClient } from "@tanstack/react-query";
-import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip as RechartsTooltip, BarChart, Bar, XAxis, YAxis, Cell as BarCell, LabelList } from "recharts";
+import {
+ PieChart,
+ Pie,
+ Cell,
+ ResponsiveContainer,
+ Tooltip as RechartsTooltip,
+ BarChart,
+ Bar,
+ XAxis,
+ YAxis,
+ Cell as BarCell,
+ LabelList,
+} from "recharts";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ScrollArea } from "@/components/ui/scroll-area";
@@ -18,11 +30,19 @@ import {
import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
import { useStatsWebSocket } from "@/lib/websocket";
import { Favicon } from "@/components/common";
-import { DomainStatsTable, IPStatsTable } from "@/components/features/stats/table";
+import {
+ DomainStatsTable,
+ IPStatsTable,
+} from "@/components/features/stats/table";
import { InsightChartSkeleton } from "@/components/ui/insight-skeleton";
import { COLORS, type PageSize } from "@/lib/stats-utils";
import { useDeviceDomains, useDeviceIPs } from "@/hooks/api/use-devices";
-import type { DeviceStats, DomainStats, IPStats, StatsSummary } from "@neko-master/shared";
+import type {
+ DeviceStats,
+ DomainStats,
+ IPStats,
+ StatsSummary,
+} from "@neko-master/shared";
interface InteractiveDeviceStatsProps {
data: DeviceStats[];
@@ -33,12 +53,17 @@ interface InteractiveDeviceStatsProps {
}
const DEVICE_DETAIL_WS_MIN_PUSH_MS = 3_000;
-
-
function renderCustomBarLabel(props: any) {
const { x, y, width, value, height } = props;
return (
- <text x={x + width + 6} y={y + height / 2} fill="currentColor" fontSize={11} dominantBaseline="central" textAnchor="start" style={{ fontVariantNumeric: "tabular-nums" }}>
+ <text
+ x={x + width + 6}
+ y={y + height / 2}
+ fill="currentColor"
+ fontSize={11}
+ dominantBaseline="central"
+ textAnchor="start"
+ style={{ fontVariantNumeric: "tabular-nums" }}>
{formatBytes(value, 0)}
</text>
);
@@ -56,7 +81,7 @@ export function InteractiveDeviceStats({
const backendT = useTranslations("dashboard");
const detailTimeRange = useStableTimeRange(timeRange);
const queryClient = useQueryClient();
-
+
const [selectedDevice, setSelectedDevice] = useState<string | null>(null);
const [activeTab, setActiveTab] = useState("domains");
const [detailPageSize, setDetailPageSize] = useState<PageSize>(10);
@@ -84,16 +109,27 @@ export function InteractiveDeviceStats({
}));
}, [data]);
- const totalTraffic = useMemo(() => chartData.reduce((sum, item) => sum + item.value, 0), [chartData]);
- const topDevices = useMemo(() => [...chartData].sort((a, b) => b.value - a.value).slice(0, 4), [chartData]);
- const maxTotal = useMemo(() => chartData.length ? Math.max(...chartData.map(d => d.value)) : 1, [chartData]);
+ const totalTraffic = useMemo(
+ () => chartData.reduce((sum, item) => sum + item.value, 0),
+ [chartData],
+ );
+ const topDevices = useMemo(
+ () => [...chartData].sort((a, b) => b.value - a.value).slice(0, 4),
+ [chartData],
+ );
+ const maxTotal = useMemo(
+ () => (chartData.length ? Math.max(...chartData.map((d) => d.value)) : 1),
+ [chartData],
+ );
useEffect(() => {
if (chartData.length === 0) {
setSelectedDevice(null);
return;
}
- const exists = !!selectedDevice && chartData.some((item) => item.rawName === selectedDevice);
+ const exists =
+ !!selectedDevice &&
+ chartData.some((item) => item.rawName === selectedDevice);
if (!exists) {
setSelectedDevice(chartData[0].rawName);
}
@@ -109,23 +145,34 @@ export function InteractiveDeviceStats({
deviceDetailLimit: 5000,
trackLastMessage: false,
enabled: wsDetailEnabled,
- onMessage: useCallback((stats: StatsSummary) => {
- if (!selectedDevice) return;
- if (stats.deviceDetailSourceIP !== selectedDevice) return;
-
- if (stats.deviceDomains) {
- queryClient.setQueryData(
- getDeviceDomainsQueryKey(selectedDevice, activeBackendId, detailTimeRange),
- stats.deviceDomains
- );
- }
- if (stats.deviceIPs) {
- queryClient.setQueryData(
- getDeviceIPsQueryKey(selectedDevice, activeBackendId, detailTimeRange),
- stats.deviceIPs
- );
- }
- }, [selectedDevice, activeBackendId, detailTimeRange, queryClient]),
+ onMessage: useCallback(
+ (stats: StatsSummary) => {
+ if (!selectedDevice) return;
+ if (stats.deviceDetailSourceIP !== selectedDevice) return;
+
+ if (stats.deviceDomains) {
+ queryClient.setQueryData(
+ getDeviceDomainsQueryKey(
+ selectedDevice,
+ activeBackendId,
+ detailTimeRange,
+ ),
+ stats.deviceDomains,
+ );
+ }
+ if (stats.deviceIPs) {
+ queryClient.setQueryData(
+ getDeviceIPsQueryKey(
+ selectedDevice,
+ activeBackendId,
+ detailTimeRange,
+ ),
+ stats.deviceIPs,
+ );
+ }
+ },
+ [selectedDevice, activeBackendId, detailTimeRange, queryClient],
+ ),
});
const { data: domainsData, isLoading: domainsLoading } = useDeviceDomains({
@@ -144,20 +191,33 @@ export function InteractiveDeviceStats({
const deviceDomains = domainsData ?? [];
const deviceIPs = ipsData ?? [];
-
- const loading = !!selectedDevice && (domainsLoading || ipsLoading) && deviceDomains.length === 0 && deviceIPs.length === 0;
- const handleDeviceClick = useCallback((rawName: string) => {
- if (selectedDevice !== rawName) {
- setSelectedDevice(rawName);
- }
- }, [selectedDevice]);
+ const loading =
+ !!selectedDevice &&
+ (domainsLoading || ipsLoading) &&
+ deviceDomains.length === 0 &&
+ deviceIPs.length === 0;
+
+ const handleDeviceClick = useCallback(
+ (rawName: string) => {
+ if (selectedDevice !== rawName) {
+ setSelectedDevice(rawName);
+ }
+ },
+ [selectedDevice],
+ );
- const selectedDeviceData = useMemo(() => chartData.find(d => d.rawName === selectedDevice), [chartData, selectedDevice]);
+ const selectedDeviceData = useMemo(
+ () => chartData.find((d) => d.rawName === selectedDevice),
+ [chartData, selectedDevice],
+ );
const domainChartData = useMemo(() => {
return [...deviceDomains]
- .sort((a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload))
+ .sort(
+ (a, b) =>
+ b.totalDownload + b.totalUpload - (a.totalDownload + a.totalUpload),
+ )
.slice(0, 10)
.map((d, i) => ({
name: d.domain.length > 25 ? d.domain.slice(0, 22) + "..." : d.domain,
@@ -181,8 +241,12 @@ export function InteractiveDeviceStats({
<CardContent className="p-5 sm:p-6">
<div className="min-h-[220px] rounded-xl border border-dashed border-border/60 bg-card/30 px-4 py-6 flex flex-col items-center justify-center text-center">
<Smartphone className="h-8 w-8 text-muted-foreground/70 mb-2" />
- <p className="text-sm font-medium text-muted-foreground">{t("noData")}</p>
- <p className="text-xs text-muted-foreground/80 mt-1 max-w-xs">{emptyHint}</p>
+ <p className="text-sm font-medium text-muted-foreground">
+ {t("noData")}
+ </p>
+ <p className="text-xs text-muted-foreground/80 mt-1 max-w-xs">
+ {emptyHint}
+ </p>
</div>
</CardContent>
</Card>
@@ -195,37 +259,78 @@ export function InteractiveDeviceStats({
{/* Pie Chart */}
<Card className="min-w-0 md:col-span-1 xl:col-span-3">
<CardHeader className="pb-2">
- <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">{t("title")}</CardTitle>
+ <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
+ {t("title")}
+ </CardTitle>
</CardHeader>
<CardContent className="pt-2 pb-4">
<div className="h-[165px] w-full">
<ResponsiveContainer width="100%" height="100%">
<PieChart>
- <Pie data={chartData} cx="50%" cy="50%" innerRadius={50} outerRadius={80} paddingAngle={2} dataKey="value" isAnimationActive={false}>
- {chartData.map((entry, index) => (<Cell key={`cell-${index}`} fill={entry.color} />))}
+ <Pie
+ data={chartData}
+ cx="50%"
+ cy="50%"
+ innerRadius={50}
+ outerRadius={80}
+ paddingAngle={2}
+ dataKey="value"
+ isAnimationActive={false}>
+ {chartData.map((entry, index) => (
+ <Cell key={`cell-${index}`} fill={entry.color} />
+ ))}
</Pie>
- <RechartsTooltip content={({ active, payload }) => {
- if (active && payload && payload.length) {
- const item = payload[0].payload;
- return (<div className="bg-background border border-border p-3 rounded-lg shadow-lg"><p className="font-medium text-sm mb-1">{item.name}</p><p className="text-xs text-muted-foreground">{formatBytes(item.value)}</p></div>);
- }
- return null;
- }} />
+ <RechartsTooltip
+ content={({ active, payload }) => {
+ if (active && payload && payload.length) {
+ const item = payload[0].payload;
+ return (
+ <div className="bg-background border border-border p-3 rounded-lg shadow-lg">
+ <p className="font-medium text-sm mb-1">
+ {item.name}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {formatBytes(item.value)}
+ </p>
+ </div>
+ );
+ }
+ return null;
+ }}
+ />
</PieChart>
</ResponsiveContainer>
</div>
{topDevices.length > 0 && (
<div className="mt-2">
- <p className="text-[10px] text-muted-foreground uppercase tracking-wider text-center">Top 4</p>
+ <p className="text-[10px] text-muted-foreground uppercase tracking-wider text-center">
+ Top 4
+ </p>
<div className="mt-1 space-y-1.5">
{topDevices.map((item, idx) => {
- const rankBadgeClass = idx === 0 ? "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300" : idx === 1 ? "bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300" : idx === 2 ? "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300" : "bg-muted text-muted-foreground";
+ const rankBadgeClass =
+ idx === 0
+ ? "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300"
+ : idx === 1
+ ? "bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300"
+ : idx === 2
+ ? "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300"
+ : "bg-muted text-muted-foreground";
return (
- <div key={item.rawName} title={item.name} className="flex items-center gap-1.5 min-w-0">
- <span className={cn("w-5 h-5 rounded-md text-[10px] font-bold flex items-center justify-center shrink-0", rankBadgeClass)}>
+ <div
+ key={item.rawName}
+ title={item.name}
+ className="flex items-center gap-1.5 min-w-0">
+ <span
+ className={cn(
+ "w-5 h-5 rounded-md text-[10px] font-bold flex items-center justify-center shrink-0",
+ rankBadgeClass,
+ )}>
{idx + 1}
</span>
- <div className="px-1.5 py-0.5 rounded-md text-[10px] font-medium text-white/90 truncate min-w-0 max-w-[140px] flex items-center gap-1" style={{ backgroundColor: item.color }}>
+ <div
+ className="px-1.5 py-0.5 rounded-md text-[10px] font-medium text-white/90 truncate min-w-0 max-w-[140px] flex items-center gap-1"
+ style={{ backgroundColor: item.color }}>
<span className="truncate">{item.name}</span>
</div>
</div>
@@ -239,34 +344,85 @@ export function InteractiveDeviceStats({
{/* Device List */}
<Card className="min-w-0 md:col-span-1 xl:col-span-4">
- <CardHeader className="pb-2"><CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">{t("title")}</CardTitle></CardHeader>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
+ {t("title")}
+ </CardTitle>
+ </CardHeader>
<CardContent className="p-3">
<ScrollArea className="h-[280px] pr-3">
<div className="space-y-2">
{chartData.map((item) => {
- const percentage = totalTraffic > 0 ? (item.value / totalTraffic) * 100 : 0;
+ const percentage =
+ totalTraffic > 0 ? (item.value / totalTraffic) * 100 : 0;
const barPercent = (item.value / maxTotal) * 100;
const isSelected = selectedDevice === item.rawName;
- const badgeColor = item.rank === 0 ? "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400" : item.rank === 1 ? "bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300" : item.rank === 2 ? "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400" : "bg-muted text-muted-foreground";
+ const badgeColor =
+ item.rank === 0
+ ? "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400"
+ : item.rank === 1
+ ? "bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300"
+ : item.rank === 2
+ ? "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400"
+ : "bg-muted text-muted-foreground";
return (
- <button key={item.rawName} onClick={() => handleDeviceClick(item.rawName)} className={cn("w-full p-2.5 rounded-xl border text-left transition-all duration-200", isSelected ? "border-primary bg-primary/5 ring-1 ring-primary/20" : "border-border/50 bg-card/50 hover:bg-card hover:border-primary/30")}>
+ <button
+ key={item.rawName}
+ onClick={() => handleDeviceClick(item.rawName)}
+ className={cn(
+ "w-full p-2.5 rounded-xl border text-left transition-all duration-200 overflow-hidden",
+ isSelected
+ ? "border-primary bg-primary/5 ring-1 ring-primary/20"
+ : "border-border/50 bg-card/50 hover:bg-card hover:border-primary/30",
+ )}>
<div className="flex items-center gap-2 mb-1.5 min-w-0">
- <span className={cn("w-5 h-5 rounded-md text-[10px] font-bold flex items-center justify-center shrink-0", badgeColor)}>{item.rank + 1}</span>
- <span className="flex-1 text-sm font-medium truncate min-w-0 max-w-[120px] sm:max-w-[180px]" title={item.name}>{item.name}</span>
- <span className="text-sm font-bold tabular-nums shrink-0 whitespace-nowrap ml-auto">{formatBytes(item.value)}</span>
+ <span
+ className={cn(
+ "w-5 h-5 rounded-md text-[10px] font-bold flex items-center justify-center shrink-0",
+ badgeColor,
+ )}>
+ {item.rank + 1}
+ </span>
+ <span
+ className="flex-1 text-sm font-medium truncate min-w-0"
+ title={item.name}>
+ {item.name}
+ </span>
+ <span className="text-sm font-bold tabular-nums shrink-0 whitespace-nowrap ml-auto">
+ {formatBytes(item.value)}
+ </span>
</div>
<div className="pl-7 space-y-1">
<div className="h-1.5 rounded-full bg-muted overflow-hidden flex">
- <div className="h-full bg-blue-500 dark:bg-blue-400" style={{ width: `${item.value > 0 ? (item.download / item.value) * barPercent : 0}%` }} />
- <div className="h-full bg-purple-500 dark:bg-purple-400" style={{ width: `${item.value > 0 ? (item.upload / item.value) * barPercent : 0}%` }} />
+ <div
+ className="h-full bg-blue-500 dark:bg-blue-400"
+ style={{
+ width: `${item.value > 0 ? (item.download / item.value) * barPercent : 0}%`,
+ }}
+ />
+ <div
+ className="h-full bg-purple-500 dark:bg-purple-400"
+ style={{
+ width: `${item.value > 0 ? (item.upload / item.value) * barPercent : 0}%`,
+ }}
+ />
</div>
<div className="flex flex-wrap items-center justify-between gap-1 text-xs text-muted-foreground">
<div className="flex flex-wrap items-center gap-1.5 sm:gap-2">
- <span className="text-blue-500 dark:text-blue-400 whitespace-nowrap">↓ {formatBytes(item.download)}</span>
- <span className="text-purple-500 dark:text-purple-400 whitespace-nowrap">↑ {formatBytes(item.upload)}</span>
- <span className="flex items-center gap-1 tabular-nums"><Link2 className="w-3 h-3" />{formatNumber(item.connections)}</span>
+ <span className="text-blue-500 dark:text-blue-400 whitespace-nowrap">
+ ↓ {formatBytes(item.download)}
+ </span>
+ <span className="text-purple-500 dark:text-purple-400 whitespace-nowrap">
+ ↑ {formatBytes(item.upload)}
+ </span>
+ <span className="flex items-center gap-1 tabular-nums">
+ <Link2 className="w-3 h-3" />
+ {formatNumber(item.connections)}
+ </span>
</div>
- <span className="tabular-nums">{percentage.toFixed(1)}%</span>
+ <span className="tabular-nums">
+ {percentage.toFixed(1)}%
+ </span>
</div>
</div>
</button>
@@ -281,34 +437,115 @@ export function InteractiveDeviceStats({
<Card className="min-w-0 md:col-span-2 xl:col-span-5">
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
- <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2"><BarChart3 className="h-4 w-4" />{domainsT("title")}</CardTitle>
- {selectedDeviceData && (<span className="text-xs text-muted-foreground">{selectedDeviceData.name}</span>)}
+ <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2">
+ <BarChart3 className="h-4 w-4" />
+ {domainsT("title")}
+ </CardTitle>
+ {selectedDeviceData && (
+ <span className="text-xs text-muted-foreground">
+ {selectedDeviceData.name}
+ </span>
+ )}
</div>
</CardHeader>
<CardContent className="pt-0">
- {loading ? (<InsightChartSkeleton />
+ {loading ? (
+ <InsightChartSkeleton />
) : domainChartData.length === 0 ? (
<div className="h-[280px] rounded-xl border border-dashed border-border/60 bg-card/30 px-4 py-5 flex flex-col items-center justify-center text-center">
<BarChart3 className="h-5 w-5 text-muted-foreground/70 mb-2" />
- <p className="text-sm font-medium text-muted-foreground">{domainsT("noData")}</p>
- <p className="text-xs text-muted-foreground/80 mt-1 max-w-xs">{emptyHint}</p>
+ <p className="text-sm font-medium text-muted-foreground">
+ {domainsT("noData")}
+ </p>
+ <p className="text-xs text-muted-foreground/80 mt-1 max-w-xs">
+ {emptyHint}
+ </p>
</div>
) : (
<div className="h-[280px] w-full">
<ResponsiveContainer width="100%" height="100%">
- <BarChart data={domainChartData} layout="vertical" margin={{ left: 0, right: showDomainBarLabels ? 60 : 10, top: 5, bottom: 5 }}>
+ <BarChart
+ data={domainChartData}
+ layout="vertical"
+ margin={{
+ left: 0,
+ right: showDomainBarLabels ? 60 : 10,
+ top: 5,
+ bottom: 5,
+ }}>
<XAxis type="number" hide />
- <YAxis type="category" dataKey="name" width={100} tick={{ fontSize: 11 }} tickLine={false} axisLine={false} />
- <RechartsTooltip content={({ active, payload }) => {
- if (active && payload && payload.length) {
- const item = payload[0].payload;
- return (<div className="bg-background border border-border p-3 rounded-lg shadow-lg min-w-[160px]"><div className="flex items-center gap-2 mb-2 pb-2 border-b border-border/50"><Favicon domain={item.fullName} size="sm" /><span className="font-medium text-sm truncate max-w-[180px]" title={item.fullName}>{item.fullName}</span></div><div className="space-y-2 text-xs"><div className="flex justify-between items-center"><span className="text-muted-foreground">Total</span><span className="font-semibold">{formatBytes(item.total)}</span></div><div className="flex justify-between items-center"><span className="text-blue-500">Download</span><span>{formatBytes(item.download)}</span></div><div className="flex justify-between items-center"><span className="text-purple-500">Upload</span><span>{formatBytes(item.upload)}</span></div><div className="flex justify-between items-center pt-1 border-t border-border/50"><span className="text-emerald-500">Connections</span><span>{formatNumber(item.connections)}</span></div></div></div>);
- }
- return null;
- }} cursor={{ fill: "rgba(128, 128, 128, 0.1)" }} />
- <Bar dataKey="total" radius={[0, 4, 4, 0]} maxBarSize={24} isAnimationActive={false}>
- {domainChartData.map((entry, index) => (<BarCell key={`cell-${index}`} fill={entry.color} />))}
- {showDomainBarLabels && (<LabelList dataKey="total" position="right" content={renderCustomBarLabel} />)}
+ <YAxis
+ type="category"
+ dataKey="name"
+ width={100}
+ tick={{ fontSize: 11 }}
+ tickLine={false}
+ axisLine={false}
+ />
+ <RechartsTooltip
+ content={({ active, payload }) => {
+ if (active && payload && payload.length) {
+ const item = payload[0].payload;
+ return (
+ <div className="bg-background border border-border p-3 rounded-lg shadow-lg min-w-[160px]">
+ <div className="flex items-center gap-2 mb-2 pb-2 border-b border-border/50">
+ <Favicon domain={item.fullName} size="sm" />
+ <span
+ className="font-medium text-sm truncate max-w-[180px]"
+ title={item.fullName}>
+ {item.fullName}
+ </span>
+ </div>
+ <div className="space-y-2 text-xs">
+ <div className="flex justify-between items-center">
+ <span className="text-muted-foreground">
+ Total
+ </span>
+ <span className="font-semibold">
+ {formatBytes(item.total)}
+ </span>
+ </div>
+ <div className="flex justify-between items-center">
+ <span className="text-blue-500">
+ Download
+ </span>
+ <span>{formatBytes(item.download)}</span>
+ </div>
+ <div className="flex justify-between items-center">
+ <span className="text-purple-500">
+ Upload
+ </span>
+ <span>{formatBytes(item.upload)}</span>
+ </div>
+ <div className="flex justify-between items-center pt-1 border-t border-border/50">
+ <span className="text-emerald-500">
+ Connections
+ </span>
+ <span>{formatNumber(item.connections)}</span>
+ </div>
+ </div>
+ </div>
+ );
+ }
+ return null;
+ }}
+ cursor={{ fill: "rgba(128, 128, 128, 0.1)" }}
+ />
+ <Bar
+ dataKey="total"
+ radius={[0, 4, 4, 0]}
+ maxBarSize={24}
+ isAnimationActive={false}>
+ {domainChartData.map((entry, index) => (
+ <BarCell key={`cell-${index}`} fill={entry.color} />
+ ))}
+ {showDomainBarLabels && (
+ <LabelList
+ dataKey="total"
+ position="right"
+ content={renderCustomBarLabel}
+ />
+ )}
</Bar>
</BarChart>
</ResponsiveContainer>
diff --git a/apps/web/components/features/proxies/interactive-proxy-stats.tsx b/apps/web/components/features/proxies/interactive-proxy-stats.tsx
index 9a0ebb1..9956b19 100644
--- a/apps/web/components/features/proxies/interactive-proxy-stats.tsx
+++ b/apps/web/components/features/proxies/interactive-proxy-stats.tsx
@@ -265,9 +265,9 @@ export function InteractiveProxyStats({
return (
<div className="space-y-6">
- <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 lg:gap-6">
+ <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-12 gap-6">
{/* Pie Chart */}
- <Card className="min-w-0">
+ <Card className="min-w-0 md:col-span-1 xl:col-span-3">
<CardHeader className="pb-2">
<CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">{t("title")}</CardTitle>
</CardHeader>
@@ -319,7 +319,7 @@ export function InteractiveProxyStats({
</Card>
{/* Proxy List */}
- <Card className="min-w-0">
+ <Card className="min-w-0 md:col-span-1 xl:col-span-4">
<CardHeader className="pb-2"><CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">{t("title")}</CardTitle></CardHeader>
<CardContent className="p-3">
<ScrollArea className="h-[280px] pr-3">
@@ -331,13 +331,13 @@ export function InteractiveProxyStats({
const badgeColor = item.rank === 0 ? "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400" : item.rank === 1 ? "bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300" : item.rank === 2 ? "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400" : "bg-muted text-muted-foreground";
const rawDisplayName = item.rawName || item.name;
return (
- <button key={item.rawName} onClick={() => handleProxyClick(item.rawName)} className={cn("w-full p-2.5 rounded-xl border text-left transition-all duration-200", isSelected ? "border-primary bg-primary/5 ring-1 ring-primary/20" : "border-border/50 bg-card/50 hover:bg-card hover:border-primary/30")}>
- <div className="flex items-center gap-2 mb-1.5">
+ <button key={item.rawName} onClick={() => handleProxyClick(item.rawName)} className={cn("w-full p-2.5 rounded-xl border text-left transition-all duration-200 overflow-hidden", isSelected ? "border-primary bg-primary/5 ring-1 ring-primary/20" : "border-border/50 bg-card/50 hover:bg-card hover:border-primary/30")}>
+ <div className="flex items-center gap-2 mb-1.5 min-w-0">
<span className={cn("w-5 h-5 rounded-md text-[10px] font-bold flex items-center justify-center shrink-0", badgeColor)}>{item.rank + 1}</span>
- <span className="flex-1 text-sm font-medium truncate" title={rawDisplayName}>
- {rawDisplayName.length > 24 ? rawDisplayName.slice(0, 24) + "..." : rawDisplayName}
+ <span className="flex-1 text-sm font-medium truncate min-w-0" title={rawDisplayName}>
+ {rawDisplayName}
</span>
- <span className="text-sm font-bold tabular-nums shrink-0 whitespace-nowrap">{formatBytes(item.value)}</span>
+ <span className="text-sm font-bold tabular-nums shrink-0 whitespace-nowrap ml-auto">{formatBytes(item.value)}</span>
</div>
<div className="pl-7 space-y-1">
<div className="h-1.5 rounded-full bg-muted overflow-hidden flex">
@@ -361,9 +361,8 @@ export function InteractiveProxyStats({
</CardContent>
</Card>
- {/* Top Domains Chart - Full width on single column, adapts to container */}
- <div className="min-w-0 md:col-span-2 xl:col-span-1 @container">
- <Card className="min-w-0 h-full">
+ {/* Top Domains Chart */}
+ <Card className="min-w-0 md:col-span-2 xl:col-span-5" ref={topDomainsCardRef}>
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2"><BarChart3 className="h-4 w-4" />{domainsT("title")}</CardTitle>
@@ -384,7 +383,7 @@ export function InteractiveProxyStats({
<p className="text-xs text-muted-foreground/80 mt-1 max-w-xs">{emptyHint}</p>
</div>
) : (
- <div className="h-[280px] @min-[500px]:h-[320px] w-full">
+ <div className="h-[280px] w-full">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={domainChartData} layout="vertical" margin={{ left: 0, right: showDomainBarLabels ? 70 : 10, top: 5, bottom: 5 }}>
<XAxis type="number" hide />
@@ -406,7 +405,6 @@ export function InteractiveProxyStats({
)}
</CardContent>
</Card>
- </div>
</div>
{/* Bottom: Tabs with shared table components */}
diff --git a/apps/web/components/features/rules/interactive-rule-stats.tsx b/apps/web/components/features/rules/interactive-rule-stats.tsx
index 076f535..4d2696f 100644
--- a/apps/web/components/features/rules/interactive-rule-stats.tsx
+++ b/apps/web/components/features/rules/interactive-rule-stats.tsx
@@ -628,9 +628,9 @@ export function InteractiveRuleStats({
return (
<div className="space-y-6">
{/* Top Section: Three Column Layout */}
- <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 lg:gap-6">
+ <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-12 gap-6">
{/* Left: Pie Chart */}
- <Card className="min-w-0">
+ <Card className="min-w-0 md:col-span-1 xl:col-span-3">
<CardHeader className="pb-2">
<CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
{t("distribution")}
@@ -715,7 +715,7 @@ export function InteractiveRuleStats({
</Card>
{/* Middle: Rule List */}
- <Card className="min-w-0">
+ <Card className="min-w-0 md:col-span-1 xl:col-span-4">
<CardHeader className="pb-2">
<CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
{t("ruleList")}
@@ -746,7 +746,7 @@ export function InteractiveRuleStats({
key={item.rawName}
onClick={() => !noTraffic && handleRuleClick(item.rawName)}
className={cn(
- "w-full p-2.5 rounded-xl border text-left transition-all duration-200 @container",
+ "w-full p-2.5 rounded-xl border text-left transition-all duration-200 overflow-hidden @container",
noTraffic
? "border-border/30 bg-card/30 opacity-50 cursor-default"
: isSelected
@@ -876,8 +876,7 @@ export function InteractiveRuleStats({
</Card>
{/* Right: Top Domains Chart - Full width on single column, adapts to container */}
- <div ref={topDomainsCardRef} className="min-w-0 md:col-span-2 xl:col-span-1">
- <Card className="min-w-0 @container h-full">
+ <Card className="min-w-0 md:col-span-2 xl:col-span-5 @container h-full" ref={topDomainsCardRef}>
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2">
@@ -989,7 +988,6 @@ export function InteractiveRuleStats({
)}
</CardContent>
</Card>
- </div>
</div>
{/* Unified Chain Flow Visualization - shows all rules, highlights selected */}
diff --git a/apps/web/components/ui/scroll-area.tsx b/apps/web/components/ui/scroll-area.tsx
index 69c548a..78dbc91 100644
--- a/apps/web/components/ui/scroll-area.tsx
+++ b/apps/web/components/ui/scroll-area.tsx
@@ -14,7 +14,7 @@ const ScrollArea = React.forwardRef<
className={cn("relative overflow-hidden", className)}
{...props}
>
- <ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
+ <ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit] [&>div]:!block">
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
diff --git a/docker-start.sh b/docker-start.sh
index 412be40..885be42 100755
--- a/docker-start.sh
+++ b/docker-start.sh
@@ -9,6 +9,21 @@ API_PORT="${API_PORT:-3001}"
COLLECTOR_WS_PORT="${COLLECTOR_WS_PORT:-3002}"
DB_PATH="${DB_PATH:-/app/data/stats.db}"
+# Auto-generate COOKIE_SECRET if not set (persisted in data volume)
+if [ -z "$COOKIE_SECRET" ]; then
+ SECRET_FILE="$(dirname "$DB_PATH")/.cookie-secret"
+ if [ -f "$SECRET_FILE" ]; then
+ COOKIE_SECRET=$(cat "$SECRET_FILE")
+ else
+ COOKIE_SECRET=$(head -c 32 /dev/urandom | od -A n -t x1 | tr -d ' \n')
+ mkdir -p "$(dirname "$SECRET_FILE")"
+ echo -n "$COOKIE_SECRET" > "$SECRET_FILE"
+ chmod 600 "$SECRET_FILE"
+ echo "🔑 Generated new COOKIE_SECRET (persisted in data volume)"
+ fi
+ export COOKIE_SECRET
+fi
+
export API_PORT COLLECTOR_WS_PORT DB_PATH
echo "╔════════════════════════════════════════════════════════╗"
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 24d0ce8..b9bba8f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -36,6 +36,9 @@ importers:
specifier: ^8.19.0
version: 8.19.0
devDependencies:
+ '@eslint/js':
+ specifier: ^9.39.2
+ version: 9.39.2
'@types/better-sqlite3':
specifier: ^7.6.13
version: 7.6.13
@@ -45,12 +48,21 @@ importers:
'@types/ws':
specifier: ^8.18.1
version: 8.18.1
+ eslint:
+ specifier: ^9
+ version: 9.39.2([email protected])
tsx:
specifier: ^4.21.0
version: 4.21.0
typescript:
specifier: ^5
version: 5.9.3
+ typescript-eslint:
+ specifier: ^8.55.0
+ vitest:
+ specifier: ^4.0.18
apps/web:
dependencies:
@@ -2071,12 +2083,140 @@ packages:
rollup:
optional: true
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-A6ehUVSiSaaliTxai040ZpZ2zTevHYbvu/lDoeAteHI8QnaosIzm4qwtezfRg1jOYaUmnzLX1AOD6Z+UJjtifg==}
+ cpu: [arm]
+ os: [android]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-dQaAddCY9YgkFHZcFNS/606Exo8vcLHwArFZ7vxXq4rigo2bb494/xKMMwRRQW6ug7Js6yXmBZhSBRuBvCCQ3w==}
+ cpu: [arm64]
+ os: [android]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-crNPrwJOrRxagUYeMn/DZwqN88SDmwaJ8Cvi/TN1HnWBU7GwknckyosC2gd0IqYRsHDEnXf328o9/HC6OkPgOg==}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-Ji8g8ChVbKrhFtig5QBV7iMaJrGtpHelkB3lsaKzadFBe58gmjfGXAOfI5FV0lYMH8wiqsxKQ1C9B0YTRXVy4w==}
+ cpu: [x64]
+ os: [darwin]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-R+/WwhsjmwodAcz65guCGFRkMb4gKWTcIeLy60JJQbXrJ97BOXHxnkPFrP+YwFlaS0m+uWJTstrUA9o+UchFug==}
+ cpu: [arm64]
+ os: [freebsd]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-IEQTCHeiTOnAUC3IDQdzRAGj3jOAYNr9kBguI7MQAAZK3caezRrg0GxAb6Hchg4lxdZEI5Oq3iov/w/hnFWY9Q==}
+ cpu: [x64]
+ os: [freebsd]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-F8sWbhZ7tyuEfsmOxwc2giKDQzN3+kuBLPwwZGyVkLlKGdV1nvnNwYD0fKQ8+XS6hp9nY7B+ZeK01EBUE7aHaw==}
+ cpu: [arm]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-rGfNUfn0GIeXtBP1wL5MnzSj98+PZe/AXaGBCRmT0ts80lU5CATYGxXukeTX39XBKsxzFpEeK+Mrp9faXOlmrw==}
+ cpu: [arm]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-MMtej3YHWeg/0klK2Qodf3yrNzz6CGjo2UntLvk2RSPlhzgLvYEB3frRvbEF2wRKh1Z2fDIg9KRPe1fawv7C+g==}
+ cpu: [arm64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-1a/qhaaOXhqXGpMFMET9VqwZakkljWHLmZOX48R0I/YLbhdxr1m4gtG1Hq7++VhVUmf+L3sTAf9op4JlhQ5u1Q==}
+ cpu: [arm64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-QWO6RQTZ/cqYtJMtxhkRkidoNGXc7ERPbZN7dVW5SdURuLeVU7lwKMpo18XdcmpWYd0qsP1bwKPf7DNSUinhvA==}
+ cpu: [loong64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-xpObYIf+8gprgWaPP32xiN5RVTi/s5FCR+XMXSKmhfoJjrpRAjCuuqQXyxUa/eJTdAE6eJ+KDKaoEqjZQxh3Gw==}
+ cpu: [loong64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-4BrCgrpZo4hvzMDKRqEaW1zeecScDCR+2nZ86ATLhAoJ5FQ+lbHVD3ttKe74/c7tNT9c6F2viwB3ufwp01Oh2w==}
+ cpu: [ppc64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-NOlUuzesGauESAyEYFSe3QTUguL+lvrN1HtwEEsU2rOwdUDeTMJdO5dUYl/2hKf9jWydJrO9OL/XSSf65R5+Xw==}
+ cpu: [ppc64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-ptA88htVp0AwUUqhVghwDIKlvJMD/fmL/wrQj99PRHFRAG6Z5nbWoWG4o81Nt9FT+IuqUQi+L31ZKAFeJ5Is+A==}
+ cpu: [riscv64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-S51t7aMMTNdmAMPpBg7OOsTdn4tySRQvklmL3RpDRyknk87+Sp3xaumlatU+ppQ+5raY7sSTcC2beGgvhENfuw==}
+ cpu: [riscv64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-Bl00OFnVFkL82FHbEqy3k5CUCKH6OEJL54KCyx2oqsmZnFTR8IoNqBF+mjQVcRCT5sB6yOvK8A37LNm/kPJiZg==}
+ cpu: [s390x]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-ABca4ceT4N+Tv/GtotnWAeXZUZuM/9AQyCyKYyKnpk4yoA7QIAuBt6Hkgpw8kActYlew2mvckXkvx0FfoInnLg==}
+ cpu: [x64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-HFps0JeGtuOR2convgRRkHCekD7j+gdAuXM+/i6kGzQtFhlCtQkpwtNzkNj6QhCDp7DRJ7+qC/1Vg2jt5iSOFw==}
+ cpu: [x64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-H+hXEv9gdVQuDTgnqD+SQffoWoc0Of59AStSzTEj/feWTBAnSfSD3+Dql1ZruJQxmykT/JVY0dE8Ka7z0DH1hw==}
+ cpu: [x64]
+ os: [openbsd]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-4wYoDpNg6o/oPximyc/NG+mYUejZrCU2q+2w6YZqrAs2UcNUChIZXjtafAiiZSUc7On8v5NyNj34Kzj/Ltk6dQ==}
+ cpu: [arm64]
+ os: [openharmony]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-O54mtsV/6LW3P8qdTcamQmuC990HDfR71lo44oZMZlXU4tzLrbvTii87Ni9opq60ds0YzuAlEr/GNwuNluZyMQ==}
+ cpu: [arm64]
+ os: [win32]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-P3dLS+IerxCT/7D2q2FYcRdWRl22dNbrbBEtxdWhXrfIMPP9lQhb5h4Du04mdl5Woq05jVCDPCMF7Ub0NAjIew==}
+ cpu: [ia32]
+ os: [win32]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-VMBH2eOOaKGtIJYleXsi2B8CPVADrh+TyNxJ4mWPnKfLB/DBUmzW+5m1xUrcwWoMfSLagIRpjUFeW5CO5hyciQ==}
+ cpu: [x64]
+ os: [win32]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-mxRFDdHIWRxg3UfIIAwCm6NzvxG0jDX/wBN6KsQFTvKFqqg9vTrWUE68qEjHt19A5wwx5X5aUi2zuZT7YR0jrA==}
+ cpu: [x64]
+ os: [win32]
+
resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==}
'@schummar/[email protected]':
resolution: {integrity: sha512-bXHSaW5jRTmke9Vd0h5P7BtWZG9Znqb8gSDxZnxaGSJnGwPLDPfS+3g0BKzeWqzgZPsIVZkM7m2tbo18cm5HBw==}
+ '@standard-schema/[email protected]':
+ resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
+
resolution: {integrity: sha512-lR8q/9W7hZpMWweNiAKU7NQerBnzQQLvi8qnTDU/fxItPhtZVMbPV3lbCwjhIlNBe9Bbr5V+KHshvWmVSG9cxQ==}
@@ -2269,6 +2409,9 @@ packages:
resolution: {integrity: sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
+
resolution: {integrity: sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==}
@@ -2308,6 +2451,9 @@ packages:
resolution: {integrity: sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
+
resolution: {integrity: sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg==}
@@ -2357,6 +2503,14 @@ packages:
eslint: ^8.57.0 || ^9.0.0
typescript: '>=4.8.4 <6.0.0'
+ '@typescript-eslint/[email protected]':
+ resolution: {integrity: sha512-1y/MVSz0NglV1ijHC8OT49mPJ4qhPYjiK08YUQVbIOyu+5k862LKUHFkpKHWu//zmr7hDR2rhwUm6gnCGNmGBQ==}
+ engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
+ peerDependencies:
+ '@typescript-eslint/parser': ^8.55.0
+ eslint: ^8.57.0 || ^9.0.0
+ typescript: '>=4.8.4 <6.0.0'
+
'@typescript-eslint/[email protected]':
resolution: {integrity: sha512-BtE0k6cjwjLZoZixN0t5AKP0kSzlGu7FctRXYuPAm//aaiZhmfq1JwdYpYr1brzEspYyFeF+8XF5j2VK6oalrA==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
@@ -2364,22 +2518,45 @@ packages:
eslint: ^8.57.0 || ^9.0.0
typescript: '>=4.8.4 <6.0.0'
+ '@typescript-eslint/[email protected]':
+ resolution: {integrity: sha512-4z2nCSBfVIMnbuu8uinj+f0o4qOeggYJLbjpPHka3KH1om7e+H9yLKTYgksTaHcGco+NClhhY2vyO3HsMH1RGw==}
+ engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
+ peerDependencies:
+ eslint: ^8.57.0 || ^9.0.0
+ typescript: '>=4.8.4 <6.0.0'
+
'@typescript-eslint/[email protected]':
resolution: {integrity: sha512-YPf+rvJ1s7MyiWM4uTRhE4DvBXrEV+d8oC3P9Y2eT7S+HBS0clybdMIPnhiATi9vZOYDc7OQ1L/i6ga6NFYK/g==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
typescript: '>=4.8.4 <6.0.0'
+ '@typescript-eslint/[email protected]':
+ resolution: {integrity: sha512-zRcVVPFUYWa3kNnjaZGXSu3xkKV1zXy8M4nO/pElzQhFweb7PPtluDLQtKArEOGmjXoRjnUZ29NjOiF0eCDkcQ==}
+ engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
+ peerDependencies:
+ typescript: '>=4.8.4 <6.0.0'
+
'@typescript-eslint/[email protected]':
resolution: {integrity: sha512-27rYVQku26j/PbHYcVfRPonmOlVI6gihHtXFbTdB5sb6qA0wdAQAbyXFVarQ5t4HRojIz64IV90YtsjQSSGlQg==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
+ '@typescript-eslint/[email protected]':
+ resolution: {integrity: sha512-fVu5Omrd3jeqeQLiB9f1YsuK/iHFOwb04bCtY4BSCLgjNbOD33ZdV6KyEqplHr+IlpgT0QTZ/iJ+wT7hvTx49Q==}
+ engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
+
'@typescript-eslint/[email protected]':
resolution: {integrity: sha512-dRgOyT2hPk/JwxNMZDsIXDgyl9axdJI3ogZ2XWhBPsnZUv+hPesa5iuhdYt2gzwA9t8RE5ytOJ6xB0moV0Ujvw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
typescript: '>=4.8.4 <6.0.0'
+ '@typescript-eslint/[email protected]':
+ resolution: {integrity: sha512-1R9cXqY7RQd7WuqSN47PK9EDpgFUK3VqdmbYrvWJZYDd0cavROGn+74ktWBlmJ13NXUQKlZ/iAEQHI/V0kKe0Q==}
+ engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
+ peerDependencies:
+ typescript: '>=4.8.4 <6.0.0'
+
'@typescript-eslint/[email protected]':
resolution: {integrity: sha512-hiLguxJWHjjwL6xMBwD903ciAwd7DmK30Y9Axs/etOkftC3ZNN9K44IuRD/EB08amu+Zw6W37x9RecLkOo3pMA==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
@@ -2387,16 +2564,33 @@ packages:
eslint: ^8.57.0 || ^9.0.0
typescript: '>=4.8.4 <6.0.0'
+ '@typescript-eslint/[email protected]':
+ resolution: {integrity: sha512-x1iH2unH4qAt6I37I2CGlsNs+B9WGxurP2uyZLRz6UJoZWDBx9cJL1xVN/FiOmHEONEg6RIufdvyT0TEYIgC5g==}
+ engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
+ peerDependencies:
+ eslint: ^8.57.0 || ^9.0.0
+ typescript: '>=4.8.4 <6.0.0'
+
'@typescript-eslint/[email protected]':
resolution: {integrity: sha512-PDUI9R1BVjqu7AUDsRBbKMtwmjWcn4J3le+5LpcFgWULN3LvHC5rkc9gCVxbrsrGmO1jfPybN5s6h4Jy+OnkAA==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
+ '@typescript-eslint/[email protected]':
+ resolution: {integrity: sha512-ujT0Je8GI5BJWi+/mMoR0wxwVEQaxM+pi30xuMiJETlX80OPovb2p9E8ss87gnSVtYXtJoU9U1Cowcr6w2FE0w==}
+ engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
+
'@typescript-eslint/[email protected]':
resolution: {integrity: sha512-BUwcskRaPvTk6fzVWgDPdUndLjB87KYDrN5EYGetnktoeAvPtO4ONHlAZDnj5VFnUANg0Sjm7j4usBlnoVMHwA==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
typescript: '>=4.8.4 <6.0.0'
+ '@typescript-eslint/[email protected]':
+ resolution: {integrity: sha512-EwrH67bSWdx/3aRQhCoxDaHM+CrZjotc2UCCpEDVqfCE+7OjKAGWNY2HsCSTEVvWH2clYQK8pdeLp42EVs+xQw==}
+ engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
+ peerDependencies:
+ typescript: '>=4.8.4 <6.0.0'
+
'@typescript-eslint/[email protected]':
resolution: {integrity: sha512-9Cnda8GS57AQakvRyG0PTejJNlA2xhvyNtEVIMlDWOOeEyBkYWhGPnfrIAnqxLMTSTo6q8g12XVjjev5l1NvMA==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
@@ -2404,10 +2598,21 @@ packages:
eslint: ^8.57.0 || ^9.0.0
typescript: '>=4.8.4 <6.0.0'
+ '@typescript-eslint/[email protected]':
+ resolution: {integrity: sha512-BqZEsnPGdYpgyEIkDC1BadNY8oMwckftxBT+C8W0g1iKPdeqKZBtTfnvcq0nf60u7MkjFO8RBvpRGZBPw4L2ow==}
+ engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
+ peerDependencies:
+ eslint: ^8.57.0 || ^9.0.0
+ typescript: '>=4.8.4 <6.0.0'
+
'@typescript-eslint/[email protected]':
resolution: {integrity: sha512-VFlhGSl4opC0bprJiItPQ1RfUhGDIBokcPwaFH4yiBCaNPeld/9VeXbiPO1cLyorQi1G1vL+ecBk1x8o1axORA==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
+ '@typescript-eslint/[email protected]':
+ resolution: {integrity: sha512-AxNRwEie8Nn4eFS1FzDMJWIISMGoXMb037sgCBJ3UR6o0fQTzr2tqN9WT+DkWJPhIdQCfV7T6D387566VtnCJA==}
+ engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
+
resolution: {integrity: sha512-ppLRUgHVaGRWUx0R0Ut06Mjo9gBaBkg3v/8AxusGLhsIotbBLuRk51rAzqLC8gq6NyyAojEXglNjzf6R948DNw==}
cpu: [arm]
@@ -2503,6 +2708,35 @@ packages:
cpu: [x64]
os: [win32]
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-8sCWUyckXXYvx4opfzVY03EOiYVxyNrHS5QxX3DAIi5dpJAAkyJezHCP77VMX4HKA2LDT/Jpfo8i2r5BE3GnQQ==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-HhVd0MDnzzsgevnOWCBj5Otnzobjy5wLBe4EdeeFGv8luMsGcYqDuFRMcttKWZA5vVO8RFjexVovXvAM4JoJDQ==}
+ peerDependencies:
+ msw: ^2.4.9
+ vite: ^6.0.0 || ^7.0.0-0
+ peerDependenciesMeta:
+ msw:
+ optional: true
+ vite:
+ optional: true
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-P24GK3GulZWC5tz87ux0m8OADrQIUVDPIjjj65vBXYG17ZeU3qD7r+MNZ1RNv4l8CGU2vtTRqixrOi9fYk/yKw==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-rpk9y12PGa22Jg6g5M3UVVnTS7+zycIGk9ZNGN+m6tZHKQb7jrP7/77WfZy13Y/EUDd52NDsLRQhYKtv7XfPQw==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-PCiV0rcl7jKQjbgYqjtakly6T1uwv/5BQ9SwBLekVg/EaYeQFPiXcgrC2Y7vDMA8dM1SUEAEV82kgSQIlXNMvA==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-cbQt3PTSD7P2OARdVW3qWER5EGq7PHlvE+QfzSC0lbwO+xnt7+XH06ZzFjFRgzUX//JmpxrCu92VdwvEPlWSNw==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-msMRKLMVLWygpK3u2Hybgi4MNjcYJvwTb0Ru09+fOyCXIgT5raYP041DRRdiJiI3k/2U6SEbAETB3YtBrUkCFA==}
+
'@webassemblyjs/[email protected]':
resolution: {integrity: sha512-nuBEDgQfm1ccRp/8bCQrx1frohyufl4JlbMMZ4P1wpeOfDhF6FQkxZJ1b/e+PLwr6X1Nhw6OLme5usuBWYBvuQ==}
@@ -2656,6 +2890,10 @@ packages:
resolution: {integrity: sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-OH/2E5Fg20h2aPrbe+QL8JZQFko0YZaF+j4mnQ7BGhfavO7OpSLa8a0y9sBwomHdSbkhTS8TQNayBfnW5DwbvQ==}
@@ -2763,6 +3001,10 @@ packages:
resolution: {integrity: sha512-34+zUAMhSH+r+9eKmYG+k2Rpt8XttfE4yXAjoZvkAPs15xcYQhyBYdalJ65BzivAvGRMViEjy6oKr/S91loekQ==}
+ resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}
engines: {node: '>=10'}
@@ -3049,6 +3291,9 @@ packages:
resolution: {integrity: sha512-BrUQ0cPTB/IwXj23HtwHjS9n7O4h9FX94b4xc5zlTHxeLgTAdzYUDyy6KdExAl9lbN5rtfe44xpjpmj9grxs5w==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==}
+
resolution: {integrity: sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw==}
@@ -3207,6 +3452,9 @@ packages:
resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==}
+ resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}
+
resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==}
engines: {node: '>=0.10.0'}
@@ -3222,6 +3470,10 @@ packages:
resolution: {integrity: sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==}
+ engines: {node: '>=12.0.0'}
+
resolution: {integrity: sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==}
@@ -3979,6 +4231,9 @@ packages:
resolution: {integrity: sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==}
+
resolution: {integrity: sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==}
engines: {node: '>=14.0.0'}
@@ -4021,6 +4276,9 @@ packages:
resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==}
+ resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
+
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
@@ -4267,6 +4525,11 @@ packages:
engines: {node: '>=10.0.0'}
hasBin: true
+ resolution: {integrity: sha512-oQL6lgK3e2QZeQ7gcgIkS2YZPg5slw37hYufJ3edKlfQSGGm8ICoxswK15ntSzF/a8+h7ekRy7k7oWc3BQ7y8A==}
+ engines: {node: '>=18.0.0', npm: '>=8.0.0'}
+ hasBin: true
+
resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==}
@@ -4362,6 +4625,9 @@ packages:
resolution: {integrity: sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
+
resolution: {integrity: sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==}
@@ -4410,6 +4676,12 @@ packages:
resolution: {integrity: sha512-+L3ccpzibovGXFK+Ap/f8LOS0ahMrHTf3xu7mMLSpEGU0EO9ucaysSylKo9eRDFNhWve/y275iPmIZ4z39a9iA==}
+ resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
+
+ resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==}
+
resolution: {integrity: sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==}
engines: {node: '>= 0.4'}
@@ -4538,10 +4810,21 @@ packages:
resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==}
+ resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
+
+ resolution: {integrity: sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==}
engines: {node: '>=12.0.0'}
+ resolution: {integrity: sha512-PSkbLUoxOFRzJYjjxHJt9xro7D+iilgMX/C9lawzVuYiIdcihh9DXmVibBe8lmcFrRi/VzlPjBxbN7rH24q8/Q==}
+ engines: {node: '>=14.0.0'}
+
resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==}
engines: {node: '>=8.0'}
@@ -4645,6 +4928,13 @@ packages:
eslint: ^8.57.0 || ^9.0.0
typescript: '>=4.8.4 <6.0.0'
+ resolution: {integrity: sha512-HE4wj+r5lmDVS9gdaN0/+iqNvPZwGfnJ5lZuz7s5vLlg9ODw0bIiiETaios9LvFI1U94/VBXGm3CB2Y5cNFMpw==}
+ engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
+ peerDependencies:
+ eslint: ^8.57.0 || ^9.0.0
+ typescript: '>=4.8.4 <6.0.0'
+
resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}
engines: {node: '>=14.17'}
@@ -4733,6 +5023,80 @@ packages:
resolution: {integrity: sha512-PnpQQMuxlwYdocC8fIJqVXvkeViHYzotI+NJrCuav0ZYFoq912ZHBk3mCeuj+5/VpodOjPe1z0Fk2ihgzlXqjQ==}
+ resolution: {integrity: sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ hasBin: true
+ peerDependencies:
+ '@types/node': ^20.19.0 || >=22.12.0
+ jiti: '>=1.21.0'
+ less: ^4.0.0
+ lightningcss: ^1.21.0
+ sass: ^1.70.0
+ sass-embedded: ^1.70.0
+ stylus: '>=0.54.8'
+ sugarss: ^5.0.0
+ terser: ^5.16.0
+ tsx: ^4.8.1
+ yaml: ^2.4.2
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+ jiti:
+ optional: true
+ less:
+ optional: true
+ lightningcss:
+ optional: true
+ sass:
+ optional: true
+ sass-embedded:
+ optional: true
+ stylus:
+ optional: true
+ sugarss:
+ optional: true
+ terser:
+ optional: true
+ tsx:
+ optional: true
+ yaml:
+ optional: true
+
+ resolution: {integrity: sha512-hOQuK7h0FGKgBAas7v0mSAsnvrIgAvWmRFjmzpJ7SwFHH3g1k2u37JtYwOwmEKhK6ZO3v9ggDBBm0La1LCK4uQ==}
+ engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0}
+ hasBin: true
+ peerDependencies:
+ '@edge-runtime/vm': '*'
+ '@opentelemetry/api': ^1.9.0
+ '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0
+ '@vitest/browser-playwright': 4.0.18
+ '@vitest/browser-preview': 4.0.18
+ '@vitest/browser-webdriverio': 4.0.18
+ '@vitest/ui': 4.0.18
+ happy-dom: '*'
+ jsdom: '*'
+ peerDependenciesMeta:
+ '@edge-runtime/vm':
+ optional: true
+ '@opentelemetry/api':
+ optional: true
+ '@types/node':
+ optional: true
+ '@vitest/browser-playwright':
+ optional: true
+ '@vitest/browser-preview':
+ optional: true
+ '@vitest/browser-webdriverio':
+ optional: true
+ '@vitest/ui':
+ optional: true
+ happy-dom:
+ optional: true
+ jsdom:
+ optional: true
+
resolution: {integrity: sha512-Zn5uXdcFNIA1+1Ei5McRd+iRzfhENPCe7LeABkJtNulSxjma+l7ltNx55BWZkRlwRnpOgHqxnjyaDgJnNXnqzg==}
engines: {node: '>=10.13.0'}
@@ -4781,6 +5145,11 @@ packages:
engines: {node: '>= 8'}
hasBin: true
+ resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}
+ engines: {node: '>=8'}
+ hasBin: true
+
resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}
engines: {node: '>=0.10.0'}
@@ -6857,10 +7226,87 @@ snapshots:
optionalDependencies:
rollup: 2.79.2
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
'@rtsao/[email protected]': {}
'@schummar/[email protected]': {}
+ '@standard-schema/[email protected]': {}
+
dependencies:
ejs: 3.1.10
@@ -7017,6 +7463,11 @@ snapshots:
dependencies:
'@types/node': 22.19.9
+ '@types/[email protected]':
+ dependencies:
+ '@types/deep-eql': 4.0.2
+ assertion-error: 2.0.1
+
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -7056,6 +7507,8 @@ snapshots:
'@types/d3-interpolate': 3.0.4
'@types/d3-selection': 3.0.11
+ '@types/[email protected]': {}
+
dependencies:
'@types/eslint': 9.6.1
@@ -7114,6 +7567,22 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@eslint-community/regexpp': 4.12.2
+ '@typescript-eslint/parser': 8.55.0([email protected]([email protected]))([email protected])
+ '@typescript-eslint/scope-manager': 8.55.0
+ '@typescript-eslint/type-utils': 8.55.0([email protected]([email protected]))([email protected])
+ '@typescript-eslint/utils': 8.55.0([email protected]([email protected]))([email protected])
+ '@typescript-eslint/visitor-keys': 8.55.0
+ eslint: 9.39.2([email protected])
+ ignore: 7.0.5
+ natural-compare: 1.4.0
+ ts-api-utils: 2.4.0([email protected])
+ typescript: 5.9.3
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
'@typescript-eslint/scope-manager': 8.54.0
@@ -7126,6 +7595,18 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@typescript-eslint/scope-manager': 8.55.0
+ '@typescript-eslint/types': 8.55.0
+ '@typescript-eslint/typescript-estree': 8.55.0([email protected])
+ '@typescript-eslint/visitor-keys': 8.55.0
+ debug: 4.4.3
+ eslint: 9.39.2([email protected])
+ typescript: 5.9.3
+ transitivePeerDependencies:
+ - supports-color
+
'@typescript-eslint/[email protected]([email protected])':
dependencies:
'@typescript-eslint/tsconfig-utils': 8.54.0([email protected])
@@ -7135,15 +7616,33 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ '@typescript-eslint/[email protected]([email protected])':
+ dependencies:
+ '@typescript-eslint/tsconfig-utils': 8.55.0([email protected])
+ '@typescript-eslint/types': 8.55.0
+ debug: 4.4.3
+ typescript: 5.9.3
+ transitivePeerDependencies:
+ - supports-color
+
'@typescript-eslint/[email protected]':
dependencies:
'@typescript-eslint/types': 8.54.0
'@typescript-eslint/visitor-keys': 8.54.0
+ '@typescript-eslint/[email protected]':
+ dependencies:
+ '@typescript-eslint/types': 8.55.0
+ '@typescript-eslint/visitor-keys': 8.55.0
+
'@typescript-eslint/[email protected]([email protected])':
dependencies:
typescript: 5.9.3
+ '@typescript-eslint/[email protected]([email protected])':
+ dependencies:
+ typescript: 5.9.3
+
dependencies:
'@typescript-eslint/types': 8.54.0
@@ -7156,8 +7655,22 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@typescript-eslint/types': 8.55.0
+ '@typescript-eslint/typescript-estree': 8.55.0([email protected])
+ '@typescript-eslint/utils': 8.55.0([email protected]([email protected]))([email protected])
+ debug: 4.4.3
+ eslint: 9.39.2([email protected])
+ ts-api-utils: 2.4.0([email protected])
+ typescript: 5.9.3
+ transitivePeerDependencies:
+ - supports-color
+
'@typescript-eslint/[email protected]': {}
+ '@typescript-eslint/[email protected]': {}
+
'@typescript-eslint/[email protected]([email protected])':
dependencies:
'@typescript-eslint/project-service': 8.54.0([email protected])
@@ -7173,6 +7686,21 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ '@typescript-eslint/[email protected]([email protected])':
+ dependencies:
+ '@typescript-eslint/project-service': 8.55.0([email protected])
+ '@typescript-eslint/tsconfig-utils': 8.55.0([email protected])
+ '@typescript-eslint/types': 8.55.0
+ '@typescript-eslint/visitor-keys': 8.55.0
+ debug: 4.4.3
+ minimatch: 9.0.5
+ semver: 7.7.3
+ tinyglobby: 0.2.15
+ ts-api-utils: 2.4.0([email protected])
+ typescript: 5.9.3
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
'@eslint-community/eslint-utils': 4.9.1([email protected]([email protected]))
@@ -7184,11 +7712,27 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@eslint-community/eslint-utils': 4.9.1([email protected]([email protected]))
+ '@typescript-eslint/scope-manager': 8.55.0
+ '@typescript-eslint/types': 8.55.0
+ '@typescript-eslint/typescript-estree': 8.55.0([email protected])
+ eslint: 9.39.2([email protected])
+ typescript: 5.9.3
+ transitivePeerDependencies:
+ - supports-color
+
'@typescript-eslint/[email protected]':
dependencies:
'@typescript-eslint/types': 8.54.0
eslint-visitor-keys: 4.2.1
+ '@typescript-eslint/[email protected]':
+ dependencies:
+ '@typescript-eslint/types': 8.55.0
+ eslint-visitor-keys: 4.2.1
+
optional: true
@@ -7248,6 +7792,45 @@ snapshots:
optional: true
+ '@vitest/[email protected]':
+ dependencies:
+ '@standard-schema/spec': 1.1.0
+ '@types/chai': 5.2.3
+ '@vitest/spy': 4.0.18
+ '@vitest/utils': 4.0.18
+ chai: 6.2.2
+ tinyrainbow: 3.0.3
+
+ dependencies:
+ '@vitest/spy': 4.0.18
+ estree-walker: 3.0.3
+ magic-string: 0.30.21
+ optionalDependencies:
+
+ '@vitest/[email protected]':
+ dependencies:
+ tinyrainbow: 3.0.3
+
+ '@vitest/[email protected]':
+ dependencies:
+ '@vitest/utils': 4.0.18
+ pathe: 2.0.3
+
+ '@vitest/[email protected]':
+ dependencies:
+ '@vitest/pretty-format': 4.0.18
+ magic-string: 0.30.21
+ pathe: 2.0.3
+
+ '@vitest/[email protected]': {}
+
+ '@vitest/[email protected]':
+ dependencies:
+ '@vitest/pretty-format': 4.0.18
+ tinyrainbow: 3.0.3
+
'@webassemblyjs/[email protected]':
dependencies:
'@webassemblyjs/helper-numbers': 1.13.2
@@ -7469,6 +8052,8 @@ snapshots:
get-intrinsic: 1.3.0
is-array-buffer: 3.0.5
+
@@ -7586,6 +8171,8 @@ snapshots:
+
dependencies:
ansi-styles: 4.3.0
@@ -7925,6 +8512,8 @@ snapshots:
iterator.prototype: 1.1.5
safe-array-concat: 1.1.3
+
@@ -7986,7 +8575,7 @@ snapshots:
'@next/eslint-plugin-next': 16.1.6
eslint: 9.39.2([email protected])
eslint-import-resolver-node: 0.3.9
- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))
eslint-plugin-react: 7.37.5([email protected]([email protected]))
@@ -8009,7 +8598,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@nolyfill/is-core-module': 1.0.39
debug: 4.4.3
@@ -8024,14 +8613,14 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
debug: 3.2.7
optionalDependencies:
'@typescript-eslint/parser': 8.54.0([email protected]([email protected]))([email protected])
eslint: 9.39.2([email protected])
eslint-import-resolver-node: 0.3.9
- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
@@ -8046,7 +8635,7 @@ snapshots:
doctrine: 2.1.0
eslint: 9.39.2([email protected])
eslint-import-resolver-node: 0.3.9
hasown: 2.0.2
is-core-module: 2.16.1
is-glob: 4.0.3
@@ -8193,6 +8782,10 @@ snapshots:
+ dependencies:
+ '@types/estree': 1.0.8
+
@@ -8201,6 +8794,8 @@ snapshots:
+
@@ -8938,6 +9533,8 @@ snapshots:
define-properties: 1.2.1
es-object-atoms: 1.1.1
+
@@ -8979,6 +9576,8 @@ snapshots:
+
@@ -9307,6 +9906,37 @@ snapshots:
optionalDependencies:
fsevents: 2.3.3
+ dependencies:
+ '@types/estree': 1.0.8
+ optionalDependencies:
+ '@rollup/rollup-android-arm-eabi': 4.57.1
+ '@rollup/rollup-android-arm64': 4.57.1
+ '@rollup/rollup-darwin-arm64': 4.57.1
+ '@rollup/rollup-darwin-x64': 4.57.1
+ '@rollup/rollup-freebsd-arm64': 4.57.1
+ '@rollup/rollup-freebsd-x64': 4.57.1
+ '@rollup/rollup-linux-arm-gnueabihf': 4.57.1
+ '@rollup/rollup-linux-arm-musleabihf': 4.57.1
+ '@rollup/rollup-linux-arm64-gnu': 4.57.1
+ '@rollup/rollup-linux-arm64-musl': 4.57.1
+ '@rollup/rollup-linux-loong64-gnu': 4.57.1
+ '@rollup/rollup-linux-loong64-musl': 4.57.1
+ '@rollup/rollup-linux-ppc64-gnu': 4.57.1
+ '@rollup/rollup-linux-ppc64-musl': 4.57.1
+ '@rollup/rollup-linux-riscv64-gnu': 4.57.1
+ '@rollup/rollup-linux-riscv64-musl': 4.57.1
+ '@rollup/rollup-linux-s390x-gnu': 4.57.1
+ '@rollup/rollup-linux-x64-gnu': 4.57.1
+ '@rollup/rollup-linux-x64-musl': 4.57.1
+ '@rollup/rollup-openbsd-x64': 4.57.1
+ '@rollup/rollup-openharmony-arm64': 4.57.1
+ '@rollup/rollup-win32-arm64-msvc': 4.57.1
+ '@rollup/rollup-win32-ia32-msvc': 4.57.1
+ '@rollup/rollup-win32-x64-gnu': 4.57.1
+ '@rollup/rollup-win32-x64-msvc': 4.57.1
+ fsevents: 2.3.3
+
dependencies:
queue-microtask: 1.2.3
@@ -9449,6 +10079,8 @@ snapshots:
side-channel-map: 1.0.1
side-channel-weakmap: 1.0.2
+
@@ -9489,6 +10121,10 @@ snapshots:
+
+
dependencies:
es-errors: 1.3.0
@@ -9631,11 +10267,17 @@ snapshots:
+
+
dependencies:
fdir: 6.5.0([email protected])
picomatch: 4.0.3
+
dependencies:
is-number: 7.0.0
@@ -9753,6 +10395,17 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@typescript-eslint/parser': 8.55.0([email protected]([email protected]))([email protected])
+ '@typescript-eslint/typescript-estree': 8.55.0([email protected])
+ '@typescript-eslint/utils': 8.55.0([email protected]([email protected]))([email protected])
+ eslint: 9.39.2([email protected])
+ typescript: 5.9.3
+ transitivePeerDependencies:
+ - supports-color
+
@@ -9863,6 +10516,59 @@ snapshots:
d3-time: 3.1.0
d3-timer: 3.0.1
+ dependencies:
+ esbuild: 0.27.2
+ fdir: 6.5.0([email protected])
+ picomatch: 4.0.3
+ postcss: 8.5.6
+ rollup: 4.57.1
+ tinyglobby: 0.2.15
+ optionalDependencies:
+ '@types/node': 22.19.9
+ fsevents: 2.3.3
+ jiti: 2.6.1
+ lightningcss: 1.30.2
+ terser: 5.46.0
+ tsx: 4.21.0
+
+ dependencies:
+ '@vitest/expect': 4.0.18
+ '@vitest/pretty-format': 4.0.18
+ '@vitest/runner': 4.0.18
+ '@vitest/snapshot': 4.0.18
+ '@vitest/spy': 4.0.18
+ '@vitest/utils': 4.0.18
+ es-module-lexer: 1.7.0
+ expect-type: 1.3.0
+ magic-string: 0.30.21
+ obug: 2.1.1
+ pathe: 2.0.3
+ picomatch: 4.0.3
+ std-env: 3.10.0
+ tinybench: 2.9.0
+ tinyexec: 1.0.2
+ tinyglobby: 0.2.15
+ tinyrainbow: 3.0.3
+ why-is-node-running: 2.3.0
+ optionalDependencies:
+ '@types/node': 22.19.9
+ transitivePeerDependencies:
+ - jiti
+ - less
+ - lightningcss
+ - msw
+ - sass
+ - sass-embedded
+ - stylus
+ - sugarss
+ - terser
+ - tsx
+ - yaml
+
dependencies:
glob-to-regexp: 0.4.1
@@ -9960,6 +10666,11 @@ snapshots:
dependencies:
isexe: 2.0.0
+ dependencies:
+ siginfo: 2.0.0
+ stackback: 0.0.2
+