chore: 初始化 monorepo 脚手架与代码骨架
- Bun workspaces:apps/web(Vue 3.5 + Vite 8 + naive-ui)· apps/server(Hono 4.13 + Drizzle)· packages/shared(契约类型) - 代码骨架:四表 Drizzle schema · 11 个端点占位(501)· 管理面口令中间件 · 同步引擎占位(5 分钟 tick + 防重入) - 命令链:dev / build / test / lint / type-check / db:*(见 AGENTS.md)
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
# 环境变量样例 —— 复制为 .env 并填真实值(.env 不入库;部署时由实例运营方经 env 注入)
|
||||
|
||||
# ---- 服务端(apps/server) ----
|
||||
|
||||
# 监听端口(Vite dev 代理与生产反代都指向它)
|
||||
PORT=3000
|
||||
|
||||
# PostgreSQL 连接串
|
||||
DATABASE_URL=postgres://user:password@localhost:5432/new_api_key_usage
|
||||
|
||||
# 管理面口令(请求头 X-Manage-Token;见 API 契约 约定 6)
|
||||
MANAGE_TOKEN=change-me
|
||||
|
||||
# 凭证主密钥(HKDF 派生 hmac / aes 子密钥;丢失 = 全部 key 需重新登记)
|
||||
KEYS_MASTER_KEY=change-me-32-bytes-base64
|
||||
|
||||
# 上游 NewAPI 站点地址(同步引擎调用的 BaseURL,不带尾部斜杠)
|
||||
NEWAPI_BASE=https://your-newapi-instance.example.com
|
||||
+11
@@ -6,9 +6,20 @@
|
||||
.vscode/
|
||||
*.swp
|
||||
|
||||
# Node / Bun
|
||||
node_modules/
|
||||
dist/
|
||||
*.tsbuildinfo
|
||||
|
||||
# 日志
|
||||
*.log
|
||||
|
||||
# 实测数据样例(未脱敏,不入库)
|
||||
/api*.json
|
||||
|
||||
# AI 工具运行目录(Reasonix)
|
||||
.reasonix/
|
||||
|
||||
# 环境变量 / 密钥(不要提交到仓库)
|
||||
.env
|
||||
.env.*
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# deps
|
||||
node_modules/
|
||||
@@ -0,0 +1,11 @@
|
||||
import { defineConfig } from 'drizzle-kit'
|
||||
|
||||
/** drizzle-kit 配置(迁移产物在 ./drizzle;命令见根 package.json 的 db:* 脚本) */
|
||||
export default defineConfig({
|
||||
schema: './src/db/schema.ts',
|
||||
out: './drizzle',
|
||||
dialect: 'postgresql',
|
||||
dbCredentials: {
|
||||
url: process.env.DATABASE_URL ?? '',
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "@naku/server",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "bun run --hot src/index.ts",
|
||||
"start": "bun run src/index.ts",
|
||||
"db:generate": "drizzle-kit generate",
|
||||
"db:migrate": "drizzle-kit migrate",
|
||||
"db:push": "drizzle-kit push"
|
||||
},
|
||||
"dependencies": {
|
||||
"@naku/shared": "workspace:*",
|
||||
"drizzle-orm": "^0.45.2",
|
||||
"hono": "^4.13.7",
|
||||
"zod": "^4.6.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "latest",
|
||||
"drizzle-kit": "^0.31.10"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* 数据库连接(Bun 原生 SQL + Drizzle)。
|
||||
* 懒初始化:首次调用 `getDb()` 时才建连接——骨架阶段缺 DATABASE_URL 也能起服务。
|
||||
*/
|
||||
import { drizzle, type BunSQLDatabase } from 'drizzle-orm/bun-sql'
|
||||
import { env } from '../lib/env'
|
||||
import * as schema from './schema'
|
||||
|
||||
let db: BunSQLDatabase<typeof schema> | null = null
|
||||
|
||||
export function getDb(): BunSQLDatabase<typeof schema> {
|
||||
if (!db) {
|
||||
if (!env.databaseUrl) {
|
||||
throw new Error('缺少环境变量 DATABASE_URL(见 .env.example)')
|
||||
}
|
||||
db = drizzle(env.databaseUrl, { schema })
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
export { schema }
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* 数据库 schema(Drizzle ORM)—— 逐列对应 `docs/design/` 的四张表字段设计:
|
||||
* `api_keys`(17 列)· `usage_logs`(23 列)· `purchases`(9 列)· `qpu_history`(3 列)。
|
||||
* TS 侧字段用 camelCase,列名保持 snake_case(与 API 字段同名同形,契约 约定 3)。
|
||||
*/
|
||||
import {
|
||||
bigint,
|
||||
bigserial,
|
||||
boolean,
|
||||
customType,
|
||||
index,
|
||||
integer,
|
||||
jsonb,
|
||||
numeric,
|
||||
pgTable,
|
||||
smallint,
|
||||
text,
|
||||
timestamp,
|
||||
} from 'drizzle-orm/pg-core'
|
||||
|
||||
/** PostgreSQL bytea(Drizzle 无内置;用于 `key_ciphertext`) */
|
||||
const bytea = customType<{ data: Uint8Array; driverData: Uint8Array }>({
|
||||
dataType() {
|
||||
return 'bytea'
|
||||
},
|
||||
})
|
||||
|
||||
/** 第一张表:API key 登记表(api_keys 表字段设计,17 列) */
|
||||
export const apiKeys = pgTable('api_keys', {
|
||||
id: bigserial('id', { mode: 'number' }).primaryKey(),
|
||||
/** 登记时 HMAC-SHA256(命中判定,不可逆) */
|
||||
keyHash: text('key_hash').notNull().unique(),
|
||||
/** 登记时 AES-256-GCM(nonce + 密文 + tag 打包;唯一用途是调上游) */
|
||||
keyCiphertext: bytea('key_ciphertext').notNull(),
|
||||
/** active | disabled */
|
||||
status: text('status').notNull().default('active'),
|
||||
/** manual | auto_401 | null(区分「已失效」与「已停用」) */
|
||||
disabledSource: text('disabled_source'),
|
||||
/** 连续 401 计数:401 时 +1、成功清零、其他失败不动 */
|
||||
consecutive401s: integer('consecutive_401s').notNull().default(0),
|
||||
registeredAt: timestamp('registered_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
/** 「数据截止」的唯一来源(取请求发起时刻) */
|
||||
logSyncedAt: timestamp('log_synced_at', { withTimezone: true }),
|
||||
usageSyncedAt: timestamp('usage_synced_at', { withTimezone: true }),
|
||||
// —— 上游字段(GET /api/usage/token,整组一起写) ——
|
||||
tokenName: text('token_name').notNull(),
|
||||
totalGranted: bigint('total_granted', { mode: 'number' }).notNull().default(0),
|
||||
totalUsed: bigint('total_used', { mode: 'number' }).notNull().default(0),
|
||||
totalAvailable: bigint('total_available', { mode: 'number' }).notNull().default(0),
|
||||
unlimitedQuota: boolean('unlimited_quota').notNull().default(false),
|
||||
modelLimits: jsonb('model_limits').notNull().default({}),
|
||||
modelLimitsEnabled: boolean('model_limits_enabled').notNull().default(false),
|
||||
/** 上游 0 = 永不过期 → NULL */
|
||||
expiresAt: timestamp('expires_at', { withTimezone: true }),
|
||||
})
|
||||
|
||||
/** 第二张表:调用日志明细(usage_logs 表字段设计,23 列) */
|
||||
export const usageLogs = pgTable(
|
||||
'usage_logs',
|
||||
{
|
||||
id: bigserial('id', { mode: 'number' }).primaryKey(),
|
||||
keyId: bigint('key_id', { mode: 'number' })
|
||||
.notNull()
|
||||
.references(() => apiKeys.id),
|
||||
/** 去重唯一键:`${key_id}:${request_id}`;request_id 空时退化为内容指纹 */
|
||||
dedupeKey: text('dedupe_key').notNull().unique(),
|
||||
userId: bigint('user_id', { mode: 'number' }).notNull(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull(),
|
||||
type: smallint('type').notNull(),
|
||||
content: text('content').notNull().default(''),
|
||||
username: text('username').notNull(),
|
||||
/** 日志快照名(展示取当前名的口径见 API 契约 §2.1) */
|
||||
tokenName: text('token_name').notNull(),
|
||||
modelName: text('model_name').notNull(),
|
||||
quota: bigint('quota', { mode: 'number' }).notNull(),
|
||||
promptTokens: integer('prompt_tokens').notNull(),
|
||||
completionTokens: integer('completion_tokens').notNull(),
|
||||
useTime: integer('use_time').notNull(),
|
||||
isStream: boolean('is_stream').notNull(),
|
||||
channel: integer('channel').notNull(),
|
||||
channelName: text('channel_name').notNull().default(''),
|
||||
tokenId: bigint('token_id', { mode: 'number' }).notNull(),
|
||||
groupName: text('group_name').notNull().default('default'),
|
||||
ip: text('ip').notNull().default(''),
|
||||
requestId: text('request_id').notNull(),
|
||||
upstreamRequestId: text('upstream_request_id'),
|
||||
other: jsonb('other').notNull().default({}),
|
||||
},
|
||||
(t) => [
|
||||
index('usage_logs_key_created_idx').on(t.keyId, t.createdAt.desc()),
|
||||
index('usage_logs_created_idx').on(t.createdAt.desc()),
|
||||
],
|
||||
)
|
||||
|
||||
/** 第三张表:购买记录(purchases 表字段设计,9 列;全人工登记) */
|
||||
export const purchases = pgTable('purchases', {
|
||||
id: bigserial('id', { mode: 'number' }).primaryKey(),
|
||||
/** subscription | topup */
|
||||
kind: text('kind').notNull(),
|
||||
paidAt: timestamp('paid_at', { withTimezone: true }).notNull(),
|
||||
/** 实付人民币(唯一「只有作者知道」的信息) */
|
||||
paidAmount: numeric('paid_amount', { mode: 'number' }).notNull(),
|
||||
note: text('note'),
|
||||
/** 期间左闭右开 [period_start, period_end);未结束可空 */
|
||||
periodStart: timestamp('period_start', { withTimezone: true }),
|
||||
periodEnd: timestamp('period_end', { withTimezone: true }),
|
||||
/** 上游订阅实例 ID(与日志 other.subscription_id 匹配) */
|
||||
subscriptionId: bigint('subscription_id', { mode: 'number' }),
|
||||
/** 本笔额度(折算链的分母) */
|
||||
quotaGranted: bigint('quota_granted', { mode: 'number' }),
|
||||
})
|
||||
|
||||
/** 第四张表:换算参数时间线(qpu_history 表字段设计,3 列;纯只读,唯一写入者是同步引擎) */
|
||||
export const qpuHistory = pgTable('qpu_history', {
|
||||
id: bigserial('id', { mode: 'number' }).primaryKey(),
|
||||
/** 当时的 quota_per_unit 值 */
|
||||
qpu: numeric('qpu', { mode: 'number' }).notNull(),
|
||||
/** 生效时间;正常全表仅 1 行(出厂默认值从未变过) */
|
||||
effectiveFrom: timestamp('effective_from', { withTimezone: true }).notNull(),
|
||||
})
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* 服务入口:Hono 应用 + 同步引擎定时器(后端单进程、单实例——见同步引擎设计 §3.1)。
|
||||
* 路由骨架按 `docs/design/API契约.md` 的 11 个端点预留,业务逻辑逐步实现。
|
||||
*/
|
||||
import { Hono } from 'hono'
|
||||
|
||||
import { env } from './lib/env'
|
||||
import { apiKeysRoutes } from './routes/manage/api-keys'
|
||||
import { purchasesRoutes } from './routes/manage/purchases'
|
||||
import { qpuRoutes } from './routes/manage/qpu'
|
||||
import { usageRoutes } from './routes/usage'
|
||||
import { startSyncEngine } from './sync'
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
/** 健康检查(非契约端点,运维用) */
|
||||
app.get('/api/health', (c) =>
|
||||
c.json({ ok: true, served_at: new Date().toISOString() }),
|
||||
)
|
||||
|
||||
// 查看面(无会话、无状态;key 集合随请求体,见契约 约定 5 / 19)
|
||||
app.route('/api/usage', usageRoutes)
|
||||
|
||||
// 管理面(X-Manage-Token 口令门帘;见契约 约定 6)
|
||||
app.route('/api/manage/api-keys', apiKeysRoutes)
|
||||
app.route('/api/manage/purchases', purchasesRoutes)
|
||||
app.route('/api/manage/qpu', qpuRoutes)
|
||||
|
||||
// 同步引擎:随进程启动,启动即跑一轮(同步引擎设计 §3.2)
|
||||
startSyncEngine()
|
||||
|
||||
console.log(`[server] Hono 已就绪,监听 :${env.port}`)
|
||||
|
||||
export default {
|
||||
port: env.port,
|
||||
fetch: app.fetch,
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* 环境变量(部署时经 env 注入;全量清单见仓库根 `.env.example`)。
|
||||
* 缺关键变量时在「首次使用处」报错,不在进程启动时硬崩(便于本地起骨架)。
|
||||
*/
|
||||
function required(name: string): string {
|
||||
const v = process.env[name]
|
||||
if (!v) {
|
||||
throw new Error(`缺少环境变量 ${name}(见 .env.example)`)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
export const env = {
|
||||
/** 监听端口(Vite dev 代理与生产反代都指向它) */
|
||||
port: Number(process.env.PORT ?? 3000),
|
||||
/** PostgreSQL 连接串 */
|
||||
databaseUrl: process.env.DATABASE_URL ?? '',
|
||||
/** 管理面口令(X-Manage-Token;见 API 契约 约定 6) */
|
||||
manageToken: process.env.MANAGE_TOKEN ?? '',
|
||||
/** 凭证主密钥(HKDF 派生 hmac / aes 子密钥;丢失 = 全部 key 需重新登记) */
|
||||
keysMasterKey: process.env.KEYS_MASTER_KEY ?? '',
|
||||
/** 上游 NewAPI 站点地址(同步引擎调用的 BaseURL) */
|
||||
newapiBase: process.env.NEWAPI_BASE ?? '',
|
||||
}
|
||||
|
||||
export { required }
|
||||
@@ -0,0 +1,18 @@
|
||||
import { createMiddleware } from 'hono/factory'
|
||||
|
||||
import { env } from '../lib/env'
|
||||
|
||||
/**
|
||||
* 管理面口令门帘(契约 约定 6):每次请求校验 `X-Manage-Token`。
|
||||
* 无登录端点、无令牌签发;常量时间比较等加固归技术稿(API 契约 §3)。
|
||||
*/
|
||||
export const manageAuth = createMiddleware(async (c, next) => {
|
||||
const token = c.req.header('x-manage-token')
|
||||
if (!env.manageToken || token !== env.manageToken) {
|
||||
return c.json(
|
||||
{ error: { code: 'manage_unauthorized', message: '口令无效' } },
|
||||
401,
|
||||
)
|
||||
}
|
||||
await next()
|
||||
})
|
||||
@@ -0,0 +1,50 @@
|
||||
import { Hono } from 'hono'
|
||||
|
||||
import { manageAuth } from '../../middleware/manage-auth'
|
||||
|
||||
/**
|
||||
* 管理面 · key 管理(契约 §2.2):清单 / 登记 / 启停。
|
||||
* 清单与 `api_keys` 表 1:1——`key_hash` / `key_ciphertext` 两个敏感列永不出接口。
|
||||
*/
|
||||
export const apiKeysRoutes = new Hono()
|
||||
|
||||
apiKeysRoutes.use(manageAuth)
|
||||
|
||||
/** 清单(按 id 升序,不分页) */
|
||||
apiKeysRoutes.get('/', (c) =>
|
||||
c.json(
|
||||
{
|
||||
error: {
|
||||
code: 'internal',
|
||||
message: '未实现:key 清单(见 docs/design/API契约.md §2.2)',
|
||||
},
|
||||
},
|
||||
501,
|
||||
),
|
||||
)
|
||||
|
||||
/** 登记:body `{ key }`;上游验证通过 → 入库(不阻塞首轮同步) */
|
||||
apiKeysRoutes.post('/', (c) =>
|
||||
c.json(
|
||||
{
|
||||
error: {
|
||||
code: 'internal',
|
||||
message: '未实现:登记 key(见 docs/design/API契约.md §2.2)',
|
||||
},
|
||||
},
|
||||
501,
|
||||
),
|
||||
)
|
||||
|
||||
/** 启停:body `{ status: 'active' | 'disabled' }`;启用需上游验证、成功清零 consecutive_401s */
|
||||
apiKeysRoutes.patch('/:id', (c) =>
|
||||
c.json(
|
||||
{
|
||||
error: {
|
||||
code: 'internal',
|
||||
message: '未实现:启停(见 docs/design/API契约.md §2.2)',
|
||||
},
|
||||
},
|
||||
501,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,76 @@
|
||||
import { Hono } from 'hono'
|
||||
|
||||
import { manageAuth } from '../../middleware/manage-auth'
|
||||
|
||||
/**
|
||||
* 管理面 · 购买记录(契约 §2.3):清单 / 登记 / 编辑 / 删除 / 观测(核对提示)。
|
||||
* 登记必填:`kind` / `paid_at` / `paid_amount` / `quota_granted`。
|
||||
*/
|
||||
export const purchasesRoutes = new Hono()
|
||||
|
||||
purchasesRoutes.use(manageAuth)
|
||||
|
||||
/** 清单(按 paid_at DESC,同时间按 id DESC;不分页) */
|
||||
purchasesRoutes.get('/', (c) =>
|
||||
c.json(
|
||||
{
|
||||
error: {
|
||||
code: 'internal',
|
||||
message: '未实现:purchases 清单(见 docs/design/API契约.md §2.3)',
|
||||
},
|
||||
},
|
||||
501,
|
||||
),
|
||||
)
|
||||
|
||||
/** 观测(核对提示的数据面):按日志 other.subscription_id 聚合 */
|
||||
purchasesRoutes.get('/observations', (c) =>
|
||||
c.json(
|
||||
{
|
||||
error: {
|
||||
code: 'internal',
|
||||
message: '未实现:观测(见 docs/design/API契约.md §2.3)',
|
||||
},
|
||||
},
|
||||
501,
|
||||
),
|
||||
)
|
||||
|
||||
/** 登记 */
|
||||
purchasesRoutes.post('/', (c) =>
|
||||
c.json(
|
||||
{
|
||||
error: {
|
||||
code: 'internal',
|
||||
message: '未实现:登记购买记录(见 docs/design/API契约.md §2.3)',
|
||||
},
|
||||
},
|
||||
501,
|
||||
),
|
||||
)
|
||||
|
||||
/** 编辑(部分更新) */
|
||||
purchasesRoutes.patch('/:id', (c) =>
|
||||
c.json(
|
||||
{
|
||||
error: {
|
||||
code: 'internal',
|
||||
message: '未实现:编辑购买记录(见 docs/design/API契约.md §2.3)',
|
||||
},
|
||||
},
|
||||
501,
|
||||
),
|
||||
)
|
||||
|
||||
/** 删除(物理) */
|
||||
purchasesRoutes.delete('/:id', (c) =>
|
||||
c.json(
|
||||
{
|
||||
error: {
|
||||
code: 'internal',
|
||||
message: '未实现:删除购买记录(见 docs/design/API契约.md §2.3)',
|
||||
},
|
||||
},
|
||||
501,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Hono } from 'hono'
|
||||
|
||||
import { manageAuth } from '../../middleware/manage-auth'
|
||||
|
||||
/**
|
||||
* 管理面 · 换算参数时间线(契约 §2.4):纯只读——`qpu_history` 唯一写入者是同步引擎。
|
||||
*/
|
||||
export const qpuRoutes = new Hono()
|
||||
|
||||
qpuRoutes.use(manageAuth)
|
||||
|
||||
/** 时间线清单(按 effective_from 升序;不分页) */
|
||||
qpuRoutes.get('/', (c) =>
|
||||
c.json(
|
||||
{
|
||||
error: {
|
||||
code: 'internal',
|
||||
message: '未实现:QPU 时间线(见 docs/design/API契约.md §2.4)',
|
||||
},
|
||||
},
|
||||
501,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,31 @@
|
||||
import { Hono } from 'hono'
|
||||
|
||||
/**
|
||||
* 查看面(契约 §2.1):无会话、无服务端状态——key 集合与过滤参数全在请求体。
|
||||
* 两个端点:`/logs/query`(明细,分页)· `/summary`(卡片汇总);首次并行请求,翻页只调明细。
|
||||
*/
|
||||
export const usageRoutes = new Hono()
|
||||
|
||||
usageRoutes.post('/logs/query', (c) =>
|
||||
c.json(
|
||||
{
|
||||
error: {
|
||||
code: 'internal',
|
||||
message: '未实现:明细查询(见 docs/design/API契约.md §2.1)',
|
||||
},
|
||||
},
|
||||
501,
|
||||
),
|
||||
)
|
||||
|
||||
usageRoutes.post('/summary', (c) =>
|
||||
c.json(
|
||||
{
|
||||
error: {
|
||||
code: 'internal',
|
||||
message: '未实现:卡片汇总(见 docs/design/API契约.md §2.1)',
|
||||
},
|
||||
},
|
||||
501,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* 同步引擎(见 `docs/design/同步引擎设计.md`)——骨架占位。
|
||||
*
|
||||
* 已定骨架(§3.2 / §3.3 / §3.4):
|
||||
* - 后端进程内定时器(不引 worker、不拆进程)
|
||||
* - 周期 5 分钟,固定 tick + 防重入
|
||||
* - 启动立即跑一轮
|
||||
* - 单轮串行遍历全部 active key
|
||||
* - 每轮:日志(整批单事务入库 → log_synced_at 取请求发起时刻)· 额度(上游字段全组 + usage_synced_at)· QPU 采样(每轮一次、值变化才追加)
|
||||
* - 失败:401 计数(N=3 摘除)· 403/500/网络不计数 · 不单轮重试
|
||||
*/
|
||||
|
||||
const TICK_MS = 5 * 60 * 1000
|
||||
|
||||
let running = false
|
||||
|
||||
/** 一轮:遍历全部 active key(串行)→ 日志 / 额度;每轮一次 QPU 采样 */
|
||||
async function runOnce(): Promise<void> {
|
||||
// TODO(#5): 日志同步 —— GET /api/log/token → 整批单事务入库(ON CONFLICT (dedupe_key) DO NOTHING)→ 写 log_synced_at
|
||||
// TODO(#6): 额度采集 —— GET /api/usage/token → 上游字段全组 + usage_synced_at(与日志各自独立)
|
||||
// TODO(#7): QPU 采样 —— GET /api/status → 值变化才追加 qpu_history(每轮一次,独立于 key 循环)
|
||||
}
|
||||
|
||||
async function tick(): Promise<void> {
|
||||
if (running) {
|
||||
console.log('[sync] 上一轮未结束,跳过本轮(防重入)')
|
||||
return
|
||||
}
|
||||
running = true
|
||||
try {
|
||||
await runOnce()
|
||||
console.log('[sync] 轮次完成(骨架占位:暂无实际采集动作)')
|
||||
} catch (err) {
|
||||
console.error('[sync] 轮次异常', err)
|
||||
} finally {
|
||||
running = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 启动引擎:立即跑一轮,随后每 5 分钟一次 */
|
||||
export function startSyncEngine(): void {
|
||||
console.log('[sync] 引擎启动:立即跑一轮,随后每 5 分钟一次')
|
||||
void tick()
|
||||
setInterval(() => void tick(), TICK_MS)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "esnext",
|
||||
"module": "preserve",
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"skipLibCheck": true,
|
||||
"types": ["bun"],
|
||||
"jsx": "react-jsx",
|
||||
"jsxImportSource": "hono/jsx"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
[*.{js,jsx,mjs,cjs,ts,tsx,mts,cts,vue,css,scss,sass,less,styl}]
|
||||
charset = utf-8
|
||||
indent_size = 2
|
||||
indent_style = space
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
end_of_line = lf
|
||||
max_line_length = 100
|
||||
@@ -0,0 +1 @@
|
||||
* text=auto eol=lf
|
||||
@@ -0,0 +1,39 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
.DS_Store
|
||||
dist
|
||||
dist-ssr
|
||||
coverage
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
*.tsbuildinfo
|
||||
|
||||
.eslintcache
|
||||
|
||||
# Cypress
|
||||
/cypress/videos/
|
||||
/cypress/screenshots/
|
||||
|
||||
# Vitest
|
||||
__screenshots__/
|
||||
|
||||
# Vite
|
||||
*.timestamp-*-*.mjs
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["eslint", "typescript", "unicorn", "oxc", "vue", "vitest"],
|
||||
"env": {
|
||||
"browser": true
|
||||
},
|
||||
"categories": {
|
||||
"correctness": "error"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/prettierrc",
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"printWidth": 100
|
||||
}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,32 @@
|
||||
import { globalIgnores } from 'eslint/config'
|
||||
import { defineConfigWithVueTs, vueTsConfigs } from '@vue/eslint-config-typescript'
|
||||
import pluginVue from 'eslint-plugin-vue'
|
||||
import pluginVitest from '@vitest/eslint-plugin'
|
||||
import pluginOxlint from 'eslint-plugin-oxlint'
|
||||
import skipFormatting from 'eslint-config-prettier/flat'
|
||||
|
||||
// To allow more languages other than `ts` in `.vue` files, uncomment the following lines:
|
||||
// import { configureVueProject } from '@vue/eslint-config-typescript'
|
||||
// configureVueProject({ scriptLangs: ['ts', 'tsx'] })
|
||||
// More info at https://github.com/vuejs/eslint-config-typescript/#advanced-setup
|
||||
|
||||
export default defineConfigWithVueTs(
|
||||
{
|
||||
name: 'app/files-to-lint',
|
||||
files: ['**/*.{vue,ts,mts,tsx}'],
|
||||
},
|
||||
|
||||
globalIgnores(['**/dist/**', '**/dist-ssr/**', '**/coverage/**']),
|
||||
|
||||
...pluginVue.configs['flat/essential'],
|
||||
vueTsConfigs.recommended,
|
||||
|
||||
{
|
||||
...pluginVitest.configs.recommended,
|
||||
files: ['src/**/__tests__/*'],
|
||||
},
|
||||
|
||||
...pluginOxlint.buildFromOxlintConfigFile('.oxlintrc.json'),
|
||||
|
||||
skipFormatting,
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Vite App</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"name": "@naku/web",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "run-p type-check \"build-only {@}\" --",
|
||||
"preview": "vite preview",
|
||||
"test:unit": "vitest",
|
||||
"build-only": "vite build",
|
||||
"type-check": "vue-tsc --build",
|
||||
"lint": "run-s \"lint:*\"",
|
||||
"lint:oxlint": "oxlint . --fix",
|
||||
"lint:eslint": "eslint . --fix --cache",
|
||||
"format": "prettier --write --experimental-cli src/"
|
||||
},
|
||||
"dependencies": {
|
||||
"@naku/shared": "workspace:*",
|
||||
"naive-ui": "^2.45.3",
|
||||
"vue": "^3.5.40",
|
||||
"vue-router": "^5.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tsconfig/node24": "^24.0.4",
|
||||
"@types/jsdom": "^28.0.3",
|
||||
"@types/node": "^24.13.3",
|
||||
"@vitejs/plugin-vue": "^6.0.8",
|
||||
"@vitest/eslint-plugin": "^1.6.23",
|
||||
"@vue/eslint-config-typescript": "^14.9.0",
|
||||
"@vue/test-utils": "^2.4.11",
|
||||
"@vue/tsconfig": "^0.9.1",
|
||||
"eslint": "^10.7.0",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-plugin-oxlint": "~1.73.0",
|
||||
"eslint-plugin-vue": "~10.9.2",
|
||||
"jiti": "^2.7.0",
|
||||
"jsdom": "^29.1.1",
|
||||
"npm-run-all2": "^9.0.2",
|
||||
"oxlint": "~1.74.0",
|
||||
"prettier": "3.9.5",
|
||||
"typescript": "~6.0.0",
|
||||
"unplugin-auto-import": "^21.1.0",
|
||||
"unplugin-vue-components": "^32.1.0",
|
||||
"vite": "^8.1.5",
|
||||
"vite-plugin-vue-devtools": "^8.1.5",
|
||||
"vitest": "^4.1.10",
|
||||
"vue-eslint-parser": "^10.4.1",
|
||||
"vue-tsc": "^3.3.7"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.18.0 || >=24.12.0"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
@@ -0,0 +1,34 @@
|
||||
<script setup lang="ts">
|
||||
// 根组件:全局 provider(message / dialog / notification)+ 路由出口
|
||||
import { RouterView } from 'vue-router'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<n-message-provider>
|
||||
<n-dialog-provider>
|
||||
<n-notification-provider>
|
||||
<RouterView />
|
||||
</n-notification-provider>
|
||||
</n-dialog-provider>
|
||||
</n-message-provider>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
/* 全局基础样式(浅色单主题,交互设计 §2 #2) */
|
||||
html,
|
||||
body,
|
||||
#app {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family:
|
||||
system-ui,
|
||||
-apple-system,
|
||||
'Segoe UI',
|
||||
'PingFang SC',
|
||||
'Microsoft YaHei',
|
||||
sans-serif;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import router from '@/router'
|
||||
|
||||
describe('router', () => {
|
||||
it('路由表包含查看面与管理面三页', () => {
|
||||
const paths = router.getRoutes().map((r) => r.path)
|
||||
for (const p of ['/usage-log', '/manage/api-keys', '/manage/purchases', '/manage/qpu']) {
|
||||
expect(paths).toContain(p)
|
||||
}
|
||||
})
|
||||
|
||||
it(
|
||||
'根路径重定向到 /usage-log(真实导航;首次含懒加载组件转换,放宽超时)',
|
||||
async () => {
|
||||
await router.push('/')
|
||||
expect(router.currentRoute.value.path).toBe('/usage-log')
|
||||
},
|
||||
20_000,
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* API 客户端(契约 约定 20 / 24):
|
||||
* - 成功 = 裸数据体;失败 = `{ error: { code, message } }`(非 2xx)
|
||||
* - 管理面请求自动附加 `X-Manage-Token`(存 sessionStorage,关标签即忘)
|
||||
* - 401 `manage_unauthorized` → 通知口令门帘(ManageLayout 监听)
|
||||
*/
|
||||
import { MANAGE_TOKEN_HEADER, type ApiErrorBody } from '@naku/shared'
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
readonly code: string,
|
||||
readonly status: number,
|
||||
message: string,
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'ApiError'
|
||||
}
|
||||
}
|
||||
|
||||
const MANAGE_TOKEN_KEY = 'naku:manage-token'
|
||||
|
||||
export function getManageToken(): string {
|
||||
return sessionStorage.getItem(MANAGE_TOKEN_KEY) ?? ''
|
||||
}
|
||||
|
||||
export function setManageToken(token: string): void {
|
||||
sessionStorage.setItem(MANAGE_TOKEN_KEY, token)
|
||||
}
|
||||
|
||||
export function clearManageToken(): void {
|
||||
sessionStorage.removeItem(MANAGE_TOKEN_KEY)
|
||||
}
|
||||
|
||||
/** 口令失效通知(订阅返回取消函数) */
|
||||
const unauthorizedListeners = new Set<() => void>()
|
||||
|
||||
export function onManageUnauthorized(fn: () => void): () => void {
|
||||
unauthorizedListeners.add(fn)
|
||||
return () => {
|
||||
unauthorizedListeners.delete(fn)
|
||||
}
|
||||
}
|
||||
|
||||
interface RequestOptions {
|
||||
method?: 'GET' | 'POST' | 'PATCH' | 'DELETE'
|
||||
body?: unknown
|
||||
/** 管理面请求:附加 X-Manage-Token */
|
||||
manage?: boolean
|
||||
}
|
||||
|
||||
export async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
|
||||
const { method = 'GET', body, manage = false } = options
|
||||
|
||||
const headers: Record<string, string> = {}
|
||||
if (body !== undefined) headers['content-type'] = 'application/json'
|
||||
if (manage) headers[MANAGE_TOKEN_HEADER] = getManageToken()
|
||||
|
||||
const res = await fetch(path, {
|
||||
method,
|
||||
headers,
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
// 失败体未必是我们的 JSON(反代 502 / 网关错误页)——兜底解析
|
||||
const parsed = (await res.json().catch(() => null)) as ApiErrorBody | null
|
||||
const code = parsed?.error?.code ?? 'unknown'
|
||||
const message = parsed?.error?.message ?? `HTTP ${res.status}`
|
||||
if (manage && res.status === 401 && code === 'manage_unauthorized') {
|
||||
unauthorizedListeners.forEach((fn) => fn())
|
||||
}
|
||||
throw new ApiError(code, res.status, message)
|
||||
}
|
||||
|
||||
return (await res.json()) as T
|
||||
}
|
||||
|
||||
// ---- 查看面(无会话;key 集合随请求体,契约 约定 5 / 19) ----
|
||||
|
||||
export const api = {
|
||||
usageLogsQuery: <T>(body: unknown) => request<T>('/api/usage/logs/query', { method: 'POST', body }),
|
||||
usageSummary: <T>(body: unknown) => request<T>('/api/usage/summary', { method: 'POST', body }),
|
||||
|
||||
// ---- 管理面(manage: true 自动带口令) ----
|
||||
apiKeysList: <T>() => request<T>('/api/manage/api-keys', { manage: true }),
|
||||
apiKeyRegister: <T>(body: unknown) =>
|
||||
request<T>('/api/manage/api-keys', { method: 'POST', body, manage: true }),
|
||||
apiKeyPatch: <T>(id: number, body: unknown) =>
|
||||
request<T>(`/api/manage/api-keys/${id}`, { method: 'PATCH', body, manage: true }),
|
||||
|
||||
purchasesList: <T>() => request<T>('/api/manage/purchases', { manage: true }),
|
||||
purchasesCreate: <T>(body: unknown) =>
|
||||
request<T>('/api/manage/purchases', { method: 'POST', body, manage: true }),
|
||||
purchasesPatch: <T>(id: number, body: unknown) =>
|
||||
request<T>(`/api/manage/purchases/${id}`, { method: 'PATCH', body, manage: true }),
|
||||
purchasesDelete: <T>(id: number) =>
|
||||
request<T>(`/api/manage/purchases/${id}`, { method: 'DELETE', manage: true }),
|
||||
purchasesObservations: <T>() => request<T>('/api/manage/purchases/observations', { manage: true }),
|
||||
|
||||
qpuList: <T>() => request<T>('/api/manage/qpu', { manage: true }),
|
||||
}
|
||||
Vendored
+15
@@ -0,0 +1,15 @@
|
||||
/* eslint-disable */
|
||||
/* prettier-ignore */
|
||||
/* oxlint-disable */
|
||||
/* oxfmt-ignore */
|
||||
// @ts-nocheck
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
// Generated by unplugin-auto-import
|
||||
// biome-ignore lint: disable
|
||||
export {}
|
||||
declare global {
|
||||
const useDialog: typeof import('naive-ui').useDialog
|
||||
const useLoadingBar: typeof import('naive-ui').useLoadingBar
|
||||
const useMessage: typeof import('naive-ui').useMessage
|
||||
const useNotification: typeof import('naive-ui').useNotification
|
||||
}
|
||||
Vendored
+30
@@ -0,0 +1,30 @@
|
||||
/* eslint-disable */
|
||||
// @ts-nocheck
|
||||
// biome-ignore lint: disable
|
||||
// oxlint-disable
|
||||
// ------
|
||||
// Generated by unplugin-vue-components
|
||||
// Read more: https://github.com/vuejs/core/pull/3399
|
||||
|
||||
export {}
|
||||
|
||||
/* prettier-ignore */
|
||||
declare module 'vue' {
|
||||
export interface GlobalComponents {
|
||||
NButton: typeof import('naive-ui')['NButton']
|
||||
NCard: typeof import('naive-ui')['NCard']
|
||||
NDialogProvider: typeof import('naive-ui')['NDialogProvider']
|
||||
NEmpty: typeof import('naive-ui')['NEmpty']
|
||||
NInput: typeof import('naive-ui')['NInput']
|
||||
NLayout: typeof import('naive-ui')['NLayout']
|
||||
NLayoutContent: typeof import('naive-ui')['NLayoutContent']
|
||||
NLayoutSider: typeof import('naive-ui')['NLayoutSider']
|
||||
NMenu: typeof import('naive-ui')['NMenu']
|
||||
NMessageProvider: typeof import('naive-ui')['NMessageProvider']
|
||||
NNotificationProvider: typeof import('naive-ui')['NNotificationProvider']
|
||||
NSpace: typeof import('naive-ui')['NSpace']
|
||||
NText: typeof import('naive-ui')['NText']
|
||||
RouterLink: typeof import('vue-router')['RouterLink']
|
||||
RouterView: typeof import('vue-router')['RouterView']
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
|
||||
const app = createApp(App)
|
||||
|
||||
app.use(router)
|
||||
|
||||
app.mount('#app')
|
||||
@@ -0,0 +1,42 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
|
||||
/**
|
||||
* 路由(交互设计 §0.1 / §1):
|
||||
* - 无前缀 = 查看面(一期仅 `/usage-log`,`/` 重定向到它;二期候选 `/dashboard`)
|
||||
* - `/manage` 前缀 = 管理面(口令门帘由 ManageLayout 承担;入口在查看面不暴露)
|
||||
*/
|
||||
const router = createRouter({
|
||||
history: createWebHistory(import.meta.env.BASE_URL),
|
||||
routes: [
|
||||
{ path: '/', redirect: '/usage-log' },
|
||||
{
|
||||
path: '/usage-log',
|
||||
name: 'usage-log',
|
||||
component: () => import('@/views/UsageLogView.vue'),
|
||||
},
|
||||
{
|
||||
path: '/manage',
|
||||
component: () => import('@/views/manage/ManageLayout.vue'),
|
||||
children: [
|
||||
{ path: '', redirect: '/manage/api-keys' },
|
||||
{
|
||||
path: 'api-keys',
|
||||
name: 'manage-api-keys',
|
||||
component: () => import('@/views/manage/ApiKeysView.vue'),
|
||||
},
|
||||
{
|
||||
path: 'purchases',
|
||||
name: 'manage-purchases',
|
||||
component: () => import('@/views/manage/PurchasesView.vue'),
|
||||
},
|
||||
{
|
||||
path: 'qpu',
|
||||
name: 'manage-qpu',
|
||||
component: () => import('@/views/manage/QpuView.vue'),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,20 @@
|
||||
<script setup lang="ts">
|
||||
// 用量日志页(交互设计 §3.1)——骨架占位:
|
||||
// 筛选区(key 标签输入 + datetimerange + 查询)→ 卡片区(次数 / 用量 / 消费)→ 未收录提示 → 明细表格 + 分页器
|
||||
// 数据形状见 docs/design/API契约.md §2.1
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="usage-log">
|
||||
<h1>用量日志</h1>
|
||||
<n-empty description="骨架占位——页面结构见 docs/design/交互设计.md §3.1" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.usage-log {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 24px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
// key 管理页(交互设计 §3.2)——骨架占位:
|
||||
// 清单 8 列(key 名 / 状态徽章 / 已用 / 剩余 / 到期 / 登记时间 / 数据截止 / 操作)
|
||||
// 登记:页头「+ 登记 key」→ n-modal;启停:行内按钮(停用弹确认、启用直接执行)
|
||||
// 数据形状见 docs/design/API契约.md §2.2
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="api-keys">
|
||||
<h2>key 管理</h2>
|
||||
<n-empty description="骨架占位——页面结构见 docs/design/交互设计.md §3.2" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,140 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 管理面布局(交互设计 §2 #7 + 口令门帘细节):
|
||||
* - 未验证:全屏居中卡片(口令 + 「进入」)——校验直接用管理面请求,401 即口令错
|
||||
* - 已验证:侧边栏菜单(三页)+ 内容区;底部「← 查看面」
|
||||
* - 口令存 sessionStorage(关标签即忘);401 时自动退回门帘
|
||||
*/
|
||||
import { onMounted, onUnmounted, ref } from 'vue'
|
||||
import { RouterView, useRoute, useRouter } from 'vue-router'
|
||||
|
||||
import {
|
||||
ApiError,
|
||||
api,
|
||||
clearManageToken,
|
||||
getManageToken,
|
||||
onManageUnauthorized,
|
||||
setManageToken,
|
||||
} from '@/api/client'
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
|
||||
const unlocked = ref(false)
|
||||
const checking = ref(false)
|
||||
const tokenInput = ref('')
|
||||
const errorText = ref('')
|
||||
|
||||
async function verifyAndUnlock(): Promise<void> {
|
||||
checking.value = true
|
||||
errorText.value = ''
|
||||
try {
|
||||
await api.apiKeysList()
|
||||
unlocked.value = true
|
||||
} catch (err) {
|
||||
clearManageToken()
|
||||
errorText.value =
|
||||
err instanceof ApiError && err.code === 'manage_unauthorized'
|
||||
? '口令不正确'
|
||||
: '校验失败,请稍后重试'
|
||||
unlocked.value = false
|
||||
} finally {
|
||||
checking.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function tryUnlock(): Promise<void> {
|
||||
if (!tokenInput.value) {
|
||||
errorText.value = '请输入口令'
|
||||
return
|
||||
}
|
||||
setManageToken(tokenInput.value)
|
||||
await verifyAndUnlock()
|
||||
}
|
||||
|
||||
let off: (() => void) | null = null
|
||||
|
||||
onMounted(() => {
|
||||
off = onManageUnauthorized(() => {
|
||||
unlocked.value = false
|
||||
errorText.value = '口令已失效,请重新输入'
|
||||
})
|
||||
if (getManageToken()) {
|
||||
void verifyAndUnlock()
|
||||
}
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
off?.()
|
||||
})
|
||||
|
||||
const menuOptions = [
|
||||
{ label: 'key 管理', key: 'manage-api-keys' },
|
||||
{ label: '购买记录', key: 'manage-purchases' },
|
||||
{ label: '换算参数', key: 'manage-qpu' },
|
||||
]
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="!unlocked" class="gate">
|
||||
<n-card class="gate-card" title="管理通道">
|
||||
<n-space vertical :size="16">
|
||||
<n-input
|
||||
v-model:value="tokenInput"
|
||||
type="password"
|
||||
show-password-on="click"
|
||||
placeholder="部署口令"
|
||||
@keyup.enter="tryUnlock"
|
||||
/>
|
||||
<n-text v-if="errorText" type="error">{{ errorText }}</n-text>
|
||||
<n-button type="primary" block :loading="checking" @click="tryUnlock">进入</n-button>
|
||||
</n-space>
|
||||
</n-card>
|
||||
</div>
|
||||
|
||||
<n-layout v-else has-sider class="manage">
|
||||
<n-layout-sider bordered :width="200">
|
||||
<div class="sider">
|
||||
<n-menu
|
||||
:value="String(route.name ?? '')"
|
||||
:options="menuOptions"
|
||||
@update:value="(key: string) => router.push({ name: key })"
|
||||
/>
|
||||
<n-button text class="back" @click="router.push('/usage-log')">← 查看面</n-button>
|
||||
</div>
|
||||
</n-layout-sider>
|
||||
<n-layout-content class="content">
|
||||
<RouterView />
|
||||
</n-layout-content>
|
||||
</n-layout>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.gate {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100vh;
|
||||
}
|
||||
.gate-card {
|
||||
width: 360px;
|
||||
}
|
||||
.manage {
|
||||
height: 100vh;
|
||||
}
|
||||
.sider {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
height: 100%;
|
||||
padding: 16px 0;
|
||||
}
|
||||
.back {
|
||||
margin-left: 24px;
|
||||
align-self: flex-start;
|
||||
}
|
||||
.content {
|
||||
padding: 24px;
|
||||
overflow: auto;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
// 购买记录页(交互设计 §3.3)——骨架占位:
|
||||
// 清单 8 列 + 核对提示(未登记观测提示条 + 折叠区 + 补录)+ 登记/编辑用右侧 n-drawer
|
||||
// 数据形状见 docs/design/API契约.md §2.3
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="purchases">
|
||||
<h2>购买记录</h2>
|
||||
<n-empty description="骨架占位——页面结构见 docs/design/交互设计.md §3.3" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
// 换算参数时间线页(交互设计 §3.3)——骨架占位:
|
||||
// 表格两列(生效时间 / QPU 值)+「当前生效」标记 + 页首说明文案;纯只读
|
||||
// 数据形状见 docs/design/API契约.md §2.4
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="qpu">
|
||||
<h2>换算参数时间线</h2>
|
||||
<n-empty description="骨架占位——页面结构见 docs/design/交互设计.md §3.3" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"extends": "@vue/tsconfig/tsconfig.dom.json",
|
||||
"include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
|
||||
"exclude": ["src/**/__tests__/*"],
|
||||
"compilerOptions": {
|
||||
// Extra safety for array and object lookups, but may have false positives.
|
||||
"noUncheckedIndexedAccess": true,
|
||||
|
||||
// Path mapping for cleaner imports.
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
},
|
||||
|
||||
// `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking.
|
||||
// Specified here to keep it out of the root directory.
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.node.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.app.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.vitest.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// TSConfig for modules that run in Node.js environment via either transpilation or type-stripping.
|
||||
{
|
||||
"extends": "@tsconfig/node24/tsconfig.json",
|
||||
"include": [
|
||||
"vite.config.*",
|
||||
"vitest.config.*",
|
||||
"cypress.config.*",
|
||||
"playwright.config.*",
|
||||
"eslint.config.*"
|
||||
],
|
||||
"compilerOptions": {
|
||||
// Most tools use transpilation instead of Node.js's native type-stripping.
|
||||
// Bundler mode provides a smoother developer experience.
|
||||
"module": "preserve",
|
||||
"moduleResolution": "bundler",
|
||||
|
||||
// Include Node.js types and avoid accidentally including other `@types/*` packages.
|
||||
"types": ["node"],
|
||||
|
||||
// Disable emitting output during `vue-tsc --build`, which is used for type-checking only.
|
||||
"noEmit": true,
|
||||
|
||||
// `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking.
|
||||
// Specified here to keep it out of the root directory.
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"extends": "./tsconfig.app.json",
|
||||
|
||||
// Override to include only test files and clear exclusions.
|
||||
// Application code imported in tests is automatically included via module resolution.
|
||||
"include": ["src/**/__tests__/*", "env.d.ts"],
|
||||
"exclude": [],
|
||||
|
||||
"compilerOptions": {
|
||||
// Vitest runs in a different environment than the application code.
|
||||
// Adjust lib and types accordingly.
|
||||
"lib": [],
|
||||
"types": ["node", "jsdom"],
|
||||
|
||||
// `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking.
|
||||
// Specified here to keep it out of the root directory.
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.vitest.tsbuildinfo"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { fileURLToPath, URL } from 'node:url'
|
||||
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
import AutoImport from 'unplugin-auto-import/vite'
|
||||
import Components from 'unplugin-vue-components/vite'
|
||||
import { NaiveUiResolver } from 'unplugin-vue-components/resolvers'
|
||||
import { defineConfig } from 'vite'
|
||||
import vueDevTools from 'vite-plugin-vue-devtools'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
vue(),
|
||||
vueDevTools(),
|
||||
// naive-ui 按需引入(交互设计 §2 #3)
|
||||
AutoImport({
|
||||
imports: [
|
||||
{
|
||||
'naive-ui': ['useDialog', 'useMessage', 'useNotification', 'useLoadingBar'],
|
||||
},
|
||||
],
|
||||
dts: 'src/auto-imports.d.ts',
|
||||
}),
|
||||
Components({
|
||||
resolvers: [NaiveUiResolver()],
|
||||
dts: 'src/components.d.ts',
|
||||
}),
|
||||
],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
proxy: {
|
||||
// 开发期把 /api 代理到后端;生产由同域反代承担(见 README 工程注记)
|
||||
'/api': {
|
||||
target: 'http://localhost:3000',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,14 @@
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { mergeConfig, defineConfig, configDefaults } from 'vitest/config'
|
||||
import viteConfig from './vite.config'
|
||||
|
||||
export default mergeConfig(
|
||||
viteConfig,
|
||||
defineConfig({
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
exclude: [...configDefaults.exclude, 'e2e/**'],
|
||||
root: fileURLToPath(new URL('./', import.meta.url)),
|
||||
},
|
||||
}),
|
||||
)
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "new-api-key-usage",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"workspaces": [
|
||||
"apps/*",
|
||||
"packages/*"
|
||||
],
|
||||
"scripts": {
|
||||
"dev": "bun run --filter '*' dev",
|
||||
"dev:web": "bun run --filter '@naku/web' dev",
|
||||
"dev:server": "bun run --filter '@naku/server' dev",
|
||||
"build": "bun run --filter '@naku/web' build",
|
||||
"test": "bun run --filter '@naku/web' test:unit",
|
||||
"lint": "bun run --filter '@naku/web' lint",
|
||||
"format": "bun run --filter '@naku/web' format",
|
||||
"type-check": "bun run --filter '@naku/web' type-check && bunx tsc --noEmit -p apps/server",
|
||||
"db:generate": "bun run --filter '@naku/server' db:generate",
|
||||
"db:migrate": "bun run --filter '@naku/server' db:migrate",
|
||||
"db:push": "bun run --filter '@naku/server' db:push"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^6.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"name": "@naku/shared",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* 契约常量 —— 与 `docs/design/API契约.md` 保持同步。
|
||||
*/
|
||||
|
||||
/** 明细分页:默认每页条数(契约 §2.1 请求参数) */
|
||||
export const LOGS_DEFAULT_LIMIT = 50
|
||||
|
||||
/** 明细分页:每页条数上限 */
|
||||
export const LOGS_MAX_LIMIT = 200
|
||||
|
||||
/** 每页条数选择器的可选值 */
|
||||
export const LOGS_LIMIT_OPTIONS = [20, 50, 100, 200] as const
|
||||
|
||||
/** 单次查询的 key 集合上限(初值,技术稿可调) */
|
||||
export const KEYS_MAX = 20
|
||||
|
||||
/** 日志类型(上游 model/log.go;常量注释明确「刻意不用 iota」,枚举值永不改变) */
|
||||
export const LOG_TYPE = {
|
||||
Unknown: 0,
|
||||
Topup: 1,
|
||||
Consume: 2,
|
||||
Manage: 3,
|
||||
System: 4,
|
||||
Error: 5,
|
||||
Refund: 6,
|
||||
Login: 7,
|
||||
} as const
|
||||
|
||||
/** 日志类型的中文标签(展示层用;未知值原样显示数字) */
|
||||
export const LOG_TYPE_LABEL: Record<number, string> = {
|
||||
[LOG_TYPE.Unknown]: '未知',
|
||||
[LOG_TYPE.Topup]: '充值',
|
||||
[LOG_TYPE.Consume]: '消费',
|
||||
[LOG_TYPE.Manage]: '管理',
|
||||
[LOG_TYPE.System]: '系统',
|
||||
[LOG_TYPE.Error]: '错误',
|
||||
[LOG_TYPE.Refund]: '退款',
|
||||
[LOG_TYPE.Login]: '登录',
|
||||
}
|
||||
|
||||
/** 额度美元换算的出厂默认(仅兜底展示;实际取值一律从 qpu_history 时间线来) */
|
||||
export const DEFAULT_QUOTA_PER_UNIT = 500000
|
||||
|
||||
/** 管理面请求头(契约 约定 6) */
|
||||
export const MANAGE_TOKEN_HEADER = 'x-manage-token'
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './types'
|
||||
export * from './constants'
|
||||
@@ -0,0 +1,223 @@
|
||||
/**
|
||||
* API 契约类型 —— 与 `docs/design/API契约.md` 保持同步(全链路 snake_case,契约 约定 3)。
|
||||
* 字段集稳定:可空列返回 `null` 而非省略(约定「字段集稳定」)。
|
||||
*/
|
||||
|
||||
// ---------- 通用:错误与元信息 ----------
|
||||
|
||||
/** 错误码枚举(契约 约定 21) */
|
||||
export type ApiErrorCode =
|
||||
| 'invalid_params'
|
||||
| 'manage_unauthorized'
|
||||
| 'not_found'
|
||||
| 'internal'
|
||||
| 'key_rejected'
|
||||
| 'already_registered'
|
||||
| 'upstream_unavailable'
|
||||
|
||||
/** 失败响应体(约定 20:非 2xx + error 信封) */
|
||||
export interface ApiErrorBody {
|
||||
error: {
|
||||
code: ApiErrorCode | (string & {})
|
||||
message: string
|
||||
}
|
||||
}
|
||||
|
||||
/** 查看面查询响应统一携带的 meta(约定 22) */
|
||||
export interface QueryMetaKeyRegistered {
|
||||
key_id: number
|
||||
token_name: string
|
||||
registered: true
|
||||
status: 'active' | 'disabled'
|
||||
/** 该 key 自己的同步进度(新登记未首同步时为 null) */
|
||||
log_synced_at: string | null
|
||||
}
|
||||
|
||||
export interface QueryMetaKeyUnregistered {
|
||||
registered: false
|
||||
/** 即时生成、不落库:`sk-…a1b2` */
|
||||
key_hint: string
|
||||
}
|
||||
|
||||
export type QueryMetaKey = QueryMetaKeyRegistered | QueryMetaKeyUnregistered
|
||||
|
||||
export interface QueryMeta {
|
||||
/** 参与 key 中最慢的 log_synced_at(取非 null 的最慢值);全部未同步时为 null */
|
||||
data_until: string | null
|
||||
served_at: string
|
||||
keys: QueryMetaKey[]
|
||||
}
|
||||
|
||||
// ---------- /usage-log ----------
|
||||
|
||||
/** 日志类型(上游 model/log.go 的稳定枚举,照存不过滤) */
|
||||
export type LogType = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7
|
||||
|
||||
/** 日志行的 `other`(实测 26 键中的常用项;完整键集合见 docs/upstream 实测记录) */
|
||||
export interface LogOther {
|
||||
billing_source?: 'subscription' | 'wallet'
|
||||
cache_tokens?: number
|
||||
model_ratio?: number
|
||||
request_path?: string
|
||||
subscription_id?: number
|
||||
subscription_plan_title?: string
|
||||
subscription_total?: number
|
||||
subscription_used?: number
|
||||
subscription_remain?: number
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
/** 明细行 = `usage_logs` 表 1:1(除内部列 `dedupe_key`)+ 计算字段 */
|
||||
export interface UsageLogRow {
|
||||
id: number
|
||||
key_id: number
|
||||
user_id: number
|
||||
username: string
|
||||
created_at: string
|
||||
type: LogType
|
||||
content: string
|
||||
/** 当前名(join api_keys),非日志快照名 */
|
||||
token_name: string
|
||||
model_name: string
|
||||
quota: number
|
||||
prompt_tokens: number
|
||||
completion_tokens: number
|
||||
use_time: number
|
||||
is_stream: boolean
|
||||
channel: number
|
||||
channel_name: string
|
||||
token_id: number
|
||||
group_name: string
|
||||
ip: string
|
||||
request_id: string
|
||||
upstream_request_id: string | null
|
||||
/** 该行折算实付人民币(错误行 quota = 0 → 0) */
|
||||
amount_rmb: number
|
||||
other: LogOther
|
||||
}
|
||||
|
||||
export interface LogsQueryRequest {
|
||||
/** 必填;去重后最多 KEYS_MAX 个 */
|
||||
keys: string[]
|
||||
/** 必填;ISO 8601(输出 +08:00,输入宽容),左闭右开 [start, end) */
|
||||
start: string
|
||||
end: string
|
||||
/** 可选;缺省 = 全部类型;只作用于本端点 */
|
||||
type?: number[]
|
||||
/** 可选;默认 50,上限 200 */
|
||||
limit?: number
|
||||
offset?: number
|
||||
}
|
||||
|
||||
export interface LogsQueryResponse {
|
||||
items: UsageLogRow[]
|
||||
total: number
|
||||
meta: QueryMeta
|
||||
}
|
||||
|
||||
export interface SummaryRequest {
|
||||
keys: string[]
|
||||
start: string
|
||||
end: string
|
||||
}
|
||||
|
||||
export interface SummaryResponse {
|
||||
request_count: number
|
||||
consume_count: number
|
||||
error_count: number
|
||||
prompt_tokens: number
|
||||
completion_tokens: number
|
||||
cache_tokens: number
|
||||
/** quota 合计(原值,供核对) */
|
||||
quota: number
|
||||
/** 折算实付人民币(跨期按购买期间分段累加) */
|
||||
amount_rmb: number
|
||||
meta: QueryMeta
|
||||
}
|
||||
|
||||
// ---------- /manage/api-keys ----------
|
||||
|
||||
/** 清单行 = `api_keys` 表 1:1(除 key_hash / key_ciphertext 两个永不出接口的敏感列) */
|
||||
export interface ApiKeyRow {
|
||||
id: number
|
||||
token_name: string
|
||||
status: 'active' | 'disabled'
|
||||
/** 停用来源(可辨「已失效」与「已停用」) */
|
||||
disabled_source: 'manual' | 'auto_401' | null
|
||||
consecutive_401s: number
|
||||
registered_at: string
|
||||
log_synced_at: string | null
|
||||
usage_synced_at: string | null
|
||||
total_granted: number
|
||||
total_used: number
|
||||
total_available: number
|
||||
unlimited_quota: boolean
|
||||
model_limits: Record<string, unknown>
|
||||
model_limits_enabled: boolean
|
||||
expires_at: string | null
|
||||
}
|
||||
|
||||
export interface RegisterApiKeyRequest {
|
||||
key: string
|
||||
}
|
||||
|
||||
export interface PatchApiKeyRequest {
|
||||
status: 'active' | 'disabled'
|
||||
}
|
||||
|
||||
// ---------- /manage/purchases ----------
|
||||
|
||||
export type PurchaseKind = 'subscription' | 'topup'
|
||||
|
||||
/** 清单行 = `purchases` 表 1:1(9 列) */
|
||||
export interface PurchaseRow {
|
||||
id: number
|
||||
kind: PurchaseKind
|
||||
paid_at: string
|
||||
paid_amount: number
|
||||
note: string | null
|
||||
period_start: string | null
|
||||
period_end: string | null
|
||||
subscription_id: number | null
|
||||
quota_granted: number | null
|
||||
}
|
||||
|
||||
/** 登记请求(必填:kind / paid_at / paid_amount / quota_granted) */
|
||||
export interface PurchaseCreateRequest {
|
||||
kind: PurchaseKind
|
||||
paid_at: string
|
||||
paid_amount: number
|
||||
quota_granted: number
|
||||
note?: string | null
|
||||
period_start?: string | null
|
||||
period_end?: string | null
|
||||
subscription_id?: number | null
|
||||
}
|
||||
|
||||
/** 编辑请求:部分更新语义(提交哪些改哪些) */
|
||||
export type PurchasePatchRequest = Partial<PurchaseCreateRequest>
|
||||
|
||||
/** 观测项(核对提示的数据面) */
|
||||
export interface ObservationItem {
|
||||
subscription_id: number
|
||||
plan_title: string | null
|
||||
observed_quota_total: number | null
|
||||
first_seen_at: string
|
||||
last_seen_at: string
|
||||
log_count: number
|
||||
/** null = 观测到但未登记(补录引导的目标) */
|
||||
matched_purchase_id: number | null
|
||||
}
|
||||
|
||||
export interface ObservationsResponse {
|
||||
items: ObservationItem[]
|
||||
}
|
||||
|
||||
// ---------- /manage/qpu ----------
|
||||
|
||||
/** 时间线行 = `qpu_history` 表 1:1(3 列,纯只读) */
|
||||
export interface QpuRow {
|
||||
id: number
|
||||
qpu: number
|
||||
effective_from: string
|
||||
}
|
||||
Reference in New Issue
Block a user