|
| 1 | +import { BailianError, ExitCode, defineCommand, unwrapResponse } from "bailian-cli-core"; |
| 2 | +import { ansi, displayWidth, emitResult, type TextStyle } from "bailian-cli-runtime"; |
| 3 | + |
| 4 | +const TOKEN_PLAN_USAGE_API = "zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage"; |
| 5 | +const BOX_WIDTH = 76; |
| 6 | +const PROGRESS_WIDTH = 32; |
| 7 | + |
| 8 | +interface TokenPlanUsage { |
| 9 | + per5HourPercentage: number; |
| 10 | + per5HourResetTime: number; |
| 11 | + per1WeekPercentage: number; |
| 12 | + per1WeekResetTime: number; |
| 13 | +} |
| 14 | + |
| 15 | +function readUsage(result: unknown): TokenPlanUsage { |
| 16 | + const response = unwrapResponse(result as Record<string, unknown>); |
| 17 | + const usage = { |
| 18 | + per5HourPercentage: response.per5HourPercentage, |
| 19 | + per5HourResetTime: response.per5HourResetTime, |
| 20 | + per1WeekPercentage: response.per1WeekPercentage, |
| 21 | + per1WeekResetTime: response.per1WeekResetTime, |
| 22 | + }; |
| 23 | + |
| 24 | + if (!Object.values(usage).every((value) => typeof value === "number" && Number.isFinite(value))) { |
| 25 | + throw new BailianError("Token Plan usage response has an unexpected format.", ExitCode.GENERAL); |
| 26 | + } |
| 27 | + |
| 28 | + return usage as TokenPlanUsage; |
| 29 | +} |
| 30 | + |
| 31 | +function formatPercentage(ratio: number): string { |
| 32 | + return `${(ratio * 100).toFixed(2)}%`; |
| 33 | +} |
| 34 | + |
| 35 | +function formatDateTime(timestamp: number): string { |
| 36 | + const date = new Date(timestamp); |
| 37 | + const year = date.getFullYear(); |
| 38 | + const month = String(date.getMonth() + 1).padStart(2, "0"); |
| 39 | + const day = String(date.getDate()).padStart(2, "0"); |
| 40 | + const hour = String(date.getHours()).padStart(2, "0"); |
| 41 | + const minute = String(date.getMinutes()).padStart(2, "0"); |
| 42 | + const second = String(date.getSeconds()).padStart(2, "0"); |
| 43 | + return `${year}-${month}-${day} ${hour}:${minute}:${second}`; |
| 44 | +} |
| 45 | + |
| 46 | +function formatRemainingTime(resetTime: number, now: number): string { |
| 47 | + const remainingMs = Math.max(0, resetTime - now); |
| 48 | + const totalMinutes = Math.floor(remainingMs / 60_000); |
| 49 | + if (totalMinutes === 0) return "now"; |
| 50 | + |
| 51 | + const days = Math.floor(totalMinutes / (24 * 60)); |
| 52 | + const hours = Math.floor((totalMinutes % (24 * 60)) / 60); |
| 53 | + const minutes = totalMinutes % 60; |
| 54 | + const parts: string[] = []; |
| 55 | + if (days > 0) parts.push(`${days}d`); |
| 56 | + if (hours > 0) parts.push(`${hours}h`); |
| 57 | + if (minutes > 0 || parts.length === 0) parts.push(`${minutes}m`); |
| 58 | + return parts.join(" "); |
| 59 | +} |
| 60 | + |
| 61 | +function progressBar(ratio: number): string { |
| 62 | + const clampedRatio = Math.min(1, Math.max(0, ratio)); |
| 63 | + const filled = Math.round(clampedRatio * PROGRESS_WIDTH); |
| 64 | + return `[${"█".repeat(filled)}${"░".repeat(PROGRESS_WIDTH - filled)}]`; |
| 65 | +} |
| 66 | + |
| 67 | +function progressStyle( |
| 68 | + percentage: number, |
| 69 | + green: TextStyle, |
| 70 | + yellow: TextStyle, |
| 71 | + red: TextStyle, |
| 72 | +): TextStyle { |
| 73 | + if (percentage >= 0.9) return red; |
| 74 | + if (percentage >= 0.75) return yellow; |
| 75 | + return green; |
| 76 | +} |
| 77 | + |
| 78 | +function printView(usage: TokenPlanUsage, generatedAt: number): void { |
| 79 | + const color = ansi(process.stdout); |
| 80 | + const writeLine = (content = "", visibleContent = content) => { |
| 81 | + const padding = Math.max(0, BOX_WIDTH - displayWidth(` ${visibleContent}`)); |
| 82 | + process.stdout.write(`│ ${content}${" ".repeat(padding)}│\n`); |
| 83 | + }; |
| 84 | + const writeQuota = (label: string, percentage: number, resetTime: number) => { |
| 85 | + const percentageText = formatPercentage(percentage); |
| 86 | + const bar = progressBar(percentage); |
| 87 | + const style = progressStyle(percentage, color.green, color.yellow, color.red); |
| 88 | + writeLine(color.bold(label), label); |
| 89 | + writeLine(`${percentageText} used ${style(bar)}`, `${percentageText} used ${bar}`); |
| 90 | + writeLine( |
| 91 | + color.dim( |
| 92 | + `Resets: ${formatDateTime(resetTime)} (in ${formatRemainingTime(resetTime, generatedAt)})`, |
| 93 | + ), |
| 94 | + `Resets: ${formatDateTime(resetTime)} (in ${formatRemainingTime(resetTime, generatedAt)})`, |
| 95 | + ); |
| 96 | + }; |
| 97 | + |
| 98 | + process.stdout.write(`┌${"─".repeat(BOX_WIDTH)}┐\n`); |
| 99 | + writeLine(color.cyan("Token Plan Usage"), "Token Plan Usage"); |
| 100 | + const generatedAtText = `Generated at: ${formatDateTime(generatedAt)} (local time)`; |
| 101 | + writeLine(color.dim(generatedAtText), generatedAtText); |
| 102 | + process.stdout.write(`├${"─".repeat(BOX_WIDTH)}┤\n`); |
| 103 | + writeQuota("5-hour quota", usage.per5HourPercentage, usage.per5HourResetTime); |
| 104 | + process.stdout.write(`├${"─".repeat(BOX_WIDTH)}┤\n`); |
| 105 | + writeQuota("1-week quota", usage.per1WeekPercentage, usage.per1WeekResetTime); |
| 106 | + process.stdout.write(`└${"─".repeat(BOX_WIDTH)}┘\n`); |
| 107 | +} |
| 108 | + |
| 109 | +export default defineCommand({ |
| 110 | + description: "Show Token Plan quota usage as core JSON or a human-readable view", |
| 111 | + auth: "console", |
| 112 | + usageArgs: "<--json | --view> [flags]", |
| 113 | + flags: { |
| 114 | + json: { |
| 115 | + type: "switch", |
| 116 | + description: "Output only the four core usage fields as JSON", |
| 117 | + }, |
| 118 | + view: { |
| 119 | + type: "switch", |
| 120 | + description: "Render a compact human-readable quota view", |
| 121 | + }, |
| 122 | + }, |
| 123 | + exampleArgs: ["--json", "--view"], |
| 124 | + validate: (flags) => |
| 125 | + flags.json === flags.view ? "Choose exactly one of --json or --view." : undefined, |
| 126 | + async run(ctx) { |
| 127 | + const { flags, settings } = ctx; |
| 128 | + |
| 129 | + if (settings.dryRun) { |
| 130 | + emitResult({ api: TOKEN_PLAN_USAGE_API, data: {} }, "json"); |
| 131 | + return; |
| 132 | + } |
| 133 | + |
| 134 | + const result = await ctx.client.console(TOKEN_PLAN_USAGE_API, {}); |
| 135 | + const usage = readUsage(result); |
| 136 | + |
| 137 | + if (flags.json) { |
| 138 | + emitResult(usage, "json"); |
| 139 | + return; |
| 140 | + } |
| 141 | + |
| 142 | + printView(usage, Date.now()); |
| 143 | + }, |
| 144 | +}); |
0 commit comments