Open History to see the last commit
1// @effect-diagnostics globalDate:off -- Usage windows are calendar days in the viewer's zone, derived from wall-clock "now" via Intl.
2import {
3 UsageDay,
4 type UsageResolution,
5 type UsageSource,
6 type UsageSummaryInput,
7} from "@t3tools/contracts";
8
9import { sourceIdentity } from "./usageMerge.ts";
10
11const CURRENCY = new Intl.NumberFormat("en-US", {
12 style: "currency",
13 currency: "USD",
14 minimumFractionDigits: 2,
15 maximumFractionDigits: 2,
16});
17
18const INTEGER = new Intl.NumberFormat("en-US");
19
20// Clients pass their UI locale; English (and the server, which passes none) keeps en-US.
21function formatLocale(locale: string | undefined): string {
22 return locale === undefined || locale === "en" ? "en-US" : locale;
23}
24
25const numberFormatters = new Map<string, Intl.NumberFormat>();
26
27function numberFormatter(locale: string, currency: boolean): Intl.NumberFormat {
28 if (locale === "en-US") return currency ? CURRENCY : INTEGER;
29 const key = `${locale}:${currency}`;
30 let formatter = numberFormatters.get(key);
31 if (formatter === undefined) {
32 formatter = currency
33 ? new Intl.NumberFormat(locale, {
34 style: "currency",
35 currency: "USD",
36 minimumFractionDigits: 2,
37 maximumFractionDigits: 2,
38 })
39 : new Intl.NumberFormat(locale);
40 numberFormatters.set(key, formatter);
41 }
42 return formatter;
43}
44
45export function formatMalformedUsageWarning(count: number): string {
46 return `${count} malformed or inconsistent usage record(s) were skipped; usage may be incomplete.`;
47}
48
49export function usageSourceMessages(
50 sources: readonly UsageSource[],
51 malformedWarning: (count: number) => string = formatMalformedUsageWarning,
52): readonly string[] {
53 const sourceKey = sourceIdentity(sources.map((source) => source.fingerprint));
54 const messages = new Set<string>();
55 const malformedBySource = new Map<string, number>();
56 for (const source of sources) {
57 if (
58 source.status !== "partial" &&
59 source.status !== "failed" &&
60 source.fingerprint.provider !== "cursor" &&
61 !(source.status === "missing" && source.malformedRecords > 0)
62 ) {
63 continue;
64 }
65 let message = source.message;
66 if (source.malformedRecords > 0) {
67 const key = sourceKey(source.fingerprint);
68 malformedBySource.set(
69 key,
70 Math.max(malformedBySource.get(key) ?? 0, source.malformedRecords),
71 );
72 // Servers also append this warning to message; retain any preceding read failure.
73 const warning = formatMalformedUsageWarning(source.malformedRecords);
74 if (message?.endsWith(warning)) message = message.slice(0, -warning.length).trim();
75 }
76 if (message) messages.add(message);
77 }
78 const malformedRecords = [...malformedBySource.values()].reduce(
79 (total, count) => total + count,
80 0,
81 );
82 if (malformedRecords > 0) messages.add(malformedWarning(malformedRecords));
83 return [...messages];
84}
85
86export function formatUsd(value: number, locale?: string): string {
87 return numberFormatter(formatLocale(locale), true).format(value);
88}
89
90export function formatCount(value: number, locale?: string): string {
91 return numberFormatter(formatLocale(locale), false).format(Math.round(value));
92}
93
94const TOKEN_SUFFIXES = ["K", "M", "B", "T"] as const;
95
96export function formatTokens(value: number): string {
97 if (Math.abs(Math.round(value)) < 1e3) return INTEGER.format(Math.round(value));
98 let scaled = value / 1e3;
99 let unit = 0;
100 // Choose the unit after rounding, so 999,999 reads 1M rather than 1000K.
101 while (Math.abs(Number(trim(scaled))) >= 1e3 && unit < TOKEN_SUFFIXES.length - 1) {
102 scaled /= 1e3;
103 unit += 1;
104 }
105 return `${trim(scaled)}${TOKEN_SUFFIXES[unit]}`;
106}
107
108function trim(value: number): string {
109 const abs = Math.abs(value);
110 const digits = abs >= 100 ? 0 : abs >= 10 ? 1 : 2;
111 return value.toFixed(digits).replace(/\.0+$/, "");
112}
113
114export function formatPercent(share: number, digits = 1): string {
115 const percent = share * 100;
116 const smallest = 10 ** -digits;
117 if (percent > 0 && percent < smallest) return `<${smallest.toFixed(digits)}%`;
118 return `${percent.toFixed(digits)}%`;
119}
120
121export function formatDayShort(day: string, locale?: string): string {
122 const [year, month, dayOfMonth] = day.split("-").map((part) => Number(part));
123 if (year === undefined || month === undefined || dayOfMonth === undefined) return day;
124 const intlLocale = formatLocale(locale);
125 if (intlLocale !== "en-US") {
126 const date = new Date(Date.UTC(year, month - 1, dayOfMonth));
127 return Number.isNaN(date.getTime())
128 ? day
129 : dateTimeFormatter(intlLocale, { timeZone: "UTC", month: "short", day: "numeric" }).format(
130 date,
131 );
132 }
133 const MONTHS = [
134 "Jan",
135 "Feb",
136 "Mar",
137 "Apr",
138 "May",
139 "Jun",
140 "Jul",
141 "Aug",
142 "Sep",
143 "Oct",
144 "Nov",
145 "Dec",
146 ];
147 return `${MONTHS[month - 1] ?? ""} ${dayOfMonth}`;
148}
149
150export function enumerateDays(sinceDay: string, untilDay: string): readonly string[] {
151 const days: string[] = [];
152 const start = Date.parse(`${sinceDay}T00:00:00Z`);
153 const end = Date.parse(`${untilDay}T00:00:00Z`);
154 if (Number.isNaN(start) || Number.isNaN(end) || end < start) return days;
155
156 for (let cursor = start; cursor <= end; cursor += 86_400_000) {
157 days.push(new Date(cursor).toISOString().slice(0, 10));
158 }
159 return days;
160}
161
162const HOUR_MS = 60 * 60 * 1000;
163
164const dateTimeFormatters = new Map<string, Intl.DateTimeFormat>();
165
166function dateTimeFormatter(
167 locale: string,
168 options: Intl.DateTimeFormatOptions,
169): Intl.DateTimeFormat {
170 if (options.timeZone === undefined) return new Intl.DateTimeFormat(locale, options);
171 const key = JSON.stringify([locale, options]);
172 let formatter = dateTimeFormatters.get(key);
173 if (formatter === undefined) {
174 formatter = new Intl.DateTimeFormat(locale, options);
175 if (dateTimeFormatters.size >= 16) dateTimeFormatters.clear();
176 dateTimeFormatters.set(key, formatter);
177 }
178 return formatter;
179}
180
181export function enumerateHourStarts(sinceTime: string, untilTime: string): readonly string[] {
182 const starts: string[] = [];
183 const start = Date.parse(sinceTime);
184 const end = Date.parse(untilTime);
185 if (Number.isNaN(start) || Number.isNaN(end) || end <= start) return starts;
186
187 for (let cursor = start; cursor < end; cursor += HOUR_MS) {
188 starts.push(new Date(cursor).toISOString());
189 }
190 return starts;
191}
192
193function hourOptions(hour12: boolean): Intl.DateTimeFormatOptions {
194 return hour12 ? { hour: "numeric", hour12: true } : { hour: "2-digit", hourCycle: "h23" };
195}
196
197function formatHour(formatter: Intl.DateTimeFormat, date: Date, hour12: boolean): string {
198 if (hour12) return formatter.format(date);
199 // Rolling buckets can start between whole hours, but their labels always name the hour.
200 return formatter
201 .formatToParts(date)
202 .map((part) => (part.type === "hour" ? `${part.value}:00` : part.value))
203 .join("");
204}
205
206/**
207 * Repeated wall-clock hours during a fall-back transition include their short zone name so the
208 * two distinct buckets remain distinguishable.
209 */
210export function formatHourShort(
211 hourStart: string,
212 timeZone?: string,
213 hour12 = true,
214 locale?: string,
215): string {
216 const instant = new Date(hourStart);
217 if (Number.isNaN(instant.getTime())) return hourStart;
218 const options = timeZone === undefined ? {} : { timeZone };
219 const intlLocale = formatLocale(locale);
220 const hourFormat = dateTimeFormatter(intlLocale, {
221 ...options,
222 ...hourOptions(hour12),
223 });
224 const wallHourFormat = dateTimeFormatter("en-CA", {
225 ...options,
226 year: "numeric",
227 month: "2-digit",
228 day: "2-digit",
229 hour: "2-digit",
230 hourCycle: "h23",
231 });
232 const wallHour = wallHourFormat.format(instant);
233 const isRepeatedHour = [-HOUR_MS, HOUR_MS].some(
234 (offset) => wallHourFormat.format(new Date(instant.getTime() + offset)) === wallHour,
235 );
236
237 if (!isRepeatedHour) return formatHour(hourFormat, instant, hour12);
238 const zonedHourFormat = dateTimeFormatter(intlLocale, {
239 ...options,
240 ...hourOptions(hour12),
241 timeZoneName: "short",
242 });
243 return formatHour(zonedHourFormat, instant, hour12);
244}
245
246export function formatDateTimeShort(
247 instant: string,
248 timeZone?: string,
249 hour12 = true,
250 locale?: string,
251): string {
252 const date = new Date(instant);
253 if (Number.isNaN(date.getTime())) return instant;
254 const dateHourFormat = dateTimeFormatter(formatLocale(locale), {
255 ...(timeZone === undefined ? {} : { timeZone }),
256 month: "short",
257 day: "numeric",
258 ...hourOptions(hour12),
259 });
260 return formatHour(dateHourFormat, date, hour12);
261}
262
263export function formatRelativeHourShort(
264 hourStart: string,
265 relativeTo: string,
266 timeZone?: string,
267 hour12 = true,
268 relativeDay: (hour: string, daysAgo: 0 | 1) => string = (hour, daysAgo) =>
269 daysAgo === 0 ? `${hour} today` : `${hour} yesterday`,
270 locale?: string,
271): string {
272 const instant = new Date(hourStart);
273 const reference = new Date(relativeTo);
274 if (Number.isNaN(instant.getTime()) || Number.isNaN(reference.getTime())) {
275 return formatDateTimeShort(hourStart, timeZone, hour12, locale);
276 }
277
278 const dayFormat = dateTimeFormatter("en-CA", {
279 ...(timeZone === undefined ? {} : { timeZone }),
280 year: "numeric",
281 month: "2-digit",
282 day: "2-digit",
283 });
284 const instantDay = Date.parse(`${dayFormat.format(instant)}T00:00:00Z`);
285 const referenceDay = Date.parse(`${dayFormat.format(reference)}T00:00:00Z`);
286 const calendarDaysAgo = Math.round((referenceDay - instantDay) / (24 * HOUR_MS));
287 const hour = formatHourShort(hourStart, timeZone, hour12, locale);
288
289 if (calendarDaysAgo === 0 || calendarDaysAgo === 1) return relativeDay(hour, calendarDaysAgo);
290 return formatDateTimeShort(hourStart, timeZone, hour12, locale);
291}
292
293export function makeWindow(
294 days: number,
295 now = new Date(),
296 resolution: UsageResolution = "day",
297): UsageSummaryInput {
298 let timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
299 let format: Intl.DateTimeFormat;
300 try {
301 format = new Intl.DateTimeFormat("en-CA", {
302 timeZone,
303 year: "numeric",
304 month: "2-digit",
305 day: "2-digit",
306 });
307 } catch {
308 timeZone = "UTC";
309 format = new Intl.DateTimeFormat("en-CA", {
310 timeZone: "UTC",
311 year: "numeric",
312 month: "2-digit",
313 day: "2-digit",
314 });
315 }
316 const untilDay = format.format(now);
317 if (resolution === "hour") {
318 const untilTimeMs = Math.floor(now.getTime() / 60_000) * 60_000;
319 const sinceTimeMs = untilTimeMs - 24 * HOUR_MS;
320 const sinceTime = new Date(sinceTimeMs);
321 const untilTime = new Date(untilTimeMs);
322 return {
323 sinceDay: UsageDay.make(format.format(sinceTime)),
324 untilDay: UsageDay.make(format.format(untilTime)),
325 timeZone,
326 resolution,
327 sinceTime: sinceTime.toISOString(),
328 untilTime: untilTime.toISOString(),
329 };
330 }
331 // Use calendar arithmetic in UTC; fixed millisecond subtraction crosses DST days incorrectly.
332 const [year = 0, month = 1, dayOfMonth = 1] = untilDay
333 .split("-")
334 .map((part) => Number.parseInt(part, 10));
335 const start = new Date(Date.UTC(year, month - 1, dayOfMonth - (days - 1)));
336 return {
337 sinceDay: UsageDay.make(start.toISOString().slice(0, 10)),
338 untilDay: UsageDay.make(untilDay),
339 timeZone,
340 resolution,
341 };
342}