🏁 Final commit: Project Token Usage Viewer completed

This commit is contained in:
2026-01-21 14:21:43 +08:00
parent b967deb4b1
commit a77fcdd3dc
24 changed files with 1087 additions and 651 deletions

View File

@@ -1,12 +1,83 @@
import { existsSync, readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { createEnv } from '@t3-oss/env-core'
import { z } from 'zod'
/** 默认的 TOKEN_USAGE_URL */
const DEFAULT_TOKEN_USAGE_URL = 'http://10.0.1.1:8318/usage'
/**
* 从同目录的 .env 配置文件读取环境变量
*
* 优先级:
* 1. 系统环境变量 (process.env)
* 2. 可执行文件同目录的 .env 文件
* 3. 默认值
*/
function loadEnvFromFile(): Record<string, string> {
const result: Record<string, string> = {}
// 确定可执行文件所在目录
const execPath = process.execPath
const isBundled = !execPath.includes('node') && !execPath.includes('bun')
const baseDir = isBundled ? dirname(execPath) : process.cwd()
const envPath = join(baseDir, '.env')
// 如果 .env 文件存在,解析它
if (existsSync(envPath)) {
try {
const content = readFileSync(envPath, 'utf-8')
for (const line of content.split('\n')) {
const trimmed = line.trim()
// 跳过空行和注释
if (!trimmed || trimmed.startsWith('#')) continue
const eqIndex = trimmed.indexOf('=')
if (eqIndex > 0) {
const key = trimmed.slice(0, eqIndex).trim()
const value = trimmed.slice(eqIndex + 1).trim()
// 只设置不存在的环境变量
if (!process.env[key]) {
result[key] = value
}
}
}
} catch {
// 忽略读取错误
}
}
return result
}
// 加载配置文件中的环境变量
const fileEnv = loadEnvFromFile()
// 合并环境变量: process.env > fileEnv > 默认值
const mergedEnv: Record<string, string | undefined> = {
...process.env,
}
// 从文件填充缺失的变量
for (const [key, value] of Object.entries(fileEnv)) {
if (!mergedEnv[key]) {
mergedEnv[key] = value
}
}
// 如果仍然没有 TOKEN_USAGE_URL使用默认值
if (!mergedEnv.TOKEN_USAGE_URL) {
mergedEnv.TOKEN_USAGE_URL = DEFAULT_TOKEN_USAGE_URL
}
export const env = createEnv({
server: {},
server: {
TOKEN_USAGE_URL: z.string().url(),
},
clientPrefix: 'VITE_',
client: {
VITE_APP_TITLE: z.string().min(1).optional(),
},
runtimeEnv: process.env,
runtimeEnv: mergedEnv,
emptyStringAsUndefined: true,
})