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 { UsageDay, type UsageResolution, type UsageSummaryInput } from "@t3tools/contracts";
3
4import type { UsageContractMismatch } from "./usageMerge.ts";
5
6const CURRENCY = new Intl.NumberFormat("en-US", {
7 style: "currency",
8 currency: "USD",
9 minimumFractionDigits: 2,
10 maximumFractionDigits: 2,
11});
12
13const INTEGER = new Intl.NumberFormat("en-US");
14
15export function formatUsd(value: number): string {
16 return CURRENCY.format(value);
17}
18
19export function formatCount(value: number): string {
20 return INTEGER.format(Math.round(value));
21}
22
23export function formatTokens(value: number): string {
24 const abs = Math.abs(value);
25 if (abs >= 1e12) return `${trim(value / 1e12)}T`;
26 if (abs >= 1e9) return `${trim(value / 1e9)}B`;
27 if (abs >= 1e6) return `${trim(value / 1e6)}M`;
28 if (abs >= 1e3) return `${trim(value / 1e3)}K`;
29 return INTEGER.format(Math.round(value));
30}
31
32function trim(value: number): string {
33 const abs = Math.abs(value);
34 const digits = abs >= 100 ? 0 : abs >= 10 ? 1 : 2;
35 return value.toFixed(digits).replace(/\.0+$/, "");
36}
37
38export function formatPercent(share: number, digits = 1): string {
39 const percent = share * 100;
40 const smallest = 10 ** -digits;
41 if (percent > 0 && percent < smallest) return `<${smallest.toFixed(digits)}%`;
42 return `${percent.toFixed(digits)}%`;
43}
44
45export function formatUsageContractMismatch(
46 environmentLabel: string,
47 mismatch: Pick<UsageContractMismatch, "direction">,
48): string {
49 return mismatch.direction === "serverBehind"
50 ? `${environmentLabel} runs an older server version and is excluded from totals.`
51 : `This client is older than the server on ${environmentLabel}; its usage is excluded from totals.`;
52}
53
54export function formatDayShort(day: string): string {
55 const [year, month, dayOfMonth] = day.split("-").map((part) => Number(part));
56 if (year === undefined || month === undefined || dayOfMonth === undefined) return day;
57 const MONTHS = [
58 "Jan",
59 "Feb",
60 "Mar",
61 "Apr",
62 "May",
63 "Jun",
64 "Jul",
65 "Aug",
66 "Sep",
67 "Oct",
68 "Nov",
69 "Dec",
70 ];
71 return `${MONTHS[month - 1] ?? ""} ${dayOfMonth}`;
72}
73
74export function enumerateDays(sinceDay: string, untilDay: string): readonly string[] {
75 const days: string[] = [];
76 const start = Date.parse(`${sinceDay}T00:00:00Z`);
77 const end = Date.parse(`${untilDay}T00:00:00Z`);
78 if (Number.isNaN(start) || Number.isNaN(end) || end < start) return days;
79
80 for (let cursor = start; cursor <= end; cursor += 86_400_000) {
81 days.push(new Date(cursor).toISOString().slice(0, 10));
82 }
83 return days;
84}
85
86const HOUR_MS = 60 * 60 * 1000;
87
88const dateTimeFormatters = new Map<string, Intl.DateTimeFormat>();
89
90function dateTimeFormatter(
91 locale: string,
92 options: Intl.DateTimeFormatOptions,
93): Intl.DateTimeFormat {
94 if (options.timeZone === undefined) return new Intl.DateTimeFormat(locale, options);
95 const key = JSON.stringify([locale, options]);
96 let formatter = dateTimeFormatters.get(key);
97 if (formatter === undefined) {
98 formatter = new Intl.DateTimeFormat(locale, options);
99 if (dateTimeFormatters.size >= 16) dateTimeFormatters.clear();
100 dateTimeFormatters.set(key, formatter);
101 }
102 return formatter;
103}
104
105export function enumerateHourStarts(sinceTime: string, untilTime: string): readonly string[] {
106 const starts: string[] = [];
107 const start = Date.parse(sinceTime);
108 const end = Date.parse(untilTime);
109 if (Number.isNaN(start) || Number.isNaN(end) || end <= start) return starts;
110
111 for (let cursor = start; cursor < end; cursor += HOUR_MS) {
112 starts.push(new Date(cursor).toISOString());
113 }
114 return starts;
115}
116
117function hourOptions(hour12: boolean): Intl.DateTimeFormatOptions {
118 return hour12 ? { hour: "numeric" } : { hour: "2-digit", hourCycle: "h23" };
119}
120
121function formatHour(formatter: Intl.DateTimeFormat, date: Date, hour12: boolean): string {
122 if (hour12) return formatter.format(date);
123 // Rolling buckets can start between whole hours, but their labels always name the hour.
124 return formatter
125 .formatToParts(date)
126 .map((part) => (part.type === "hour" ? `${part.value}:00` : part.value))
127 .join("");
128}
129
130/**
131 * Repeated wall-clock hours during a fall-back transition include their short zone name so the
132 * two distinct buckets remain distinguishable.
133 */
134export function formatHourShort(hourStart: string, timeZone?: string, hour12 = true): string {
135 const instant = new Date(hourStart);
136 if (Number.isNaN(instant.getTime())) return hourStart;
137 const options = timeZone === undefined ? {} : { timeZone };
138 const hourFormat = dateTimeFormatter("en-US", {
139 ...options,
140 ...hourOptions(hour12),
141 });
142 const wallHourFormat = dateTimeFormatter("en-CA", {
143 ...options,
144 year: "numeric",
145 month: "2-digit",
146 day: "2-digit",
147 hour: "2-digit",
148 hourCycle: "h23",
149 });
150 const wallHour = wallHourFormat.format(instant);
151 const isRepeatedHour = [-HOUR_MS, HOUR_MS].some(
152 (offset) => wallHourFormat.format(new Date(instant.getTime() + offset)) === wallHour,
153 );
154
155 if (!isRepeatedHour) return formatHour(hourFormat, instant, hour12);
156 const zonedHourFormat = dateTimeFormatter("en-US", {
157 ...options,
158 ...hourOptions(hour12),
159 timeZoneName: "short",
160 });
161 return formatHour(zonedHourFormat, instant, hour12);
162}
163
164export function formatDateTimeShort(instant: string, timeZone?: string, hour12 = true): string {
165 const date = new Date(instant);
166 if (Number.isNaN(date.getTime())) return instant;
167 const dateHourFormat = dateTimeFormatter("en-US", {
168 ...(timeZone === undefined ? {} : { timeZone }),
169 month: "short",
170 day: "numeric",
171 ...hourOptions(hour12),
172 });
173 return formatHour(dateHourFormat, date, hour12);
174}
175
176export function formatRelativeHourShort(
177 hourStart: string,
178 relativeTo: string,
179 timeZone?: string,
180 hour12 = true,
181): string {
182 const instant = new Date(hourStart);
183 const reference = new Date(relativeTo);
184 if (Number.isNaN(instant.getTime()) || Number.isNaN(reference.getTime())) {
185 return formatDateTimeShort(hourStart, timeZone, hour12);
186 }
187
188 const dayFormat = dateTimeFormatter("en-CA", {
189 ...(timeZone === undefined ? {} : { timeZone }),
190 year: "numeric",
191 month: "2-digit",
192 day: "2-digit",
193 });
194 const instantDay = Date.parse(`${dayFormat.format(instant)}T00:00:00Z`);
195 const referenceDay = Date.parse(`${dayFormat.format(reference)}T00:00:00Z`);
196 const calendarDaysAgo = Math.round((referenceDay - instantDay) / (24 * HOUR_MS));
197 const hour = formatHourShort(hourStart, timeZone, hour12);
198
199 if (calendarDaysAgo === 0) return `${hour} today`;
200 if (calendarDaysAgo === 1) return `${hour} yesterday`;
201 return formatDateTimeShort(hourStart, timeZone, hour12);
202}
203
204export function makeWindow(
205 days: number,
206 now = new Date(),
207 resolution: UsageResolution = "day",
208): UsageSummaryInput {
209 let timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
210 let format: Intl.DateTimeFormat;
211 try {
212 format = new Intl.DateTimeFormat("en-CA", {
213 timeZone,
214 year: "numeric",
215 month: "2-digit",
216 day: "2-digit",
217 });
218 } catch {
219 timeZone = "UTC";
220 format = new Intl.DateTimeFormat("en-CA", {
221 timeZone: "UTC",
222 year: "numeric",
223 month: "2-digit",
224 day: "2-digit",
225 });
226 }
227 const untilDay = format.format(now);
228 if (resolution === "hour") {
229 const untilTimeMs = Math.floor(now.getTime() / 60_000) * 60_000;
230 const sinceTimeMs = untilTimeMs - 24 * HOUR_MS;
231 const sinceTime = new Date(sinceTimeMs);
232 const untilTime = new Date(untilTimeMs);
233 return {
234 sinceDay: UsageDay.make(format.format(sinceTime)),
235 untilDay: UsageDay.make(format.format(untilTime)),
236 timeZone,
237 resolution,
238 sinceTime: sinceTime.toISOString(),
239 untilTime: untilTime.toISOString(),
240 };
241 }
242 // Subtracting fixed milliseconds from `now` lands on the wrong calendar day
243 // around a DST transition. The window start is pure calendar arithmetic on
244 // the local end day, done in UTC where days are uniform.
245 const [year = 0, month = 1, dayOfMonth = 1] = untilDay
246 .split("-")
247 .map((part) => Number.parseInt(part, 10));
248 const start = new Date(Date.UTC(year, month - 1, dayOfMonth - (days - 1)));
249 return {
250 sinceDay: UsageDay.make(start.toISOString().slice(0, 10)),
251 untilDay: UsageDay.make(untilDay),
252 timeZone,
253 resolution,
254 };
255}