diff --git a/.github/workflows/ui-npm-publish.yml b/.github/workflows/ui-npm-publish.yml new file mode 100644 index 00000000..a7a43044 --- /dev/null +++ b/.github/workflows/ui-npm-publish.yml @@ -0,0 +1,103 @@ +name: Publish UI to npm + +on: + push: + branches: [main] + paths: + - 'packages/ui/**' + - 'package.json' + - 'pnpm-lock.yaml' + - 'pnpm-workspace.yaml' + - 'tsconfig.base.json' + workflow_dispatch: + +permissions: + contents: read + id-token: write + +concurrency: + group: ui-npm-publish-${{ github.ref }} + cancel-in-progress: false + +jobs: + publish: + name: Build and publish UI + runs-on: ubuntu-latest + environment: SnowLuma + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Setup pnpm + uses: pnpm/action-setup@v6 + with: + version: 10.28.0 + run_install: false + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: '22' + cache: 'pnpm' + registry-url: 'https://registry.npmjs.org' + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Type check UI + run: pnpm --filter @snowluma/ui typecheck + + - name: Build UI + run: pnpm --filter @snowluma/ui build + + - name: Check npm package version + id: npm + working-directory: packages/ui + shell: bash + run: | + set -euo pipefail + package_name="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).name)")" + package_version="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).version)")" + + { + echo "package_name=${package_name}" + echo "package_version=${package_version}" + } >> "${GITHUB_OUTPUT}" + + if npm view "${package_name}@${package_version}" version >/dev/null 2>&1; then + echo "already_published=true" >> "${GITHUB_OUTPUT}" + echo "::notice::${package_name}@${package_version} already exists on npm; skipping publish." + else + echo "already_published=false" >> "${GITHUB_OUTPUT}" + fi + + - name: Validate npm token + if: steps.npm.outputs.already_published != 'true' + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + run: | + if [ -z "${NODE_AUTH_TOKEN}" ]; then + echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2 + exit 1 + fi + + - name: Publish UI to npm + if: steps.npm.outputs.already_published != 'true' + working-directory: packages/ui + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + run: npm publish --access public --provenance + + - name: Summary + shell: bash + run: | + { + echo "## UI npm publish" + echo + echo "| Key | Value |" + echo "| --- | --- |" + echo "| Package | \`${{ steps.npm.outputs.package_name }}\` |" + echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |" + echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |" + echo "| Environment | \`SnowLuma\` |" + } >> "${GITHUB_STEP_SUMMARY}" diff --git a/compat/qq.json b/compat/qq.json new file mode 100644 index 00000000..abb081bf --- /dev/null +++ b/compat/qq.json @@ -0,0 +1,19 @@ +{ + "$schema": "./qq.schema.json", + "version": 1, + "updatedAt": "2026-05-16T00:00:00Z", + "policy": { + "allowUnknown": true, + "warnUnknown": true + }, + "knownGoodVersions": [], + "knownBadVersions": [], + "minVersion": null, + "notes": [ + "QQ 兼容性 manifest — Desktop 启动时拉 https://raw.githubusercontent.com/SnowLuma/SnowLuma/main/compat/qq.json 校验本地 QQ 版本", + "policy.allowUnknown = true: 任何不在 knownBadVersions 里的版本都允许(理论上所有 QQ 新版本都可用)", + "knownBadVersions: 列在这里的版本 Desktop 会拒绝注入,弹出引导让用户切版本", + "minVersion: 设为 SemVer 字符串则更早的版本会被拒", + "知道某个版本会破坏 Hook 后把它加进 knownBadVersions,加 reason 字段说明" + ] +} diff --git a/compat/qq.schema.json b/compat/qq.schema.json new file mode 100644 index 00000000..0f0e3061 --- /dev/null +++ b/compat/qq.schema.json @@ -0,0 +1,56 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "SnowLuma QQ compatibility manifest", + "type": "object", + "required": ["version", "policy", "knownGoodVersions", "knownBadVersions"], + "properties": { + "$schema": { "type": "string" }, + "version": { "type": "integer", "const": 1 }, + "updatedAt": { "type": "string", "format": "date-time" }, + "policy": { + "type": "object", + "required": ["allowUnknown"], + "properties": { + "allowUnknown": { + "type": "boolean", + "description": "若 true,未在 known* 中列出的版本视为允许;若 false,需明确出现在 knownGoodVersions" + }, + "warnUnknown": { + "type": "boolean", + "description": "未列出的版本启动时是否弹警告" + } + } + }, + "knownGoodVersions": { + "type": "array", + "items": { + "type": "object", + "required": ["version"], + "properties": { + "version": { "type": "string", "description": "QQ 版本号字符串,如 '9.9.20.123'" }, + "note": { "type": "string" } + } + } + }, + "knownBadVersions": { + "type": "array", + "items": { + "type": "object", + "required": ["version"], + "properties": { + "version": { "type": "string" }, + "reason": { "type": "string" }, + "fixedInDesktopVersion": { "type": "string" } + } + } + }, + "minVersion": { + "type": ["string", "null"], + "description": "最低支持版本(SemVer),null = 不限" + }, + "notes": { + "type": "array", + "items": { "type": "string" } + } + } +} diff --git a/package.json b/package.json index 57eb5c9f..3de5e909 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "snowluma-monorepo", - "version": "1.8.1", + "version": "1.8.2", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", diff --git a/packages/core/package.json b/packages/core/package.json index 0b706b72..9c52bf0b 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/core", - "version": "1.8.1", + "version": "1.8.2", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", diff --git a/packages/core/src/bridge/actions/forward.ts b/packages/core/src/bridge/actions/forward.ts index 0181a5fc..6558c4b7 100644 --- a/packages/core/src/bridge/actions/forward.ts +++ b/packages/core/src/bridge/actions/forward.ts @@ -28,12 +28,16 @@ const forwardResCache = new Map(); async function buildForwardPushBody( bridge: Bridge, node: ForwardNodePayload, + groupId?: number, ): Promise> { const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.identity.uin); if (fromUin <= 0) throw new Error('forward node user uin is invalid'); const nickname = node.nickname.trim() || String(fromUin); - const elems = await buildSendElems(node.elements); + const sendCtx = groupId !== undefined + ? { bridge, groupId } + : { bridge }; + const elems = await buildSendElems(node.elements, sendCtx); const now = Math.floor(Date.now() / 1000); const random = Math.floor(Math.random() * 0x7fffffff) >>> 0; const seq = Math.floor(Math.random() * 9000000) + 1000000; @@ -67,7 +71,7 @@ export async function uploadForwardNodes(bridge: Bridge, nodes: ForwardNodePaylo throw new Error('forward nodes are required'); } - const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node))); + const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node, groupId))); const longMsgResult = protoEncode({ action: [ { diff --git a/packages/core/src/bridge/actions/group-file.ts b/packages/core/src/bridge/actions/group-file.ts index 969b13ff..06f8c123 100644 --- a/packages/core/src/bridge/actions/group-file.ts +++ b/packages/core/src/bridge/actions/group-file.ts @@ -9,7 +9,7 @@ import type { Bridge } from '../bridge'; import { protoEncode } from '../../protobuf/decode'; import { runOidb } from '../bridge-oidb'; import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client'; -import { computeHashes, computeMd5, loadBinarySource } from '../highway/utils'; +import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '../highway/utils'; import { OidbGroupFileCountViewReqSchema, OidbGroupFileCountViewRespSchema, @@ -288,7 +288,9 @@ export async function uploadGroupFile( folderId = '/', uploadFile = true, ): Promise { - const loaded = await loadBinarySource(source, 'file'); + // Group/private files may legitimately be up to 4 GiB on QQ's wire, + // so override the default 1 GiB cap with the protocol ceiling. + const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES); if (!loaded.bytes.length) throw new Error('group file is empty'); const fileName = normalizeUploadFileName(name, loaded.fileName); @@ -366,7 +368,9 @@ export async function uploadPrivateFile( name = '', uploadFile = true, ): Promise { - const loaded = await loadBinarySource(source, 'file'); + // Group/private files may legitimately be up to 4 GiB on QQ's wire, + // so override the default 1 GiB cap with the protocol ceiling. + const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES); if (!loaded.bytes.length) throw new Error('private file is empty'); const targetUid = await bridge.resolveUserUid(userId); diff --git a/packages/core/src/bridge/element-builder.ts b/packages/core/src/bridge/element-builder.ts index b07f7980..74217fd4 100644 --- a/packages/core/src/bridge/element-builder.ts +++ b/packages/core/src/bridge/element-builder.ts @@ -37,19 +37,43 @@ function makeFaceElem(faceId: number): ProtoElem { }; } -function makeMentionElem(element: MessageElement): ProtoElem { +function resolveMentionDisplay(ctx: SendContext | undefined, targetUin: number): string { + if (!ctx || !targetUin) return ''; + if (ctx.groupId !== undefined) { + const member = ctx.bridge.identity.findGroupMember(ctx.groupId, targetUin); + return member?.card?.trim() || member?.nickname?.trim() || ''; + } + const friend = ctx.bridge.identity.findFriend(targetUin); + return friend?.remark?.trim() || friend?.nickname?.trim() || ''; +} + +function makeMentionElem(element: MessageElement, ctx?: SendContext): ProtoElem { const mentionAll = element.uid === 'all' || element.targetUin === 0; + const targetUin = element.targetUin ?? 0; const extra = protoEncode({ type: mentionAll ? 1 : 2, - uin: mentionAll ? 0 : (element.targetUin ?? 0), + uin: mentionAll ? 0 : targetUin, field5: 0, uid: mentionAll ? 'all' : (element.uid ?? ''), }, MentionExtraSendSchema); + // Prefer an explicit display string from the caller; otherwise look the + // target up in the roster so QQ renders `@昵称` instead of `@QQ号`. + // Falls back to the bare uin when the roster doesn't know them yet. + let str = element.text; + if (!str) { + if (mentionAll) { + str = '@全体成员 '; + } else { + const name = resolveMentionDisplay(ctx, targetUin); + str = name ? `@${name} ` : `@${targetUin} `; + } + } + return { text: { - str: element.text || (mentionAll ? '@全体成员 ' : `@${element.targetUin} `), + str, pbReserve: extra, } as any, }; @@ -260,7 +284,7 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte break; case 'at': - result.push(makeMentionElem(elem)); + result.push(makeMentionElem(elem, ctx)); break; case 'reply': diff --git a/packages/core/src/bridge/highway/highway-client.ts b/packages/core/src/bridge/highway/highway-client.ts index dcffbd74..99d3c385 100644 --- a/packages/core/src/bridge/highway/highway-client.ts +++ b/packages/core/src/bridge/highway/highway-client.ts @@ -129,10 +129,31 @@ export function buildHighwayExtend( function tcpConnect(host: string, port: number, timeoutMs = 10000): Promise { return new Promise((resolve, reject) => { - const socket = net.createConnection({ host, port }, () => resolve(socket)); + let settled = false; + const onTimeout = () => { + if (settled) return; + settled = true; + socket.destroy(); + reject(new Error('TCP connect timeout')); + }; + const onError = (err: Error) => { + if (settled) return; + settled = true; + reject(err); + }; + const socket = net.createConnection({ host, port }, () => { + if (settled) return; + settled = true; + // Drop the connect-only listeners so subsequent IO errors / idle + // timeouts don't try to reject this already-resolved promise. + socket.setTimeout(0); + socket.removeListener('timeout', onTimeout); + socket.removeListener('error', onError); + resolve(socket); + }); socket.setTimeout(timeoutMs); - socket.on('timeout', () => { socket.destroy(); reject(new Error('TCP connect timeout')); }); - socket.on('error', reject); + socket.once('timeout', onTimeout); + socket.once('error', onError); }); } @@ -148,8 +169,21 @@ function readHttpResponseBody(socket: net.Socket): Promise { let headerEnd = -1; let contentLength = 0; let totalNeeded = 0; + let settled = false; - const checkComplete = () => { + const detach = () => { + socket.off('data', onData); + socket.off('error', onError); + socket.off('close', onClose); + }; + const finish = (fn: () => void) => { + if (settled) return; + settled = true; + detach(); + fn(); + }; + const onData = (chunk: Buffer) => { + chunks.push(chunk); const buf = Buffer.concat(chunks); if (headerEnd < 0) { const idx = buf.indexOf('\r\n\r\n'); @@ -162,19 +196,19 @@ function readHttpResponseBody(socket: net.Socket): Promise { } } if (headerEnd >= 0 && buf.length >= totalNeeded) { - socket.removeAllListeners('data'); - socket.removeAllListeners('error'); - resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded))); + finish(() => resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded)))); } }; - - socket.on('data', (chunk) => { chunks.push(chunk); checkComplete(); }); - socket.on('error', reject); - socket.on('close', () => { + const onError = (err: Error) => finish(() => reject(err)); + const onClose = () => finish(() => { const buf = Buffer.concat(chunks); if (headerEnd >= 0) resolve(new Uint8Array(buf.subarray(headerEnd))); else reject(new Error('connection closed before response')); }); + + socket.on('data', onData); + socket.on('error', onError); + socket.on('close', onClose); }); } diff --git a/packages/core/src/bridge/highway/utils.ts b/packages/core/src/bridge/highway/utils.ts index a39ceabf..963c7323 100644 --- a/packages/core/src/bridge/highway/utils.ts +++ b/packages/core/src/bridge/highway/utils.ts @@ -11,6 +11,20 @@ export interface LoadedBinary { fileName: string; } +/** + * Default cap on a single binary load issued through this helper. Callers + * that route here (image / voice via base64+HTTP, group/private file + * uploads, avatar) get bounded reads. Not all callers route through here + * — in particular `video-upload.stageVideoSource` reads local-video files + * directly and enforces its own cap via `MAX_VIDEO_SIZE`. Group/private + * file uploads override this via `FILE_UPLOAD_MAX_BYTES` because QQ's + * file protocol legitimately supports up to 4 GiB. + */ +const DEFAULT_MAX_BINARY_SIZE = 1024 * 1024 * 1024; // 1 GiB +/** Hard ceiling QQ's file protocol supports — used by group/private files. */ +export const FILE_UPLOAD_MAX_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB +const FETCH_TIMEOUT_MS = 60_000; + export interface ImageHashes { md5: Uint8Array; sha1: Uint8Array; @@ -54,24 +68,74 @@ export function resolveLocalFilePath(source: string): string | null { return filePath; } -export async function loadBinarySource(source: string, resourceName: string): Promise { +export async function loadBinarySource( + source: string, + resourceName: string, + maxBytes: number = DEFAULT_MAX_BINARY_SIZE, +): Promise { if (!source) throw new Error(`${resourceName} source is empty`); if (/^base64:\/\//i.test(source)) { - return { bytes: Buffer.from(source.slice(9), 'base64'), fileName: '' }; + const bytes = Buffer.from(source.slice(9), 'base64'); + if (bytes.length > maxBytes) { + throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`); + } + return { bytes, fileName: '' }; } if (/^https?:\/\//i.test(source)) { - const resp = await fetch(source); + const resp = await fetch(source, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) }); if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`); - const bytes = new Uint8Array(await resp.arrayBuffer()); + const declared = Number(resp.headers.get('content-length') ?? '0'); + if (Number.isFinite(declared) && declared > maxBytes) { + throw new Error(`${resourceName} too large: ${declared} > ${maxBytes}`); + } const fileName = guessFileNameFromUrl(source); + // Stream the body incrementally so a server that omits or + // understates Content-Length can't make us buffer a chunked response + // past maxBytes — `await resp.arrayBuffer()` would happily allocate + // the entire payload before we get a chance to length-check it. + const reader = resp.body?.getReader(); + if (!reader) { + const bytes = new Uint8Array(await resp.arrayBuffer()); + if (bytes.length > maxBytes) { + throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`); + } + return { bytes, fileName }; + } + const chunks: Uint8Array[] = []; + let total = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + if (!value) continue; + total += value.byteLength; + if (total > maxBytes) { + await reader.cancel().catch(() => { /* ignore */ }); + throw new Error(`${resourceName} too large: > ${maxBytes}`); + } + chunks.push(value); + } + } finally { + reader.releaseLock(); + } + const bytes = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } return { bytes, fileName }; } const filePath = resolveLocalFilePath(source); if (!filePath) throw new Error(`${resourceName} source is not a local file`); + const stat = fs.statSync(filePath); + if (stat.size > maxBytes) { + throw new Error(`${resourceName} too large: ${stat.size} > ${maxBytes}`); + } const bytes = fs.readFileSync(filePath); const fileName = path.basename(filePath); return { bytes, fileName }; @@ -183,7 +247,12 @@ export function detectImageFormat(bytes: Uint8Array): ImageFormat { if (offset + 4 > bytes.length) break; const segLen = readBE16(bytes, offset + 2); if (segLen < 2 || offset + 2 + segLen > bytes.length) break; - if ((marker & 0xFC) === 0xC0 && offset + 9 <= bytes.length) { + // Real SOF markers: 0xC0..0xCF EXCEPT 0xC4 (DHT), 0xC8 (JPG), 0xCC + // (DAC). The previous `(marker & 0xFC) === 0xC0` check accepted DHT + // and friends, then misread Huffman table bytes as image dimensions. + const isSof = marker >= 0xC0 && marker <= 0xCF + && marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC; + if (isSof && segLen >= 7 && offset + 9 <= bytes.length) { height = readBE16(bytes, offset + 5); width = readBE16(bytes, offset + 7); return { format: 1000, width, height }; diff --git a/packages/core/src/bridge/highway/video-upload.ts b/packages/core/src/bridge/highway/video-upload.ts index b8990ce3..a0778c6e 100644 --- a/packages/core/src/bridge/highway/video-upload.ts +++ b/packages/core/src/bridge/highway/video-upload.ts @@ -280,6 +280,14 @@ async function stageVideoSource(element: MessageElement, tempDir: string, cleanu const local = resolveLocalFilePath(source); if (local && fs.existsSync(local)) { + // Pre-check on disk size BEFORE reading bytes into memory. The later + // `staged.bytes.length > MAX_VIDEO_SIZE` guard would otherwise only + // run after we'd already allocated the entire file (so a 10 GiB + // local path still OOMs us before the check fires). + const stat = fs.statSync(local); + if (stat.size > MAX_VIDEO_SIZE) { + throw new Error(`video file too large: ${(stat.size / (1024 * 1024)).toFixed(2)} MB > ${MAX_VIDEO_SIZE / (1024 * 1024)} MB. Use upload_group_file / upload_private_file for files larger than 100 MB.`); + } return { bytes: new Uint8Array(fs.readFileSync(local)), filePath: local, @@ -287,7 +295,7 @@ async function stageVideoSource(element: MessageElement, tempDir: string, cleanu }; } - const loaded = await loadBinarySource(source, 'video'); + const loaded = await loadBinarySource(source, 'video', MAX_VIDEO_SIZE); const fileName = element.fileName || loaded.fileName || ''; const stagedPath = path.join(tempDir, `snowluma-video-in-${crypto.randomUUID()}${sourceExtension(fileName, source)}`); fs.writeFileSync(stagedPath, Buffer.from(loaded.bytes)); @@ -375,7 +383,7 @@ async function loadVideo(element: MessageElement): Promise { const staged = await stageVideoSource(element, tempDir, cleanups); if (staged.bytes.length === 0) throw new Error('video file is empty'); if (staged.bytes.length > MAX_VIDEO_SIZE) { - throw new Error(`video file too large: ${(staged.bytes.length / (1024 * 1024)).toFixed(2)} MB > 100 MB`); + throw new Error(`video file too large: ${(staged.bytes.length / (1024 * 1024)).toFixed(2)} MB > 100 MB. Use upload_group_file / upload_private_file for files larger than 100 MB.`); } const hashes = computeHashes(staged.bytes); @@ -487,11 +495,17 @@ export async function uploadVideoMsgInfo( subFileType: 100, }, ], - // Scene tag the NTV2 upload registers under. image-upload and - // ptt-upload both differentiate (group=2, c2c=1); video was - // hardcoded to the group value, which contributed to the c2c - // send-back rejection (PbSendMsg result=79). - compatQmsgSceneType: isGroup ? 2 : 1, + // Hardcoded 2 even on c2c (matches NapCat). Image/PTT use + // `isGroup ? 2 : 1` because their legacy compat elements differ + // per scene (notOnlineImage vs customFace; ptt c2c vs group), + // but the legacy `videoFile` element has no scene split — its + // fromChatType/toChatType live inside the element itself — so + // the server generates a single group-shaped compat payload + // regardless. Setting 1 here makes the server emit a c2c-scene + // shaped compat blob that old QQ clients fail to resolve, + // showing the message as "视频已过期" on those receivers while + // new clients (which only read the commonElem) display fine. + compatQmsgSceneType: 2, extBizInfo: { pic: { bizType: 0, textSummary: 'Nya~' }, video: { bytesPbReserve: new Uint8Array([0x80, 0x01, 0x00]) }, diff --git a/packages/core/src/bridge/identity-service.ts b/packages/core/src/bridge/identity-service.ts index 3b3dfbe2..c6918284 100644 --- a/packages/core/src/bridge/identity-service.ts +++ b/packages/core/src/bridge/identity-service.ts @@ -440,6 +440,13 @@ export class IdentityService { const normalizedUid = normalizeUid(uid); const normalizedUin = normalizeUin(uin); if (!normalizedUid || normalizedUin === null) return; + // Drop any stale mapping for the old partner first; otherwise the two + // maps disagree (`findUinByUid(oldUid) -> uin` while + // `findUidByUin(uin) -> newUid`) after a uid/uin re-binding. + const oldUid = this.uidByUin.get(normalizedUin); + if (oldUid && oldUid !== normalizedUid) this.uinByUid.delete(oldUid); + const oldUin = this.uinByUid.get(normalizedUid); + if (oldUin !== undefined && oldUin !== normalizedUin) this.uidByUin.delete(oldUin); this.uinByUid.set(normalizedUid, normalizedUin); this.uidByUin.set(normalizedUin, normalizedUid); } diff --git a/packages/core/src/common/runtime.ts b/packages/core/src/common/runtime.ts index bfaa9737..d1f5e610 100644 --- a/packages/core/src/common/runtime.ts +++ b/packages/core/src/common/runtime.ts @@ -21,26 +21,45 @@ export function loadRuntimeConfig(): RuntimeConfig { fs.mkdirSync(CONFIG_DIR, { recursive: true }); const loaded = tryLoadRuntimeConfig(); + let normalized: RuntimeConfig; if (!loaded) { saveRuntimeConfig(DEFAULT_RUNTIME_CONFIG); - return { ...DEFAULT_RUNTIME_CONFIG }; + normalized = { ...DEFAULT_RUNTIME_CONFIG }; + } else { + normalized = { + webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099), + hookAutoLoad: normalizeBool(loaded.hookAutoLoad, false), + }; + if ( + normalized.webuiPort !== loaded.webuiPort + || normalized.hookAutoLoad !== loaded.hookAutoLoad + ) { + saveRuntimeConfig(normalized); + } } - const normalized: RuntimeConfig = { - webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099), - hookAutoLoad: normalizeBool(loaded.hookAutoLoad, false), - }; - - if ( - normalized.webuiPort !== loaded.webuiPort - || normalized.hookAutoLoad !== loaded.hookAutoLoad - ) { - saveRuntimeConfig(normalized); + // SNOWLUMA_WEBUI_PORT overrides the on-disk value at runtime without + // rewriting runtime.json. Lets a trusted launcher (e.g. SnowLumaDesktop) + // pick a free port per-launch while CLI/Docker users continue to drive + // it from runtime.json. + const envPort = envPortOverride(); + if (envPort !== undefined) { + normalized = { ...normalized, webuiPort: envPort }; } return normalized; } +function envPortOverride(): number | undefined { + const raw = process.env.SNOWLUMA_WEBUI_PORT; + if (!raw || typeof raw !== 'string') return undefined; + const n = Number(raw.trim()); + if (!Number.isFinite(n)) return undefined; + const port = Math.trunc(n); + if (port <= 0 || port > 65535) return undefined; + return port; +} + function tryLoadRuntimeConfig(): RuntimeConfig | null { if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null; diff --git a/packages/core/src/hook/qq-hook-client.ts b/packages/core/src/hook/qq-hook-client.ts index 9844a750..4b195f39 100644 --- a/packages/core/src/hook/qq-hook-client.ts +++ b/packages/core/src/hook/qq-hook-client.ts @@ -444,7 +444,18 @@ export class QqHookClient extends EventEmitter { }: QqHookSendOptions = {}): Promise { await this.connect(); - const requestId = this.nextRequestId++ >>> 0; + // Wrap inside uint32 explicitly. `nextRequestId++ >>> 0` would + // misbehave once the integer exceeds Number.MAX_SAFE_INTEGER (the + // postfix increment loses precision before the shift), letting two + // distinct requests collide on the same id. Skip 0 because zero is + // used as a sentinel by the wire protocol. + let requestId = this.nextRequestId; + while (this.pendingAcks.has(requestId) || this.pendingReplies.has(requestId)) { + requestId = (requestId + 1) >>> 0; + if (requestId === 0) requestId = 1; + } + this.nextRequestId = (requestId + 1) >>> 0; + if (this.nextRequestId === 0) this.nextRequestId = 1; const payload = encodeFrame({ op: PipeOp.sendRequest, requestId, diff --git a/packages/core/src/onebot/actions/extended.ts b/packages/core/src/onebot/actions/extended.ts index 82fd4f99..3935872d 100644 --- a/packages/core/src/onebot/actions/extended.ts +++ b/packages/core/src/onebot/actions/extended.ts @@ -3,6 +3,62 @@ import { asMessage, asNumber, asString, asBoolean } from '../api-handler'; import type { ForwardPreviewMeta } from '../modules/message-actions'; import { RETCODE, failedResponse, okResponse } from '../types'; +// Bounded download for the OneBot `download_file` action. An authenticated +// client could otherwise hand us a multi-GB URL (or chunked response with +// no Content-Length) and OOM the bot — `await response.arrayBuffer()` +// happily allocates the whole payload before any size check fires. +const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB +const DOWNLOAD_FILE_TIMEOUT_MS = 60_000; + +async function fetchDownloadFile( + url: string, + headers: Record, + maxBytes: number, + timeoutMs: number, +): Promise { + const response = await fetch(url, { + headers, + signal: AbortSignal.timeout(timeoutMs), + }); + if (!response.ok) throw new Error(`download failed: HTTP ${response.status}`); + + const declared = Number(response.headers.get('content-length') ?? '0'); + if (Number.isFinite(declared) && declared > maxBytes) { + throw new Error(`download too large: ${declared} > ${maxBytes}`); + } + + const reader = response.body?.getReader(); + if (!reader) { + const bytes = Buffer.from(await response.arrayBuffer()); + if (bytes.length > maxBytes) { + throw new Error(`download too large: ${bytes.length} > ${maxBytes}`); + } + return bytes; + } + + // Stream so a server that omits / understates Content-Length can't make + // us buffer past maxBytes — abort the read as soon as the running total + // crosses the cap. + const chunks: Uint8Array[] = []; + let total = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + if (!value) continue; + total += value.byteLength; + if (total > maxBytes) { + await reader.cancel().catch(() => { /* ignore */ }); + throw new Error(`download too large: > ${maxBytes}`); + } + chunks.push(value); + } + } finally { + reader.releaseLock(); + } + return Buffer.concat(chunks, total); +} + /** * Pull NapCat-compatible forward preview overrides off a send_*_forward_msg * payload. All four fields are optional — when omitted, the module layer @@ -157,8 +213,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); } const meta = ctx.getMessageMeta(messageId); - if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found'); - if (!meta || !meta.isGroup) { return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a group message'); } @@ -167,8 +221,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session'); } - - await ctx.bridge.markGroupMsgAsRead(groupId, meta.sequence); + await ctx.bridge.markGroupMsgAsRead(meta.targetId, meta.sequence); return okResponse(); }); @@ -180,8 +233,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); } const meta = ctx.getMessageMeta(messageId); - if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found'); - if (!meta || meta.isGroup) { return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a private message'); } @@ -190,8 +241,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.BAD_REQUEST, 'user_id does not match message session'); } - - await ctx.bridge.markPrivateMsgAsRead(userId, meta.sequence); + await ctx.bridge.markPrivateMsgAsRead(meta.targetId, meta.sequence); return okResponse(); }); @@ -205,15 +255,14 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const meta = ctx.getMessageMeta(messageId); if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found'); - if (targetId && targetId !== meta.targetId) { return failedResponse(RETCODE.BAD_REQUEST, 'target_id does not match message session'); } if (meta.isGroup) { - await ctx.bridge.markGroupMsgAsRead(targetId, meta.sequence); + await ctx.bridge.markGroupMsgAsRead(meta.targetId, meta.sequence); } else { - await ctx.bridge.markPrivateMsgAsRead(targetId, meta.sequence); + await ctx.bridge.markPrivateMsgAsRead(meta.targetId, meta.sequence); } return okResponse(); }); @@ -310,7 +359,11 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const groupId = asNumber(params.group_id); if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); - const result = await ctx.sendForwardMsg(messages); + // Group and private forwards live in different resId namespaces + // (see bridge/actions/forward.ts: type=3+groupUin vs type=1+selfUid). + // Passing groupId through is what makes the resulting resId usable + // when the caller later sends it into the same group. + const result = await ctx.sendForwardMsg(messages, groupId > 0 ? groupId : undefined); const data: Record = { res_id: result.forwardId, forward_id: result.forwardId, @@ -320,10 +373,13 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return okResponse(data as any); }); + // Kept for backward compat with clients that follow the historical + // gocqhttp/NapCat docs misspelling; same semantics as upload_forward_msg. h.registerAction('upload_foward_msg', async (params) => { const messages = asMessage(params.messages ?? params.message); + const groupId = asNumber(params.group_id); if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); - const result = await ctx.sendForwardMsg(messages); + const result = await ctx.sendForwardMsg(messages, groupId > 0 ? groupId : undefined); return okResponse({ res_id: result.forwardId, forward_id: result.forwardId, message_id: 0 }); }); @@ -482,17 +538,23 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('set_friend_remark', async (params) => { const userId = asNumber(params.user_id); - const remark = asString(params.remark) ?? ''; if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - await ctx.bridge.setFriendRemark(userId, remark); + // remark must be explicitly provided. Falling back to '' on a missing + // field would silently CLEAR the operator's existing remark. + if (params.remark === undefined) { + return failedResponse(RETCODE.BAD_REQUEST, 'remark is required (pass an empty string to clear)'); + } + await ctx.bridge.setFriendRemark(userId, asString(params.remark)); return okResponse(); }); h.registerAction('set_group_remark', async (params) => { const groupId = asNumber(params.group_id); - const remark = asString(params.remark) ?? ''; if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - await ctx.bridge.setGroupRemark(groupId, remark); + if (params.remark === undefined) { + return failedResponse(RETCODE.BAD_REQUEST, 'remark is required (pass an empty string to clear)'); + } + await ctx.bridge.setGroupRemark(groupId, asString(params.remark)); return okResponse(); }); @@ -545,26 +607,55 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const fs = await import('fs'); const pathMod = await import('path'); const cryptoMod = await import('crypto'); - const tempDir = pathMod.join('data', 'downloads'); + const tempDir = pathMod.resolve('data', 'downloads'); if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true }); - let filePath: string; + // Sanitize file name: strip any path components, reject anything that + // resolves outside `tempDir`. Without this guard, `name = "../../config/onebot_x.json"` + // would let an authenticated OneBot client overwrite arbitrary files + // (config / dist / node_modules) under the working directory. + const resolveSafePath = (preferredName: string, fallbackBuf: Buffer): string | null => { + const raw = preferredName || cryptoMod.createHash('md5').update(fallbackBuf).digest('hex'); + const safeName = pathMod.basename(raw); + if (!safeName || safeName === '.' || safeName === '..' || /[\\/]/.test(safeName)) return null; + const resolved = pathMod.resolve(tempDir, safeName); + const rel = pathMod.relative(tempDir, resolved); + if (rel.startsWith('..') || pathMod.isAbsolute(rel)) return null; + return resolved; + }; + + let buf: Buffer; if (base64) { - const buf = Buffer.from(base64, 'base64'); - const fileName = name || cryptoMod.createHash('md5').update(buf).digest('hex'); - filePath = pathMod.join(tempDir, fileName); - fs.writeFileSync(filePath, buf); + // Every 4 base64 chars decode to at most 3 bytes. Reject before + // `Buffer.from` allocates anything to avoid OOM on a giant payload + // that wouldn't pass the post-decode check anyway. + const upperBound = Math.floor((base64.length * 3) / 4); + if (upperBound > DOWNLOAD_FILE_MAX_BYTES) { + return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: > ${DOWNLOAD_FILE_MAX_BYTES} bytes`); + } + buf = Buffer.from(base64, 'base64'); + if (buf.length > DOWNLOAD_FILE_MAX_BYTES) { + return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: ${buf.length} > ${DOWNLOAD_FILE_MAX_BYTES} bytes`); + } } else { - const response = await fetch(url!, { - headers: parseDownloadHeaders(params.headers), - }); - if (!response.ok) return failedResponse(RETCODE.ACTION_FAILED, `download failed: ${response.status}`); - const buf = Buffer.from(await response.arrayBuffer()); - const fileName = name || cryptoMod.createHash('md5').update(buf).digest('hex'); - filePath = pathMod.join(tempDir, fileName); - fs.writeFileSync(filePath, buf); + try { + buf = await fetchDownloadFile( + url!, + parseDownloadHeaders(params.headers), + DOWNLOAD_FILE_MAX_BYTES, + DOWNLOAD_FILE_TIMEOUT_MS, + ); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } } - return okResponse({ file: pathMod.resolve(filePath) }); + + const safe = resolveSafePath(name, buf); + if (!safe) return failedResponse(RETCODE.BAD_REQUEST, 'invalid file name'); + // Async write so we don't block the event loop on a GiB-class download + // (the prior `writeFileSync` stalled every other bot action while it ran). + await fs.promises.writeFile(safe, buf); + return okResponse({ file: safe }); }); h.registerAction('set_qq_profile', async (params) => { diff --git a/packages/core/src/onebot/api-handler.ts b/packages/core/src/onebot/api-handler.ts index 57f1dabf..2be74ec7 100644 --- a/packages/core/src/onebot/api-handler.ts +++ b/packages/core/src/onebot/api-handler.ts @@ -12,9 +12,6 @@ import { register as registerGroupFile } from './actions/group-file'; import { register as registerRequest } from './actions/request'; import { register as registerExtended } from './actions/extended'; -import { WebHonorType } from '@/bridge/web/group-honor'; -// import {ClientKeyInfo} from "@/bridge/bridge"; - export interface MessageSendResult { messageId: number; meta?: MessageMeta; @@ -91,7 +88,7 @@ export interface ApiActionContext { getDownloadRKeys: () => Promise; sendGroupForwardMsg: (groupId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>; sendPrivateForwardMsg: (userId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>; - sendForwardMsg: (messages: JsonValue) => Promise<{ forwardId: string }>; + sendForwardMsg: (messages: JsonValue, groupId?: number) => Promise<{ forwardId: string }>; getForwardMsg: (resId: string) => Promise; forwardSingleMsg: (messageId: number, target: { groupId?: number; userId?: number }) => Promise<{ messageId: number }>; setMsgEmojiLike: (messageId: number, emojiId: string, set: boolean) => Promise; diff --git a/packages/core/src/onebot/config.ts b/packages/core/src/onebot/config.ts index c4cb902e..5e1605df 100644 --- a/packages/core/src/onebot/config.ts +++ b/packages/core/src/onebot/config.ts @@ -1,6 +1,7 @@ import fs from 'fs'; import path from 'path'; import { randomBytes } from 'crypto'; +import { createLogger } from '../utils/logger'; import type { HttpClientNetwork, HttpServerNetwork, @@ -13,6 +14,8 @@ import type { WsServerNetwork, } from './types'; +const log = createLogger('OneBot.Config'); + const CONFIG_DIR = 'config'; const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json'); const DEFAULT_ACCESS_TOKEN_BYTES = 32; @@ -50,7 +53,18 @@ function generateAccessToken(): string { return randomBytes(DEFAULT_ACCESS_TOKEN_BYTES).toString('base64url'); } -export function loadOneBotConfig(uin: string): OneBotConfig { +export interface LoadOneBotConfigOptions { + /** + * Persist the normalized config to disk when the file is missing or was + * in legacy format. Default `false` so accidental call sites (read-only + * GETs in particular) don't generate fresh access tokens, race on + * concurrent writes, or surprise the operator with materialized files. + * Pass `true` from boot / explicit POST handlers. + */ + persistDefaults?: boolean; +} + +export function loadOneBotConfig(uin: string, options: LoadOneBotConfigOptions = {}): OneBotConfig { ensureConfigDir(); const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`); @@ -65,12 +79,11 @@ export function loadOneBotConfig(uin: string): OneBotConfig { if (globalRaw) sources.push(globalRaw); if (perUinRaw) sources.push(perUinRaw); - const config = fromJson(sources); + const config = fromJson(sources, !perUinRaw && !globalRaw); - // Persist normalized form whenever the file is missing OR was in legacy - // format, so downstream code can rely on the unified shape on disk. - const shouldSave = !perUinRaw || legacy; - if (shouldSave) saveOneBotConfig(uin, config); + if (options.persistDefaults && (!perUinRaw || legacy)) { + saveOneBotConfig(uin, config); + } return config; } @@ -148,7 +161,7 @@ function wsClientToJson(n: WsClientNetwork): JsonObject { return out; } -function fromJson(sources: JsonObject[]): OneBotConfig { +function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig { // Legacy top-level scalars are pulled DOWN into each adapter on the first // load: the on-disk schema has no globals anymore, every adapter is // self-describing. We compute the legacy fallbacks here so that adapters @@ -175,8 +188,11 @@ function fromJson(sources: JsonObject[]): OneBotConfig { const wsServers = collectByName(sources, 'wsServers', (raw) => parseWsServer(raw, adapterDefaults)); const wsClients = collectByName(sources, 'wsClients', (raw) => parseWsClient(raw, adapterDefaults)); - // Seed defaults if all four arrays are empty (brand-new install). + // Seed defaults ONLY for a brand-new install (no source files at all). + // If the operator deliberately emptied every adapter, respect that and + // do NOT silently revive default 0.0.0.0 listeners. if ( + freshInstall && httpServers.length === 0 && httpClients.length === 0 && wsServers.length === 0 && @@ -354,7 +370,8 @@ function tryLoadJson(filePath: string): JsonObject | null { const raw = fs.readFileSync(filePath, 'utf8'); const parsed = JSON.parse(raw) as unknown; return isObject(parsed) ? parsed : null; - } catch { + } catch (err) { + log.warn('config file %s is corrupt and will be ignored: %s', filePath, err instanceof Error ? err.message : String(err)); return null; } } @@ -364,20 +381,6 @@ function saveJson(filePath: string, json: JsonObject): void { fs.writeFileSync(filePath, JSON.stringify(json, null, 2), 'utf8'); } -function deepClone(obj: JsonObject): JsonObject { - return JSON.parse(JSON.stringify(obj)) as JsonObject; -} - -function deepMerge(base: JsonObject, override: JsonObject): void { - for (const [key, value] of Object.entries(override)) { - if (isObject(base[key]) && isObject(value)) { - deepMerge(base[key] as JsonObject, value); - } else { - base[key] = value as never; - } - } -} - function isObject(value: unknown): value is JsonObject { return typeof value === 'object' && value !== null && !Array.isArray(value); } diff --git a/packages/core/src/onebot/instance-context.ts b/packages/core/src/onebot/instance-context.ts index e9eba0e5..6c295d18 100644 --- a/packages/core/src/onebot/instance-context.ts +++ b/packages/core/src/onebot/instance-context.ts @@ -158,7 +158,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { getDownloadRKeys: () => getDownloadRKeys(bridge), sendGroupForwardMsg: (groupId, messages, meta) => sendGroupForwardMessage(ref, groupId, messages, meta), sendPrivateForwardMsg: (userId, messages, meta) => sendPrivateForwardMessage(ref, userId, messages, meta), - sendForwardMsg: (messages) => uploadForwardMessage(ref, messages), + sendForwardMsg: (messages, groupId) => uploadForwardMessage(ref, messages, groupId), getForwardMsg: (resId) => getForwardMessage(ref, resId), forwardSingleMsg: (messageId, target) => forwardSingleMessage(ref, messageId, target), handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block), diff --git a/packages/core/src/onebot/manager.ts b/packages/core/src/onebot/manager.ts index ec4dfca4..a2a4b8d0 100644 --- a/packages/core/src/onebot/manager.ts +++ b/packages/core/src/onebot/manager.ts @@ -35,7 +35,7 @@ export class OneBotManager { const instance = this.instances.get(uin); if (!instance) return false; - const config = loadOneBotConfig(uin); + const config = loadOneBotConfig(uin, { persistDefaults: true }); instance.reloadConfig(config); log.info('configuration reloaded: UIN=%s', uin); return true; @@ -51,7 +51,7 @@ export class OneBotManager { private onSessionStarted(uin: string, bridge: BridgeInterface): void { if (this.instances.has(uin)) return; - const config = loadOneBotConfig(uin); + const config = loadOneBotConfig(uin, { persistDefaults: true }); const instance = new OneBotInstance(uin, bridge, config); const activePid = bridge.activePid; diff --git a/packages/core/src/onebot/message-parser.ts b/packages/core/src/onebot/message-parser.ts index 89339ef1..2d9f7950 100644 --- a/packages/core/src/onebot/message-parser.ts +++ b/packages/core/src/onebot/message-parser.ts @@ -16,6 +16,19 @@ export interface ParseMessageOptions { const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g; +/** + * Best-effort base-10 integer coercion. Falls back to `fallback` (default 0) + * when the input can't be parsed as a finite integer — `parseInt('abc')` + * is `NaN`, which silently turns into `0`/`null` further down the wire + * pipeline and produces undebuggable protocol-level failures. + */ +function intOr(value: unknown, fallback = 0): number { + if (value === undefined || value === null) return fallback; + if (typeof value === 'number') return Number.isFinite(value) ? Math.trunc(value) : fallback; + const n = parseInt(String(value), 10); + return Number.isFinite(n) ? n : fallback; +} + function parseCQParams(raw: string): Record { const params: Record = {}; if (!raw) return params; @@ -33,9 +46,12 @@ function parseCQParams(raw: string): Record { } function cqUnescape(text: string): string { + // Order matters: `&` MUST be last so that, e.g., `&#91;` keeps + // the literal `[` instead of decoding twice into `[`. return text .replace(/[/g, '[') .replace(/]/g, ']') + .replace(/,/g, ',') .replace(/&/g, '&'); } @@ -88,7 +104,8 @@ async function segmentToElement(type: string, data: Record, opt return text ? { type: 'text', text } : null; } case 'face': { - const id = parseInt(String(data.id ?? '0'), 10); + const id = intOr(data.id, -1); + if (id < 0) return null; return { type: 'face', faceId: id }; } case 'at': { @@ -96,7 +113,7 @@ async function segmentToElement(type: string, data: Record, opt if (qq === 'all') { return { type: 'at', targetUin: 0, uid: 'all', text: '@全体成员 ' }; } - const uin = parseInt(qq, 10); + const uin = intOr(qq, 0); if (uin <= 0) return null; const name = String(data.name ?? data.nickname ?? data.card ?? '').trim(); @@ -105,16 +122,17 @@ async function segmentToElement(type: string, data: Record, opt uid = (await options.resolveMentionUid(uin))?.trim() ?? ''; } - return { - type: 'at', - targetUin: uin, - uid: uid || undefined, - text: name ? `@${name} ` : `@${uin} `, - }; + // Leave `text` undefined when the caller didn't supply a display + // name. The element-builder then resolves it from the group roster + // (so QQ renders `@昵称` instead of `@QQ号`). + const element: MessageElement = { type: 'at', targetUin: uin }; + if (uid) element.uid = uid; + if (name) element.text = `@${name} `; + return element; } case 'reply': { - const id = parseInt(String(data.id ?? '0'), 10); - if (!Number.isInteger(id) || id === 0) return null; + const id = intOr(data.id, 0); + if (id === 0) return null; if (options?.resolveReplySequence) { const resolved = options.resolveReplySequence(id); @@ -147,7 +165,7 @@ async function segmentToElement(type: string, data: Record, opt type: 'image', url: String(data.file ?? data.url ?? data.path ?? data.media ?? ''), flash: data.type === 'flash', - subType: parseInt(String(data.subType ?? '0'), 10), + subType: intOr(data.subType, 0), summary: data.summary ? String(data.summary) : undefined, }; } @@ -178,13 +196,13 @@ async function segmentToElement(type: string, data: Record, opt return { type: 'xml', text: String(data.data ?? ''), - subType: parseInt(String(data.id ?? '0'), 10), + subType: intOr(data.id, 0), }; } case 'poke': { return { type: 'poke', - faceId: parseInt(String(data.type ?? data.id ?? '0'), 10), + faceId: intOr(data.type ?? data.id, 0), }; } case 'forward': { @@ -196,11 +214,10 @@ async function segmentToElement(type: string, data: Record, opt case 'node': { // Fake forward node segment — store the raw data for later processing // The content field may be a segment array, a single segment, or a CQ string - const uin = String(data.user_id ?? data.uin ?? '0'); const name = String(data.nickname ?? data.name ?? ''); return { type: 'node', - targetUin: parseInt(uin, 10) || 0, + targetUin: intOr(data.user_id ?? data.uin, 0), text: name, // Raw content is stored as JSON string in resId for later processing resId: JSON.stringify(data.content ?? ''), diff --git a/packages/core/src/onebot/modules/message-actions.ts b/packages/core/src/onebot/modules/message-actions.ts index a2b2a0a5..5a847f9c 100644 --- a/packages/core/src/onebot/modules/message-actions.ts +++ b/packages/core/src/onebot/modules/message-actions.ts @@ -99,10 +99,32 @@ export async function sendPrivateMessage( return ref.messageStore.resolveReplySequence(false, userId, replyMessageId); }, resolveReplyMeta: (replyMessageId) => { + // Prefer the cached event (it carries the REAL sender). When only + // meta exists — typically because the message we're replying to was + // sent by the bot itself and never round-tripped through dispatch + // (reportSelfMessage off / no message_sent event) — fall back to + // selfId. The previous code used `meta.targetId` here, which is the + // conversation PEER and shows the wrong "回复 @某人" in QQ for any + // self-reply. + const event = ref.messageStore.findEvent(replyMessageId); + if (event) { + const senderUin = typeof event.user_id === 'number' + ? event.user_id + : parseInt(String(event.user_id || '0'), 10); + const time = typeof event.time === 'number' + ? event.time + : parseInt(String(event.time || '0'), 10); + const meta = ref.messageStore.findMeta(replyMessageId); + return { + senderUin, + time, + random: meta?.random ?? 0, + }; + } const meta = ref.messageStore.findMeta(replyMessageId); if (meta) { return { - senderUin: meta.targetId, + senderUin: ref.selfId, time: meta.timestamp, random: meta.random, }; @@ -240,9 +262,12 @@ export async function sendPrivateForwardMessage( export async function uploadForwardMessage( ref: OneBotInstanceContext, messages: JsonValue, + groupId?: number, ): Promise<{ forwardId: string }> { const nodes = await parseForwardNodes(ref, messages); - const forwardId = await ref.bridge.uploadForwardNodes(nodes); + // groupId controls the resId namespace (group vs private). Without it, + // a resId minted here is unusable when later sent into a group. + const forwardId = await ref.bridge.uploadForwardNodes(nodes, groupId); return { forwardId }; } diff --git a/packages/core/src/onebot/network/utils.ts b/packages/core/src/onebot/network/utils.ts index 2e445bb3..5e229ec3 100644 --- a/packages/core/src/onebot/network/utils.ts +++ b/packages/core/src/onebot/network/utils.ts @@ -6,8 +6,7 @@ import type { WebSocket } from '@snowluma/websocket'; /** Validate a request's bearer token / `?access_token=` query against the configured token. */ export function isAuthorized(request: IncomingMessage, token: string): boolean { if (!token) return true; - const rawAuth = request.headers.authorization; - const auth = Array.isArray(rawAuth) ? rawAuth[0] : rawAuth ?? ''; + const auth = request.headers.authorization ?? ''; if (auth === `Bearer ${token}`) return true; try { const url = new URL(request.url ?? '/', 'http://127.0.0.1'); diff --git a/packages/core/src/webui/auth.ts b/packages/core/src/webui/auth.ts index 725d9981..c8f6732e 100644 --- a/packages/core/src/webui/auth.ts +++ b/packages/core/src/webui/auth.ts @@ -1,6 +1,9 @@ import fs from 'fs'; import path from 'path'; import { randomBytes, scryptSync, timingSafeEqual } from 'crypto'; +import { createLogger } from '../utils/logger'; + +const log = createLogger('WebUI.Auth'); const CONFIG_DIR = 'config'; const WEBUI_CONFIG_PATH = path.join(CONFIG_DIR, 'webui.json'); @@ -21,6 +24,16 @@ export function isDevAuthMode(): boolean { return process.env.SNOWLUMA_DEV_MODE === '1'; } +function envBootstrapPassword(): string | null { + const raw = process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD; + if (!raw || typeof raw !== 'string') return null; + // Minimum sanity: avoid accidental empty / 1-char seeds. Strength + // rules still don't apply because we want trusted launchers to be + // able to pick a high-entropy random secret (e.g. base64(16)). + if (raw.length < 8) return null; + return raw; +} + export interface WebuiAuthState { passwordHash: string; // hex passwordSalt: string; // hex @@ -84,6 +97,16 @@ function generateInitialState(initialPassword: string): WebuiAuthState { }; } +function backupCorruptConfig(): void { + try { + const dest = `${WEBUI_CONFIG_PATH}.bak.${Date.now()}`; + fs.renameSync(WEBUI_CONFIG_PATH, dest); + log.warn('previous webui.json moved to %s', dest); + } catch (err) { + log.warn('failed to back up corrupt webui.json: %s', err instanceof Error ? err.message : String(err)); + } +} + function atomicWrite(state: WebuiAuthState): void { ensureConfigDir(); const tmp = WEBUI_CONFIG_PATH + '.tmp'; @@ -128,12 +151,50 @@ export class WebuiAuth { const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8'); const parsed = JSON.parse(raw) as unknown; if (isValidState(parsed)) { + if (parsed.mustChangePassword) { + // Previous start generated a bootstrap password but the operator + // never completed the forced-change flow. The plaintext is gone + // (only the hash is on disk, and the log line from last run may + // be lost), so rotate to a fresh CSPRNG password they can see. + const initialPassword = randomBytes(8).toString('hex'); + const state = generateInitialState(initialPassword); + atomicWrite(state); + log.warn('previous bootstrap password was never rotated; regenerated a new one'); + return new WebuiAuth(state, initialPassword, false); + } return new WebuiAuth(parsed, null, false); } - } catch { - /* fallthrough — regenerate */ + log.error('webui.json schema invalid; backing up and regenerating credentials'); + backupCorruptConfig(); + } catch (err) { + log.error( + 'webui.json is corrupt and will be regenerated; the previous file is backed up: %s', + err instanceof Error ? err.message : String(err), + ); + backupCorruptConfig(); } } + // SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD lets a trusted launcher seed the + // password on first run instead of having to scrape it from logs. + // Effect: write webui.json with the env-provided password, hashed, + // and mustChangePassword=false. Only honoured when there is NO existing + // webui.json — once persisted, password changes happen via the UI. + const envPassword = envBootstrapPassword(); + if (envPassword !== null) { + const salt = randomBytes(16); + const hash = hashPassword(envPassword, salt); + const now = new Date().toISOString(); + const state: WebuiAuthState = { + passwordHash: hash.toString('hex'), + passwordSalt: salt.toString('hex'), + mustChangePassword: false, + generatedAt: now, + updatedAt: now, + }; + atomicWrite(state); + log.info('webui credentials seeded from SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD'); + return new WebuiAuth(state, null, false); + } const initialPassword = randomBytes(8).toString('hex'); const state = generateInitialState(initialPassword); atomicWrite(state); diff --git a/packages/core/src/webui/client-ip.ts b/packages/core/src/webui/client-ip.ts new file mode 100644 index 00000000..a8765bc1 --- /dev/null +++ b/packages/core/src/webui/client-ip.ts @@ -0,0 +1,106 @@ +// Resolve the request's "real" client IP for per-IP rate limiting. +// +// Threat model: +// - By default we ONLY trust the TCP socket peer. `X-Forwarded-For` and +// `X-Real-IP` are client-controllable, so honoring them lets any +// client rotate the header to escape the 5-attempts/15-min login +// lockout. +// - Operators who actually run behind a reverse proxy (nginx, Caddy, +// a SaaS CDN) need a way to opt back into the real client IP. The +// `SNOWLUMA_WEBUI_TRUST_PROXY` env var lets them say "when the +// immediate TCP peer is THIS, treat the headers as authoritative". +// +// Supported values for SNOWLUMA_WEBUI_TRUST_PROXY: +// - unset / empty — default; ignore headers, use socket peer +// - "loopback" — trust headers when the socket peer is 127.0.0.1 +// or ::1 (typical for nginx/Caddy on the same host) +// - "1" / "true" / — trust headers from any peer (only safe behind a +// "all" trusted SaaS CDN that strips client-set headers) +// - comma-separated — trust headers when the socket peer matches one +// IP list of these IPs (reverse proxy on another machine) +// +// When trusted, we prefer X-Real-IP (a single value the reverse proxy +// overwrites unconditionally) and fall back to the first hop of +// X-Forwarded-For. We never parse the FULL XFF chain — if the proxy +// chain isn't fully trusted, the leftmost value can still be spoofed +// by the original client, and a single-tier proxy is the only setup +// this app realistically sees. + +import type { Context } from 'hono'; +import { getConnInfo } from '@hono/node-server/conninfo'; + +export type TrustProxyMode = + | { kind: 'none' } + | { kind: 'loopback' } + | { kind: 'all' } + | { kind: 'ip-list'; ips: Set }; + +export function parseTrustProxy(raw: string | undefined): TrustProxyMode { + const value = raw?.trim().toLowerCase() ?? ''; + if (!value) return { kind: 'none' }; + if (value === '1' || value === 'true' || value === 'all') return { kind: 'all' }; + if (value === 'loopback') return { kind: 'loopback' }; + const ips = new Set( + value.split(',').map((s) => s.trim()).filter(Boolean), + ); + if (ips.size === 0) return { kind: 'none' }; + return { kind: 'ip-list', ips }; +} + +export function describeTrustProxy(mode: TrustProxyMode): string { + switch (mode.kind) { + case 'none': return 'socket peer (default)'; + case 'all': return 'X-Real-IP / X-Forwarded-For from any peer'; + case 'loopback': return 'X-Real-IP / X-Forwarded-For when socket peer is loopback'; + case 'ip-list': return `X-Real-IP / X-Forwarded-For when socket peer is in [${[...mode.ips].join(',')}]`; + } +} + +function isLoopback(ip: string): boolean { + return ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1'; +} + +function shouldTrustHeaders(mode: TrustProxyMode, socketIp: string): boolean { + switch (mode.kind) { + case 'none': return false; + case 'all': return true; + case 'loopback': return isLoopback(socketIp); + case 'ip-list': return mode.ips.has(socketIp); + } +} + +/** + * Pick the right "client IP" for rate-limit keying. + * + * Exposed as a pure function over a small dependency surface so the + * unit tests can fabricate request shapes without spinning up a server. + */ +export function pickClientIp( + c: Pick, + mode: TrustProxyMode, + getSocketIp: () => string, +): string { + const socketIp = (() => { + try { return getSocketIp() || '127.0.0.1'; } + catch { return '127.0.0.1'; } + })(); + + if (!shouldTrustHeaders(mode, socketIp)) return socketIp; + + const realIp = c.req.header('x-real-ip')?.trim(); + if (realIp) return realIp; + const xff = c.req.header('x-forwarded-for'); + if (xff) { + const first = xff.split(',')[0].trim(); + if (first) return first; + } + return socketIp; +} + +/** Convenience binding for the live server: read socket via getConnInfo. */ +export function makeClientIpResolver(mode: TrustProxyMode): (c: Context) => string { + return (c) => pickClientIp(c, mode, () => { + try { return getConnInfo(c).remote.address ?? '127.0.0.1'; } + catch { return '127.0.0.1'; } + }); +} diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 4bec10db..0c704a19 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -1,12 +1,13 @@ import { serve } from '@hono/node-server'; import { serveStatic } from '@hono/node-server/serve-static'; -import { Hono } from 'hono'; +import { Hono, type Context } from 'hono'; +import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip'; import { createLogger, getRecentLogs, subscribeLogs } from '../utils/logger'; import { randomBytes } from 'crypto'; import type { OneBotManager } from '../onebot/manager'; import { loadOneBotConfig, saveOneBotConfig } from '../onebot/config'; import type { OneBotConfig } from '../onebot/types'; -import type { HookManager } from '../hook/hook-manager'; +import type { HookManager, HookProcessInfo } from '../hook/hook-manager'; import path from 'path'; import { existsSync, readFileSync } from 'fs'; import { fileURLToPath } from 'url'; @@ -40,6 +41,14 @@ const MUST_CHANGE_ALLOWLIST = new Set([ '/api/logout', ]); +// Endpoints that may authenticate via `?token=` query parameter. Only the +// SSE log stream is here because EventSource cannot set custom headers; all +// other endpoints MUST use the Authorization header so tokens never leak +// into access logs / Referer / browser history. +const TOKEN_QUERY_ALLOWLIST = new Set([ + '/api/logs/stream', +]); + // uin = QQ number; 5–12 digits. Used to construct config file paths, // so we MUST refuse anything else (path traversal, NUL bytes, etc.). const UIN_REGEX = /^\d{5,12}$/; @@ -51,11 +60,19 @@ function purgeExpiredTokens() { for (const [token, info] of sessionTokens) { if (now > info.expiresAt) sessionTokens.delete(token); } + for (const [ip, attempt] of loginAttempts) { + if (now > attempt.resetAt) loginAttempts.delete(ip); + } } -function getClientIp(req: Request): string { - return req.headers.get('x-forwarded-for')?.split(',')[0].trim() ?? '127.0.0.1'; -} +/** + * Resolve the client IP for per-IP rate limiting. Default is the TCP + * socket peer (cannot be spoofed by the client). Operators behind a + * reverse proxy must opt in via the `SNOWLUMA_WEBUI_TRUST_PROXY` env + * var; see `./client-ip.ts` for the accepted values. + */ +const trustProxyMode = parseTrustProxy(process.env.SNOWLUMA_WEBUI_TRUST_PROXY); +const getClientIp = makeClientIpResolver(trustProxyMode); async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentType: string }> { const response = await fetch(`https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(uin)}&s=100`, { @@ -81,11 +98,21 @@ export async function initWebUI( log.warn('dev mode enabled: password=%s', WebuiAuth.devPassword); log.warn('dev mode skips config/webui.json and password rotation'); } else if (initialPassword) { + log.info('════════════════════════════════════════════════════════════════'); + log.info(' ★ WebUI 初始登录凭据 / Initial WebUI Credentials ★'); + log.info(' 请立即登录并修改密码 —— 关闭程序后此密码无法找回。'); + log.info(' 若跳过初始改密,下次启动将自动生成新的随机密码。'); + log.info(' Log in and change the password now; it will not be shown again.'); + log.info('────────────────────────────────────────────────────────────────'); log.info('initial credentials: user=admin password=%s', initialPassword); - log.info('password change required after first login'); + log.info('════════════════════════════════════════════════════════════════'); } else if (auth.mustChangePassword()) { log.warn('password change is still required'); } + log.info('login rate-limit keyed by: %s', describeTrustProxy(trustProxyMode)); + if (trustProxyMode.kind === 'all') { + log.warn('SNOWLUMA_WEBUI_TRUST_PROXY=1 — only safe behind a reverse proxy that strips client-set X-Real-IP / X-Forwarded-For'); + } const app = new Hono(); @@ -96,11 +123,10 @@ export async function initWebUI( const authHeader = c.req.header('Authorization'); const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : ''; - const queryToken = c.req.query('token') ?? ''; + const queryToken = TOKEN_QUERY_ALLOWLIST.has(reqPath) ? (c.req.query('token') ?? '') : ''; const token = bearerToken || queryToken; if (!token) return c.json({ status: 'failed', message: 'Unauthorized' }, 401); - purgeExpiredTokens(); const info = sessionTokens.get(token); if (!info || Date.now() > info.expiresAt) { return c.json({ status: 'failed', message: 'Token expired or invalid' }, 401); @@ -114,9 +140,14 @@ export async function initWebUI( await next(); }); + // Periodic janitor — keeps sessionTokens / loginAttempts from growing + // unbounded and replaces the per-request O(n) sweep we used to do. + const tokenJanitor = setInterval(purgeExpiredTokens, 60_000); + tokenJanitor.unref?.(); + // ─── Login ─────────────────────────────────────────────────────────────── app.post('/api/login', async (c) => { - const ip = getClientIp(c.req.raw); + const ip = getClientIp(c); const now = Date.now(); const attempt = loginAttempts.get(ip); if (attempt && attempt.count >= LOGIN_MAX_ATTEMPTS && now < attempt.resetAt) { @@ -140,7 +171,6 @@ export async function initWebUI( } loginAttempts.delete(ip); - purgeExpiredTokens(); const token = randomBytes(32).toString('hex'); const mustChange = auth.mustChangePassword(); sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: mustChange }); @@ -196,20 +226,15 @@ export async function initWebUI( try { auth.setPassword(newPassword); } catch (err) { - return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 400); + log.warn('change password failed: %s', err instanceof Error ? err.message : String(err)); + return c.json({ success: false, message: '密码修改失败' }, 400); } - // Invalidate all other sessions; current keeps but loses must-change flag. - const currentToken = c.get('sessionToken' as never) as string | undefined; - for (const [tok, info] of sessionTokens) { - if (tok === currentToken) { - info.mustChangePassword = false; - sessionTokens.set(tok, info); - } else { - sessionTokens.delete(tok); - } - } - log.info('password updated'); - return c.json({ success: true }); + // Invalidate every session, including the current one. If the old + // password was compromised, the attacker may already hold the current + // token; rotating credentials must rotate sessions too. + sessionTokens.clear(); + log.info('password updated; all sessions invalidated'); + return c.json({ success: true, requireRelogin: true }); }); // ─── Avatar proxy (uin validated) ──────────────────────────────────────── @@ -319,23 +344,35 @@ export async function initWebUI( const stream = new ReadableStream({ start(controller) { const encoder = new TextEncoder(); + let closed = false; + let unsubscribe: (() => void) | undefined; + let heartbeat: NodeJS.Timeout | undefined; + const teardown = () => { + if (closed) return; + closed = true; + if (heartbeat) clearInterval(heartbeat); + unsubscribe?.(); + try { controller.close(); } catch { /* ignore */ } + }; + const safeEnqueue = (chunk: Uint8Array) => { + if (closed) return; + try { + controller.enqueue(chunk); + } catch { + // The peer dropped between abort and the next enqueue — + // treat as end-of-stream so we don't leak listeners. + teardown(); + } + }; const send = (event: unknown) => { - controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`)); + safeEnqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`)); }; send({ type: 'ready' }); - const unsubscribe = subscribeLogs((entry) => send(entry)); - const heartbeat = setInterval(() => { - controller.enqueue(encoder.encode(': heartbeat\n\n')); + unsubscribe = subscribeLogs((entry) => send(entry)); + heartbeat = setInterval(() => { + safeEnqueue(encoder.encode(': heartbeat\n\n')); }, 15000); - c.req.raw.signal.addEventListener('abort', () => { - clearInterval(heartbeat); - unsubscribe(); - try { - controller.close(); - } catch { - /* ignore */ - } - }); + c.req.raw.signal.addEventListener('abort', teardown); }, }); return new Response(stream, { @@ -356,62 +393,43 @@ export async function initWebUI( } }); - app.post('/api/processes/:pid/load', async (c) => { - if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503); - const pid = Number(c.req.param('pid')); - if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) { - return c.json({ success: false, message: 'invalid pid' }, 400); - } - try { - const processInfo = await hookManager.loadProcess(pid); - return c.json({ success: processInfo.status !== 'error', process: processInfo }); - } catch (err) { - return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500); - } - }); - - app.post('/api/processes/:pid/unload', async (c) => { - if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503); - const pid = Number(c.req.param('pid')); - if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) { - return c.json({ success: false, message: 'invalid pid' }, 400); - } - try { - const processInfo = await hookManager.unloadProcess(pid); - return c.json({ success: processInfo.status !== 'error', process: processInfo }); - } catch (err) { - return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500); - } - }); - - app.post('/api/processes/:pid/refresh', async (c) => { - if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503); - const pid = Number(c.req.param('pid')); - if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) { - return c.json({ success: false, message: 'invalid pid' }, 400); - } - try { - const processInfo = await hookManager.refreshProcess(pid); - return c.json({ success: processInfo.status !== 'error', process: processInfo }); - } catch (err) { - return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500); - } - }); + // Per-process action handler. The three routes below differ only in + // which HookManager method they call. + const MAX_PID = 4_194_304; + function processAction(label: string, action: (pid: number) => Promise) { + return async (c: Context) => { + if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503); + const pid = Number(c.req.param('pid')); + if (!Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) { + return c.json({ success: false, message: 'invalid pid' }, 400); + } + try { + const processInfo = await action(pid); + return c.json({ success: processInfo.status !== 'error', process: processInfo }); + } catch (err) { + log.warn('%s pid=%d failed: %s', label, pid, err instanceof Error ? err.message : String(err)); + return c.json({ success: false, message: '操作失败,请检查服务器日志' }, 500); + } + }; + } + app.post('/api/processes/:pid/load', processAction('load', (pid) => hookManager!.loadProcess(pid))); + app.post('/api/processes/:pid/unload', processAction('unload', (pid) => hookManager!.unloadProcess(pid))); + app.post('/api/processes/:pid/refresh', processAction('refresh', (pid) => hookManager!.refreshProcess(pid))); app.get('/api/config/:uin', (c) => { const uin = c.req.param('uin'); if (!UIN_REGEX.test(uin)) return c.json({ message: 'invalid uin' }, 400); + // Read-only: never write defaults to disk on a GET. The persisted + // file is created when manager.onSessionStarted boots an instance + // or when the operator POSTs from this very endpoint. const config = loadOneBotConfig(uin); - return c.json({ - ...config, - config, - }); + return c.json({ config }); }); app.post('/api/config/:uin', async (c) => { + const uin = c.req.param('uin'); + if (!UIN_REGEX.test(uin)) return c.json({ success: false, message: 'invalid uin' }, 400); try { - const uin = c.req.param('uin'); - if (!UIN_REGEX.test(uin)) return c.json({ success: false, message: 'invalid uin' }, 400); const body = (await c.req.json()) as OneBotConfig; saveOneBotConfig(uin, body); const reloaded = oneBotManager.reloadConfig(uin); @@ -422,7 +440,8 @@ export async function initWebUI( message: reloaded ? '配置保存成功,已热重载当前会话。' : '配置保存成功,当前会话未在线,将在下次连接时生效。', }); } catch (err) { - return c.json({ success: false, message: String(err) }, 400); + log.warn('save config for uin=%s failed: %s', uin, err instanceof Error ? err.message : String(err)); + return c.json({ success: false, message: '配置保存失败,请检查服务器日志' }, 400); } }); diff --git a/packages/core/tests/actions/group-file.test.ts b/packages/core/tests/actions/group-file.test.ts index a6ce62cf..2f71bc76 100644 --- a/packages/core/tests/actions/group-file.test.ts +++ b/packages/core/tests/actions/group-file.test.ts @@ -16,6 +16,7 @@ vi.mock('../../src/bridge/highway/utils', () => ({ })), computeHashes: vi.fn(() => ({ md5: new Uint8Array(16), sha1: new Uint8Array(20) })), computeMd5: vi.fn(() => new Uint8Array(16)), + FILE_UPLOAD_MAX_BYTES: 4 * 1024 * 1024 * 1024, })); import * as oidb from '../../src/bridge/bridge-oidb'; diff --git a/packages/core/tests/config.test.ts b/packages/core/tests/config.test.ts index dc670636..6a667f50 100644 --- a/packages/core/tests/config.test.ts +++ b/packages/core/tests/config.test.ts @@ -45,7 +45,7 @@ describe('loadOneBotConfig', () => { it('creates and persists default config when none exists', () => { const uin = '10001'; - const config = loadOneBotConfig(uin); + const config = loadOneBotConfig(uin, { persistDefaults: true }); expect(config.networks.httpServers).toHaveLength(1); const onDisk = JSON.parse(fs.readFileSync(path.join(tempDir, 'config', `onebot_${uin}.json`), 'utf8')); @@ -74,7 +74,7 @@ describe('loadOneBotConfig', () => { }; fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify(legacy), 'utf8'); - const config = loadOneBotConfig(uin); + const config = loadOneBotConfig(uin, { persistDefaults: true }); expect(config.networks.httpServers).toHaveLength(1); expect(config.networks.httpServers[0].port).toBe(3100); expect(config.networks.httpServers[0].accessToken).toBe('tok'); @@ -128,6 +128,34 @@ describe('loadOneBotConfig', () => { expect(reloaded.networks.httpClients[0].reportSelfMessage).toBe(true); }); + it('does not write to disk by default (read-only contract)', () => { + const uin = '10006'; + const cfgPath = path.join(tempDir, 'config', `onebot_${uin}.json`); + + // Default call must not materialize the file or mint a fresh access token. + const config = loadOneBotConfig(uin); + expect(config.networks.httpServers).toHaveLength(1); + expect(fs.existsSync(cfgPath)).toBe(false); + + // Explicit opt-in still writes. + loadOneBotConfig(uin, { persistDefaults: true }); + expect(fs.existsSync(cfgPath)).toBe(true); + }); + + it('respects an operator-emptied adapter list instead of seeding defaults back', () => { + const uin = '10007'; + const dir = path.join(tempDir, 'config'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify({ + networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] }, + musicSignUrl: '', + }), 'utf8'); + + const config = loadOneBotConfig(uin, { persistDefaults: true }); + expect(config.networks.httpServers).toEqual([]); + expect(config.networks.wsServers).toEqual([]); + }); + it('migrates legacy lowercase WsRole values into canonical uppercase form', () => { const uin = '10005'; const dir = path.join(tempDir, 'config'); diff --git a/packages/core/tests/highway-utils.test.ts b/packages/core/tests/highway-utils.test.ts index 087f22cd..130f8e68 100644 --- a/packages/core/tests/highway-utils.test.ts +++ b/packages/core/tests/highway-utils.test.ts @@ -2,7 +2,7 @@ import fs from 'fs'; import os from 'os'; import path from 'path'; import { pathToFileURL } from 'url'; -import { describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { loadBinarySource, resolveLocalFilePath } from '../src/bridge/highway/utils'; describe('highway source paths', () => { @@ -26,3 +26,76 @@ describe('highway source paths', () => { } }); }); + +describe('loadBinarySource maxBytes enforcement', () => { + const originalFetch = globalThis.fetch; + afterEach(() => { + globalThis.fetch = originalFetch; + vi.restoreAllMocks(); + }); + + it('rejects HTTP downloads larger than maxBytes via streaming, even without Content-Length', async () => { + // Streamed chunk-encoded response: no Content-Length, totals > cap. + const chunkSize = 4 * 1024; + const totalChunks = 16; + const stream = new ReadableStream({ + start(controller) { + for (let i = 0; i < totalChunks; i++) controller.enqueue(new Uint8Array(chunkSize)); + controller.close(); + }, + }); + globalThis.fetch = vi.fn(async () => new Response(stream, { + status: 200, + headers: { /* no content-length */ }, + })) as typeof fetch; + + // Cap below total: 16*4096 = 65536, cap 32 KiB → should throw mid-stream. + await expect( + loadBinarySource('https://example.test/big.bin', 'test', 32 * 1024), + ).rejects.toThrow(/too large/); + }); + + it('rejects HTTP downloads when Content-Length already exceeds maxBytes', async () => { + globalThis.fetch = vi.fn(async () => new Response(new Uint8Array(0), { + status: 200, + headers: { 'content-length': String(10 * 1024 * 1024) }, + })) as typeof fetch; + + await expect( + loadBinarySource('https://example.test/big.bin', 'test', 1024), + ).rejects.toThrow(/too large: 10485760/); + }); + + it('accepts a streamed download that fits inside maxBytes', async () => { + const stream = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([1, 2, 3])); + controller.enqueue(new Uint8Array([4, 5])); + controller.close(); + }, + }); + globalThis.fetch = vi.fn(async () => new Response(stream, { status: 200 })) as typeof fetch; + + const loaded = await loadBinarySource('https://example.test/small.bin', 'test', 1024); + expect(Array.from(loaded.bytes)).toEqual([1, 2, 3, 4, 5]); + }); + + it('rejects oversized local files via fs.stat before reading them', async () => { + const filePath = path.join(os.tmpdir(), `snowluma-binary-cap-${process.pid}-${Date.now()}.bin`); + fs.writeFileSync(filePath, Buffer.alloc(128)); + try { + await expect( + loadBinarySource(filePath, 'test', 64), + ).rejects.toThrow(/too large: 128 > 64/); + } finally { + try { fs.unlinkSync(filePath); } catch { /* ignore */ } + } + }); + + it('rejects oversized base64 payloads', async () => { + const big = Buffer.alloc(128).toString('base64'); + await expect( + loadBinarySource(`base64://${big}`, 'test', 64), + ).rejects.toThrow(/too large: 128 > 64/); + }); +}); diff --git a/packages/core/tests/webui-client-ip.test.ts b/packages/core/tests/webui-client-ip.test.ts new file mode 100644 index 00000000..0a8159f3 --- /dev/null +++ b/packages/core/tests/webui-client-ip.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from 'vitest'; +import { + describeTrustProxy, + parseTrustProxy, + pickClientIp, + type TrustProxyMode, +} from '../src/webui/client-ip'; + +function mockCtx(headers: Record = {}) { + return { + req: { + header: (name: string) => headers[name.toLowerCase()], + }, + } as unknown as Parameters[0]; +} + +describe('parseTrustProxy', () => { + it('treats empty / unset as none (safe default)', () => { + expect(parseTrustProxy(undefined)).toEqual({ kind: 'none' }); + expect(parseTrustProxy('')).toEqual({ kind: 'none' }); + expect(parseTrustProxy(' ')).toEqual({ kind: 'none' }); + }); + + it('recognises "1" / "true" / "all" as full trust', () => { + expect(parseTrustProxy('1')).toEqual({ kind: 'all' }); + expect(parseTrustProxy('true')).toEqual({ kind: 'all' }); + expect(parseTrustProxy('ALL')).toEqual({ kind: 'all' }); + }); + + it('recognises "loopback" case-insensitively', () => { + expect(parseTrustProxy('Loopback')).toEqual({ kind: 'loopback' }); + }); + + it('parses a comma-separated IP list', () => { + const mode = parseTrustProxy('10.0.0.1, 192.168.1.5, '); + expect(mode.kind).toBe('ip-list'); + if (mode.kind !== 'ip-list') throw new Error('unreachable'); + expect([...mode.ips].sort()).toEqual(['10.0.0.1', '192.168.1.5']); + }); +}); + +describe('pickClientIp', () => { + const xff = { 'x-forwarded-for': '203.0.113.7, 10.0.0.1' }; + const realIp = { 'x-real-ip': '203.0.113.42' }; + const both = { ...xff, ...realIp }; + + it('returns socket peer and IGNORES headers when trust=none (default)', () => { + const mode: TrustProxyMode = { kind: 'none' }; + expect(pickClientIp(mockCtx(both), mode, () => '198.51.100.9')).toBe('198.51.100.9'); + }); + + it('honors X-Real-IP first, then XFF first hop, when trust=all', () => { + const mode: TrustProxyMode = { kind: 'all' }; + expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.1')).toBe('203.0.113.42'); + expect(pickClientIp(mockCtx(xff), mode, () => '10.0.0.1')).toBe('203.0.113.7'); + }); + + it('falls back to socket peer when trust=all but no headers present', () => { + const mode: TrustProxyMode = { kind: 'all' }; + expect(pickClientIp(mockCtx({}), mode, () => '10.0.0.1')).toBe('10.0.0.1'); + }); + + it('trust=loopback honors headers only when socket is loopback', () => { + const mode: TrustProxyMode = { kind: 'loopback' }; + expect(pickClientIp(mockCtx(both), mode, () => '127.0.0.1')).toBe('203.0.113.42'); + expect(pickClientIp(mockCtx(both), mode, () => '::1')).toBe('203.0.113.42'); + expect(pickClientIp(mockCtx(both), mode, () => '::ffff:127.0.0.1')).toBe('203.0.113.42'); + // Non-loopback peer → headers ignored, socket wins. + expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.1')).toBe('10.0.0.1'); + }); + + it('trust=ip-list honors headers only when socket is in the list', () => { + const mode: TrustProxyMode = { kind: 'ip-list', ips: new Set(['10.0.0.1', '10.0.0.2']) }; + expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.2')).toBe('203.0.113.42'); + expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.9')).toBe('10.0.0.9'); + }); + + it('survives a socket resolver that throws', () => { + const mode: TrustProxyMode = { kind: 'none' }; + expect(pickClientIp(mockCtx({}), mode, () => { throw new Error('boom'); })).toBe('127.0.0.1'); + }); +}); + +describe('describeTrustProxy', () => { + it('renders each mode in a recognisable form for the boot log', () => { + expect(describeTrustProxy({ kind: 'none' })).toContain('socket peer'); + expect(describeTrustProxy({ kind: 'all' })).toContain('any peer'); + expect(describeTrustProxy({ kind: 'loopback' })).toContain('loopback'); + expect(describeTrustProxy({ kind: 'ip-list', ips: new Set(['10.0.0.1']) })) + .toContain('10.0.0.1'); + }); +}); diff --git a/packages/runtime/package.json b/packages/runtime/package.json index 3cfbfdd6..aed52074 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/runtime", - "version": "1.8.1", + "version": "1.8.2", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 1e072aee..0cbb085e 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.8.1", + "version": "1.8.2", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "keywords": [ "snowluma", diff --git a/packages/sdk/src/actions.ts b/packages/sdk/src/actions.ts index 3618bb8f..f3782ca7 100644 --- a/packages/sdk/src/actions.ts +++ b/packages/sdk/src/actions.ts @@ -122,6 +122,24 @@ export const SNOWLUMA_ACTIONS = [ 'rename_group_file', 'get_file', '.send_packet', + + // napcat-parity extensions (Tier 1 + Tier 2) + 'send_packet', + 'bot_exit', + 'nc_get_packet_status', + 'nc_get_rkey', + 'nc_get_user_status', + 'get_group_ignore_add_request', + 'delete_group_folder', + 'set_group_todo', + 'complete_group_todo', + 'cancel_group_todo', + // Tier 3: DIY status + 'set_diy_online_status', + // AI voice trio + 'get_ai_characters', + 'get_ai_record', + 'send_group_ai_record', ] as const satisfies readonly (keyof SnowLumaActionMap)[]; export type SnowLumaKnownAction = typeof SNOWLUMA_ACTIONS[number]; diff --git a/packages/sdk/src/types/actions.ts b/packages/sdk/src/types/actions.ts index f784504a..53b4a0d3 100644 --- a/packages/sdk/src/types/actions.ts +++ b/packages/sdk/src/types/actions.ts @@ -60,6 +60,13 @@ import type { UploadPrivateFileParams, UserIdParams, QuickOperationParams, + SetDiyOnlineStatusParams, + NcGetUserStatusParams, + GroupTodoParams, + GetAiCharactersParams, + AiVoiceParams, + DeleteGroupFolderParams, + SendPacketParams, } from './params'; import type { CapabilityInfo, @@ -84,6 +91,9 @@ import type { UploadForwardResult, UrlSafetyInfo, VersionInfo, + AiCharacterCategory, + UserOnlineStatus, + SendGroupAiRecordResult, } from './results'; export type ActionData = JsonValue; @@ -209,7 +219,27 @@ export interface SnowLumaActionMap { trans_group_file: { params: JsonObject; data: JsonValue }; rename_group_file: { params: JsonObject; data: JsonValue }; get_file: { params: GetMediaParams; data: JsonValue }; - '.send_packet': { params: JsonObject; data: JsonValue }; + '.send_packet': { params: SendPacketParams; data: string }; + + // — napcat-parity extensions (Tier 1 + Tier 2) — + send_packet: { params: SendPacketParams; data: string }; + bot_exit: { params: JsonObject; data: EmptyData }; + nc_get_packet_status: { params: JsonObject; data: JsonValue }; + nc_get_rkey: { params: JsonObject; data: JsonObject[] }; + nc_get_user_status: { params: NcGetUserStatusParams; data: UserOnlineStatus }; + get_group_ignore_add_request: { params: JsonObject; data: JsonArray }; + delete_group_folder: { params: DeleteGroupFolderParams; data: EmptyData }; + set_group_todo: { params: GroupTodoParams; data: EmptyData }; + complete_group_todo: { params: GroupTodoParams; data: EmptyData }; + cancel_group_todo: { params: GroupTodoParams; data: EmptyData }; + + // — Tier 3: DIY status — + set_diy_online_status: { params: SetDiyOnlineStatusParams; data: EmptyData }; + + // — AI voice trio — + get_ai_characters: { params: GetAiCharactersParams; data: AiCharacterCategory[] }; + get_ai_record: { params: AiVoiceParams; data: string }; + send_group_ai_record: { params: AiVoiceParams; data: SendGroupAiRecordResult }; } export type SnowLumaAction = keyof SnowLumaActionMap | (string & {}); diff --git a/packages/sdk/src/types/params.ts b/packages/sdk/src/types/params.ts index 4935154c..df741b51 100644 --- a/packages/sdk/src/types/params.ts +++ b/packages/sdk/src/types/params.ts @@ -316,3 +316,47 @@ export interface SetOnlineStatusParams extends JsonObject { ext_status?: number; battery_status?: number; } + +// DIY online status — status/extStatus are forced to 10/2000 server-side, +// and these three fields land in the customExt sub-message. +export interface SetDiyOnlineStatusParams extends JsonObject { + face_id: number | string; + wording?: string; + face_type?: number | string; +} + +// nc_get_user_status — read the QQ-side online/ext-status word for a uin. +export interface NcGetUserStatusParams extends UserIdParams {} + +// set_/complete_/cancel_group_todo all share this shape; the action verb +// lives in the route, not the body. +export interface GroupTodoParams extends GroupIdParams { + message_id: number | string; +} + +// AI voice — fetch the in-group AI character list. +export interface GetAiCharactersParams extends GroupIdParams { + chat_type?: number | string; +} + +// AI voice — `get_ai_record` and `send_group_ai_record` share params. +// The action's verb (read vs send) is the route, not the body. +export interface AiVoiceParams extends GroupIdParams { + character: string; + text: string; + chat_type?: number | string; +} + +// delete_group_folder — napcat's alias for delete_group_file_folder. +// Same body, different action name. +export interface DeleteGroupFolderParams extends GroupIdParams { + folder_id: string; +} + +// send_packet — debug endpoint, sends a hex-encoded raw packet. +// `rsp=false` skips waiting for a response. +export interface SendPacketParams extends JsonObject { + cmd: string; + data?: string; + rsp?: boolean; +} diff --git a/packages/sdk/src/types/results.ts b/packages/sdk/src/types/results.ts index 37cd1e35..f7e26cbe 100644 --- a/packages/sdk/src/types/results.ts +++ b/packages/sdk/src/types/results.ts @@ -101,3 +101,26 @@ export interface GroupAtAllRemainInfo { } export type EmptyData = null; + +// — AI 语音角色:get_ai_characters 返回的分类数组 — +export interface AiCharacter { + character_id: string; + character_name: string; + preview_url: string; +} + +export interface AiCharacterCategory { + type: string; + characters: AiCharacter[]; +} + +// — nc_get_user_status 返回的状态字 — +export interface UserOnlineStatus { + status: number; + ext_status: number; +} + +// — send_group_ai_record 返回(合成是异步副作用,message_id 总为 0) — +export interface SendGroupAiRecordResult { + message_id: number; +} diff --git a/packages/ui/package.json b/packages/ui/package.json new file mode 100644 index 00000000..5a0a7d4b --- /dev/null +++ b/packages/ui/package.json @@ -0,0 +1,89 @@ +{ + "name": "@snowluma/ui", + "author": { + "name": "MotricSeven", + "email": "motricseven@gmail.com" + }, + "version": "1.8.2", + "description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components", + "keywords": [ + "snowluma", + "ui", + "shadcn", + "tailwind", + "react" + ], + "homepage": "https://github.com/SnowLuma/SnowLuma#readme", + "bugs": { + "url": "https://github.com/SnowLuma/SnowLuma/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/SnowLuma/SnowLuma.git", + "directory": "packages/ui" + }, + "license": "UNLICENSED", + "type": "module", + "sideEffects": [ + "**/*.css" + ], + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + }, + "./styles/theme.css": "./src/styles/theme.css", + "./package.json": "./package.json" + }, + "files": [ + "dist", + "src/styles" + ], + "scripts": { + "clean": "node -e \"const fs = require('node:fs'); fs.rmSync('dist', { recursive: true, force: true })\"", + "prebuild": "pnpm run clean", + "build": "tsup", + "dev": "tsup --watch", + "prepack": "pnpm run build", + "typecheck": "tsc --noEmit" + }, + "publishConfig": { + "access": "public" + }, + "engines": { + "node": ">=22" + }, + "peerDependencies": { + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "dependencies": { + "@radix-ui/react-alert-dialog": "^1.1.7", + "@radix-ui/react-checkbox": "^1.1.5", + "@radix-ui/react-dialog": "^1.1.7", + "@radix-ui/react-label": "^2.1.3", + "@radix-ui/react-popover": "^1.1.7", + "@radix-ui/react-scroll-area": "^1.2.4", + "@radix-ui/react-select": "^2.2.6", + "@radix-ui/react-separator": "^1.1.3", + "@radix-ui/react-slot": "^1.1.3", + "@radix-ui/react-switch": "^1.2.6", + "@radix-ui/react-tabs": "^1.1.13", + "@radix-ui/react-tooltip": "^1.1.9", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "lucide-react": "^0.469.0", + "sonner": "^2.0.6", + "tailwind-merge": "^3.5.0" + }, + "devDependencies": { + "@types/react": "^19.2.14", + "@types/react-dom": "^19.2.3", + "react": "^19.2.5", + "react-dom": "^19.2.5", + "tsup": "^8.5.0", + "typescript": "catalog:" + } +} diff --git a/packages/ui/src/components/alert-dialog.tsx b/packages/ui/src/components/alert-dialog.tsx new file mode 100644 index 00000000..2cb1b30a --- /dev/null +++ b/packages/ui/src/components/alert-dialog.tsx @@ -0,0 +1,98 @@ +import * as React from 'react'; +import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog'; +import { cn } from '../lib/cn'; +import { buttonVariants } from './button'; + +const AlertDialog = AlertDialogPrimitive.Root; +const AlertDialogTrigger = AlertDialogPrimitive.Trigger; +const AlertDialogPortal = AlertDialogPrimitive.Portal; + +const AlertDialogOverlay = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +AlertDialogOverlay.displayName = 'AlertDialogOverlay'; + +const AlertDialogContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + + + + +)); +AlertDialogContent.displayName = 'AlertDialogContent'; + +const AlertDialogHeader = ({ className, ...props }: React.HTMLAttributes) => ( +
+); + +const AlertDialogFooter = ({ className, ...props }: React.HTMLAttributes) => ( +
+); + +const AlertDialogTitle = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +AlertDialogTitle.displayName = 'AlertDialogTitle'; + +const AlertDialogDescription = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +AlertDialogDescription.displayName = 'AlertDialogDescription'; + +const AlertDialogAction = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +AlertDialogAction.displayName = 'AlertDialogAction'; + +const AlertDialogCancel = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +AlertDialogCancel.displayName = 'AlertDialogCancel'; + +export { + AlertDialog, + AlertDialogPortal, + AlertDialogOverlay, + AlertDialogTrigger, + AlertDialogContent, + AlertDialogHeader, + AlertDialogFooter, + AlertDialogTitle, + AlertDialogDescription, + AlertDialogAction, + AlertDialogCancel, +}; diff --git a/packages/ui/src/components/avatar.tsx b/packages/ui/src/components/avatar.tsx new file mode 100644 index 00000000..768b6373 --- /dev/null +++ b/packages/ui/src/components/avatar.tsx @@ -0,0 +1,44 @@ +import * as React from 'react'; +import { cn } from '../lib/cn'; + +interface AvatarProps extends React.HTMLAttributes { + size?: number; +} + +const Avatar = React.forwardRef( + ({ className, size = 36, style, ...props }, ref) => ( +
+ ) +); +Avatar.displayName = 'Avatar'; + +const AvatarImage = React.forwardRef>( + ({ className, alt = '', ...props }, ref) => ( + {alt} + ) +); +AvatarImage.displayName = 'AvatarImage'; + +const AvatarFallback = React.forwardRef>( + ({ className, ...props }, ref) => ( + + ) +); +AvatarFallback.displayName = 'AvatarFallback'; + +export { Avatar, AvatarImage, AvatarFallback }; diff --git a/packages/ui/src/components/badge.tsx b/packages/ui/src/components/badge.tsx new file mode 100644 index 00000000..45290da2 --- /dev/null +++ b/packages/ui/src/components/badge.tsx @@ -0,0 +1,35 @@ +import * as React from 'react'; +import { cva, type VariantProps } from 'class-variance-authority'; +import { cn } from '../lib/cn'; + +export const badgeVariants = cva( + 'inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-medium leading-none transition-colors', + { + variants: { + variant: { + default: 'border-transparent bg-primary/15 text-primary', + secondary: 'border-transparent bg-secondary text-secondary-foreground', + destructive: 'border-transparent bg-destructive/15 text-destructive', + success: 'border-transparent bg-success/15 text-success', + warning: 'border-transparent bg-warning/15 text-warning', + info: 'border-transparent bg-info/15 text-info', + outline: 'border-border bg-card text-foreground', + soft: 'border-transparent bg-muted text-muted-foreground', + }, + size: { + default: 'px-2 py-0.5 text-[11px]', + sm: 'px-1.5 py-px text-[10px]', + lg: 'px-2.5 py-1 text-xs', + }, + }, + defaultVariants: { variant: 'default', size: 'default' }, + }, +); + +export interface BadgeProps + extends React.HTMLAttributes, + VariantProps {} + +export function Badge({ className, variant, size, ...props }: BadgeProps) { + return ; +} diff --git a/packages/ui/src/components/button.tsx b/packages/ui/src/components/button.tsx new file mode 100644 index 00000000..25a16a0c --- /dev/null +++ b/packages/ui/src/components/button.tsx @@ -0,0 +1,54 @@ +import * as React from 'react'; +import { Slot } from '@radix-ui/react-slot'; +import { cva, type VariantProps } from 'class-variance-authority'; +import { cn } from '../lib/cn'; + +export const buttonVariants = cva( + [ + "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg text-sm font-medium", + "transition-[color,background-color,border-color,box-shadow,transform] duration-150 ease-out", + "disabled:pointer-events-none disabled:opacity-50", + "[&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0", + "outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40 focus-visible:border-ring", + "active:translate-y-px cursor-pointer", + ].join(' '), + { + variants: { + variant: { + default: 'bg-primary text-primary-foreground shadow-sm hover:bg-primary/90 active:bg-primary/95', + destructive: + 'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90 active:bg-destructive/95', + outline: + 'border border-border bg-card text-foreground shadow-xs hover:bg-accent hover:text-accent-foreground hover:border-border/80', + secondary: 'bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80', + ghost: 'text-foreground hover:bg-accent hover:text-accent-foreground', + link: 'text-primary underline-offset-4 hover:underline shadow-none', + success: 'bg-success text-success-foreground shadow-sm hover:bg-success/90', + warning: 'bg-warning text-warning-foreground shadow-sm hover:bg-warning/90', + }, + size: { + default: 'h-9 px-4 py-2', + sm: 'h-8 rounded-md px-3 text-xs', + lg: 'h-10 rounded-lg px-6', + icon: 'size-9 rounded-lg', + 'icon-sm': 'size-8 rounded-md', + 'icon-xs': 'size-7 rounded-md', + }, + }, + defaultVariants: { variant: 'default', size: 'default' }, + }, +); + +export interface ButtonProps + extends React.ButtonHTMLAttributes, + VariantProps { + asChild?: boolean; +} + +export const Button = React.forwardRef( + ({ className, variant, size, asChild = false, ...props }, ref) => { + const Comp = asChild ? Slot : 'button'; + return ; + }, +); +Button.displayName = 'Button'; diff --git a/packages/ui/src/components/card.tsx b/packages/ui/src/components/card.tsx new file mode 100644 index 00000000..87ff0efd --- /dev/null +++ b/packages/ui/src/components/card.tsx @@ -0,0 +1,50 @@ +import * as React from 'react'; +import { cn } from '../lib/cn'; + +const Card = React.forwardRef>( + ({ className, ...props }, ref) => ( +
+ ), +); +Card.displayName = 'Card'; + +const CardHeader = React.forwardRef>( + ({ className, ...props }, ref) => ( +
+ ), +); +CardHeader.displayName = 'CardHeader'; + +const CardTitle = React.forwardRef>( + ({ className, ...props }, ref) => ( +
+ ), +); +CardTitle.displayName = 'CardTitle'; + +const CardDescription = React.forwardRef>( + ({ className, ...props }, ref) => ( +
+ ), +); +CardDescription.displayName = 'CardDescription'; + +const CardContent = React.forwardRef>( + ({ className, ...props }, ref) => ( +
+ ), +); +CardContent.displayName = 'CardContent'; + +const CardFooter = React.forwardRef>( + ({ className, ...props }, ref) => ( +
+ ), +); +CardFooter.displayName = 'CardFooter'; + +export { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter }; diff --git a/packages/ui/src/components/checkbox.tsx b/packages/ui/src/components/checkbox.tsx new file mode 100644 index 00000000..e8119416 --- /dev/null +++ b/packages/ui/src/components/checkbox.tsx @@ -0,0 +1,30 @@ +import * as React from 'react'; +import * as CheckboxPrimitive from '@radix-ui/react-checkbox'; +import { Check, Minus } from 'lucide-react'; +import { cn } from '../lib/cn'; + +const Checkbox = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + + + {props.checked === 'indeterminate' ? : } + + +)); +Checkbox.displayName = 'Checkbox'; + +export { Checkbox }; diff --git a/packages/ui/src/components/dialog.tsx b/packages/ui/src/components/dialog.tsx new file mode 100644 index 00000000..25b1f6d6 --- /dev/null +++ b/packages/ui/src/components/dialog.tsx @@ -0,0 +1,102 @@ +import * as React from 'react'; +import * as DialogPrimitive from '@radix-ui/react-dialog'; +import { X } from 'lucide-react'; +import { cn } from '../lib/cn'; + +const Dialog = DialogPrimitive.Root; +const DialogTrigger = DialogPrimitive.Trigger; +const DialogPortal = DialogPrimitive.Portal; +const DialogClose = DialogPrimitive.Close; + +const DialogOverlay = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DialogOverlay.displayName = 'DialogOverlay'; + +const DialogContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { showClose?: boolean } +>(({ className, children, showClose = true, ...props }, ref) => ( + + + + {children} + {showClose && ( + + + Close + + )} + + +)); +DialogContent.displayName = 'DialogContent'; + +const DialogHeader = ({ className, ...props }: React.HTMLAttributes) => ( +
+); + +const DialogFooter = ({ className, ...props }: React.HTMLAttributes) => ( +
+); + +const DialogTitle = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DialogTitle.displayName = 'DialogTitle'; + +const DialogDescription = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DialogDescription.displayName = 'DialogDescription'; + +export { + Dialog, + DialogPortal, + DialogOverlay, + DialogTrigger, + DialogClose, + DialogContent, + DialogHeader, + DialogFooter, + DialogTitle, + DialogDescription, +}; diff --git a/packages/ui/src/components/empty-state.tsx b/packages/ui/src/components/empty-state.tsx new file mode 100644 index 00000000..77e1b51f --- /dev/null +++ b/packages/ui/src/components/empty-state.tsx @@ -0,0 +1,36 @@ +import * as React from 'react'; +import { cn } from '../lib/cn'; + +interface EmptyStateProps extends Omit, 'title'> { + icon?: React.ReactNode; + title: React.ReactNode; + description?: React.ReactNode; + action?: React.ReactNode; +} + +/** + * Generic "nothing here yet" placeholder. Used by Bot list, search-with-no- + * results, log filters that filtered everything out, etc. + */ +export function EmptyState({ icon, title, description, action, className, ...props }: EmptyStateProps) { + return ( +
+ {icon && ( +
+ {icon} +
+ )} +
+

{title}

+ {description &&

{description}

} +
+ {action &&
{action}
} +
+ ); +} diff --git a/packages/ui/src/components/input.tsx b/packages/ui/src/components/input.tsx new file mode 100644 index 00000000..f8abeacb --- /dev/null +++ b/packages/ui/src/components/input.tsx @@ -0,0 +1,25 @@ +import * as React from 'react'; +import { cn } from '../lib/cn'; + +const Input = React.forwardRef>( + ({ className, type, ...props }, ref) => ( + + ), +); +Input.displayName = 'Input'; + +export { Input }; diff --git a/packages/ui/src/components/kbd.tsx b/packages/ui/src/components/kbd.tsx new file mode 100644 index 00000000..5a93fe38 --- /dev/null +++ b/packages/ui/src/components/kbd.tsx @@ -0,0 +1,17 @@ +import * as React from 'react'; +import { cn } from '../lib/cn'; + +/** Small inline keyboard-key label, e.g. `⌘K`. */ +export const Kbd = React.forwardRef>( + ({ className, ...props }, ref) => ( + + ), +); +Kbd.displayName = 'Kbd'; diff --git a/packages/ui/src/components/label.tsx b/packages/ui/src/components/label.tsx new file mode 100644 index 00000000..6fdbf875 --- /dev/null +++ b/packages/ui/src/components/label.tsx @@ -0,0 +1,17 @@ +import * as React from 'react'; +import * as LabelPrimitive from '@radix-ui/react-label'; +import { cn } from '../lib/cn'; + +const Label = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +Label.displayName = 'Label'; + +export { Label }; diff --git a/packages/ui/src/components/popover.tsx b/packages/ui/src/components/popover.tsx new file mode 100644 index 00000000..86ac8997 --- /dev/null +++ b/packages/ui/src/components/popover.tsx @@ -0,0 +1,31 @@ +import * as React from 'react'; +import * as PopoverPrimitive from '@radix-ui/react-popover'; +import { cn } from '../lib/cn'; + +const Popover = PopoverPrimitive.Root; +const PopoverTrigger = PopoverPrimitive.Trigger; +const PopoverAnchor = PopoverPrimitive.Anchor; + +const PopoverContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, align = 'center', sideOffset = 6, ...props }, ref) => ( + + + +)); +PopoverContent.displayName = 'PopoverContent'; + +export { Popover, PopoverTrigger, PopoverAnchor, PopoverContent }; diff --git a/packages/ui/src/components/progress.tsx b/packages/ui/src/components/progress.tsx new file mode 100644 index 00000000..446ab746 --- /dev/null +++ b/packages/ui/src/components/progress.tsx @@ -0,0 +1,54 @@ +import * as React from 'react'; +import { cn } from '../lib/cn'; + +interface ProgressProps extends React.HTMLAttributes { + value?: number; + indicatorClassName?: string; + /** + * When true, the bar shows an animated marquee instead of a fixed + * width — useful when we know a job is running but don't yet know + * the total size (e.g. a download whose Content-Length is unknown). + */ + indeterminate?: boolean; +} + +const Progress = React.forwardRef( + ({ className, value = 0, indicatorClassName, indeterminate = false, ...props }, ref) => { + const clamped = Math.max(0, Math.min(100, value)); + return ( +
+ {indeterminate ? ( +
+ ) : ( +
+ )} +
+ ); + }, +); +Progress.displayName = 'Progress'; + +export { Progress }; diff --git a/packages/ui/src/components/scroll-area.tsx b/packages/ui/src/components/scroll-area.tsx new file mode 100644 index 00000000..c842f3aa --- /dev/null +++ b/packages/ui/src/components/scroll-area.tsx @@ -0,0 +1,50 @@ +import * as React from 'react'; +import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area'; +import { cn } from '../lib/cn'; + +interface ScrollAreaProps extends React.ComponentPropsWithoutRef { + viewportClassName?: string; +} + +const ScrollArea = React.forwardRef, ScrollAreaProps>( + ({ className, children, viewportClassName, type = 'hover', ...props }, ref) => ( + + div]:!block', viewportClassName)} + > + {children} + + + + + + ), +); +ScrollArea.displayName = 'ScrollArea'; + +const ScrollBar = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, orientation = 'vertical', ...props }, ref) => ( + + + +)); +ScrollBar.displayName = 'ScrollBar'; + +export { ScrollArea, ScrollBar }; diff --git a/packages/ui/src/components/select.tsx b/packages/ui/src/components/select.tsx new file mode 100644 index 00000000..04dabb47 --- /dev/null +++ b/packages/ui/src/components/select.tsx @@ -0,0 +1,158 @@ +import * as React from 'react'; +import * as SelectPrimitive from '@radix-ui/react-select'; +import { Check, ChevronDown, ChevronUp } from 'lucide-react'; +import { cn } from '../lib/cn'; + +const Select = SelectPrimitive.Root; +const SelectGroup = SelectPrimitive.Group; +const SelectValue = SelectPrimitive.Value; + +const SelectTrigger = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + span:not([data-radix-select-icon])]:flex-1 [&>span:not([data-radix-select-icon])]:min-w-0 [&>span:not([data-radix-select-icon])]:truncate [&>span:not([data-radix-select-icon])]:text-left', + className, + )} + {...props} + > + {children} + + + + +)); +SelectTrigger.displayName = 'SelectTrigger'; + +const SelectScrollUpButton = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + + + +)); +SelectScrollUpButton.displayName = 'SelectScrollUpButton'; + +const SelectScrollDownButton = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + + + +)); +SelectScrollDownButton.displayName = 'SelectScrollDownButton'; + +const SelectContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, position = 'popper', ...props }, ref) => ( + + + + + {children} + + + + +)); +SelectContent.displayName = 'SelectContent'; + +const SelectLabel = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +SelectLabel.displayName = 'SelectLabel'; + +const SelectItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + + + + + + + {children} + +)); +SelectItem.displayName = 'SelectItem'; + +const SelectSeparator = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +SelectSeparator.displayName = 'SelectSeparator'; + +export { + Select, + SelectGroup, + SelectValue, + SelectTrigger, + SelectContent, + SelectLabel, + SelectItem, + SelectSeparator, + SelectScrollUpButton, + SelectScrollDownButton, +}; diff --git a/packages/ui/src/components/separator.tsx b/packages/ui/src/components/separator.tsx new file mode 100644 index 00000000..63dfdd8b --- /dev/null +++ b/packages/ui/src/components/separator.tsx @@ -0,0 +1,23 @@ +import * as React from 'react'; +import * as SeparatorPrimitive from '@radix-ui/react-separator'; +import { cn } from '../lib/cn'; + +const Separator = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, orientation = 'horizontal', decorative = true, ...props }, ref) => ( + +)); +Separator.displayName = 'Separator'; + +export { Separator }; diff --git a/packages/ui/src/components/sheet.tsx b/packages/ui/src/components/sheet.tsx new file mode 100644 index 00000000..9f4a8406 --- /dev/null +++ b/packages/ui/src/components/sheet.tsx @@ -0,0 +1,66 @@ +import * as React from 'react'; +import * as DialogPrimitive from '@radix-ui/react-dialog'; +import { X } from 'lucide-react'; +import { cva, type VariantProps } from 'class-variance-authority'; +import { cn } from '../lib/cn'; + +const Sheet = DialogPrimitive.Root; +const SheetTrigger = DialogPrimitive.Trigger; +const SheetClose = DialogPrimitive.Close; +const SheetPortal = DialogPrimitive.Portal; + +const SheetOverlay = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +SheetOverlay.displayName = 'SheetOverlay'; + +const sheetVariants = cva( + 'fixed z-50 gap-4 bg-card p-0 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500 outline-none', + { + variants: { + side: { + top: 'inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top', + bottom: 'inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom', + left: 'inset-y-0 left-0 h-full w-3/4 max-w-xs border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm', + right: 'inset-y-0 right-0 h-full w-3/4 max-w-xs border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm', + }, + }, + defaultVariants: { side: 'right' }, + } +); + +interface SheetContentProps + extends React.ComponentPropsWithoutRef, + VariantProps { + showClose?: boolean; +} + +const SheetContent = React.forwardRef, SheetContentProps>( + ({ side = 'right', className, children, showClose = true, ...props }, ref) => ( + + + + {children} + {showClose && ( + + + Close + + )} + + + ) +); +SheetContent.displayName = 'SheetContent'; + +export { Sheet, SheetTrigger, SheetClose, SheetContent, SheetPortal, SheetOverlay }; diff --git a/packages/ui/src/components/skeleton.tsx b/packages/ui/src/components/skeleton.tsx new file mode 100644 index 00000000..f89e9f2b --- /dev/null +++ b/packages/ui/src/components/skeleton.tsx @@ -0,0 +1,6 @@ +import * as React from 'react'; +import { cn } from '../lib/cn'; + +export function Skeleton({ className, ...props }: React.HTMLAttributes) { + return
; +} diff --git a/packages/ui/src/components/status-dot.tsx b/packages/ui/src/components/status-dot.tsx new file mode 100644 index 00000000..2f66c1ec --- /dev/null +++ b/packages/ui/src/components/status-dot.tsx @@ -0,0 +1,49 @@ +import * as React from 'react'; +import { cva, type VariantProps } from 'class-variance-authority'; +import { cn } from '../lib/cn'; + +/** + * A semantic colored status dot — drop-in replacement for ad-hoc emoji + * (🟢 / 🟡 / 🔴) so we keep visual rhythm with the rest of the Lucide + * iconography. `pulse` adds a soft halo for the "active" state. + */ +const dotVariants = cva('inline-block shrink-0 rounded-full', { + variants: { + tone: { + success: 'bg-success', + warning: 'bg-warning', + destructive: 'bg-destructive', + info: 'bg-info', + muted: 'bg-muted-foreground/50', + primary: 'bg-primary', + }, + size: { + xs: 'size-1.5', + sm: 'size-2', + md: 'size-2.5', + lg: 'size-3', + }, + }, + defaultVariants: { tone: 'muted', size: 'sm' }, +}); + +export interface StatusDotProps + extends React.HTMLAttributes, + VariantProps { + pulse?: boolean; +} + +export function StatusDot({ className, tone, size, pulse, ...props }: StatusDotProps) { + return ( + + + + ); +} diff --git a/packages/ui/src/components/switch.tsx b/packages/ui/src/components/switch.tsx new file mode 100644 index 00000000..4f4bf43f --- /dev/null +++ b/packages/ui/src/components/switch.tsx @@ -0,0 +1,35 @@ +import * as React from 'react'; +import * as SwitchPrimitive from '@radix-ui/react-switch'; +import { cn } from '../lib/cn'; + +const Switch = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + + + +)); +Switch.displayName = 'Switch'; + +export { Switch }; diff --git a/packages/ui/src/components/tabs.tsx b/packages/ui/src/components/tabs.tsx new file mode 100644 index 00000000..21d44c14 --- /dev/null +++ b/packages/ui/src/components/tabs.tsx @@ -0,0 +1,52 @@ +import * as React from 'react'; +import * as TabsPrimitive from '@radix-ui/react-tabs'; +import { cn } from '../lib/cn'; + +const Tabs = TabsPrimitive.Root; + +const TabsList = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +TabsList.displayName = 'TabsList'; + +const TabsTrigger = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +TabsTrigger.displayName = 'TabsTrigger'; + +const TabsContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +TabsContent.displayName = 'TabsContent'; + +export { Tabs, TabsList, TabsTrigger, TabsContent }; diff --git a/packages/ui/src/components/toaster.tsx b/packages/ui/src/components/toaster.tsx new file mode 100644 index 00000000..73b50998 --- /dev/null +++ b/packages/ui/src/components/toaster.tsx @@ -0,0 +1,29 @@ +import { Toaster as Sonner, toast, type ToasterProps } from 'sonner'; + +/** + * SnowLuma-themed toaster. Uses the Tailwind `--*-foreground / --background` + * tokens defined in `@snowluma/ui/styles/theme.css` so toasts match the + * surrounding chrome in both light and dark mode. + */ +export function Toaster(props: ToasterProps) { + return ( + + ); +} + +export { toast }; +export type { ToasterProps }; diff --git a/packages/ui/src/components/tooltip.tsx b/packages/ui/src/components/tooltip.tsx new file mode 100644 index 00000000..f30b970a --- /dev/null +++ b/packages/ui/src/components/tooltip.tsx @@ -0,0 +1,29 @@ +import * as React from 'react'; +import * as TooltipPrimitive from '@radix-ui/react-tooltip'; +import { cn } from '../lib/cn'; + +const TooltipProvider = TooltipPrimitive.Provider; +const Tooltip = TooltipPrimitive.Root; +const TooltipTrigger = TooltipPrimitive.Trigger; + +const TooltipContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, sideOffset = 6, ...props }, ref) => ( + + + +)); +TooltipContent.displayName = 'TooltipContent'; + +export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }; diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts new file mode 100644 index 00000000..b9eac5a2 --- /dev/null +++ b/packages/ui/src/index.ts @@ -0,0 +1,72 @@ +export { cn } from './lib/cn'; +export { Button, buttonVariants, type ButtonProps } from './components/button'; +export { + AlertDialog, + AlertDialogPortal, + AlertDialogOverlay, + AlertDialogTrigger, + AlertDialogContent, + AlertDialogHeader, + AlertDialogFooter, + AlertDialogTitle, + AlertDialogDescription, + AlertDialogAction, + AlertDialogCancel, +} from './components/alert-dialog'; +export { Avatar, AvatarImage, AvatarFallback } from './components/avatar'; +export { Badge, badgeVariants, type BadgeProps } from './components/badge'; +export { + Card, + CardHeader, + CardTitle, + CardDescription, + CardContent, + CardFooter, +} from './components/card'; +export { Checkbox } from './components/checkbox'; +export { + Dialog, + DialogPortal, + DialogOverlay, + DialogTrigger, + DialogClose, + DialogContent, + DialogHeader, + DialogFooter, + DialogTitle, + DialogDescription, +} from './components/dialog'; +export { Input } from './components/input'; +export { Label } from './components/label'; +export { Progress } from './components/progress'; +export { ScrollArea, ScrollBar } from './components/scroll-area'; +export { + Select, + SelectGroup, + SelectValue, + SelectTrigger, + SelectContent, + SelectLabel, + SelectItem, + SelectSeparator, + SelectScrollUpButton, + SelectScrollDownButton, +} from './components/select'; +export { Separator } from './components/separator'; +export { + Sheet, + SheetTrigger, + SheetClose, + SheetContent, + SheetPortal, + SheetOverlay, +} from './components/sheet'; +export { Skeleton } from './components/skeleton'; +export { Switch } from './components/switch'; +export { Tabs, TabsList, TabsTrigger, TabsContent } from './components/tabs'; +export { Toaster, toast, type ToasterProps } from './components/toaster'; +export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } from './components/tooltip'; +export { Popover, PopoverTrigger, PopoverAnchor, PopoverContent } from './components/popover'; +export { Kbd } from './components/kbd'; +export { StatusDot, type StatusDotProps } from './components/status-dot'; +export { EmptyState } from './components/empty-state'; diff --git a/packages/ui/src/lib/cn.ts b/packages/ui/src/lib/cn.ts new file mode 100644 index 00000000..a7c26636 --- /dev/null +++ b/packages/ui/src/lib/cn.ts @@ -0,0 +1,6 @@ +import { clsx, type ClassValue } from 'clsx'; +import { twMerge } from 'tailwind-merge'; + +export function cn(...inputs: ClassValue[]): string { + return twMerge(clsx(inputs)); +} diff --git a/packages/ui/src/styles/theme.css b/packages/ui/src/styles/theme.css new file mode 100644 index 00000000..608b8b96 --- /dev/null +++ b/packages/ui/src/styles/theme.css @@ -0,0 +1,259 @@ +/** + * @snowluma/ui — Tailwind 4 theme tokens. + * + * Consumer setup: + * @import "tailwindcss"; + * @import "tw-animate-css"; + * @import "@snowluma/ui/styles/theme.css"; + * @source "../node_modules/@snowluma/ui/dist/**\/*.js"; + */ + +@custom-variant dark (&:where(.dark, .dark *)); + +:root { + /* Surface ramp — light mode: near-white surfaces over a faint blue base. */ + --radius: 0.625rem; + + --background: oklch(99% 0.004 240); + --foreground: oklch(20% 0.03 250); + + --card: oklch(100% 0 0); + --card-foreground: oklch(20% 0.03 250); + + --popover: oklch(100% 0 0); + --popover-foreground: oklch(20% 0.03 250); + + /* sky accent ramp */ + --primary: oklch(64% 0.16 230); + --primary-foreground: oklch(99% 0.005 240); + + --secondary: oklch(96.5% 0.012 240); + --secondary-foreground: oklch(22% 0.03 250); + + --muted: oklch(96.5% 0.012 240); + --muted-foreground: oklch(48% 0.02 250); + + --accent: oklch(94% 0.04 230); + --accent-foreground: oklch(28% 0.08 230); + + --destructive: oklch(58% 0.22 27); + --destructive-foreground: oklch(99% 0.005 240); + + --success: oklch(64% 0.16 155); + --success-foreground: oklch(99% 0.005 240); + + --warning: oklch(76% 0.16 75); + --warning-foreground: oklch(20% 0.05 75); + + --info: oklch(64% 0.16 230); + --info-foreground: oklch(99% 0.005 240); + + --border: oklch(91% 0.012 240); + --input: oklch(94% 0.012 240); + --ring: oklch(64% 0.16 230); + + --sidebar: oklch(98% 0.006 240); + --sidebar-foreground: oklch(25% 0.03 250); + --sidebar-primary: oklch(64% 0.16 230); + --sidebar-primary-foreground: oklch(99% 0.005 240); + --sidebar-accent: oklch(94% 0.03 230); + --sidebar-accent-foreground: oklch(28% 0.08 230); + --sidebar-border: oklch(91% 0.012 240); + --sidebar-ring: oklch(64% 0.16 230); + + --chrome-height: 3.25rem; /* 52px — uniform top-bar height */ + --titlebar-height: 2rem; /* 32px — Windows native titlebar height */ + + --shadow-color: 240 6% 10%; + --shadow-xs: 0 1px 2px 0 hsl(var(--shadow-color) / 0.05); + --shadow-sm: 0 1px 3px 0 hsl(var(--shadow-color) / 0.08), 0 1px 2px -1px hsl(var(--shadow-color) / 0.06); + --shadow-md: 0 4px 6px -1px hsl(var(--shadow-color) / 0.08), 0 2px 4px -2px hsl(var(--shadow-color) / 0.04); + --shadow-lg: 0 10px 16px -3px hsl(var(--shadow-color) / 0.10), 0 4px 6px -4px hsl(var(--shadow-color) / 0.05); + --shadow-xl: 0 20px 28px -8px hsl(var(--shadow-color) / 0.14); +} + +.dark { + --background: oklch(13% 0.02 250); + --foreground: oklch(96% 0.012 240); + + --card: oklch(17% 0.022 250); + --card-foreground: oklch(96% 0.012 240); + + --popover: oklch(20% 0.025 250); + --popover-foreground: oklch(96% 0.012 240); + + --primary: oklch(72% 0.16 230); + --primary-foreground: oklch(12% 0.025 250); + + --secondary: oklch(22% 0.025 250); + --secondary-foreground: oklch(94% 0.012 240); + + --muted: oklch(20% 0.022 250); + --muted-foreground: oklch(72% 0.02 240); + + --accent: oklch(30% 0.06 230); + --accent-foreground: oklch(88% 0.12 230); + + --destructive: oklch(66% 0.22 27); + --destructive-foreground: oklch(98% 0.005 240); + + --success: oklch(70% 0.16 155); + --success-foreground: oklch(12% 0.025 250); + + --warning: oklch(80% 0.16 75); + --warning-foreground: oklch(20% 0.05 75); + + --info: oklch(72% 0.16 230); + --info-foreground: oklch(12% 0.025 250); + + --border: oklch(28% 0.025 250); + --input: oklch(26% 0.025 250); + --ring: oklch(72% 0.16 230); + + --sidebar: oklch(15% 0.022 250); + --sidebar-foreground: oklch(92% 0.012 240); + --sidebar-primary: oklch(72% 0.16 230); + --sidebar-primary-foreground: oklch(12% 0.025 250); + --sidebar-accent: oklch(28% 0.06 230); + --sidebar-accent-foreground: oklch(88% 0.12 230); + --sidebar-border: oklch(24% 0.025 250); + --sidebar-ring: oklch(72% 0.16 230); + + --shadow-color: 240 14% 4%; + --shadow-xs: 0 1px 2px 0 hsl(var(--shadow-color) / 0.30); + --shadow-sm: 0 1px 3px 0 hsl(var(--shadow-color) / 0.36), 0 1px 2px -1px hsl(var(--shadow-color) / 0.28); + --shadow-md: 0 4px 6px -1px hsl(var(--shadow-color) / 0.40), 0 2px 4px -2px hsl(var(--shadow-color) / 0.28); + --shadow-lg: 0 10px 16px -3px hsl(var(--shadow-color) / 0.50), 0 4px 6px -4px hsl(var(--shadow-color) / 0.32); + --shadow-xl: 0 20px 28px -8px hsl(var(--shadow-color) / 0.55); +} + +@theme inline { + --color-background: var(--background); + --color-foreground: var(--foreground); + --color-card: var(--card); + --color-card-foreground: var(--card-foreground); + --color-popover: var(--popover); + --color-popover-foreground: var(--popover-foreground); + --color-primary: var(--primary); + --color-primary-foreground: var(--primary-foreground); + --color-secondary: var(--secondary); + --color-secondary-foreground: var(--secondary-foreground); + --color-muted: var(--muted); + --color-muted-foreground: var(--muted-foreground); + --color-accent: var(--accent); + --color-accent-foreground: var(--accent-foreground); + --color-destructive: var(--destructive); + --color-destructive-foreground: var(--destructive-foreground); + --color-success: var(--success); + --color-success-foreground: var(--success-foreground); + --color-warning: var(--warning); + --color-warning-foreground: var(--warning-foreground); + --color-info: var(--info); + --color-info-foreground: var(--info-foreground); + --color-border: var(--border); + --color-input: var(--input); + --color-ring: var(--ring); + --color-sidebar: var(--sidebar); + --color-sidebar-foreground: var(--sidebar-foreground); + --color-sidebar-primary: var(--sidebar-primary); + --color-sidebar-primary-foreground: var(--sidebar-primary-foreground); + --color-sidebar-accent: var(--sidebar-accent); + --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); + --color-sidebar-border: var(--sidebar-border); + --color-sidebar-ring: var(--sidebar-ring); + + --radius-xs: calc(var(--radius) - 6px); + --radius-sm: calc(var(--radius) - 4px); + --radius-md: calc(var(--radius) - 2px); + --radius-lg: var(--radius); + --radius-xl: calc(var(--radius) + 4px); + --radius-2xl: calc(var(--radius) + 8px); + --radius-3xl: calc(var(--radius) + 16px); + + --shadow-xs: var(--shadow-xs); + --shadow-sm: var(--shadow-sm); + --shadow-md: var(--shadow-md); + --shadow-lg: var(--shadow-lg); + --shadow-xl: var(--shadow-xl); + + --font-sans: 'Inter', 'Noto Sans SC', system-ui, -apple-system, sans-serif; + --font-mono: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace; +} + +@layer base { + * { + border-color: var(--border); + } + html, body, #root { + height: 100%; + } + body { + margin: 0; + background-color: var(--background); + color: var(--foreground); + font-family: var(--font-sans); + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + line-height: 1.5; + overflow: hidden; /* desktop chrome: no body scroll, panels manage their own */ + } + ::selection { + background-color: color-mix(in oklab, var(--primary) 28%, transparent); + color: var(--foreground); + } + + *::-webkit-scrollbar { + width: 10px; + height: 10px; + } + *::-webkit-scrollbar-track { + background: transparent; + } + *::-webkit-scrollbar-thumb { + background-color: color-mix(in oklab, var(--muted-foreground) 35%, transparent); + border-radius: 9999px; + border: 2px solid transparent; + background-clip: content-box; + } + *::-webkit-scrollbar-thumb:hover { + background-color: color-mix(in oklab, var(--muted-foreground) 55%, transparent); + background-clip: content-box; + } + + html[data-density="compact"] body { + font-size: 13.5px; + line-height: 1.45; + } +} + +@layer utilities { + .hover-lift { + transition: transform 180ms cubic-bezier(0.22, 1, 0.36, 1), + box-shadow 220ms cubic-bezier(0.22, 1, 0.36, 1); + } + .hover-lift:hover { + transform: translateY(-1px); + box-shadow: var(--shadow-md); + } + .surface-gloss { + background-image: linear-gradient( + 180deg, + color-mix(in oklab, var(--foreground) 3%, transparent) 0%, + transparent 80% + ); + } + .surface-glass { + background-color: color-mix(in oklab, var(--popover) 92%, transparent); + backdrop-filter: saturate(180%) blur(12px); + -webkit-backdrop-filter: saturate(180%) blur(12px); + } +} + +@keyframes progress-marquee { + 0% { + transform: translateX(-100%); + } + 100% { + transform: translateX(400%); + } +} diff --git a/packages/ui/tsconfig.json b/packages/ui/tsconfig.json new file mode 100644 index 00000000..8b69c957 --- /dev/null +++ b/packages/ui/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src", + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "jsx": "react-jsx", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "types": ["react", "react-dom"], + "ignoreDeprecations": "6.0" + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/ui/tsup.config.ts b/packages/ui/tsup.config.ts new file mode 100644 index 00000000..4908bb7e --- /dev/null +++ b/packages/ui/tsup.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from 'tsup'; + +export default defineConfig({ + entry: ['src/index.ts'], + format: ['esm'], + dts: true, + sourcemap: true, + clean: true, + external: ['react', 'react-dom'], + target: 'es2022', + treeshake: true, +}); diff --git a/packages/websocket/package.json b/packages/websocket/package.json index 6a11dc09..cd32d250 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/websocket", - "version": "1.8.1", + "version": "1.8.2", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/webui/package.json b/packages/webui/package.json index bf46cf99..086dd109 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -1,7 +1,7 @@ { "name": "webui", "private": true, - "version": "1.8.1", + "version": "1.8.2", "type": "module", "scripts": { "dev": "vite", @@ -18,6 +18,7 @@ "@radix-ui/react-separator": "^1.1.3", "@radix-ui/react-slot": "^1.1.3", "@radix-ui/react-tooltip": "^1.1.9", + "@tanstack/react-router": "^1.169.2", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "lucide-react": "^0.469.0", diff --git a/packages/webui/src/App.tsx b/packages/webui/src/App.tsx index 24607fab..2a759e7e 100644 --- a/packages/webui/src/App.tsx +++ b/packages/webui/src/App.tsx @@ -1,421 +1,108 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from 'react'; +import { RouterProvider } from '@tanstack/react-router'; import { TooltipProvider } from '@/components/ui/tooltip'; -import { ThemeProvider, useTheme } from '@/contexts/ThemeContext'; +import { ThemeProvider } from '@/contexts/ThemeContext'; +import { SessionProvider } from '@/contexts/SessionContext'; import { LoginPage } from '@/components/pages/login-page'; -import { MainLayout } from '@/components/layout/main-layout'; -import { OverviewPage } from '@/components/pages/overview-page'; -import { ConfigPage } from '@/components/pages/config-page'; -import { LogsPage } from '@/components/pages/logs-page'; -import { SettingsPage } from '@/components/pages/settings-page'; -import { ChangePasswordPage, type PasswordRule } from '@/components/pages/change-password-page'; -import { ConfirmDialog } from '@/components/confirm-dialog'; -import type { Page } from '@/components/layout/sidebar'; -import type { HookProcessInfo, OneBotConfig, QQInfo, SystemInfo } from '@/types'; - -const TOKEN_KEY = 'snowluma_token'; - -function readToken() { - return localStorage.getItem(TOKEN_KEY) || ''; -} +import { ChangePasswordPage } from '@/components/pages/change-password-page'; +import { ApiProvider, createApiClient, useApi, type ApiClient } from '@/lib/api'; +import { appRouter } from '@/router'; export default function App() { return ( - + ); } -function AppInner() { - const { pollInterval } = useTheme(); +function AuthBoundary() { const [authChecked, setAuthChecked] = useState(false); const [authed, setAuthed] = useState(false); const [mustChange, setMustChange] = useState(false); const [status, setStatus] = useState('未连接'); - const [active, setActive] = useState('overview'); - const [qqList, setQqList] = useState([]); - const [processList, setProcessList] = useState([]); - const [systemInfo, setSystemInfo] = useState(null); - - const [processLoadingPid, setProcessLoadingPid] = useState(null); - const [processUnloadingPid, setProcessUnloadingPid] = useState(null); - const [processRefreshingPid, setProcessRefreshingPid] = useState(null); - const [processActionStatus, setProcessActionStatus] = useState(''); - const [unloadFailedAlert, setUnloadFailedAlert] = useState<{ pid: number; error: string } | null>(null); - // Tracks PIDs with an in-flight load/unload/refresh request so the UI can - // collapse spam-clicks instead of firing a second concurrent request. - const inflightProcessOps = useRef(new Set()); - - const [selectedUin, setSelectedUin] = useState(null); - const [config, setConfig] = useState(null); - const [saveStatus, setSaveStatus] = useState(''); - - const tokenRef = useRef(readToken()); - - // ---------- API helpers ---------- - const fetchApi = useCallback(async (url: string, options: RequestInit = {}) => { - const headers: Record = { - ...(options.headers as Record | undefined), - }; - if (tokenRef.current) headers['Authorization'] = `Bearer ${tokenRef.current}`; - if (options.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json'; - const res = await fetch(url, { ...options, headers }); - if (res.status === 401) { - tokenRef.current = ''; - localStorage.removeItem(TOKEN_KEY); - setAuthed(false); - setStatus('未授权'); - } - return res; - }, []); - - // ---------- Polling ---------- - const refreshQqList = useCallback(async () => { - try { - const res = await fetchApi('/api/qq-list'); - if (!res.ok) return; - const data = await res.json(); - setQqList(data.list || []); - } catch (e) { - console.error('qq-list', e); - } - }, [fetchApi]); - - const refreshProcesses = useCallback(async () => { - try { - const res = await fetchApi('/api/processes'); - if (!res.ok) return; - const data = await res.json(); - setProcessList(data.list || []); - } catch (e) { - console.error('processes', e); - } - }, [fetchApi]); - - const refreshSystem = useCallback(async () => { - try { - const res = await fetchApi('/api/system'); - if (!res.ok) return; - const data = (await res.json()) as SystemInfo; - setSystemInfo(data); - } catch (e) { - console.error('system', e); - } - }, [fetchApi]); - - const checkStatus = useCallback(async () => { - try { - const res = await fetchApi('/api/status'); - if (res.ok) { - setAuthed(true); - setStatus('已连接'); - return true; - } - setStatus('未连接'); - return false; - } catch { - setStatus('未连接'); - return false; - } - }, [fetchApi]); + const client = useMemo( + () => + createApiClient({ + onUnauthorized: () => { + setAuthed(false); + setStatus('未授权'); + }, + }), + [], + ); useEffect(() => { (async () => { - if (tokenRef.current) { - const ok = await checkStatus(); - if (ok) { - // Existing session may still need to change password. - try { - const r = await fetchApi('/api/auth/state'); - if (r.ok) { - const d = await r.json(); - setMustChange(!!d.mustChangePassword); - } - } catch { /* ignore */ } - } + const ok = await client.status(); + if (ok) { + setAuthed(true); + setStatus('已连接'); + setMustChange(await client.mustChangePassword()); } setAuthChecked(true); })(); - }, [checkStatus, fetchApi]); + }, [client]); - useEffect(() => { - if (!authed || mustChange) return; - if (pollInterval <= 0) return; - let cancelled = false; - const tick = async () => { - if (cancelled) return; - await Promise.all([refreshQqList(), refreshProcesses(), refreshSystem()]); - }; - tick(); - const interval = setInterval(tick, pollInterval); - return () => { - cancelled = true; - clearInterval(interval); - }; - }, [authed, mustChange, pollInterval, refreshQqList, refreshProcesses, refreshSystem]); - - // Auto-select first uin when navigating to config - useEffect(() => { - if (active !== 'config') return; - if (!selectedUin && qqList.length > 0) setSelectedUin(qqList[0].uin); - }, [active, qqList, selectedUin]); - - // Load config when selectedUin changes - useEffect(() => { - if (!selectedUin) { - setConfig(null); - return; - } - let cancelled = false; - (async () => { - try { - const res = await fetchApi(`/api/config/${encodeURIComponent(selectedUin)}`); - if (!res.ok) return; - const data = await res.json(); - const loaded = data?.config ?? data; - if (cancelled) return; - const nets = loaded?.networks ?? {}; - const legacyFormat = loaded?.messageFormat === 'string' ? 'string' : 'array'; - const legacyReport = !!loaded?.reportSelfMessage; - const normalizeNetwork = >(item: T) => ({ - ...item, - messageFormat: item.messageFormat === 'string' ? 'string' : legacyFormat, - reportSelfMessage: - typeof item.reportSelfMessage === 'boolean' ? item.reportSelfMessage : legacyReport, - }); - setConfig({ - networks: { - httpServers: Array.isArray(nets.httpServers) ? nets.httpServers.map(normalizeNetwork) : [], - httpClients: Array.isArray(nets.httpClients) ? nets.httpClients.map(normalizeNetwork) : [], - wsServers: Array.isArray(nets.wsServers) ? nets.wsServers.map(normalizeNetwork) : [], - wsClients: Array.isArray(nets.wsClients) ? nets.wsClients.map(normalizeNetwork) : [], - }, - musicSignUrl: loaded?.musicSignUrl, - }); - } catch (e) { - console.error('load-config', e); - } - })(); - return () => { - cancelled = true; - }; - }, [selectedUin, fetchApi]); - - // ---------- Actions ---------- - const handleLogin = useCallback(async (password: string) => { - try { - const res = await fetch('/api/login', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ password }), - }); - if (!res.ok) { - const data = await res.json().catch(() => ({})); - return { success: false, error: data.message || data.error || '令牌错误' }; - } - const data = await res.json(); - const token = data.token as string; - localStorage.setItem(TOKEN_KEY, token); - tokenRef.current = token; - setMustChange(!!data.mustChangePassword); - const ok = await checkStatus(); - return ok ? { success: true } : { success: false, error: '校验失败' }; - } catch (e) { - return { success: false, error: (e as Error).message || '网络错误' }; - } - }, [checkStatus]); - - const handleLogout = useCallback(async () => { - try { await fetchApi('/api/logout', { method: 'POST' }); } catch { /* ignore */ } - localStorage.removeItem(TOKEN_KEY); - tokenRef.current = ''; + const handleLogoutComplete = useCallback(() => { + // Reset the URL so the next login lands on the overview page, matching + // the pre-router behaviour. + window.history.replaceState({}, '', '/'); setAuthed(false); - setMustChange(false); setStatus('未连接'); - setQqList([]); - setProcessList([]); - setSystemInfo(null); - setSelectedUin(null); - setConfig(null); - }, [fetchApi]); - - const handleLoadProcess = useCallback(async (pid: number) => { - if (inflightProcessOps.current.has(pid)) return; - inflightProcessOps.current.add(pid); - setProcessLoadingPid(pid); - setProcessActionStatus(`正在向进程 ${pid} 加载 SnowLuma…`); - try { - const res = await fetchApi(`/api/processes/${pid}/load`, { method: 'POST' }); - const data = await res.json().catch(() => ({})); - if (!res.ok) throw new Error(data.message || data.error || '加载失败'); - setProcessActionStatus(`已向进程 ${pid} 注入 SnowLuma,等待管道连接…`); - await refreshProcesses(); - } catch (e) { - setProcessActionStatus(`加载失败:${(e as Error).message}`); - } finally { - inflightProcessOps.current.delete(pid); - setProcessLoadingPid(null); - setTimeout(() => setProcessActionStatus(''), 4000); - } - }, [fetchApi, refreshProcesses]); - - const handleUnloadProcess = useCallback(async (pid: number) => { - if (inflightProcessOps.current.has(pid)) return; - inflightProcessOps.current.add(pid); - setProcessUnloadingPid(pid); - setProcessActionStatus(`正在从进程 ${pid} 卸载…`); - try { - const res = await fetchApi(`/api/processes/${pid}/unload`, { method: 'POST' }); - const data = await res.json().catch(() => ({})); - if (!res.ok) throw new Error(data.message || data.error || '卸载失败'); - - // Check if unload actually failed (pipe still exists) - if (data.process?.status === 'connecting' && data.process?.error) { - setUnloadFailedAlert({ pid, error: data.process.error }); - setProcessActionStatus(`进程 ${pid} 卸载失败`); - } else { - setProcessActionStatus(`已从进程 ${pid} 卸载`); - } - - await refreshProcesses(); - } catch (e) { - setProcessActionStatus(`卸载失败:${(e as Error).message}`); - } finally { - inflightProcessOps.current.delete(pid); - setProcessUnloadingPid(null); - setTimeout(() => setProcessActionStatus(''), 4000); - } - }, [fetchApi, refreshProcesses]); - - const handleRefreshProcess = useCallback(async (pid: number) => { - if (inflightProcessOps.current.has(pid)) return; - inflightProcessOps.current.add(pid); - setProcessRefreshingPid(pid); - setProcessActionStatus(`正在刷新进程 ${pid} 的管道状态…`); - try { - const res = await fetchApi(`/api/processes/${pid}/refresh`, { method: 'POST' }); - const data = await res.json().catch(() => ({})); - if (!res.ok) throw new Error(data.message || data.error || '刷新失败'); - setProcessActionStatus(`已刷新进程 ${pid} 的管道状态`); - await refreshProcesses(); - } catch (e) { - setProcessActionStatus(`刷新失败:${(e as Error).message}`); - } finally { - inflightProcessOps.current.delete(pid); - setProcessRefreshingPid(null); - setTimeout(() => setProcessActionStatus(''), 4000); - } - }, [fetchApi, refreshProcesses]); - - const handleSaveConfig = useCallback(async () => { - if (!selectedUin || !config) return; - setSaveStatus('保存中...'); - try { - const res = await fetchApi(`/api/config/${encodeURIComponent(selectedUin)}`, { - method: 'POST', - body: JSON.stringify(config), - }); - const data = await res.json().catch(() => ({})); - if (!res.ok) throw new Error(data.error || '保存失败'); - setSaveStatus('保存成功'); - } catch (e) { - setSaveStatus(`保存失败:${(e as Error).message}`); - } finally { - setTimeout(() => setSaveStatus(''), 3000); - } - }, [selectedUin, config, fetchApi]); - - // ---------- Render ---------- - if (!authChecked) { - return ( -
- 初始化中… -
- ); - } - - const checkStrength = async (password: string) => { - const res = await fetchApi('/api/auth/check-strength', { - method: 'POST', - body: JSON.stringify({ password }), - }); - const data = (await res.json().catch(() => ({}))) as { rules?: PasswordRule[]; valid?: boolean }; - return { rules: data.rules ?? [], valid: !!data.valid }; - }; - const submitPwd = async (oldPassword: string, newPassword: string) => { - const res = await fetchApi('/api/auth/change-password', { - method: 'POST', - body: JSON.stringify({ oldPassword, newPassword }), - }); - const data = (await res.json().catch(() => ({}))) as { success?: boolean; message?: string }; - return { success: !!data.success, message: data.message }; - }; + setMustChange(false); + }, []); return ( - - {!authed ? ( - - ) : mustChange ? ( - setMustChange(false)} - /> - ) : ( - - {active === 'overview' && ( - - )} - {active === 'config' && ( - - )} - {active === 'logs' && } - {active === 'settings' && } - - )} - - !open && setUnloadFailedAlert(null)} - title="卸载失败" - description={ - unloadFailedAlert ? ( - <> -

进程 {unloadFailedAlert.pid} 的 SnowLuma DLL 卸载失败。

-

{unloadFailedAlert.error}

-

- 系统将继续尝试重新连接该进程。如需彻底卸载,请重启 QQ 进程。 -

- - ) : null - } - confirmText="知道了" - onConfirm={() => setUnloadFailedAlert(null)} - /> -
+ + + {!authChecked ? ( +
+ 初始化中… +
+ ) : !authed ? ( + { + setAuthed(true); + setStatus('已连接'); + setMustChange(needsChange); + }} + /> + ) : mustChange ? ( + setMustChange(false)} /> + ) : ( + + + + )} +
+
+ ); +} + +function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean) => void }) { + const api = useApi(); + const handleLogin = useCallback( + async (password: string) => { + const result = await api.login(password); + if (!result.ok) return { success: false, error: result.message }; + onAuthed(result.mustChangePassword); + return { success: true }; + }, + [api, onAuthed], + ); + return ; +} + +function ForcedChangePasswordGate({ onSuccess }: { onSuccess: () => void }) { + const api = useApi(); + return ( + api.checkPasswordStrength(p)} + submit={(o, n) => api.changePassword(o, n)} + onSuccess={onSuccess} + /> ); } diff --git a/packages/webui/src/components/layout/main-layout.tsx b/packages/webui/src/components/layout/main-layout.tsx index 998552f7..6a39f70a 100644 --- a/packages/webui/src/components/layout/main-layout.tsx +++ b/packages/webui/src/components/layout/main-layout.tsx @@ -1,26 +1,26 @@ import { useEffect, useState, type ReactNode } from 'react'; import { motion, AnimatePresence } from 'motion/react'; +import { useRouterState } from '@tanstack/react-router'; import { Sheet, SheetContent } from '@/components/ui/sheet'; import { ScrollArea } from '@/components/ui/scroll-area'; -import { Sidebar, type Page } from '@/components/layout/sidebar'; +import { Sidebar } from '@/components/layout/sidebar'; import { TopBar } from '@/components/layout/top-bar'; import { useMediaQuery } from '@/hooks/use-media-query'; import { cn } from '@/lib/utils'; interface MainLayoutProps { - active: Page; - onNavigate: (page: Page) => void; status: string; onLogout: () => void; children: ReactNode; } -export function MainLayout({ active, onNavigate, status, onLogout, children }: MainLayoutProps) { +export function MainLayout({ status, onLogout, children }: MainLayoutProps) { const isMobile = !useMediaQuery('(min-width: 768px)'); const [collapsed, setCollapsed] = useState(() => { return localStorage.getItem('snowluma_sidebar_collapsed') === '1'; }); const [mobileOpen, setMobileOpen] = useState(false); + const pathname = useRouterState({ select: (s) => s.location.pathname }); useEffect(() => { localStorage.setItem('snowluma_sidebar_collapsed', collapsed ? '1' : '0'); @@ -36,7 +36,7 @@ export function MainLayout({ active, onNavigate, status, onLogout, children }: M transition={{ type: 'spring', stiffness: 280, damping: 32 }} className="relative h-full shrink-0 border-r overflow-hidden" > - + )} @@ -44,11 +44,7 @@ export function MainLayout({ active, onNavigate, status, onLogout, children }: M {isMobile && ( - setMobileOpen(false)} - /> + setMobileOpen(false)} /> )} @@ -56,7 +52,6 @@ export function MainLayout({ active, onNavigate, status, onLogout, children }: M {/* Main column */}
setCollapsed((v) => !v)} @@ -70,7 +65,7 @@ export function MainLayout({ active, onNavigate, status, onLogout, children }: M
void; collapsed?: boolean; onItemClick?: () => void; } -export function Sidebar({ active, onNavigate, collapsed = false, onItemClick }: SidebarProps) { +export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) { + const pathname = useRouterState({ select: (s) => s.location.pathname }); + return (
{/* Brand */} @@ -43,23 +50,21 @@ export function Sidebar({ active, onNavigate, collapsed = false, onItemClick }: {/* Nav */} diff --git a/packages/webui/src/components/layout/top-bar.tsx b/packages/webui/src/components/layout/top-bar.tsx index 5354ad90..b5198cbe 100644 --- a/packages/webui/src/components/layout/top-bar.tsx +++ b/packages/webui/src/components/layout/top-bar.tsx @@ -1,15 +1,14 @@ import { useState } from 'react'; import { LogOut, Menu, PanelLeftClose, PanelLeftOpen } from 'lucide-react'; import { motion, AnimatePresence } from 'motion/react'; +import { useRouterState } from '@tanstack/react-router'; import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; import { ThemeToggle } from '@/components/theme-toggle'; import { ConfirmDialog } from '@/components/confirm-dialog'; -import type { Page } from '@/components/layout/sidebar'; import { NAV_ITEMS } from '@/components/layout/sidebar'; interface TopBarProps { - active: Page; status: string; collapsed: boolean; onToggleCollapse: () => void; @@ -19,7 +18,6 @@ interface TopBarProps { } export function TopBar({ - active, status, collapsed, onToggleCollapse, @@ -28,7 +26,8 @@ export function TopBar({ isMobile, }: TopBarProps) { const [confirmLogout, setConfirmLogout] = useState(false); - const meta = NAV_ITEMS.find((n) => n.page === active); + const pathname = useRouterState({ select: (s) => s.location.pathname }); + const meta = NAV_ITEMS.find((n) => n.to === pathname); const PageIcon = meta?.icon; const online = status === '已连接'; @@ -56,7 +55,7 @@ export function TopBar({ {/* Page title */} void; - onSave: () => Promise | void; - onConfigChange: (config: OneBotConfig) => void; -} +import { useOneBotInstanceConfig } from '@/hooks/use-onebot-instance-config'; +import { useAppState } from '@/contexts/AppStateContext'; function qqAvatarUrl(uin: string) { return `/avatar/${encodeURIComponent(uin)}`; @@ -98,18 +89,28 @@ function Section({ title, description, onAdd, children, count }: SectionProps) { ); } -export function ConfigPage({ - qqList, - selectedUin, - config, - saveStatus, - onSelectAccount, - onSave, - onConfigChange, -}: ConfigPageProps) { +export function ConfigPage() { + const { qqList, selectedUin, setSelectedUin } = useAppState(); + const { + config, + setConfig, + dirty, + requestSwitchUin, + pendingSwitchUin, + confirmSwitch, + cancelSwitch, + save, + saveStatus, + } = useOneBotInstanceConfig(qqList, { + selectedUin, + onSelectedUinChange: setSelectedUin, + }); const [confirmSave, setConfirmSave] = useState(false); - const update = (next: OneBotConfig) => onConfigChange(next); + const update = (next: OneBotConfig) => setConfig(next); + const pendingSwitchAccount = pendingSwitchUin + ? qqList.find((q) => q.uin === pendingSwitchUin) ?? null + : null; return (
@@ -132,7 +133,7 @@ export function ConfigPage({ type="button" whileHover={{ scale: 1.01 }} whileTap={{ scale: 0.98 }} - onClick={() => onSelectAccount(q.uin)} + onClick={() => requestSwitchUin(q.uin)} className={cn( 'flex items-center gap-2.5 rounded-lg border px-2.5 py-2 text-left transition-colors cursor-pointer', isActive ? 'border-primary/30 bg-primary/10' : 'border-transparent hover:bg-accent/40' @@ -193,7 +194,12 @@ export function ConfigPage({ {saveStatus} )} -
@@ -421,7 +427,27 @@ export function ConfigPage({ title="保存配置变更?" description={`即将把当前修改保存到 UIN ${selectedUin ?? ''} 的配置文件,并尝试热重载该会话。`} confirmText="保存" - onConfirm={onSave} + onConfirm={save} + /> + + !open && cancelSwitch()} + title="放弃未保存的修改?" + description={ + <> +

+ 当前会话 {selectedUin} 还有未保存的修改。 +

+

+ 切换到 {pendingSwitchAccount?.uin ?? pendingSwitchUin} + {pendingSwitchAccount?.nickname ? `(${pendingSwitchAccount.nickname})` : ''} 会丢弃这些修改。 +

+ + } + confirmText="放弃并切换" + destructive + onConfirm={confirmSwitch} />
); diff --git a/packages/webui/src/components/pages/logs-page.tsx b/packages/webui/src/components/pages/logs-page.tsx index bc0f07f3..36fd5669 100644 --- a/packages/webui/src/components/pages/logs-page.tsx +++ b/packages/webui/src/components/pages/logs-page.tsx @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { motion } from 'motion/react'; import { Pause, Play, RefreshCw, Trash2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; @@ -9,10 +9,7 @@ import { ScrollArea } from '@/components/ui/scroll-area'; import { ConfirmDialog } from '@/components/confirm-dialog'; import { cn } from '@/lib/utils'; import type { LogEntry } from '@/types'; - -interface LogsPageProps { - fetchApi: (url: string, options?: RequestInit) => Promise; -} +import { useApi } from '@/lib/api'; const levelClass: Record = { debug: 'text-muted-foreground', @@ -24,7 +21,8 @@ const levelClass: Record = { const LEVELS: LogEntry['level'][] = ['debug', 'info', 'success', 'warn', 'error']; -export function LogsPage({ fetchApi }: LogsPageProps) { +export function LogsPage() { + const api = useApi(); const [logs, setLogs] = useState([]); const [streamStatus, setStreamStatus] = useState('连接中'); const [paused, setPaused] = useState(false); @@ -34,36 +32,30 @@ export function LogsPage({ fetchApi }: LogsPageProps) { const endRef = useRef(null); const viewportRef = useRef(null); - const token = useMemo(() => localStorage.getItem('snowluma_token') || '', []); - - async function loadLogs() { - const res = await fetchApi('/api/logs?limit=500'); - if (!res.ok) return; - const data = await res.json(); - setLogs(data.list || []); - } + const loadLogs = useCallback(async () => { + try { + setLogs(await api.logs.list(500)); + } catch (e) { + console.error('logs', e); + } + }, [api]); useEffect(() => { - loadLogs().catch(console.error); - }, []); + void loadLogs(); + }, [loadLogs]); useEffect(() => { - if (!token) return; - const url = `/api/logs/stream?token=${encodeURIComponent(token)}`; - const source = new EventSource(url); - source.onopen = () => setStreamStatus('实时'); - source.onerror = () => setStreamStatus('重连中'); - source.onmessage = (event) => { - try { - const entry = JSON.parse(event.data) as LogEntry | { type: string }; - if ('type' in entry) return; + return api.logs.stream({ + onLine: (entry) => { setLogs((prev) => [...prev.filter((it) => it.id !== entry.id), entry].slice(-1000)); - } catch { - // ignore - } - }; - return () => source.close(); - }, [token]); + }, + onStatus: (s) => { + if (s === 'open') setStreamStatus('实时'); + else if (s === 'reconnecting') setStreamStatus('重连中'); + else setStreamStatus('已断开'); + }, + }); + }, [api]); useEffect(() => { if (paused) return; @@ -115,7 +107,7 @@ export function LogsPage({ fetchApi }: LogsPageProps) { {paused ? : } {paused ? '继续' : '暂停'} -
- @@ -270,7 +246,7 @@ export function OverviewPage({ 加载 SnowLuma 后会监听登录状态,登录后自动接入 OneBot 流程
- @@ -292,10 +268,11 @@ export function OverviewPage({ ) : (
{processList.map((proc, idx) => { - const loading = processLoadingPid === proc.pid || proc.status === 'loading'; - const unloading = processUnloadingPid === proc.pid; - const refreshing = processRefreshingPid === proc.pid; - const busy = loading || unloading || refreshing; + const op = statusOf(proc.pid); + const loading = op === 'load' || proc.status === 'loading'; + const unloading = op === 'unload'; + const refreshing = op === 'refresh'; + const busy = op != null || proc.status === 'loading'; const isOnline = proc.status === 'online'; const canUnload = proc.injected; // Refresh is meaningful whenever a hook may exist (so the user @@ -355,7 +332,7 @@ export function OverviewPage({ disabled={busy} aria-label={`刷新进程 ${proc.pid} 管道状态`} title="刷新管道状态 / 重连" - onClick={() => onRefreshProcess(proc.pid)} + onClick={() => refresh(proc.pid)} className="size-8 text-muted-foreground hover:text-foreground" > {refreshing ? ( @@ -449,8 +426,8 @@ export function OverviewPage({ destructive={confirm?.kind === 'unload'} onConfirm={async () => { if (!confirm) return; - if (confirm.kind === 'unload') await onUnloadProcess(confirm.pid); - else await onLoadProcess(confirm.pid); + if (confirm.kind === 'unload') await unload(confirm.pid); + else await load(confirm.pid); }} />
diff --git a/packages/webui/src/components/pages/settings-page.tsx b/packages/webui/src/components/pages/settings-page.tsx index bdf9e31b..a969f34c 100644 --- a/packages/webui/src/components/pages/settings-page.tsx +++ b/packages/webui/src/components/pages/settings-page.tsx @@ -14,18 +14,11 @@ import { type Density, type ThemeMode, } from '@/contexts/ThemeContext'; -import { - ChangePasswordPage, - type PasswordRule, -} from '@/components/pages/change-password-page'; +import { ChangePasswordPage } from '@/components/pages/change-password-page'; +import { useApi } from '@/lib/api'; +import { useAppState } from '@/contexts/AppStateContext'; import { cn } from '@/lib/utils'; -interface SettingsPageProps { - fetchApi: (url: string, options?: RequestInit) => Promise; - /** Called after successful logout (e.g. all-sessions invalidated). */ - onLogout: () => void; -} - const MODE_OPTIONS: { value: ThemeMode; label: string; icon: typeof Sun }[] = [ { value: 'light', label: '浅色', icon: Sun }, { value: 'dark', label: '深色', icon: Moon }, @@ -37,7 +30,9 @@ const DENSITY_OPTIONS: { value: Density; label: string; description: string }[] { value: 'compact', label: '紧凑', description: '更小的字号与行距,单屏放更多内容' }, ]; -export function SettingsPage({ fetchApi, onLogout }: SettingsPageProps) { +export function SettingsPage() { + const api = useApi(); + const { onLogout } = useAppState(); const { mode, setMode, accent, setAccent, @@ -49,30 +44,12 @@ export function SettingsPage({ fetchApi, onLogout }: SettingsPageProps) { const [showChangePwd, setShowChangePwd] = useState(false); const [pwdSavedAt, setPwdSavedAt] = useState(null); - const checkStrength = async (password: string) => { - const res = await fetchApi('/api/auth/check-strength', { - method: 'POST', - body: JSON.stringify({ password }), - }); - const data = (await res.json().catch(() => ({}))) as { rules?: PasswordRule[]; valid?: boolean }; - return { rules: data.rules ?? [], valid: !!data.valid }; - }; - - const submitPwd = async (oldPassword: string, newPassword: string) => { - const res = await fetchApi('/api/auth/change-password', { - method: 'POST', - body: JSON.stringify({ oldPassword, newPassword }), - }); - const data = (await res.json().catch(() => ({}))) as { success?: boolean; message?: string }; - return { success: !!data.success, message: data.message }; - }; - if (showChangePwd) { return ( api.checkPasswordStrength(p)} + submit={(o, n) => api.changePassword(o, n)} onSuccess={() => { setShowChangePwd(false); setPwdSavedAt(Date.now()); diff --git a/packages/webui/src/contexts/AppStateContext.tsx b/packages/webui/src/contexts/AppStateContext.tsx new file mode 100644 index 00000000..2b8e35ce --- /dev/null +++ b/packages/webui/src/contexts/AppStateContext.tsx @@ -0,0 +1,40 @@ +import { createContext, useContext, type ReactNode } from 'react'; +import type { HookProcessInfo, QQInfo, SystemInfo } from '@/types'; +import type { HookProcessOps } from '@/hooks/use-hook-process-ops'; + +/** + * Live mutable state owned by AppLayout and shared with the child route + * components rendered inside its ``. Pages used to receive these + * via prop drilling — now they pull from context so adding a new page does + * not touch AppLayout. + */ +export interface AppStateValue { + qqList: QQInfo[]; + processList: HookProcessInfo[]; + systemInfo: SystemInfo | null; + selectedUin: string | null; + setSelectedUin: (uin: string | null) => void; + processOps: HookProcessOps; + refreshProcesses: () => void; + refreshSystem: () => void; + /** Triggered from the topbar logout button. */ + onLogout: () => void; +} + +const AppStateContext = createContext(null); + +export function AppStateProvider({ + value, + children, +}: { + value: AppStateValue; + children: ReactNode; +}) { + return {children}; +} + +export function useAppState(): AppStateValue { + const v = useContext(AppStateContext); + if (!v) throw new Error('useAppState must be used inside '); + return v; +} diff --git a/packages/webui/src/contexts/SessionContext.tsx b/packages/webui/src/contexts/SessionContext.tsx new file mode 100644 index 00000000..bd6a7b05 --- /dev/null +++ b/packages/webui/src/contexts/SessionContext.tsx @@ -0,0 +1,30 @@ +import { createContext, useContext, type ReactNode } from 'react'; + +/** + * Auth-level state surfaced into the router subtree. `AuthBoundary` mints + * this and `AppLayout` consumes it — used to drive the status badge and to + * complete logout after page-local state has been cleared. + */ +export interface SessionValue { + status: string; + /** Invoked by AppLayout's logout handler after it has scrubbed its own state. */ + onLogoutComplete: () => void; +} + +const SessionContext = createContext(null); + +export function SessionProvider({ + value, + children, +}: { + value: SessionValue; + children: ReactNode; +}) { + return {children}; +} + +export function useSession(): SessionValue { + const v = useContext(SessionContext); + if (!v) throw new Error('useSession must be used inside '); + return v; +} diff --git a/packages/webui/src/hooks/use-hook-process-ops.ts b/packages/webui/src/hooks/use-hook-process-ops.ts new file mode 100644 index 00000000..1dc1efda --- /dev/null +++ b/packages/webui/src/hooks/use-hook-process-ops.ts @@ -0,0 +1,156 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useApi, type ProcessActionResult } from '@/lib/api'; + +export type HookProcessOpKind = 'load' | 'unload' | 'refresh'; + +export interface HookProcessOps { + /** Returns the in-flight op kind for a pid, or null if idle. */ + statusOf(pid: number): HookProcessOpKind | null; + /** Latest user-facing status; auto-clears a few seconds after the last update. */ + banner: string; + load(pid: number): Promise; + unload(pid: number): Promise; + refresh(pid: number): Promise; +} + +export interface UnloadFailedAlert { + pid: number; + error: string; +} + +export interface UseHookProcessOpsResult { + ops: HookProcessOps; + unloadFailedAlert: UnloadFailedAlert | null; + dismissUnloadFailedAlert: () => void; +} + +interface KindMessages { + start(pid: number): string; + ok(pid: number): string; + fail(message: string): string; +} + +const KIND_MESSAGES: Record = { + load: { + start: (pid) => `正在向进程 ${pid} 加载 SnowLuma…`, + ok: (pid) => `已向进程 ${pid} 注入 SnowLuma,等待管道连接…`, + fail: (m) => `加载失败:${m}`, + }, + unload: { + start: (pid) => `正在从进程 ${pid} 卸载…`, + ok: (pid) => `已从进程 ${pid} 卸载`, + fail: (m) => `卸载失败:${m}`, + }, + refresh: { + start: (pid) => `正在刷新进程 ${pid} 的管道状态…`, + ok: (pid) => `已刷新进程 ${pid} 的管道状态`, + fail: (m) => `刷新失败:${m}`, + }, +}; + +const BANNER_CLEAR_MS = 4000; + +/** + * Drives load/unload/refresh actions on Hook-target processes. Owns the + * per-pid inflight dedup, the per-kind status indicator, the banner message + * lifecycle, and the "unload silently failed" alert that surfaces when the + * backend reports the named pipe is still alive after an unload attempt. + */ +export function useHookProcessOps( + opts: { onAfterOp?: () => Promise | void } = {}, +): UseHookProcessOpsResult { + const api = useApi(); + const [byPid, setByPid] = useState>(() => new Map()); + const [banner, setBanner] = useState(''); + const [unloadFailedAlert, setUnloadFailedAlert] = useState(null); + + // Synchronous inflight guard — protects against rapid double-clicks that + // would race the byPid setter (state updates are batched, refs are not). + const inflightRef = useRef>(new Set()); + const bannerTimerRef = useRef(null); + const onAfterOpRef = useRef(opts.onAfterOp); + onAfterOpRef.current = opts.onAfterOp; + + useEffect( + () => () => { + if (bannerTimerRef.current != null) window.clearTimeout(bannerTimerRef.current); + }, + [], + ); + + const scheduleBannerClear = useCallback(() => { + if (bannerTimerRef.current != null) window.clearTimeout(bannerTimerRef.current); + bannerTimerRef.current = window.setTimeout(() => { + setBanner(''); + bannerTimerRef.current = null; + }, BANNER_CLEAR_MS); + }, []); + + const setKind = useCallback((pid: number, kind: HookProcessOpKind | null) => { + setByPid((prev) => { + const next = new Map(prev); + if (kind == null) next.delete(pid); + else next.set(pid, kind); + return next; + }); + }, []); + + const run = useCallback( + async ( + pid: number, + kind: HookProcessOpKind, + action: () => Promise, + ) => { + if (inflightRef.current.has(pid)) return; + inflightRef.current.add(pid); + setKind(pid, kind); + const messages = KIND_MESSAGES[kind]; + setBanner(messages.start(pid)); + try { + const result = await action(); + if (kind === 'unload' && result.process?.status === 'connecting' && result.process.error) { + setUnloadFailedAlert({ pid, error: result.process.error }); + setBanner(`进程 ${pid} 卸载失败`); + } else { + setBanner(messages.ok(pid)); + } + await onAfterOpRef.current?.(); + } catch (e) { + const msg = e instanceof Error ? e.message : '未知错误'; + setBanner(messages.fail(msg)); + } finally { + inflightRef.current.delete(pid); + setKind(pid, null); + scheduleBannerClear(); + } + }, + [setKind, scheduleBannerClear], + ); + + const load = useCallback( + (pid: number) => run(pid, 'load', () => api.processes.load(pid)), + [api, run], + ); + const unload = useCallback( + (pid: number) => run(pid, 'unload', () => api.processes.unload(pid)), + [api, run], + ); + const refresh = useCallback( + (pid: number) => run(pid, 'refresh', () => api.processes.refresh(pid)), + [api, run], + ); + + const statusOf = useCallback( + (pid: number): HookProcessOpKind | null => byPid.get(pid) ?? null, + [byPid], + ); + + const dismissUnloadFailedAlert = useCallback(() => setUnloadFailedAlert(null), []); + + const ops = useMemo( + () => ({ statusOf, banner, load, unload, refresh }), + [statusOf, banner, load, unload, refresh], + ); + + return { ops, unloadFailedAlert, dismissUnloadFailedAlert }; +} diff --git a/packages/webui/src/hooks/use-onebot-instance-config.ts b/packages/webui/src/hooks/use-onebot-instance-config.ts new file mode 100644 index 00000000..dc4b2cd0 --- /dev/null +++ b/packages/webui/src/hooks/use-onebot-instance-config.ts @@ -0,0 +1,147 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import type { OneBotConfig, QQInfo } from '@/types'; +import { useApi } from '@/lib/api'; + +/** + * Per-UIN OneBotInstance configuration editor. Owns the full lifecycle: + * selection, load, in-memory edit (with dirty tracking), save (with refetch), + * and a "switch UIN while dirty" guard that surfaces a pending switch the + * view can confirm or cancel. + */ +export interface UseOneBotInstanceConfig { + selectedUin: string | null; + /** Loaded config for the current UIN. Null while loading or before a selection. */ + config: OneBotConfig | null; + setConfig: (next: OneBotConfig) => void; + /** True if the in-memory config diverges from the last server-confirmed snapshot. */ + dirty: boolean; + /** + * Request a UIN switch. If currently dirty, the switch is parked as + * `pendingSwitchUin` and must be confirmed or cancelled. Otherwise it + * applies immediately. + */ + requestSwitchUin: (uin: string) => void; + /** Non-null while a switch is parked waiting for confirmation. */ + pendingSwitchUin: string | null; + confirmSwitch: () => void; + cancelSwitch: () => void; + save: () => Promise; + saveStatus: string; +} + +const CLEAR_SAVE_STATUS_MS = 3000; + +export interface UseOneBotInstanceConfigOptions { + /** Externally-owned current UIN. The hook reads it but does not own it. */ + selectedUin: string | null; + /** Called when the hook wants to mutate selection (auto-select / confirmed switch). */ + onSelectedUinChange: (uin: string | null) => void; +} + +export function useOneBotInstanceConfig( + accounts: QQInfo[], + options: UseOneBotInstanceConfigOptions, +): UseOneBotInstanceConfig { + const api = useApi(); + const { selectedUin, onSelectedUinChange } = options; + const [config, setConfigState] = useState(null); + const [savedSnapshot, setSavedSnapshot] = useState(null); + const [saveStatus, setSaveStatus] = useState(''); + const [pendingSwitchUin, setPendingSwitchUin] = useState(null); + const clearTimerRef = useRef(null); + + // Auto-select first account when none is selected yet. + useEffect(() => { + if (!selectedUin && accounts.length > 0) onSelectedUinChange(accounts[0].uin); + }, [accounts, selectedUin, onSelectedUinChange]); + + // Load on UIN change. The api client already runs normalizeOneBotConfig. + useEffect(() => { + if (!selectedUin) { + setConfigState(null); + setSavedSnapshot(null); + return; + } + let cancelled = false; + (async () => { + try { + const loaded = await api.config.get(selectedUin); + if (cancelled) return; + setConfigState(loaded); + setSavedSnapshot(JSON.stringify(loaded)); + } catch (e) { + console.error('load-config', e); + } + })(); + return () => { + cancelled = true; + }; + }, [selectedUin, api]); + + useEffect( + () => () => { + if (clearTimerRef.current != null) window.clearTimeout(clearTimerRef.current); + }, + [], + ); + + const dirty = useMemo(() => { + if (config == null || savedSnapshot == null) return false; + return JSON.stringify(config) !== savedSnapshot; + }, [config, savedSnapshot]); + + const setConfig = useCallback((next: OneBotConfig) => setConfigState(next), []); + + const requestSwitchUin = useCallback( + (uin: string) => { + if (uin === selectedUin) return; + if (dirty) setPendingSwitchUin(uin); + else onSelectedUinChange(uin); + }, + [dirty, selectedUin, onSelectedUinChange], + ); + + const confirmSwitch = useCallback(() => { + if (pendingSwitchUin == null) return; + onSelectedUinChange(pendingSwitchUin); + setPendingSwitchUin(null); + }, [pendingSwitchUin, onSelectedUinChange]); + + const cancelSwitch = useCallback(() => setPendingSwitchUin(null), []); + + const scheduleStatusClear = useCallback(() => { + if (clearTimerRef.current != null) window.clearTimeout(clearTimerRef.current); + clearTimerRef.current = window.setTimeout(() => { + setSaveStatus(''); + clearTimerRef.current = null; + }, CLEAR_SAVE_STATUS_MS); + }, []); + + const save = useCallback(async () => { + if (!selectedUin || !config) return; + setSaveStatus('保存中...'); + try { + const serverView = await api.config.save(selectedUin, config); + setConfigState(serverView); + setSavedSnapshot(JSON.stringify(serverView)); + setSaveStatus('保存成功'); + } catch (e) { + setSaveStatus(`保存失败:${e instanceof Error ? e.message : '未知错误'}`); + } finally { + scheduleStatusClear(); + } + }, [api, selectedUin, config, scheduleStatusClear]); + + return { + selectedUin, + config, + setConfig, + dirty, + requestSwitchUin, + pendingSwitchUin, + confirmSwitch, + cancelSwitch, + save, + saveStatus, + }; +} diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts new file mode 100644 index 00000000..b9fafc63 --- /dev/null +++ b/packages/webui/src/lib/api/client.ts @@ -0,0 +1,250 @@ +import type { HookProcessInfo, LogEntry, QQInfo, SystemInfo } from '@/types'; +import type { PasswordRule } from '@/components/pages/change-password-page'; +import { normalizeOneBotConfig } from '@/lib/onebot-config'; +import { + ApiError, + type ApiClient, + type ChangePasswordResult, + type CreateApiClientOptions, + type LoginResult, + type LogsStreamOptions, + type ProcessActionResult, + type TokenStore, +} from './types'; +import { localStorageTokenStore } from './token-store'; + +const DEFAULT_TOKEN_KEY = 'snowluma_token'; + +interface ErrorPayload { + message?: string; + error?: string; + code?: string; +} + +async function readJson(res: Response): Promise { + try { + return (await res.json()) as T; + } catch { + return {} as T; + } +} + +function extractErrorMessage(payload: ErrorPayload, fallback: string): string { + return payload.message || payload.error || fallback; +} + +class HttpApiClient implements ApiClient { + private tokenStore: TokenStore; + private currentToken: string | null; + private onUnauthorized?: () => void; + + // namespaced surfaces are bound up-front so callers can destructure + readonly processes: ApiClient['processes']; + readonly config: ApiClient['config']; + readonly logs: ApiClient['logs']; + + constructor(opts: CreateApiClientOptions = {}) { + this.tokenStore = opts.tokenStore ?? localStorageTokenStore(DEFAULT_TOKEN_KEY); + this.currentToken = this.tokenStore.load(); + this.onUnauthorized = opts.onUnauthorized; + + this.processes = { + list: () => this.getJson<{ list: HookProcessInfo[] }>('/api/processes').then((d) => d.list ?? []), + load: (pid) => this.postJson(`/api/processes/${pid}/load`), + unload: (pid) => this.postJson(`/api/processes/${pid}/unload`), + refresh: (pid) => this.postJson(`/api/processes/${pid}/refresh`), + }; + + this.config = { + get: async (uin) => { + const url = `/api/config/${encodeURIComponent(uin)}`; + const data = await this.getJson<{ config?: unknown } | unknown>(url); + const raw = + typeof data === 'object' && data != null && 'config' in (data as Record) + ? (data as { config: unknown }).config + : data; + return normalizeOneBotConfig(raw); + }, + save: async (uin, config) => { + const url = `/api/config/${encodeURIComponent(uin)}`; + // POST returns { success, reloaded, message } — no config body. To + // honour the "save returns canonical server view" contract, refetch + // after a successful POST. + await this.fetchJson(url, { + method: 'POST', + body: JSON.stringify(config), + }); + return this.config.get(uin); + }, + }; + + this.logs = { + list: async (limit = 500) => { + const data = await this.getJson<{ list: LogEntry[] }>(`/api/logs?limit=${limit}`); + return data.list ?? []; + }, + stream: (options) => this.openLogStream(options), + }; + } + + // ---------- HTTP helpers ---------- + + async request(url: string, init: RequestInit = {}): Promise { + const headers: Record = { + ...((init.headers as Record | undefined) ?? {}), + }; + if (this.currentToken) headers['Authorization'] = `Bearer ${this.currentToken}`; + if (init.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json'; + const res = await fetch(url, { ...init, headers }); + if (res.status === 401) { + this.setToken(null); + this.onUnauthorized?.(); + } + return res; + } + + /** Like request(), but throws ApiError on non-2xx and parses JSON. */ + private async fetchJson(url: string, init: RequestInit = {}): Promise { + const res = await this.request(url, init); + if (!res.ok) { + const payload = await readJson(res); + throw new ApiError(res.status, extractErrorMessage(payload, res.statusText || '请求失败'), payload.code); + } + return readJson(res); + } + + private getJson(url: string): Promise { + return this.fetchJson(url); + } + + private postJson(url: string, body?: unknown): Promise { + return this.fetchJson(url, { + method: 'POST', + body: body == null ? undefined : JSON.stringify(body), + }); + } + + // ---------- token management ---------- + + private setToken(token: string | null): void { + this.currentToken = token; + this.tokenStore.save(token); + } + + // ---------- auth ---------- + + async login(password: string): Promise { + // Login deliberately bypasses fetchJson/onUnauthorized so a bad password + // doesn't trigger a global sign-out side effect. + try { + const res = await fetch('/api/login', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ password }), + }); + if (!res.ok) { + const payload = await readJson(res); + return { ok: false, message: extractErrorMessage(payload, '令牌错误') }; + } + const payload = await readJson<{ token: string; mustChangePassword?: boolean }>(res); + this.setToken(payload.token); + return { ok: true, mustChangePassword: !!payload.mustChangePassword }; + } catch (e) { + return { ok: false, message: e instanceof Error ? e.message : '网络错误' }; + } + } + + async logout(): Promise { + try { + await this.request('/api/logout', { method: 'POST' }); + } catch { + /* ignore */ + } + this.setToken(null); + } + + async status(): Promise { + if (!this.currentToken) return false; + try { + const res = await this.request('/api/status'); + return res.ok; + } catch { + return false; + } + } + + async mustChangePassword(): Promise { + try { + const data = await this.getJson<{ mustChangePassword?: boolean }>('/api/auth/state'); + return !!data.mustChangePassword; + } catch { + return false; + } + } + + async checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }> { + try { + const data = await this.postJson<{ rules?: PasswordRule[]; valid?: boolean }>( + '/api/auth/check-strength', + { password }, + ); + return { rules: data.rules ?? [], valid: !!data.valid }; + } catch { + return { rules: [], valid: false }; + } + } + + async changePassword(oldPassword: string, newPassword: string): Promise { + try { + const data = await this.postJson<{ success?: boolean; message?: string }>( + '/api/auth/change-password', + { oldPassword, newPassword }, + ); + return { success: !!data.success, message: data.message }; + } catch (e) { + if (e instanceof ApiError) return { success: false, message: e.message }; + return { success: false, message: e instanceof Error ? e.message : '网络错误' }; + } + } + + // ---------- top-level resources ---------- + + async qqList(): Promise { + const data = await this.getJson<{ list: QQInfo[] }>('/api/qq-list'); + return data.list ?? []; + } + + system(): Promise { + return this.getJson('/api/system'); + } + + // ---------- SSE ---------- + + private openLogStream(options: LogsStreamOptions): () => void { + if (!this.currentToken) { + options.onStatus?.('closed'); + return () => {}; + } + const url = `/api/logs/stream?token=${encodeURIComponent(this.currentToken)}`; + const source = new EventSource(url); + source.onopen = () => options.onStatus?.('open'); + source.onerror = () => options.onStatus?.('reconnecting'); + source.onmessage = (event) => { + try { + const parsed = JSON.parse(event.data) as LogEntry | { type: string }; + if ('type' in parsed) return; // control frame, not a log line + options.onLine(parsed); + } catch { + /* malformed frame, skip */ + } + }; + return () => { + source.close(); + options.onStatus?.('closed'); + }; + } +} + +export function createApiClient(options: CreateApiClientOptions = {}): ApiClient { + return new HttpApiClient(options); +} diff --git a/packages/webui/src/lib/api/context.tsx b/packages/webui/src/lib/api/context.tsx new file mode 100644 index 00000000..fdeb57ef --- /dev/null +++ b/packages/webui/src/lib/api/context.tsx @@ -0,0 +1,14 @@ +import { createContext, useContext, type ReactNode } from 'react'; +import type { ApiClient } from './types'; + +const ApiContext = createContext(null); + +export function ApiProvider({ client, children }: { client: ApiClient; children: ReactNode }) { + return {children}; +} + +export function useApi(): ApiClient { + const client = useContext(ApiContext); + if (!client) throw new Error('useApi must be used inside '); + return client; +} diff --git a/packages/webui/src/lib/api/index.ts b/packages/webui/src/lib/api/index.ts new file mode 100644 index 00000000..c9439a85 --- /dev/null +++ b/packages/webui/src/lib/api/index.ts @@ -0,0 +1,13 @@ +export { createApiClient } from './client'; +export { ApiProvider, useApi } from './context'; +export { ApiError } from './types'; +export type { + ApiClient, + ChangePasswordResult, + CreateApiClientOptions, + LoginResult, + LogsStreamOptions, + ProcessActionResult, + StreamStatus, + TokenStore, +} from './types'; diff --git a/packages/webui/src/lib/api/token-store.ts b/packages/webui/src/lib/api/token-store.ts new file mode 100644 index 00000000..c0233c0d --- /dev/null +++ b/packages/webui/src/lib/api/token-store.ts @@ -0,0 +1,11 @@ +import type { TokenStore } from './types'; + +export function localStorageTokenStore(key: string): TokenStore { + return { + load: () => localStorage.getItem(key), + save: (token) => { + if (token == null) localStorage.removeItem(key); + else localStorage.setItem(key, token); + }, + }; +} diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts new file mode 100644 index 00000000..25b46934 --- /dev/null +++ b/packages/webui/src/lib/api/types.ts @@ -0,0 +1,88 @@ +import type { + HookProcessInfo, + LogEntry, + OneBotConfig, + QQInfo, + SystemInfo, +} from '@/types'; +import type { PasswordRule } from '@/components/pages/change-password-page'; + +export class ApiError extends Error { + status: number; + code: string | undefined; + constructor(status: number, message: string, code?: string) { + super(message); + this.name = 'ApiError'; + this.status = status; + this.code = code; + } +} + +export type LoginResult = + | { ok: true; mustChangePassword: boolean } + | { ok: false; message: string }; + +export type ChangePasswordResult = { success: boolean; message?: string }; + +export type ProcessActionResult = { + process?: HookProcessInfo & { error?: string }; +}; + +export type StreamStatus = 'open' | 'reconnecting' | 'closed'; + +export interface LogsStreamOptions { + onLine: (line: LogEntry) => void; + onStatus?: (status: StreamStatus) => void; +} + +export interface ApiClient { + // ---- auth ---- + login(password: string): Promise; + logout(): Promise; + /** True if the current token is still valid. */ + status(): Promise; + /** Whether the current session must rotate its password before doing anything else. */ + mustChangePassword(): Promise; + checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }>; + changePassword(oldPassword: string, newPassword: string): Promise; + + // ---- system ---- + qqList(): Promise; + system(): Promise; + + // ---- hook processes ---- + processes: { + list(): Promise; + load(pid: number): Promise; + unload(pid: number): Promise; + refresh(pid: number): Promise; + }; + + // ---- OneBotInstance per-UIN config ---- + config: { + get(uin: string): Promise; + save(uin: string, config: OneBotConfig): Promise; + }; + + // ---- logs ---- + logs: { + list(limit?: number): Promise; + /** Subscribe to the SSE log stream. Returns a disposer. */ + stream(options: LogsStreamOptions): () => void; + }; + + /** Escape hatch for endpoints not yet wrapped above. */ + request(url: string, init?: RequestInit): Promise; +} + +export interface TokenStore { + load(): string | null; + save(token: string | null): void; +} + +export interface CreateApiClientOptions { + /** Persists the bearer token across reloads. Defaults to localStorage('snowluma_token'). */ + tokenStore?: TokenStore; + /** Fires whenever a request returns 401, after the token has been cleared. */ + onUnauthorized?: () => void; +} diff --git a/packages/webui/src/lib/onebot-config.ts b/packages/webui/src/lib/onebot-config.ts new file mode 100644 index 00000000..91db11fb --- /dev/null +++ b/packages/webui/src/lib/onebot-config.ts @@ -0,0 +1,34 @@ +import type { MessageFormat, OneBotConfig } from '@/types'; + +/** + * Anti-corruption layer for the per-UIN config payload. Older backends emit + * `messageFormat` / `reportSelfMessage` at the top level instead of per + * adapter, and may omit them on adapters entirely. This collapses both shapes + * into the canonical {@link OneBotConfig} the editor expects. + */ +export function normalizeOneBotConfig(raw: unknown): OneBotConfig { + const cfg = (raw ?? {}) as Record; + const nets = (cfg.networks as Record | undefined) ?? {}; + const legacyFormat: MessageFormat = cfg.messageFormat === 'string' ? 'string' : 'array'; + const legacyReport = !!cfg.reportSelfMessage; + + const normalize = (item: Record): Record => ({ + ...item, + messageFormat: item.messageFormat === 'string' ? 'string' : legacyFormat, + reportSelfMessage: + typeof item.reportSelfMessage === 'boolean' ? item.reportSelfMessage : legacyReport, + }); + + const list = (x: unknown): Record[] => + Array.isArray(x) ? x.map((it) => normalize(it as Record)) : []; + + return { + networks: { + httpServers: list(nets.httpServers) as unknown as OneBotConfig['networks']['httpServers'], + httpClients: list(nets.httpClients) as unknown as OneBotConfig['networks']['httpClients'], + wsServers: list(nets.wsServers) as unknown as OneBotConfig['networks']['wsServers'], + wsClients: list(nets.wsClients) as unknown as OneBotConfig['networks']['wsClients'], + }, + musicSignUrl: typeof cfg.musicSignUrl === 'string' ? cfg.musicSignUrl : undefined, + }; +} diff --git a/packages/webui/src/router/app-layout.tsx b/packages/webui/src/router/app-layout.tsx new file mode 100644 index 00000000..edd73b9a --- /dev/null +++ b/packages/webui/src/router/app-layout.tsx @@ -0,0 +1,118 @@ +import { useCallback, useEffect, useState } from 'react'; +import { Outlet } from '@tanstack/react-router'; +import { useTheme } from '@/contexts/ThemeContext'; +import { useApi } from '@/lib/api'; +import { useHookProcessOps } from '@/hooks/use-hook-process-ops'; +import { MainLayout } from '@/components/layout/main-layout'; +import { ConfirmDialog } from '@/components/confirm-dialog'; +import { AppStateProvider } from '@/contexts/AppStateContext'; +import { useSession } from '@/contexts/SessionContext'; +import type { HookProcessInfo, QQInfo, SystemInfo } from '@/types'; + +/** + * The layout route. Owns the live state shared across the four pages + * (polling lists, processOps, selectedUin) and renders `` inside + * the chrome. The unload-failed alert sits here so it survives navigation + * away from the overview page. + */ +export function AppLayout() { + const api = useApi(); + const { pollInterval } = useTheme(); + const session = useSession(); + + const [qqList, setQqList] = useState([]); + const [processList, setProcessList] = useState([]); + const [systemInfo, setSystemInfo] = useState(null); + const [selectedUin, setSelectedUin] = useState(null); + + const refreshQqList = useCallback(async () => { + try { + setQqList(await api.qqList()); + } catch (e) { + console.error('qq-list', e); + } + }, [api]); + + const refreshProcesses = useCallback(async () => { + try { + setProcessList(await api.processes.list()); + } catch (e) { + console.error('processes', e); + } + }, [api]); + + const refreshSystem = useCallback(async () => { + try { + setSystemInfo(await api.system()); + } catch (e) { + console.error('system', e); + } + }, [api]); + + const { ops: processOps, unloadFailedAlert, dismissUnloadFailedAlert } = useHookProcessOps({ + onAfterOp: refreshProcesses, + }); + + useEffect(() => { + if (pollInterval <= 0) return; + let cancelled = false; + const tick = async () => { + if (cancelled) return; + await Promise.all([refreshQqList(), refreshProcesses(), refreshSystem()]); + }; + tick(); + const interval = setInterval(tick, pollInterval); + return () => { + cancelled = true; + clearInterval(interval); + }; + }, [pollInterval, refreshQqList, refreshProcesses, refreshSystem]); + + const handleLogout = useCallback(async () => { + await api.logout(); + setQqList([]); + setProcessList([]); + setSystemInfo(null); + setSelectedUin(null); + session.onLogoutComplete(); + }, [api, session]); + + return ( + + + + + + !open && dismissUnloadFailedAlert()} + title="卸载失败" + description={ + unloadFailedAlert ? ( + <> +

进程 {unloadFailedAlert.pid} 的 SnowLuma DLL 卸载失败。

+

{unloadFailedAlert.error}

+

+ 系统将继续尝试重新连接该进程。如需彻底卸载,请重启 QQ 进程。 +

+ + ) : null + } + confirmText="知道了" + onConfirm={dismissUnloadFailedAlert} + /> +
+ ); +} diff --git a/packages/webui/src/router/index.tsx b/packages/webui/src/router/index.tsx new file mode 100644 index 00000000..21e828b0 --- /dev/null +++ b/packages/webui/src/router/index.tsx @@ -0,0 +1,63 @@ +import { + createRootRoute, + createRoute, + createRouter, + Outlet, +} from '@tanstack/react-router'; +import { OverviewPage } from '@/components/pages/overview-page'; +import { ConfigPage } from '@/components/pages/config-page'; +import { LogsPage } from '@/components/pages/logs-page'; +import { SettingsPage } from '@/components/pages/settings-page'; +import { AppLayout } from './app-layout'; + +const rootRoute = createRootRoute({ + component: () => , +}); + +const appLayoutRoute = createRoute({ + id: 'app-layout', + getParentRoute: () => rootRoute, + component: AppLayout, +}); + +const overviewRoute = createRoute({ + path: '/', + getParentRoute: () => appLayoutRoute, + component: OverviewPage, +}); + +const configRoute = createRoute({ + path: '/config', + getParentRoute: () => appLayoutRoute, + component: ConfigPage, +}); + +const logsRoute = createRoute({ + path: '/logs', + getParentRoute: () => appLayoutRoute, + component: LogsPage, +}); + +const settingsRoute = createRoute({ + path: '/settings', + getParentRoute: () => appLayoutRoute, + component: SettingsPage, +}); + +const routeTree = rootRoute.addChildren([ + appLayoutRoute.addChildren([overviewRoute, configRoute, logsRoute, settingsRoute]), +]); + +export const appRouter = createRouter({ + routeTree, + defaultPreload: 'intent', +}); + +declare module '@tanstack/react-router' { + interface Register { + router: typeof appRouter; + } +} + +/** Paths registered on the layout — single source of truth for nav metadata. */ +export type AppPath = '/' | '/config' | '/logs' | '/settings'; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1fd60349..591fcfc0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -38,7 +38,7 @@ importers: version: 1.19.14(hono@4.12.18) '@rollup/plugin-node-resolve': specifier: ^16.0.3 - version: 16.0.3 + version: 16.0.3(rollup@4.60.4) '@types/node': specifier: ^24.12.2 version: 24.12.2 @@ -78,6 +78,79 @@ importers: specifier: ^4.1.4 version: 4.1.4(@types/node@24.12.2)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + packages/ui: + dependencies: + '@radix-ui/react-alert-dialog': + specifier: ^1.1.7 + version: 1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-checkbox': + specifier: ^1.1.5 + version: 1.3.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-dialog': + specifier: ^1.1.7 + version: 1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-label': + specifier: ^2.1.3 + version: 2.1.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-popover': + specifier: ^1.1.7 + version: 1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-scroll-area': + specifier: ^1.2.4 + version: 1.2.10(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-select': + specifier: ^2.2.6 + version: 2.2.6(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-separator': + specifier: ^1.1.3 + version: 1.1.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-slot': + specifier: ^1.1.3 + version: 1.2.4(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-switch': + specifier: ^1.2.6 + version: 1.2.6(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-tabs': + specifier: ^1.1.13 + version: 1.1.13(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-tooltip': + specifier: ^1.1.9 + version: 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + class-variance-authority: + specifier: ^0.7.1 + version: 0.7.1 + clsx: + specifier: ^2.1.1 + version: 2.1.1 + lucide-react: + specifier: ^0.469.0 + version: 0.469.0(react@19.2.5) + sonner: + specifier: ^2.0.6 + version: 2.0.7(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + tailwind-merge: + specifier: ^3.5.0 + version: 3.5.0 + devDependencies: + '@types/react': + specifier: ^19.2.14 + version: 19.2.14 + '@types/react-dom': + specifier: ^19.2.3 + version: 19.2.3(@types/react@19.2.14) + react: + specifier: ^19.2.5 + version: 19.2.5 + react-dom: + specifier: ^19.2.5 + version: 19.2.5(react@19.2.5) + tsup: + specifier: ^8.5.0 + version: 8.5.1(jiti@2.6.1)(postcss@8.5.10)(tsx@4.21.0)(typescript@6.0.2) + typescript: + specifier: 'catalog:' + version: 6.0.2 + packages/websocket: devDependencies: '@types/node': @@ -110,6 +183,9 @@ importers: '@radix-ui/react-tooltip': specifier: ^1.1.9 version: 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@tanstack/react-router': + specifier: ^1.169.2 + version: 1.169.2(react-dom@19.2.5(react@19.2.5))(react@19.2.5) class-variance-authority: specifier: ^0.7.1 version: 0.7.1 @@ -636,6 +712,32 @@ packages: '@types/react-dom': optional: true + '@radix-ui/react-checkbox@1.3.3': + resolution: {integrity: sha512-wBbpv+NQftHDdG86Qc0pIyXk5IR3tM8Vd0nWLKDcX8nNn4nXFOFwsKuqw2okA/1D/mpaAkmuyndrPJTYDNZtFw==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-collection@1.1.7': + resolution: {integrity: sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + '@radix-ui/react-compose-refs@1.1.2': resolution: {integrity: sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg==} peerDependencies: @@ -733,6 +835,19 @@ packages: '@types/react-dom': optional: true + '@radix-ui/react-popover@1.1.15': + resolution: {integrity: sha512-kr0X2+6Yy/vJzLYJUPCZEc8SfQcf+1COFoAqauJm74umQhta9M7lNJHP7QQS3vkvcGLQUbWpMzwrXYwrYztHKA==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + '@radix-ui/react-popper@1.2.8': resolution: {integrity: sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw==} peerDependencies: @@ -798,6 +913,19 @@ packages: '@types/react-dom': optional: true + '@radix-ui/react-roving-focus@1.1.11': + resolution: {integrity: sha512-7A6S9jSgm/S+7MdtNDSb+IU859vQqJ/QAtcYQcfFC6W8RS4IxIZDldLR0xqCFZ6DCyrQLjLPsxtTNch5jVA4lA==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + '@radix-ui/react-scroll-area@1.2.10': resolution: {integrity: sha512-tAXIa1g3sM5CGpVT0uIbUx/U3Gs5N8T52IICuCtObaos1S8fzsrPXG5WObkQN3S6NVl6wKgPhAIiBGbWnvc97A==} peerDependencies: @@ -811,6 +939,19 @@ packages: '@types/react-dom': optional: true + '@radix-ui/react-select@2.2.6': + resolution: {integrity: sha512-I30RydO+bnn2PQztvo25tswPH+wFBjehVGtmagkU78yMdwTwVf12wnAOF+AeP8S2N8xD+5UPbGhkUfPyvT+mwQ==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + '@radix-ui/react-separator@1.1.8': resolution: {integrity: sha512-sDvqVY4itsKwwSMEe0jtKgfTh+72Sy3gPmQpjqcQneqQ4PFmr/1I0YA+2/puilhggCe2gJcx5EBAYFkWkdpa5g==} peerDependencies: @@ -842,6 +983,32 @@ packages: '@types/react': optional: true + '@radix-ui/react-switch@1.2.6': + resolution: {integrity: sha512-bByzr1+ep1zk4VubeEVViV592vu2lHE2BZY5OnzehZqOOgogN80+mNtCqPkhn2gklJqOpxWgPoYTSnhBCqpOXQ==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-tabs@1.1.13': + resolution: {integrity: sha512-7xdcatg7/U+7+Udyoj2zodtI9H/IIopqo+YOIcZOq1nJwXWBZ9p8xiu5llXlekDbZkca79a/fozEYQXIA4sW6A==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + '@radix-ui/react-tooltip@1.2.8': resolution: {integrity: sha512-tY7sVt1yL9ozIxvmbtN5qtmH2krXcBCfjEiCgKGLqunJHvgvZG2Pcl2oQ3kbcZARb1BGEHdkLzcYGO8ynVlieg==} peerDependencies: @@ -900,6 +1067,15 @@ packages: '@types/react': optional: true + '@radix-ui/react-use-previous@1.1.1': + resolution: {integrity: sha512-2dHfToCj/pzca2Ck724OZ5L0EVrr3eHRNsG/b3xQJLA2hZpVCS99bLAX+hm1IHXDEnzU6by5z/5MIY794/a8NQ==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@radix-ui/react-use-rect@1.1.1': resolution: {integrity: sha512-QTYuDesS0VtuHNNvMh+CjlKJ4LJickCMUAqjlE3+j8w+RlRpwyX3apEQKGFzbZGdo7XNG1tXa+bQqIE7HIXT2w==} peerDependencies: @@ -1053,6 +1229,144 @@ packages: rollup: optional: true + '@rollup/rollup-android-arm-eabi@4.60.4': + resolution: {integrity: sha512-F5QXMSiFebS9hKZj02XhWLLnRpJ3B3AROP0tWbFBSj+6kCbg5m9j5JoHKd4mmSVy5mS/IMQloYgYxCuJC0fxEQ==} + cpu: [arm] + os: [android] + + '@rollup/rollup-android-arm64@4.60.4': + resolution: {integrity: sha512-GxxTKApUpzRhof7poWvCJHRF51C67u1R7D6DiluBE8wKU1u5GWE8t+v81JvJYtbawoBFX1hLv5Ei4eVjkWokaw==} + cpu: [arm64] + os: [android] + + '@rollup/rollup-darwin-arm64@4.60.4': + resolution: {integrity: sha512-tua0TaJxMOB1R0V0RS1jFZ/RpURFDJIOR2A6jWwQeawuFyS4gBW+rntLRaQd0EQ4bd6Vp44Z2rXW+YYDBsj6IA==} + cpu: [arm64] + os: [darwin] + + '@rollup/rollup-darwin-x64@4.60.4': + resolution: {integrity: sha512-CSKq7MsP+5PFIcydhAiR1K0UhEI1A2jWXVKHPCBZ151yOutENwvnPocgVHkivu2kviURtCEB6zUQw0vs8RrhMg==} + cpu: [x64] + os: [darwin] + + '@rollup/rollup-freebsd-arm64@4.60.4': + resolution: {integrity: sha512-+O8OkVdyvXMtJEciu2wS/pzm1IxntEEQx3z5TAVy4l32G0etZn+RsA48ARRrFm6Ri8fvqPQfgrvNxSjKAbnd3g==} + cpu: [arm64] + os: [freebsd] + + '@rollup/rollup-freebsd-x64@4.60.4': + resolution: {integrity: sha512-Iw3oMskH3AfNuhU0MSN7vNbdi4me/NiYo2azqPz/Le16zHSa+3RRmliCMWWQmh4lcndccU40xcJuTYJZxNo/lw==} + cpu: [x64] + os: [freebsd] + + '@rollup/rollup-linux-arm-gnueabihf@4.60.4': + resolution: {integrity: sha512-EIPRXTVQpHyF8WOo219AD2yEltPehLTcTMz2fn6JsatLYSzQf00hj3rulF+yauOlF9/FtM2WpkT/hJh/KJFGhA==} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-arm-musleabihf@4.60.4': + resolution: {integrity: sha512-J3Yh9PzzF1Ovah2At+lHiGQdsYgArxBbXv/zHfSyaiFQEqvNv7DcW98pCrmdjCZBrqBiKrKKe2V+aaSGWuBe/w==} + cpu: [arm] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-arm64-gnu@4.60.4': + resolution: {integrity: sha512-BFDEZMYfUvLn37ONE1yMBojPxnMlTFsdyNoqncT0qFq1mAfllL+ATMMJd8TeuVMiX84s1KbcxcZbXInmcO2mRg==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-arm64-musl@4.60.4': + resolution: {integrity: sha512-pc9EYOSlOgdQ2uPl1o9PF6/kLSgaUosia7gOuS8mB69IxJvlclko1MECXysjs5ryez1/5zjYqx3+xYU0TU6R1A==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-loong64-gnu@4.60.4': + resolution: {integrity: sha512-NxnomyxYerDh5n4iLrNa+sH+Z+U4BMEE46V2PgQ/hoB909i8gV1M5wPojWg9fk1jWpO3IQnOs20K4wyZuFLEFQ==} + cpu: [loong64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-loong64-musl@4.60.4': + resolution: {integrity: sha512-nbJnQ8a3z1mtmrwImCYhc6BGpThAyYVRQxw9uKSKG4wR6aAYno9sVjJ0zaZcW9BPJX1GbrDPf+SvdWjgTuDmnw==} + cpu: [loong64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-ppc64-gnu@4.60.4': + resolution: {integrity: sha512-2EU6acNrQLd8tYvo/LXW535wupT3m6fo7HKo6lr7ktQoItxTyOL1ZCR/GfGCuXl2vR+zmfI6eRXkSemafv+iVg==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-ppc64-musl@4.60.4': + resolution: {integrity: sha512-WeBtoMuaMxiiIrO2IYP3xs6GMWkJP2C0EoT8beTLkUPmzV1i/UcOSVw1d5r9KBODtHKilG5yFxsGRnBbK3wJ4A==} + cpu: [ppc64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-riscv64-gnu@4.60.4': + resolution: {integrity: sha512-FJHFfqpKUI3A10WrWKiFbBZ7yVbGT4q4B5o1qKFFojqpaYoh9LrQgqWCmmcxQzVSXYtyB5bzkXrYzlHTs21MYA==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-riscv64-musl@4.60.4': + resolution: {integrity: sha512-mcEl6CUT5IAUmQf1m9FYSmVqCJlpQ8r8eyftFUHG8i9OhY7BkBXSUdnLH5DOf0wCOjcP9v/QO93zpmF1SptCCw==} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-s390x-gnu@4.60.4': + resolution: {integrity: sha512-ynt3JxVd2w2buzoKDWIyiV1pJW93xlQic1THVLXilz429oijRpSHivZAgp65KBu+cMcgf1eVVjdnTLvPxgCuoQ==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-x64-gnu@4.60.4': + resolution: {integrity: sha512-Boiz5+MsaROEWDf+GGEwF8VMHGhlUoQMtIPjOgA5fv4osupqTVnJteQNKJwUcnUog2G55jYXH7KZFFiJe0TEzQ==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-x64-musl@4.60.4': + resolution: {integrity: sha512-+qfSY27qIrFfI/Hom04KYFw3GKZSGU4lXus51wsb5EuySfFlWRwjkKWoE9emgRw/ukoT4Udsj4W/+xxG8VbPKg==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rollup/rollup-openbsd-x64@4.60.4': + resolution: {integrity: sha512-VpTfOPHgVXEBeeR8hZ2O0F3aSso+JDWqTWmTmzcQKted54IAdUVbxE+j/MVxUsKa8L20HJhv3vUezVPoquqWjA==} + cpu: [x64] + os: [openbsd] + + '@rollup/rollup-openharmony-arm64@4.60.4': + resolution: {integrity: sha512-IPOsh5aRYuLv/nkU51X10Bf75Bsf6+gZdx1X+QP5QM6lIJFHHqbHLG0uJn/hWthzo13UAc2umiUorqZy3axoZg==} + cpu: [arm64] + os: [openharmony] + + '@rollup/rollup-win32-arm64-msvc@4.60.4': + resolution: {integrity: sha512-4QzE9E81OohJ/HKzHhsqU+zcYYojVOXlFMs1DdyMT6qXl/niOH7AVElmmEdUNHHS/oRkc++d5k6Vy85zFs0DEw==} + cpu: [arm64] + os: [win32] + + '@rollup/rollup-win32-ia32-msvc@4.60.4': + resolution: {integrity: sha512-zTPgT1YuHHcd+Tmx7h8aml0FWFVelV5N54oHow9SLj+GfoDy/huQ+UV396N/C7KpMDMiPspRktzM1/0r1usYEA==} + cpu: [ia32] + os: [win32] + + '@rollup/rollup-win32-x64-gnu@4.60.4': + resolution: {integrity: sha512-DRS4G7mi9lJxqEDezIkKCaUIKCrLUUDCUaCsTPCi/rtqaC6D/jjwslMQyiDU50Ka0JKpeXeRBFBAXwArY52vBw==} + cpu: [x64] + os: [win32] + + '@rollup/rollup-win32-x64-msvc@4.60.4': + resolution: {integrity: sha512-QVTUovf40zgTqlFVrKA1uXMVvU2QWEFWfAH8Wdc48IxLvrJMQVMBRjuQyUpzZCDkakImib9eVazbWlC6ksWtJw==} + cpu: [x64] + os: [win32] + '@standard-schema/spec@1.1.0': resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} @@ -1150,6 +1464,30 @@ packages: peerDependencies: vite: ^5.2.0 || ^6 || ^7 || ^8 + '@tanstack/history@1.161.6': + resolution: {integrity: sha512-NaOGLRrddszbQj9upGat6HG/4TKvXLvu+osAIgfxPYA+eIvYKv8GKDJOrY2D3/U9MRnKfMWD7bU4jeD4xmqyIg==} + engines: {node: '>=20.19'} + + '@tanstack/react-router@1.169.2': + resolution: {integrity: sha512-OJM7Kguc7ERnweaNRWsyWgIKcl3z23rD1B4jaxjzd9RGdnzpt2HfrWa9rggbT0Hfzhfo4D2ZmsfoTme035tniQ==} + engines: {node: '>=20.19'} + peerDependencies: + react: '>=18.0.0 || >=19.0.0' + react-dom: '>=18.0.0 || >=19.0.0' + + '@tanstack/react-store@0.9.3': + resolution: {integrity: sha512-y2iHd/N9OkoQbFJLUX1T9vbc2O9tjH0pQRgTcx1/Nz4IlwLvkgpuglXUx+mXt0g5ZDFrEeDnONPqkbfxXJKwRg==} + peerDependencies: + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + + '@tanstack/router-core@1.169.2': + resolution: {integrity: sha512-5sm0DJF1A7Mz+9gy4Gz/lLovNailK3yot4vYvz9MkBUPw26uLnhQiR8hSCYxucjE0wD6Mdlc5l+Z0/XTlZ7xHw==} + engines: {node: '>=20.19'} + + '@tanstack/store@0.9.3': + resolution: {integrity: sha512-8reSzl/qGWGGVKhBoxXPMWzATSbZLZFWhwBAFO9NAyp0TxzfBP0mIrGb8CP8KrQTmvzXlR/vFPPUrHTLBGyFyw==} + '@tybys/wasm-util@0.10.1': resolution: {integrity: sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==} @@ -1311,6 +1649,9 @@ packages: ajv@6.14.0: resolution: {integrity: sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==} + any-promise@1.3.0: + resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==} + aria-hidden@1.2.6: resolution: {integrity: sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==} engines: {node: '>=10'} @@ -1346,6 +1687,16 @@ packages: engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} hasBin: true + bundle-require@5.1.0: + resolution: {integrity: sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + peerDependencies: + esbuild: '>=0.18' + + cac@6.7.14: + resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==} + engines: {node: '>=8'} + caniuse-lite@1.0.30001788: resolution: {integrity: sha512-6q8HFp+lOQtcf7wBK+uEenxymVWkGKkjFpCvw5W25cmMwEDU45p1xQFBQv8JDlMMry7eNxyBaR+qxgmTUZkIRQ==} @@ -1368,9 +1719,23 @@ packages: resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==} engines: {node: '>=20'} + commander@4.1.1: + resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==} + engines: {node: '>= 6'} + + confbox@0.1.8: + resolution: {integrity: sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==} + + consola@3.4.2: + resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==} + engines: {node: ^14.18.0 || >=16.10.0} + convert-source-map@2.0.0: resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + cookie-es@3.1.1: + resolution: {integrity: sha512-UaXxwISYJPTr9hwQxMFYZ7kNhSXboMXP+Z3TRX6f1/NyaGPfuNUZOWP1pUEb75B2HjfklIYLVRfWiFZJyC6Npg==} + cross-env@10.1.0: resolution: {integrity: sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw==} engines: {node: '>=20'} @@ -1530,6 +1895,9 @@ packages: resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} engines: {node: '>=10'} + fix-dts-default-cjs-exports@1.0.1: + resolution: {integrity: sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==} + flat-cache@4.0.1: resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==} engines: {node: '>=16'} @@ -1632,6 +2000,10 @@ packages: is-what-type@1.1.4: resolution: {integrity: sha512-120PeT8LdXO7m503rQtOapWA7lHBtWErN+asRxKyxF/SFGeqLEAZhlItjNynNVABHteRMSjomQCdAnxEJldMMQ==} + isbot@5.1.40: + resolution: {integrity: sha512-yNeeynhhtIVRBk12tBV4eHNxwB42HzR4Q3Ea7vCOiJhImGaAIdIMrbJtacQlBizGLjUPw+akkFI5Dn9T70XoVQ==} + engines: {node: '>=18'} + isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} @@ -1639,6 +2011,10 @@ packages: resolution: {integrity: sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==} hasBin: true + joycon@3.1.1: + resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==} + engines: {node: '>=10'} + js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} @@ -1745,6 +2121,17 @@ packages: resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==} engines: {node: '>= 12.0.0'} + lilconfig@3.1.3: + resolution: {integrity: sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==} + engines: {node: '>=14'} + + lines-and-columns@1.2.4: + resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==} + + load-tsconfig@0.2.5: + resolution: {integrity: sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + locate-path@6.0.0: resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} engines: {node: '>=10'} @@ -1764,6 +2151,9 @@ packages: resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==} engines: {node: 18 || 20 || >=22} + mlly@1.8.2: + resolution: {integrity: sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==} + motion-dom@12.38.0: resolution: {integrity: sha512-pdkHLD8QYRp8VfiNLb8xIBJis1byQ9gPT3Jnh2jqfFtAsWUA3dEepDlsWe/xMpO8McV+VdpKVcp+E+TGJEtOoA==} @@ -1787,6 +2177,9 @@ packages: ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + mz@2.7.0: + resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==} + nanoid@3.3.11: resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -1801,6 +2194,10 @@ packages: node-releases@2.0.37: resolution: {integrity: sha512-1h5gKZCF+pO/o3Iqt5Jp7wc9rH3eJJ0+nh/CIoiRwjRxde/hAHyLPXYN4V3CqKAbiZPSeJFSWHmJsbkicta0Eg==} + object-assign@4.1.1: + resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} + engines: {node: '>=0.10.0'} + obug@2.1.1: resolution: {integrity: sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==} @@ -1837,6 +2234,31 @@ packages: resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} engines: {node: '>=12'} + pirates@4.0.7: + resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==} + engines: {node: '>= 6'} + + pkg-types@1.3.1: + resolution: {integrity: sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==} + + postcss-load-config@6.0.1: + resolution: {integrity: sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==} + engines: {node: '>= 18'} + peerDependencies: + jiti: '>=1.21.0' + postcss: '>=8.0.9' + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + jiti: + optional: true + postcss: + optional: true + tsx: + optional: true + yaml: + optional: true + postcss@8.5.10: resolution: {integrity: sha512-pMMHxBOZKFU6HgAZ4eyGnwXF/EvPGGqUr0MnZ5+99485wwW41kW91A4LOGxSHhgugZmSChL5AlElNdwlNgcnLQ==} engines: {node: ^10 || ^12 || >=14} @@ -1892,6 +2314,10 @@ packages: resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==} engines: {node: '>= 14.18.0'} + resolve-from@5.0.0: + resolution: {integrity: sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==} + engines: {node: '>=8'} + resolve-pkg-maps@1.0.0: resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} @@ -1905,6 +2331,11 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} hasBin: true + rollup@4.60.4: + resolution: {integrity: sha512-WHeFSbZYsPu3+bLoNRUuAO+wavNlocOPf3wSHTP7hcFKVnJeWsYlCDbr3mTS14FCizf9ccIxXA8sGL8zKeQN3g==} + engines: {node: '>=18.0.0', npm: '>=8.0.0'} + hasBin: true + sass@1.99.0: resolution: {integrity: sha512-kgW13M54DUB7IsIRM5LvJkNlpH+WhMpooUcaWGFARkF1Tc82v9mIWkCbCYf+MBvpIUBSeSOTilpZjEPr2VYE6Q==} engines: {node: '>=14.0.0'} @@ -1922,6 +2353,16 @@ packages: engines: {node: '>=10'} hasBin: true + seroval-plugins@1.5.4: + resolution: {integrity: sha512-S0xQPhUTefAhNvNWFg0c1J8qJArHt5KdtJ/cFAofo06KD1MVSeFWyl4iiu+ApDIuw0WhjpOfCdgConOfAnLgkw==} + engines: {node: '>=10'} + peerDependencies: + seroval: ^1.0 + + seroval@1.5.4: + resolution: {integrity: sha512-46uFvgrXTVxZcUorgSSRZ4y+ieqLLQRMlG4bnCZKW3qI6BZm7Rg4ntMW4p1mILEEBZWrFlcpp0AyIIlM6jD9iw==} + engines: {node: '>=10'} + shebang-command@2.0.0: resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} engines: {node: '>=8'} @@ -1933,16 +2374,31 @@ packages: siginfo@2.0.0: resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + sonner@2.0.7: + resolution: {integrity: sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w==} + peerDependencies: + react: ^18.0.0 || ^19.0.0 || ^19.0.0-rc + react-dom: ^18.0.0 || ^19.0.0 || ^19.0.0-rc + source-map-js@1.2.1: resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} engines: {node: '>=0.10.0'} + source-map@0.7.6: + resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==} + engines: {node: '>= 12'} + stackback@0.0.2: resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} std-env@4.1.0: resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==} + sucrase@3.35.1: + resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==} + engines: {node: '>=16 || 14 >=14.17'} + hasBin: true + supports-preserve-symlinks-flag@1.0.0: resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} engines: {node: '>= 0.4'} @@ -1957,9 +2413,19 @@ packages: resolution: {integrity: sha512-1MOpMXuhGzGL5TTCZFItxCc0AARf1EZFQkGqMm7ERKj8+Hgr5oLvJOVFcC+lRmR8hCe2S3jC4T5D7Vg/d7/fhA==} engines: {node: '>=6'} + thenify-all@1.6.0: + resolution: {integrity: sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==} + engines: {node: '>=0.8'} + + thenify@3.3.1: + resolution: {integrity: sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==} + tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + tinyexec@0.3.2: + resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==} + tinyexec@1.1.1: resolution: {integrity: sha512-VKS/ZaQhhkKFMANmAOhhXVoIfBXblQxGX1myCQ2faQrfmobMftXeJPcZGp0gS07ocvGJWDLZGyOZDadDBqYIJg==} engines: {node: '>=18'} @@ -1972,15 +2438,41 @@ packages: resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==} engines: {node: '>=14.0.0'} + tree-kill@1.2.2: + resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==} + hasBin: true + ts-api-utils@2.5.0: resolution: {integrity: sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==} engines: {node: '>=18.12'} peerDependencies: typescript: '>=4.8.4' + ts-interface-checker@0.1.13: + resolution: {integrity: sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==} + tslib@2.8.1: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + tsup@8.5.1: + resolution: {integrity: sha512-xtgkqwdhpKWr3tKPmCkvYmS9xnQK3m3XgxZHwSUjvfTjp7YfXe5tT3GgWi0F2N+ZSMsOeWeZFh7ZZFg5iPhing==} + engines: {node: '>=18'} + hasBin: true + peerDependencies: + '@microsoft/api-extractor': ^7.36.0 + '@swc/core': ^1 + postcss: ^8.4.12 + typescript: '>=4.5.0' + peerDependenciesMeta: + '@microsoft/api-extractor': + optional: true + '@swc/core': + optional: true + postcss: + optional: true + typescript: + optional: true + tsx@4.21.0: resolution: {integrity: sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==} engines: {node: '>=18.0.0'} @@ -2005,6 +2497,9 @@ packages: engines: {node: '>=14.17'} hasBin: true + ufo@1.6.4: + resolution: {integrity: sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==} + undici-types@7.16.0: resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==} @@ -2044,6 +2539,11 @@ packages: '@types/react': optional: true + use-sync-external-store@1.6.0: + resolution: {integrity: sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==} + peerDependencies: + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + vite-plugin-cp@6.0.3: resolution: {integrity: sha512-qxKGH3v9wPwUDbDchJf4IH4mRE1zkLWgzZSxwrl8LapwUWm48IFS7SlbRmcF4NquC/fESA5cHFge9E2Ps+woxg==} engines: {node: '>=14.18.0', vite: '>=3.1.0'} @@ -2546,6 +3046,34 @@ snapshots: '@types/react': 19.2.14 '@types/react-dom': 19.2.3(@types/react@19.2.14) + '@radix-ui/react-checkbox@1.3.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/primitive': 1.1.3 + '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-previous': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-size': 1.1.1(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.3(@types/react@19.2.14) + + '@radix-ui/react-collection@1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-slot': 1.2.3(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.3(@types/react@19.2.14) + '@radix-ui/react-compose-refs@1.1.2(@types/react@19.2.14)(react@19.2.5)': dependencies: react: 19.2.5 @@ -2632,6 +3160,29 @@ snapshots: '@types/react': 19.2.14 '@types/react-dom': 19.2.3(@types/react@19.2.14) + '@radix-ui/react-popover@1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/primitive': 1.1.3 + '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-dismissable-layer': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-focus-guards': 1.1.3(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-focus-scope': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-popper': 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-portal': 1.1.9(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-slot': 1.2.3(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) + aria-hidden: 1.2.6 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + react-remove-scroll: 2.7.2(@types/react@19.2.14)(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.3(@types/react@19.2.14) + '@radix-ui/react-popper@1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': dependencies: '@floating-ui/react-dom': 2.1.8(react-dom@19.2.5(react@19.2.5))(react@19.2.5) @@ -2688,6 +3239,23 @@ snapshots: '@types/react': 19.2.14 '@types/react-dom': 19.2.3(@types/react@19.2.14) + '@radix-ui/react-roving-focus@1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/primitive': 1.1.3 + '@radix-ui/react-collection': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-direction': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.3(@types/react@19.2.14) + '@radix-ui/react-scroll-area@1.2.10(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': dependencies: '@radix-ui/number': 1.1.1 @@ -2705,6 +3273,35 @@ snapshots: '@types/react': 19.2.14 '@types/react-dom': 19.2.3(@types/react@19.2.14) + '@radix-ui/react-select@2.2.6(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/number': 1.1.1 + '@radix-ui/primitive': 1.1.3 + '@radix-ui/react-collection': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-direction': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-dismissable-layer': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-focus-guards': 1.1.3(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-focus-scope': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-popper': 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-portal': 1.1.9(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-slot': 1.2.3(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-previous': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-visually-hidden': 1.2.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + aria-hidden: 1.2.6 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + react-remove-scroll: 2.7.2(@types/react@19.2.14)(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.3(@types/react@19.2.14) + '@radix-ui/react-separator@1.1.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': dependencies: '@radix-ui/react-primitive': 2.1.4(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) @@ -2728,6 +3325,37 @@ snapshots: optionalDependencies: '@types/react': 19.2.14 + '@radix-ui/react-switch@1.2.6(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/primitive': 1.1.3 + '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-previous': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-size': 1.1.1(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.3(@types/react@19.2.14) + + '@radix-ui/react-tabs@1.1.13(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/primitive': 1.1.3 + '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-direction': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-roving-focus': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.3(@types/react@19.2.14) + '@radix-ui/react-tooltip@1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': dependencies: '@radix-ui/primitive': 1.1.3 @@ -2782,6 +3410,12 @@ snapshots: optionalDependencies: '@types/react': 19.2.14 + '@radix-ui/react-use-previous@1.1.1(@types/react@19.2.14)(react@19.2.5)': + dependencies: + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + '@radix-ui/react-use-rect@1.1.1(@types/react@19.2.14)(react@19.2.5)': dependencies: '@radix-ui/rect': 1.1.1 @@ -2860,19 +3494,98 @@ snapshots: '@rolldown/pluginutils@1.0.0-rc.7': {} - '@rollup/plugin-node-resolve@16.0.3': + '@rollup/plugin-node-resolve@16.0.3(rollup@4.60.4)': dependencies: - '@rollup/pluginutils': 5.3.0 + '@rollup/pluginutils': 5.3.0(rollup@4.60.4) '@types/resolve': 1.20.2 deepmerge: 4.3.1 is-module: 1.0.0 resolve: 1.22.12 + optionalDependencies: + rollup: 4.60.4 - '@rollup/pluginutils@5.3.0': + '@rollup/pluginutils@5.3.0(rollup@4.60.4)': dependencies: '@types/estree': 1.0.8 estree-walker: 2.0.2 picomatch: 4.0.4 + optionalDependencies: + rollup: 4.60.4 + + '@rollup/rollup-android-arm-eabi@4.60.4': + optional: true + + '@rollup/rollup-android-arm64@4.60.4': + optional: true + + '@rollup/rollup-darwin-arm64@4.60.4': + optional: true + + '@rollup/rollup-darwin-x64@4.60.4': + optional: true + + '@rollup/rollup-freebsd-arm64@4.60.4': + optional: true + + '@rollup/rollup-freebsd-x64@4.60.4': + optional: true + + '@rollup/rollup-linux-arm-gnueabihf@4.60.4': + optional: true + + '@rollup/rollup-linux-arm-musleabihf@4.60.4': + optional: true + + '@rollup/rollup-linux-arm64-gnu@4.60.4': + optional: true + + '@rollup/rollup-linux-arm64-musl@4.60.4': + optional: true + + '@rollup/rollup-linux-loong64-gnu@4.60.4': + optional: true + + '@rollup/rollup-linux-loong64-musl@4.60.4': + optional: true + + '@rollup/rollup-linux-ppc64-gnu@4.60.4': + optional: true + + '@rollup/rollup-linux-ppc64-musl@4.60.4': + optional: true + + '@rollup/rollup-linux-riscv64-gnu@4.60.4': + optional: true + + '@rollup/rollup-linux-riscv64-musl@4.60.4': + optional: true + + '@rollup/rollup-linux-s390x-gnu@4.60.4': + optional: true + + '@rollup/rollup-linux-x64-gnu@4.60.4': + optional: true + + '@rollup/rollup-linux-x64-musl@4.60.4': + optional: true + + '@rollup/rollup-openbsd-x64@4.60.4': + optional: true + + '@rollup/rollup-openharmony-arm64@4.60.4': + optional: true + + '@rollup/rollup-win32-arm64-msvc@4.60.4': + optional: true + + '@rollup/rollup-win32-ia32-msvc@4.60.4': + optional: true + + '@rollup/rollup-win32-x64-gnu@4.60.4': + optional: true + + '@rollup/rollup-win32-x64-msvc@4.60.4': + optional: true '@standard-schema/spec@1.1.0': {} @@ -2944,6 +3657,33 @@ snapshots: tailwindcss: 4.2.2 vite: 8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) + '@tanstack/history@1.161.6': {} + + '@tanstack/react-router@1.169.2(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@tanstack/history': 1.161.6 + '@tanstack/react-store': 0.9.3(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@tanstack/router-core': 1.169.2 + isbot: 5.1.40 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@tanstack/react-store@0.9.3(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@tanstack/store': 0.9.3 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + use-sync-external-store: 1.6.0(react@19.2.5) + + '@tanstack/router-core@1.169.2': + dependencies: + '@tanstack/history': 1.161.6 + cookie-es: 3.1.1 + seroval: 1.5.4 + seroval-plugins: 1.5.4(seroval@1.5.4) + + '@tanstack/store@0.9.3': {} + '@tybys/wasm-util@0.10.1': dependencies: tslib: 2.8.1 @@ -3145,6 +3885,8 @@ snapshots: json-schema-traverse: 0.4.1 uri-js: 4.4.1 + any-promise@1.3.0: {} + aria-hidden@1.2.6: dependencies: tslib: 2.8.1 @@ -3187,6 +3929,13 @@ snapshots: node-releases: 2.0.37 update-browserslist-db: 1.2.3(browserslist@4.28.2) + bundle-require@5.1.0(esbuild@0.27.7): + dependencies: + esbuild: 0.27.7 + load-tsconfig: 0.2.5 + + cac@6.7.14: {} + caniuse-lite@1.0.30001788: {} chai@6.2.2: {} @@ -3194,7 +3943,6 @@ snapshots: chokidar@4.0.3: dependencies: readdirp: 4.1.2 - optional: true class-variance-authority@0.7.1: dependencies: @@ -3204,8 +3952,16 @@ snapshots: commander@14.0.3: {} + commander@4.1.1: {} + + confbox@0.1.8: {} + + consola@3.4.2: {} + convert-source-map@2.0.0: {} + cookie-es@3.1.1: {} + cross-env@10.1.0: dependencies: '@epic-web/invariant': 1.0.0 @@ -3389,6 +4145,12 @@ snapshots: locate-path: 6.0.0 path-exists: 4.0.0 + fix-dts-default-cjs-exports@1.0.1: + dependencies: + magic-string: 0.30.21 + mlly: 1.8.2 + rollup: 4.60.4 + flat-cache@4.0.1: dependencies: flatted: 3.4.2 @@ -3467,10 +4229,14 @@ snapshots: is-what-type@1.1.4: {} + isbot@5.1.40: {} + isexe@2.0.0: {} jiti@2.6.1: {} + joycon@3.1.1: {} + js-tokens@4.0.0: {} jsesc@3.1.0: {} @@ -3547,6 +4313,12 @@ snapshots: lightningcss-win32-arm64-msvc: 1.32.0 lightningcss-win32-x64-msvc: 1.32.0 + lilconfig@3.1.3: {} + + lines-and-columns@1.2.4: {} + + load-tsconfig@0.2.5: {} + locate-path@6.0.0: dependencies: p-locate: 5.0.0 @@ -3567,6 +4339,13 @@ snapshots: dependencies: brace-expansion: 5.0.5 + mlly@1.8.2: + dependencies: + acorn: 8.16.0 + pathe: 2.0.3 + pkg-types: 1.3.1 + ufo: 1.6.4 + motion-dom@12.38.0: dependencies: motion-utils: 12.36.0 @@ -3583,6 +4362,12 @@ snapshots: ms@2.1.3: {} + mz@2.7.0: + dependencies: + any-promise: 1.3.0 + object-assign: 4.1.1 + thenify-all: 1.6.0 + nanoid@3.3.11: {} natural-compare@1.4.0: {} @@ -3592,6 +4377,8 @@ snapshots: node-releases@2.0.37: {} + object-assign@4.1.1: {} + obug@2.1.1: {} optionator@0.9.4: @@ -3623,6 +4410,22 @@ snapshots: picomatch@4.0.4: {} + pirates@4.0.7: {} + + pkg-types@1.3.1: + dependencies: + confbox: 0.1.8 + mlly: 1.8.2 + pathe: 2.0.3 + + postcss-load-config@6.0.1(jiti@2.6.1)(postcss@8.5.10)(tsx@4.21.0): + dependencies: + lilconfig: 3.1.3 + optionalDependencies: + jiti: 2.6.1 + postcss: 8.5.10 + tsx: 4.21.0 + postcss@8.5.10: dependencies: nanoid: 3.3.11 @@ -3667,8 +4470,9 @@ snapshots: react@19.2.5: {} - readdirp@4.1.2: - optional: true + readdirp@4.1.2: {} + + resolve-from@5.0.0: {} resolve-pkg-maps@1.0.0: {} @@ -3700,6 +4504,37 @@ snapshots: '@rolldown/binding-win32-arm64-msvc': 1.0.0-rc.15 '@rolldown/binding-win32-x64-msvc': 1.0.0-rc.15 + rollup@4.60.4: + dependencies: + '@types/estree': 1.0.8 + optionalDependencies: + '@rollup/rollup-android-arm-eabi': 4.60.4 + '@rollup/rollup-android-arm64': 4.60.4 + '@rollup/rollup-darwin-arm64': 4.60.4 + '@rollup/rollup-darwin-x64': 4.60.4 + '@rollup/rollup-freebsd-arm64': 4.60.4 + '@rollup/rollup-freebsd-x64': 4.60.4 + '@rollup/rollup-linux-arm-gnueabihf': 4.60.4 + '@rollup/rollup-linux-arm-musleabihf': 4.60.4 + '@rollup/rollup-linux-arm64-gnu': 4.60.4 + '@rollup/rollup-linux-arm64-musl': 4.60.4 + '@rollup/rollup-linux-loong64-gnu': 4.60.4 + '@rollup/rollup-linux-loong64-musl': 4.60.4 + '@rollup/rollup-linux-ppc64-gnu': 4.60.4 + '@rollup/rollup-linux-ppc64-musl': 4.60.4 + '@rollup/rollup-linux-riscv64-gnu': 4.60.4 + '@rollup/rollup-linux-riscv64-musl': 4.60.4 + '@rollup/rollup-linux-s390x-gnu': 4.60.4 + '@rollup/rollup-linux-x64-gnu': 4.60.4 + '@rollup/rollup-linux-x64-musl': 4.60.4 + '@rollup/rollup-openbsd-x64': 4.60.4 + '@rollup/rollup-openharmony-arm64': 4.60.4 + '@rollup/rollup-win32-arm64-msvc': 4.60.4 + '@rollup/rollup-win32-ia32-msvc': 4.60.4 + '@rollup/rollup-win32-x64-gnu': 4.60.4 + '@rollup/rollup-win32-x64-msvc': 4.60.4 + fsevents: 2.3.3 + sass@1.99.0: dependencies: chokidar: 4.0.3 @@ -3715,6 +4550,12 @@ snapshots: semver@7.7.4: {} + seroval-plugins@1.5.4(seroval@1.5.4): + dependencies: + seroval: 1.5.4 + + seroval@1.5.4: {} + shebang-command@2.0.0: dependencies: shebang-regex: 3.0.0 @@ -3723,12 +4564,29 @@ snapshots: siginfo@2.0.0: {} + sonner@2.0.7(react-dom@19.2.5(react@19.2.5))(react@19.2.5): + dependencies: + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + source-map-js@1.2.1: {} + source-map@0.7.6: {} + stackback@0.0.2: {} std-env@4.1.0: {} + sucrase@3.35.1: + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + commander: 4.1.1 + lines-and-columns: 1.2.4 + mz: 2.7.0 + pirates: 4.0.7 + tinyglobby: 0.2.16 + ts-interface-checker: 0.1.13 + supports-preserve-symlinks-flag@1.0.0: {} tailwind-merge@3.5.0: {} @@ -3737,8 +4595,18 @@ snapshots: tapable@2.3.2: {} + thenify-all@1.6.0: + dependencies: + thenify: 3.3.1 + + thenify@3.3.1: + dependencies: + any-promise: 1.3.0 + tinybench@2.9.0: {} + tinyexec@0.3.2: {} + tinyexec@1.1.1: {} tinyglobby@0.2.16: @@ -3748,12 +4616,44 @@ snapshots: tinyrainbow@3.1.0: {} + tree-kill@1.2.2: {} + ts-api-utils@2.5.0(typescript@6.0.2): dependencies: typescript: 6.0.2 + ts-interface-checker@0.1.13: {} + tslib@2.8.1: {} + tsup@8.5.1(jiti@2.6.1)(postcss@8.5.10)(tsx@4.21.0)(typescript@6.0.2): + dependencies: + bundle-require: 5.1.0(esbuild@0.27.7) + cac: 6.7.14 + chokidar: 4.0.3 + consola: 3.4.2 + debug: 4.4.3 + esbuild: 0.27.7 + fix-dts-default-cjs-exports: 1.0.1 + joycon: 3.1.1 + picocolors: 1.1.1 + postcss-load-config: 6.0.1(jiti@2.6.1)(postcss@8.5.10)(tsx@4.21.0) + resolve-from: 5.0.0 + rollup: 4.60.4 + source-map: 0.7.6 + sucrase: 3.35.1 + tinyexec: 0.3.2 + tinyglobby: 0.2.16 + tree-kill: 1.2.2 + optionalDependencies: + postcss: 8.5.10 + typescript: 6.0.2 + transitivePeerDependencies: + - jiti + - supports-color + - tsx + - yaml + tsx@4.21.0: dependencies: esbuild: 0.27.7 @@ -3780,6 +4680,8 @@ snapshots: typescript@6.0.2: {} + ufo@1.6.4: {} + undici-types@7.16.0: {} undici-types@7.19.2: {} @@ -3811,6 +4713,10 @@ snapshots: optionalDependencies: '@types/react': 19.2.14 + use-sync-external-store@1.6.0(react@19.2.5): + dependencies: + react: 19.2.5 + vite-plugin-cp@6.0.3: dependencies: fs-extra: 11.3.4