Skip to content

Commit c8b71c8

Browse files
authored
chore: clean unused code and improve lint rule (#541)
* chore: lint fix and clean unused code Signed-off-by: Bob Du <i@bobdu.cc> * chore: improve lint fix Signed-off-by: Bob Du <i@bobdu.cc> * chore: improve lint fix Signed-off-by: Bob Du <i@bobdu.cc> --------- Signed-off-by: Bob Du <i@bobdu.cc>
1 parent 15d0504 commit c8b71c8

File tree

20 files changed

+61
-177
lines changed

20 files changed

+61
-177
lines changed

.eslintrc.cjs

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,6 @@
11
module.exports = {
22
root: true,
33
extends: ['@antfu'],
4-
rules: {
5-
'antfu/top-level-function': 'off',
6-
'@typescript-eslint/consistent-type-imports': 'off',
7-
'@stylistic/ts/member-delimiter-style': 'off',
8-
'@stylistic/ts/indent': 'off',
9-
'@stylistic/js/no-tabs': 'off',
10-
'vue/no-unused-refs': 'off',
11-
'import/newline-after-import': 'off',
12-
'unicorn/prefer-number-properties': 'off',
13-
},
144
ignorePatterns: [
155
'vite.config.ts',
166
'tsconfig.json',

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,4 @@ coverage
3030

3131
# Environment variables files
3232
/service/.env
33-
/docker-compose/nginx/html
33+
/docker-compose/nginx/html

service/src/chatgpt/index.ts

Lines changed: 0 additions & 106 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import * as console from 'node:console'
21
import * as dotenv from 'dotenv'
32
import 'isomorphic-fetch'
43
import type { ChatGPTAPIOptions, ChatMessage, SendMessageOptions } from 'chatgpt'
@@ -7,7 +6,6 @@ import { SocksProxyAgent } from 'socks-proxy-agent'
76
import httpsProxyAgent from 'https-proxy-agent'
87
import fetch from 'node-fetch'
98
import jwt_decode from 'jwt-decode'
10-
import dayjs from 'dayjs'
119
import type { AuditConfig, KeyConfig, UserInfo } from '../storage/model'
1210
import { Status } from '../storage/model'
1311
import { convertImageUrl } from '../utils/image'
@@ -241,112 +239,8 @@ async function containsSensitiveWords(audit: AuditConfig, text: string): Promise
241239
return false
242240
}
243241

244-
async function fetchAccessTokenExpiredTime() {
245-
const config = await getCacheConfig()
246-
const jwt = jwt_decode(config.accessToken) as JWT
247-
if (jwt.exp)
248-
return dayjs.unix(jwt.exp).format('YYYY-MM-DD HH:mm:ss')
249-
return '-'
250-
}
251-
252-
let cachedBalance: number | undefined
253-
let cacheExpiration = 0
254-
255-
async function fetchBalance() {
256-
const now = new Date().getTime()
257-
if (cachedBalance && cacheExpiration > now)
258-
return Promise.resolve(cachedBalance.toFixed(3))
259-
260-
// 计算起始日期和结束日期
261-
const startDate = new Date(now - 90 * 24 * 60 * 60 * 1000)
262-
const endDate = new Date(now + 24 * 60 * 60 * 1000)
263-
264-
const config = await getCacheConfig()
265-
const OPENAI_API_KEY = config.apiKey
266-
const OPENAI_API_BASE_URL = config.apiBaseUrl
267-
268-
if (!isNotEmptyString(OPENAI_API_KEY))
269-
return Promise.resolve('-')
270-
271-
const API_BASE_URL = isNotEmptyString(OPENAI_API_BASE_URL)
272-
? OPENAI_API_BASE_URL
273-
: 'https://api.openai.com'
274-
275-
// 查是否订阅
276-
const urlSubscription = `${API_BASE_URL}/v1/dashboard/billing/subscription`
277-
// 查普通账单
278-
// const urlBalance = `${API_BASE_URL}/dashboard/billing/credit_grants`
279-
// 查使用量
280-
const urlUsage = `${API_BASE_URL}/v1/dashboard/billing/usage?start_date=${formatDate(startDate)}&end_date=${formatDate(endDate)}`
281-
282-
const headers = {
283-
'Authorization': `Bearer ${OPENAI_API_KEY}`,
284-
'Content-Type': 'application/json',
285-
}
286-
let socksAgent
287-
let httpsAgent
288-
if (isNotEmptyString(config.socksProxy)) {
289-
socksAgent = new SocksProxyAgent({
290-
hostname: config.socksProxy.split(':')[0],
291-
port: Number.parseInt(config.socksProxy.split(':')[1]),
292-
userId: isNotEmptyString(config.socksAuth) ? config.socksAuth.split(':')[0] : undefined,
293-
password: isNotEmptyString(config.socksAuth) ? config.socksAuth.split(':')[1] : undefined,
294-
})
295-
}
296-
else if (isNotEmptyString(config.httpsProxy)) {
297-
httpsAgent = new HttpsProxyAgent(config.httpsProxy)
298-
}
299-
300-
try {
301-
// 获取API限额
302-
let response = await fetch(urlSubscription, { agent: socksAgent === undefined ? httpsAgent : socksAgent, headers })
303-
if (!response.ok) {
304-
console.error('您的账户已被封禁,请登录OpenAI进行查看。')
305-
return
306-
}
307-
interface SubscriptionData {
308-
hard_limit_usd?: number
309-
// 这里可以添加其他可能的属性
310-
}
311-
const subscriptionData: SubscriptionData = await response.json()
312-
const totalAmount = subscriptionData.hard_limit_usd
313-
314-
interface UsageData {
315-
total_usage?: number
316-
// 这里可以添加其他可能的属性
317-
}
318-
319-
// 获取已使用量
320-
response = await fetch(urlUsage, { agent: socksAgent === undefined ? httpsAgent : socksAgent, headers })
321-
const usageData: UsageData = await response.json()
322-
const totalUsage = usageData.total_usage / 100
323-
324-
// 计算剩余额度
325-
cachedBalance = totalAmount - totalUsage
326-
cacheExpiration = now + 60 * 60 * 1000
327-
328-
return Promise.resolve(cachedBalance.toFixed(3))
329-
}
330-
catch (error) {
331-
globalThis.console.error(error)
332-
return Promise.resolve('-')
333-
}
334-
}
335-
336-
function formatDate(date) {
337-
const year = date.getFullYear()
338-
const month = (date.getMonth() + 1).toString().padStart(2, '0')
339-
const day = date.getDate().toString().padStart(2, '0')
340-
341-
return `${year}-${month}-${day}`
342-
}
343-
344242
async function chatConfig() {
345243
const config = await getOriginConfig() as ModelConfig
346-
// if (config.apiModel === 'ChatGPTAPI')
347-
// config.balance = await fetchBalance()
348-
// else
349-
// config.accessTokenExpiredTime = await fetchAccessTokenExpiredTime()
350244
return sendResponse<ModelConfig>({
351245
type: 'Success',
352246
data: config,

src/components/common/PromptStore/index.vue

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ const modalMode = ref('')
6161
const tempModifiedItem = ref<any>({})
6262
6363
// 添加修改导入都使用一个Modal, 临时修改内容占用tempPromptKey,切换状态前先将内容都清楚
64-
const changeShowModal = (mode: 'add' | 'modify' | 'local_import', selected = { key: '', value: '' }) => {
64+
function changeShowModal(mode: 'add' | 'modify' | 'local_import', selected = { key: '', value: '' }) {
6565
if (mode === 'add') {
6666
tempPromptKey.value = ''
6767
tempPromptValue.value = ''
@@ -82,15 +82,15 @@ const changeShowModal = (mode: 'add' | 'modify' | 'local_import', selected = { k
8282
// 在线导入相关
8383
const downloadURL = ref('')
8484
const downloadDisabled = computed(() => downloadURL.value.trim().length < 1)
85-
const setDownloadURL = (url: string) => {
85+
function setDownloadURL(url: string) {
8686
downloadURL.value = url
8787
}
8888
8989
// 控制 input 按钮
9090
const inputStatus = computed (() => tempPromptKey.value.trim().length < 1 || tempPromptValue.value.trim().length < 1)
9191
9292
// Prompt模板相关操作
93-
const addPromptTemplate = () => {
93+
function addPromptTemplate() {
9494
for (const i of promptList.value) {
9595
if (i.key === tempPromptKey.value) {
9696
message.error(t('store.addRepeatTitleTips'))
@@ -106,7 +106,7 @@ const addPromptTemplate = () => {
106106
changeShowModal('add')
107107
}
108108
109-
const modifyPromptTemplate = () => {
109+
function modifyPromptTemplate() {
110110
let index = 0
111111
112112
// 通过临时索引把待修改项摘出来
@@ -135,19 +135,19 @@ const modifyPromptTemplate = () => {
135135
changeShowModal('modify')
136136
}
137137
138-
const deletePromptTemplate = (row: { key: string; value: string }) => {
138+
function deletePromptTemplate(row: { key: string; value: string }) {
139139
promptList.value = [
140140
...promptList.value.filter((item: { key: string; value: string }) => item.key !== row.key),
141141
] as never
142142
message.success(t('common.deleteSuccess'))
143143
}
144144
145-
const clearPromptTemplate = () => {
145+
function clearPromptTemplate() {
146146
promptList.value = []
147147
message.success(t('common.clearSuccess'))
148148
}
149149
150-
const importPromptTemplate = (from = 'online') => {
150+
function importPromptTemplate(from = 'online') {
151151
try {
152152
const jsonData = JSON.parse(tempPromptValue.value)
153153
let key = ''
@@ -196,7 +196,7 @@ const importPromptTemplate = (from = 'online') => {
196196
}
197197
198198
// 模板导出
199-
const exportPromptTemplate = () => {
199+
function exportPromptTemplate() {
200200
exportLoading.value = true
201201
const jsonDataStr = JSON.stringify(promptList.value)
202202
const blob = new Blob([jsonDataStr], { type: 'application/json' })
@@ -210,7 +210,7 @@ const exportPromptTemplate = () => {
210210
}
211211
212212
// 模板在线导入
213-
const downloadPromptTemplate = async () => {
213+
async function downloadPromptTemplate() {
214214
try {
215215
importLoading.value = true
216216
const response = await fetch(downloadURL.value)
@@ -239,7 +239,7 @@ const downloadPromptTemplate = async () => {
239239
}
240240
241241
// 移动端自适应相关
242-
const renderTemplate = () => {
242+
function renderTemplate() {
243243
const [keyLimit, valueLimit] = isMobile.value ? [10, 30] : [15, 50]
244244
245245
return promptList.value.map((item: { key: string; value: string }) => {
@@ -260,7 +260,7 @@ const pagination = computed(() => {
260260
})
261261
262262
// table相关
263-
const createColumns = (): DataTableColumns<DataProps> => {
263+
function createColumns(): DataTableColumns<DataProps> {
264264
return [
265265
{
266266
title: t('store.title'),

src/components/common/Setting/Anonuncement.vue

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<script setup lang='ts'>
22
import { onMounted, ref } from 'vue'
33
import { NButton, NInput, NSpin, NSwitch, useMessage } from 'naive-ui'
4-
import { AnnounceConfig, ConfigState } from './model'
4+
import type { AnnounceConfig, ConfigState } from './model'
55
import { fetchChatConfig, fetchUpdateAnnounce } from '@/api'
66
import { t } from '@/locales'
77

src/components/common/Setting/Audit.vue

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
<script setup lang='ts'>
22
import { onMounted, ref } from 'vue'
33
import { NButton, NInput, NSelect, NSpin, NSwitch, useMessage } from 'naive-ui'
4-
import type { AuditConfig, ConfigState } from './model'
5-
import { TextAuditServiceProvider } from './model'
4+
import type { AuditConfig, ConfigState, TextAuditServiceProvider } from './model'
65
import { fetchChatConfig, fetchTestAudit, fetchUpdateAudit } from '@/api'
76
import { t } from '@/locales'
87

src/components/common/Setting/Gift.vue

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ function parseCSV(content: string) {
8686
return giftCards
8787
}
8888
89-
function handleUploadChange(data: { file: UploadFileInfo, fileList: Array<UploadFileInfo>, event?: Event }) {
89+
function handleUploadChange(data: { file: UploadFileInfo; fileList: Array<UploadFileInfo>; event?: Event }) {
9090
fileListRef.value = data.fileList
9191
csvData.value = []
9292
if (data.event) {

src/components/common/Setting/Keys.vue

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ const handleSaving = ref(false)
1919
const keyConfig = ref(new KeyConfig('', 'ChatGPTAPI', [], [], ''))
2020
2121
const keys = ref([])
22-
const createColumns = (): DataTableColumns => {
22+
function createColumns(): DataTableColumns {
2323
return [
2424
{
2525
title: 'Key',
@@ -226,7 +226,6 @@ onMounted(async () => {
226226
</NButton>
227227
</NSpace>
228228
<NDataTable
229-
ref="table"
230229
remote
231230
:loading="loading"
232231
:row-key="(rowData) => rowData._id"

src/components/common/Setting/Site.vue

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ onMounted(() => {
128128
/>
129129
</div>
130130
</div>
131-
<!-- 增加新注册用户的全局数量设置 -->
131+
<!-- 增加新注册用户的全局数量设置 -->
132132
<div class="flex items-center space-x-4">
133133
<span class="flex-shrink-0 w-[100px]">{{ $t('setting.globalAmount') }}</span>
134134
<div class="flex-1">

src/components/common/Setting/User.vue

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ const userRef = ref(new UserInfo([UserRole.User]))
1717
1818
const users = ref([])
1919
20-
const createColumns = (): DataTableColumns => {
20+
function createColumns(): DataTableColumns {
2121
return [
2222
{
2323
title: 'Email',
@@ -279,7 +279,6 @@ onMounted(async () => {
279279
</NButton>
280280
</NSpace>
281281
<NDataTable
282-
ref="table"
283282
remote
284283
:loading="loading"
285284
:row-key="(rowData) => rowData._id"

src/components/common/Setting/model.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ export const apiModelOptions = ['ChatGPTAPI', 'ChatGPTUnofficialProxyAPI'].map((
122122
}
123123
})
124124

125-
export const userRoleOptions = Object.values(UserRole).filter(d => isNaN(Number(d))).map((role) => {
125+
export const userRoleOptions = Object.values(UserRole).filter(d => Number.isNaN(Number(d))).map((role) => {
126126
return {
127127
label: role as string,
128128
key: role as string,

src/hooks/useIconRender.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { h } from 'vue'
22
import { SvgIcon } from '@/components/common'
33

4-
export const useIconRender = () => {
4+
export function useIconRender() {
55
interface IconConfig {
66
icon?: string
77
color?: string

src/plugins/scrollbarStyle.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { darkTheme, lightTheme } from 'naive-ui'
22

3-
const setupScrollbarStyle = () => {
3+
function setupScrollbarStyle() {
44
const style = document.createElement('style')
55
const styleContent = `
66
::-webkit-scrollbar {

src/typings/chat.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ declare namespace Chat {
3131

3232
interface ChatState {
3333
active: number | null
34-
usingContext: boolean;
34+
usingContext: boolean
3535
history: History[]
3636
chat: { uuid: number; data: Chat[] }[]
3737
}

src/typings/env.d.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
/// <reference types="vite/client" />
22

33
interface ImportMetaEnv {
4-
readonly VITE_GLOB_API_URL: string;
5-
readonly VITE_APP_API_BASE_URL: string;
6-
readonly VITE_GLOB_OPEN_LONG_REPLY: string;
7-
readonly VITE_GLOB_APP_PWA: string;
4+
readonly VITE_GLOB_API_URL: string
5+
readonly VITE_APP_API_BASE_URL: string
6+
readonly VITE_GLOB_OPEN_LONG_REPLY: string
7+
readonly VITE_GLOB_APP_PWA: string
88
}

src/typings/global.d.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
interface Window {
2-
$loadingBar?: import('naive-ui').LoadingBarProviderInst;
3-
$dialog?: import('naive-ui').DialogProviderInst;
4-
$message?: import('naive-ui').MessageProviderInst;
5-
$notification?: import('naive-ui').NotificationProviderInst;
2+
$loadingBar?: import('naive-ui').LoadingBarProviderInst
3+
$dialog?: import('naive-ui').DialogProviderInst
4+
$message?: import('naive-ui').MessageProviderInst
5+
$notification?: import('naive-ui').NotificationProviderInst
66
}

0 commit comments

Comments
 (0)