forked from QuantumNous/new-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformat.ts
More file actions
283 lines (241 loc) · 8.25 KB
/
Copy pathformat.ts
File metadata and controls
283 lines (241 loc) · 8.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import dayjs from '@/lib/dayjs'
import {
formatCurrencyFromUSD,
formatQuotaWithCurrency,
getCurrencyDisplay,
} from './currency'
// ============================================================================
// Number Formatting
// ============================================================================
export function formatNumber(
value: number | null | undefined,
locales?: Intl.LocalesArgument
): string {
if (value == null || Number.isNaN(value as number)) return '-'
return Intl.NumberFormat(locales, { maximumFractionDigits: 2 }).format(
value as number
)
}
export function formatCompactNumber(
value: number | null | undefined,
locales?: Intl.LocalesArgument
): string {
if (value == null || Number.isNaN(value as number)) return '-'
return Intl.NumberFormat(locales, {
notation: 'compact',
maximumFractionDigits: 1,
}).format(value as number)
}
export function formatPercent(value: number | null | undefined): string {
if (value == null || Number.isNaN(value as number)) return '-'
return Intl.NumberFormat(undefined, {
style: 'percent',
maximumFractionDigits: 2,
}).format((value as number) / 100)
}
export function formatCurrencyUSD(value: number | null | undefined): string {
return formatCurrencyFromUSD(value == null ? null : (value as number))
}
// ============================================================================
// Quota Formatting (500,000 units = $1)
// ============================================================================
/**
* Format quota into the configured display amount.
* Quota is stored in units where `quotaPerUnit` equals 1 USD.
*/
export function formatQuota(quota: number): string {
return formatQuotaWithCurrency(quota, {
digitsLarge: 2,
digitsSmall: 4,
abbreviate: true,
})
}
/**
* Parse quota from the current display input back to quota units.
*/
export function parseQuotaFromDollars(amount: number): number {
if (!Number.isFinite(amount)) return 0
const { config, meta } = getCurrencyDisplay()
// Tokens-only or raw quota mode
if (meta.kind === 'tokens') {
return Math.round(amount)
}
const exchangeRate =
meta.kind === 'currency' || meta.kind === 'custom' ? meta.exchangeRate : 1
const usdAmount = exchangeRate > 0 ? amount / exchangeRate : amount
return Math.round(usdAmount * config.quotaPerUnit)
}
/**
* Convert quota units to the configured display amount.
* Reverse of parseQuotaFromDollars.
*/
export function quotaUnitsToDollars(units: number): number {
const { config, meta } = getCurrencyDisplay()
if (meta.kind === 'tokens') {
return units
}
const usdAmount = units / config.quotaPerUnit
const exchangeRate =
meta.kind === 'currency' || meta.kind === 'custom' ? meta.exchangeRate : 1
return usdAmount * exchangeRate
}
// ============================================================================
// Timestamp Formatting
// ============================================================================
/**
* Format Unix timestamp (seconds) to YYYY-MM-DD HH:mm:ss
*/
export function formatTimestamp(timestamp: number): string {
if (timestamp === -1) {
return 'Never'
}
return formatTimestampToDate(timestamp)
}
/**
* Format timestamp to YYYY-MM-DD HH:mm:ss
* @param timestamp - Timestamp in seconds or milliseconds
* @param unit - Unit of the timestamp ('seconds' or 'milliseconds')
*/
export function formatTimestampToDate(
timestamp?: number,
unit: 'seconds' | 'milliseconds' = 'seconds'
): string {
if (!timestamp || timestamp === -1 || timestamp === 0) {
return '-'
}
const ms = unit === 'seconds' ? timestamp * 1000 : timestamp
return dayjs(ms).format('YYYY-MM-DD HH:mm:ss')
}
/**
* Format timestamp as relative time, e.g. "30 seconds ago".
* @param timestamp - Timestamp in seconds or milliseconds
* @param unit - Unit of the timestamp ('seconds' or 'milliseconds')
* @param locales - Locale passed to Intl.RelativeTimeFormat
*/
export function formatTimestampRelative(
timestamp?: number,
unit: 'seconds' | 'milliseconds' = 'seconds',
locales?: Intl.LocalesArgument
): string {
if (!timestamp || timestamp === -1 || timestamp === 0) {
return '-'
}
const ms = unit === 'seconds' ? timestamp * 1000 : timestamp
const diffSeconds = Math.round((ms - Date.now()) / 1000)
const absSeconds = Math.abs(diffSeconds)
const formatter = new Intl.RelativeTimeFormat(locales, {
numeric: 'always',
})
if (absSeconds < 60) {
return formatter.format(diffSeconds, 'second')
}
if (absSeconds < 3600) {
return formatter.format(Math.round(diffSeconds / 60), 'minute')
}
if (absSeconds < 86400) {
return formatter.format(Math.round(diffSeconds / 3600), 'hour')
}
if (absSeconds < 2592000) {
return formatter.format(Math.round(diffSeconds / 86400), 'day')
}
if (absSeconds < 31536000) {
return formatter.format(Math.round(diffSeconds / 2592000), 'month')
}
return formatter.format(Math.round(diffSeconds / 31536000), 'year')
}
/** Format a Date object to YYYY-MM-DD HH:mm:ss */
export function formatDateTimeStr(date: Date): string {
return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}
/** Format a Date object to YYYY-MM-DD */
export function formatDateStr(date: Date): string {
return dayjs(date).format('YYYY-MM-DD')
}
/** Format a Date object to HH:mm:ss */
export function formatTimeStr(date: Date): string {
return dayjs(date).format('HH:mm:ss')
}
/**
* Format quota for usage logs with higher precision
* Uses 6 decimal places to show very small costs accurately
*/
export function formatLogQuota(quota: number): string {
return formatQuotaWithCurrency(quota, {
digitsLarge: 4,
digitsSmall: 6,
abbreviate: false,
})
}
/**
* Format tokens count with K/M suffixes
*/
export function formatTokens(tokens: number): string {
if (tokens === 0) return '-'
if (tokens < 1000) return tokens.toString()
if (tokens < 1000000) return `${(tokens / 1000).toFixed(1)}K`
return `${(tokens / 1000000).toFixed(2)}M`
}
/**
* Format use time in seconds with appropriate unit
*/
export function formatUseTime(seconds: number): string {
if (seconds < 60) return `${seconds.toFixed(1)}s`
const minutes = Math.floor(seconds / 60)
const remainingSeconds = seconds % 60
return `${minutes}m ${remainingSeconds.toFixed(0)}s`
}
/**
* Format timestamp to date input value (YYYY-MM-DDTHH:mm)
*/
export function formatTimestampForInput(timestamp: number): string {
if (timestamp === -1) {
return ''
}
return dayjs(timestamp * 1000).format('YYYY-MM-DDTHH:mm')
}
/**
* Parse datetime-local input to Unix timestamp
*/
export function parseTimestampFromInput(value: string): number {
if (!value) {
return -1
}
const date = new Date(value)
return Math.floor(date.getTime() / 1000)
}
// ============================================================================
// Color Generation
// ============================================================================
/**
* Generate a consistent color from a string
* Uses HSL for better color distribution
*/
export function stringToColor(str: string): string {
if (!str) return 'gray'
// Generate hash from string
let hash = 0
for (let i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash)
hash = hash & hash // Convert to 32-bit integer
}
// Use hash to generate hue (0-360)
const hue = Math.abs(hash % 360)
// Use saturation and lightness that work well for tags
const saturation = 65 + (Math.abs(hash) % 10) // 65-75%
const lightness = 55 + (Math.abs(hash >> 8) % 10) // 55-65%
return `hsl(${hue}, ${saturation}%, ${lightness}%)`
}