@yangzhenchen/dsh-balance 0.0.0-stage → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js ADDED
@@ -0,0 +1,1627 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "@yangzhenchen/dsh-balance",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
+ var React = require("react");
8
+ // `react-dom` is a platform seed word, but the row must survive a shell
9
+ // that does not seed it: the panel then renders inline instead of portaled.
10
+ var ReactDOM = null;
11
+ try {
12
+ ReactDOM = require("react-dom");
13
+ } catch (_error) {
14
+ ReactDOM = null;
15
+ }
16
+ /** Dictionary namespace owned by this plugin. */
17
+ const NS = "balance";
18
+ /** Sidebar seat rendered directly above the account/avatar row. */
19
+ const SLOT = "sidebar.footer.action";
20
+ /** Balance poll interval while the page is visible. */
21
+ const POLL_MS = 15000;
22
+ /** Usage poll interval while the page is visible. */
23
+ const USAGE_POLL_MS = 60000;
24
+ /** Usage route, relative to the page so a mounted sub-path still resolves. */
25
+ const USAGE_ROUTE = "dsh-balance/usage";
26
+ /** Days the Host aggregates: 53 calendar weeks. */
27
+ const USAGE_DAYS = 371;
28
+ /** Data source persistence key. */
29
+ const SOURCE_STORAGE_KEY = "dsh-balance/usage-source";
30
+ /** Calendar columns: 52 completed weeks plus the current one. */
31
+ const CALENDAR_WEEKS = 53;
32
+ /** Retry cadence while the Host is still indexing history. */
33
+ const USAGE_SCAN_RETRY_MS = 2000;
34
+ /** Maximum background retries while the Host reports `scanning`. */
35
+ const USAGE_SCAN_RETRIES = 20;
36
+ /** Hour strip height in CSS pixels. */
37
+ const HOUR_CHART_HEIGHT = 44;
38
+ /** Beijing wall clock, the basis of the price calendar (no DST). */
39
+ const BEIJING_OFFSET_MINUTES = 480;
40
+ /** Peak windows as Beijing minute-of-day, half-open: [start, end). */
41
+ const PEAK_WINDOWS = [[9 * 60, 12 * 60], [14 * 60, 18 * 60]];
42
+ /** DeepSeek's price table, the place to check the rule. */
43
+ const PRICING_URL = "https://api-docs.deepseek.com/zh-cn/quick_start/pricing";
44
+ /** Weekday statutory holidays in mainland China (weekends are off-peak all day). */
45
+ const HOLIDAYS = new Set([
46
+ "2026-01-01",
47
+ "2026-01-02",
48
+ "2026-02-16",
49
+ "2026-02-17",
50
+ "2026-02-18",
51
+ "2026-02-19",
52
+ "2026-02-20",
53
+ "2026-02-23",
54
+ "2026-04-06",
55
+ "2026-05-01",
56
+ "2026-05-04",
57
+ "2026-05-05",
58
+ "2026-06-19",
59
+ "2026-09-25",
60
+ "2026-10-01",
61
+ "2026-10-02",
62
+ "2026-10-05",
63
+ "2026-10-06",
64
+ "2026-10-07",
65
+ "2027-01-01",
66
+ "2027-02-05",
67
+ "2027-02-08",
68
+ "2027-02-09",
69
+ "2027-02-10",
70
+ "2027-02-11",
71
+ "2027-02-12",
72
+ "2027-04-05",
73
+ "2027-05-03",
74
+ "2027-05-04",
75
+ "2027-05-05",
76
+ "2027-06-09",
77
+ "2027-09-15",
78
+ "2027-10-01",
79
+ "2027-10-04",
80
+ "2027-10-05",
81
+ "2027-10-06",
82
+ "2027-10-07"
83
+ ]);
84
+ /** Years whose statutory-holiday calendar is baked in. */
85
+ const HOLIDAY_YEARS = [2026, 2027];
86
+ /** Viewport margin and trigger gap for the floating panel. */
87
+ const PANEL_MARGIN = 12;
88
+ const PANEL_GAP = 8;
89
+ const zh = {
90
+ label: "余额",
91
+ bonus: "赠金",
92
+ recharge: "充值余额",
93
+ loading: "—",
94
+ signedOut: "未登录",
95
+ retry: "点击重试",
96
+ refresh: "点击刷新余额",
97
+ updated: "更新于",
98
+ failed: "余额读取失败",
99
+ signedOutHint: "登录 DeepSeek 账号后可查看余额",
100
+ usageLabel: "Token 用量",
101
+ usageTitle: "Token 活动",
102
+ usageToday: "今日",
103
+ usageYesterday: "昨日",
104
+ usageVsYesterday: "较昨日",
105
+ usageHours: "今日时段",
106
+ usageLastMonths: "近 12 个月",
107
+ usageLast7: "近 7 天",
108
+ usageLast30: "近 30 天",
109
+ usageTotal: "总计",
110
+ usageSum: "合计",
111
+ usageLess: "少",
112
+ usageMore: "多",
113
+ usageModeDay: "每天",
114
+ usageModeWeek: "每周",
115
+ usageModeTotal: "累计总量",
116
+ usageInput: "输入",
117
+ usageOutput: "输出",
118
+ usageCacheRead: "缓存读取",
119
+ usageCacheWrite: "缓存写入",
120
+ usageRequestsLabel: "请求",
121
+ usageSessionsLabel: "会话",
122
+ usageRequests: "{count} 次",
123
+ usageSessions: "{count} 个",
124
+ usageHint: "点击查看 Token 活动",
125
+ usageRefresh: "刷新用量",
126
+ usageClose: "关闭",
127
+ usageScanning: "正在统计…",
128
+ usageFailed: "用量读取失败",
129
+ usageRetry: "点击重试",
130
+ usageEmpty: "暂无用量数据",
131
+ usageRefreshFailed: "刷新失败,显示上次结果",
132
+ usageSourceLocal: "本机",
133
+ usageSourceAccount: "账号",
134
+ usageTodayUtc: "今日(UTC)",
135
+ usageAccountMonth: "本月",
136
+ usageAccountCostToday: "今日费用",
137
+ usageAccountCostMonth: "本月费用",
138
+ usageAccountNote: "账号口径 · 平台按 UTC 日统计 · 无小时数据",
139
+ usageAccountPartial: "部分月份读取失败",
140
+ usageAccountMissing: "未登录 DeepSeek 账号,读不到账号用量",
141
+ usageAccountAuth: "登录已失效,请重新登录 DeepSeek 账号",
142
+ usageAccountNetwork: "账号用量读取失败",
143
+ tariffPeak: "峰时",
144
+ tariffOff: "谷时",
145
+ tariffPeakShort: "峰时 · 标准价",
146
+ tariffOffShort: "谷时 · 5 折",
147
+ tariffToPeak: "距峰时开始 {time}",
148
+ tariffToOff: "距峰时结束 {time}",
149
+ tariffSoon: "不到 1 分钟",
150
+ tariffMinutes: "{count} 分钟",
151
+ tariffHours: "{count} 小时",
152
+ tariffHoursMinutes: "{count} 小时 {minutes} 分",
153
+ tariffClock: "北京时间 {clock}",
154
+ tariffRule: "峰时:周一至周五 09:00–12:00、14:00–18:00(北京时间,法定节假日除外);其余时间为谷时(官方称空闲时段),价格是峰时的 50%。",
155
+ tariffRuleShort: "周一至周五 09:00–12:00、14:00–18:00 为峰时,其余时间谷时 5 折",
156
+ tariffWeekend: "周末全天谷时",
157
+ tariffHoliday: "法定节假日全天谷时",
158
+ tariffEstimate: "{year} 年节假日日历未收录,按工作日估算",
159
+ tariffBand: "浅色区间为峰时",
160
+ tariffSource: "价格规则见 DeepSeek 官方价格页"
161
+ };
162
+ const en = {
163
+ label: "Balance",
164
+ bonus: "Bonus",
165
+ recharge: "Balance",
166
+ loading: "—",
167
+ signedOut: "Signed out",
168
+ retry: "Retry",
169
+ refresh: "Refresh balance",
170
+ updated: "Updated",
171
+ failed: "Balance unavailable",
172
+ signedOutHint: "Sign in to your DeepSeek account to see your balance",
173
+ usageLabel: "Token usage",
174
+ usageTitle: "Token activity",
175
+ usageToday: "Today",
176
+ usageYesterday: "Yesterday",
177
+ usageVsYesterday: "vs yesterday",
178
+ usageHours: "Today by hour",
179
+ usageLastMonths: "Last 12 months",
180
+ usageLast7: "7 days",
181
+ usageLast30: "30 days",
182
+ usageTotal: "All time",
183
+ usageSum: "Total",
184
+ usageLess: "Less",
185
+ usageMore: "More",
186
+ usageModeDay: "Daily",
187
+ usageModeWeek: "Weekly",
188
+ usageModeTotal: "Cumulative",
189
+ usageInput: "Input",
190
+ usageOutput: "Output",
191
+ usageCacheRead: "Cache read",
192
+ usageCacheWrite: "Cache write",
193
+ usageRequestsLabel: "Requests",
194
+ usageSessionsLabel: "Sessions",
195
+ usageRequests: "{count}",
196
+ usageSessions: "{count}",
197
+ usageHint: "Click for token activity",
198
+ usageRefresh: "Refresh usage",
199
+ usageClose: "Close",
200
+ usageScanning: "Counting…",
201
+ usageFailed: "Usage unavailable",
202
+ usageRetry: "Retry",
203
+ usageEmpty: "No usage yet",
204
+ usageRefreshFailed: "Refresh failed; showing the last result",
205
+ usageSourceLocal: "This PC",
206
+ usageSourceAccount: "Account",
207
+ usageTodayUtc: "Today (UTC)",
208
+ usageAccountMonth: "This month",
209
+ usageAccountCostToday: "Today cost",
210
+ usageAccountCostMonth: "This month cost",
211
+ usageAccountNote: "Account data · platform days are UTC · no hourly breakdown",
212
+ usageAccountPartial: "some months could not be read",
213
+ usageAccountMissing: "Sign in to your DeepSeek account to read account usage",
214
+ usageAccountAuth: "Sign-in expired; sign in to your DeepSeek account again",
215
+ usageAccountNetwork: "Account usage unavailable",
216
+ tariffPeak: "Peak",
217
+ tariffOff: "Off-peak",
218
+ tariffPeakShort: "Peak · standard price",
219
+ tariffOffShort: "Off-peak · 50% off",
220
+ tariffToPeak: "Peak starts in {time}",
221
+ tariffToOff: "Peak ends in {time}",
222
+ tariffSoon: "under a minute",
223
+ tariffMinutes: "{count} min",
224
+ tariffHours: "{count} h",
225
+ tariffHoursMinutes: "{count} h {minutes} m",
226
+ tariffClock: "{clock} Beijing time",
227
+ tariffRule: "Peak: Mon–Fri 09:00–12:00 and 14:00–18:00 Beijing time, excluding statutory holidays. Off-peak costs 50% of the peak price.",
228
+ tariffRuleShort: "Peak is Mon–Fri 09:00–12:00 and 14:00–18:00; everything else is off-peak at 50%.",
229
+ tariffWeekend: "Weekend: off-peak all day",
230
+ tariffHoliday: "Statutory holiday: off-peak all day",
231
+ tariffEstimate: "No holiday calendar for {year}; assuming weekdays",
232
+ tariffBand: "Shaded hours are peak",
233
+ tariffSource: "Rule from the DeepSeek pricing page"
234
+ };
235
+ const styleText = [
236
+ ".dsb_row{display:flex;align-items:center;justify-content:space-between;gap:8px;width:100%;height:30px;box-sizing:border-box;padding:0 8px;border:0;border-radius:var(--dsw-radius-md);background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;line-height:18px;text-align:left;cursor:pointer;-webkit-app-region:no-drag}",
237
+ ".dsb_row:hover{background:var(--dsw-alias-interactive-bg-hover)}",
238
+ ".dsb_row:focus-visible{outline:var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:1px}",
239
+ ".dsb_label{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}",
240
+ ".dsb_amounts{flex:0 0 auto;display:flex;align-items:baseline;gap:5px;white-space:nowrap;font-variant-numeric:tabular-nums}",
241
+ ".dsb_value{color:var(--dsw-alias-label-primary);font-weight:500}",
242
+ ".dsb_value[data-phase=loading],.dsb_value[data-phase=failed],.dsb_value[data-phase=signed-out]{color:var(--dsw-alias-label-tertiary);font-weight:400}",
243
+ ".dsb_bonus{color:var(--dsw-alias-label-tertiary);font-size:11px}",
244
+ ".dsb_phase{flex:0 0 auto;display:inline-flex;align-items:center;height:16px;padding:0 5px;border-radius:999px;font-size:10px;font-weight:500;line-height:16px;letter-spacing:.02em;white-space:nowrap;background:var(--dsw-alias-bg-layer-3);color:var(--dsw-alias-label-secondary)}",
245
+ ".dsb_phase[data-period='off-peak']{color:var(--dsw-alias-state-success-primary);background:color-mix(in srgb,var(--dsw-alias-state-success-primary) 15%,transparent)}",
246
+ ".dsb_phase[data-period='peak']{color:var(--dsw-alias-state-warn-label,var(--dsw-alias-label-secondary));background:color-mix(in srgb,var(--dsw-alias-state-warn-primary) 15%,transparent)}",
247
+ ".dsb_row[aria-expanded=true]{background:var(--dsw-alias-interactive-bg-hover)}",
248
+ ".dsb_rows{display:flex;flex-direction:column;width:100%;min-width:0}",
249
+ ".dsu_panel{position:fixed;z-index:1100;box-sizing:border-box;width:min(680px,calc(100vw - 24px));padding:14px 16px 12px;border:.5px solid var(--dsw-alias-border-l1);border-radius:var(--dsw-radius-lg);background:var(--dsw-specific-menu,var(--dsw-alias-bg-layer-2));box-shadow:var(--dsw-elevation-prominent,0 8px 24px rgba(0,0,0,.16));backdrop-filter:var(--dsw-menu-backdrop-filter,blur(20px));color:var(--dsw-alias-label-secondary);font-size:12px;line-height:18px;overflow:auto;overscroll-behavior:contain}",
250
+ ".dsu_header{display:flex;align-items:center;gap:4px}",
251
+ ".dsu_title{flex:1 1 auto;min-width:0;color:var(--dsw-alias-label-primary);font-size:13px;font-weight:500}",
252
+ ".dsu_modes{display:inline-flex;align-items:center;gap:2px;margin-right:6px}",
253
+ ".dsu_mode{padding:2px 7px;border:0;border-radius:var(--dsw-radius-xs);background:transparent;color:var(--dsw-alias-label-tertiary);font:inherit;font-size:11px;line-height:16px;white-space:nowrap;cursor:pointer}",
254
+ ".dsu_mode:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary)}",
255
+ ".dsu_mode[data-active=true]{color:var(--dsw-alias-label-primary);font-weight:500}",
256
+ ".dsu_mode:focus-visible{outline:var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:-1px}",
257
+ ".dsu_divider{width:1px;height:14px;margin:0 6px;background:var(--dsw-alias-border-l2)}",
258
+ ".dsu_accountBody{display:flex;flex-direction:column;gap:8px;margin-top:12px;padding-top:12px;border-top:.5px solid var(--dsw-alias-border-l2)}",
259
+ ".dsu_statGrid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px 16px}",
260
+ ".dsu_accountCell{display:flex;flex-direction:column;gap:2px;min-width:0}",
261
+ ".dsu_accountCell span{color:var(--dsw-alias-label-tertiary);font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}",
262
+ ".dsu_accountCell b{color:var(--dsw-alias-label-secondary);font-size:14px;font-weight:600;line-height:20px;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}",
263
+ ".dsu_accountCell[data-emphasis=true] b{color:var(--dsw-alias-label-primary);font-size:18px;line-height:24px}",
264
+ ".dsu_icon{flex:none;display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;padding:0;border:0;border-radius:var(--dsw-radius-sm);background:transparent;color:var(--dsw-alias-label-tertiary);cursor:pointer}",
265
+ ".dsu_icon:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary)}",
266
+ ".dsu_icon:focus-visible{outline:var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:1px}",
267
+ ".dsu_icon[data-busy=true] svg{animation:dsu-spin 900ms linear infinite}",
268
+ "@keyframes dsu-spin{to{transform:rotate(360deg)}}",
269
+ ".dsu_caption{display:flex;justify-content:space-between;gap:8px;margin-top:6px;color:var(--dsw-alias-label-tertiary);font-size:11px;font-variant-numeric:tabular-nums;min-height:16px}",
270
+ ".dsu_caption b{color:var(--dsw-alias-label-secondary);font-weight:500}",
271
+ ".dsu_calendar{display:grid;grid-auto-flow:column;gap:2px;margin-top:2px}",
272
+ ".dsu_cell{width:100%;height:100%;border-radius:2px;background:var(--dsw-alias-bg-mask-2,var(--dsw-alias-bg-layer-3));cursor:default}",
273
+ ".dsu_cell[data-empty=true]{visibility:hidden}",
274
+ ".dsu_cell[data-level]{background:var(--dsw-alias-state-business-primary)}",
275
+ ".dsu_cell[data-level='1']{opacity:.28}",
276
+ ".dsu_cell[data-level='2']{opacity:.5}",
277
+ ".dsu_cell[data-level='3']{opacity:.72}",
278
+ ".dsu_cell[data-level='4']{opacity:1}",
279
+ ".dsu_cell:hover{outline:1px solid var(--dsw-alias-label-tertiary);outline-offset:0}",
280
+ ".dsu_months{display:grid;margin-top:4px;color:var(--dsw-alias-label-tertiary);font-size:10px;line-height:14px}",
281
+ ".dsu_months span{white-space:nowrap}",
282
+ ".dsu_legendRow{display:flex;justify-content:flex-end;margin-top:2px}",
283
+ ".dsu_legend{display:inline-flex;align-items:center;gap:3px;color:var(--dsw-alias-label-tertiary);font-size:10px}",
284
+ ".dsu_swatch{width:9px;height:9px;border-radius:2px;background:var(--dsw-alias-bg-mask-2,var(--dsw-alias-bg-layer-3))}",
285
+ ".dsu_swatch[data-level]{background:var(--dsw-alias-state-business-primary)}",
286
+ ".dsu_swatch[data-level='1']{opacity:.28}",
287
+ ".dsu_swatch[data-level='2']{opacity:.5}",
288
+ ".dsu_swatch[data-level='3']{opacity:.72}",
289
+ ".dsu_swatch[data-level='4']{opacity:1}",
290
+ ".dsu_body{display:flex;gap:20px;margin-top:12px;padding-top:12px;border-top:.5px solid var(--dsw-alias-border-l2)}",
291
+ ".dsu_left{flex:1 1 auto;min-width:0;display:flex;flex-direction:column;gap:2px}",
292
+ ".dsu_right{flex:0 0 230px;min-width:0;display:flex;flex-direction:column;gap:6px}",
293
+ ".dsu_headline{display:flex;align-items:baseline;gap:6px}",
294
+ ".dsu_big{color:var(--dsw-alias-label-primary);font-size:22px;font-weight:600;line-height:28px;letter-spacing:-.01em;font-variant-numeric:tabular-nums}",
295
+ ".dsu_unit{color:var(--dsw-alias-label-tertiary);font-size:11px}",
296
+ ".dsu_delta{color:var(--dsw-alias-label-tertiary);font-size:11px;white-space:nowrap}",
297
+ ".dsu_delta[data-dir=up]{color:var(--dsw-alias-state-warn-label,var(--dsw-alias-label-tertiary))}",
298
+ ".dsu_chart{position:relative;display:flex;align-items:flex-end;gap:3px;height:var(--dsu-chart-height);padding-top:2px;border-bottom:1px solid var(--dsw-alias-border-l1)}",
299
+ ".dsu_chartWrap{position:relative}",
300
+ ".dsu_bands{position:absolute;inset:0;pointer-events:none}",
301
+ ".dsu_band{position:absolute;top:0;bottom:0;background:var(--dsw-alias-state-warn-primary);opacity:.08}",
302
+ ".dsu_chartNote{margin-top:2px;color:var(--dsw-alias-label-tertiary);font-size:10px;line-height:14px}",
303
+ ".dsu_tariff{display:inline-flex;align-items:center;gap:4px;color:var(--dsw-alias-label-tertiary)}",
304
+ ".dsu_tariff[data-period='off-peak']{color:var(--dsw-alias-state-success-primary)}",
305
+ ".dsu_tariff[data-period='peak']{color:var(--dsw-alias-state-warn-label,var(--dsw-alias-label-tertiary))}",
306
+ ".dsu_tariff i{width:5px;height:5px;border-radius:50%;background:currentColor}",
307
+ ".dsu_col{flex:1 1 0;min-width:0;height:100%;display:flex;align-items:flex-end;cursor:default}",
308
+ ".dsu_bar{width:100%;min-height:0;border-radius:2px 2px 0 0;background:var(--dsw-alias-state-business-primary);opacity:.55;transition:opacity 120ms ease}",
309
+ ".dsu_bar[data-peak=true]{opacity:.95}",
310
+ ".dsu_col:hover .dsu_bar{opacity:.95}",
311
+ ".dsu_axis{display:flex;justify-content:space-between;color:var(--dsw-alias-label-tertiary);font-size:10px;line-height:14px;font-variant-numeric:tabular-nums}",
312
+ ".dsu_grid{display:grid;grid-template-columns:1fr 1fr;gap:2px 16px}",
313
+ ".dsu_pair{display:flex;align-items:baseline;justify-content:space-between;gap:8px;color:var(--dsw-alias-label-tertiary);font-size:11px}",
314
+ ".dsu_pair b{color:var(--dsw-alias-label-secondary);font-weight:500;font-variant-numeric:tabular-nums;white-space:nowrap}",
315
+ ".dsu_footer{display:flex;flex-wrap:wrap;gap:2px 14px;margin-top:10px;color:var(--dsw-alias-label-tertiary);font-size:11px}",
316
+ ".dsu_footer b{color:var(--dsw-alias-label-secondary);font-weight:500;font-variant-numeric:tabular-nums}",
317
+ ".dsu_note{margin-top:6px;color:var(--dsw-alias-label-tertiary);font-size:11px}",
318
+ ".dsu_empty{padding:26px 0;text-align:center;color:var(--dsw-alias-label-tertiary)}"
319
+ ].join("");
320
+ const styleId = "@yangzhenchen/dsh-balance/balance.css";
321
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(styleId) + "]") === null) {
322
+ const tag = document.createElement("style");
323
+ tag.dataset.plugin = "@yangzhenchen/dsh-balance";
324
+ tag.dataset.pluginCss = styleId;
325
+ tag.textContent = styleText;
326
+ document.head.appendChild(tag);
327
+ }
328
+ /**
329
+ * Render one decimal balance with Platform Web's display rules.
330
+ * @param raw - server-authored decimal string.
331
+ * @param symbol - currency symbol.
332
+ * @returns grouped signed currency text.
333
+ */
334
+ function formatAmount(raw, symbol) {
335
+ const value = Number(raw);
336
+ if (!Number.isFinite(value)) return symbol + "—";
337
+ if (value > 0 && value < 0.01) return "<" + symbol + "0.01";
338
+ if (value < 0 && value > -0.01) return "-" + symbol + "0.01";
339
+ const cents = value >= 0 ? Math.trunc(value * 100) / 100 : Math.round(value * 100) / 100;
340
+ const text = new Intl.NumberFormat("en-US", {
341
+ minimumFractionDigits: 2,
342
+ maximumFractionDigits: 2
343
+ }).format(Math.abs(cents));
344
+ return (cents < 0 ? "-" : "") + symbol + text;
345
+ }
346
+ /**
347
+ * @param currency - wallet currency code.
348
+ * @returns the symbol Platform Web uses for it.
349
+ */
350
+ function currencySymbol(currency) {
351
+ if (currency === "CNY") return "¥";
352
+ if (currency === "USD") return "$";
353
+ return String(currency ?? "") + " ";
354
+ }
355
+ /**
356
+ * @param wallets - wallet rows from the account balance.
357
+ * @returns all amounts, one per currency, joined for a single line.
358
+ */
359
+ function formatWallets(wallets) {
360
+ if (!Array.isArray(wallets) || wallets.length === 0) return formatAmount("0", "¥");
361
+ return wallets.map((wallet) => formatAmount(wallet?.balance, currencySymbol(wallet?.currency))).join(" · ");
362
+ }
363
+ /** @returns positive bonus wallets only; Platform omits zero-bonus rows. */
364
+ function positiveBonusWallets(wallets) {
365
+ if (!Array.isArray(wallets)) return [];
366
+ return wallets.filter((wallet) => Number(wallet?.balance) > 0);
367
+ }
368
+ const compactFormats = new Map();
369
+ /**
370
+ * @param tag - BCP 47 locale.
371
+ * @returns a memoized compact number formatter.
372
+ */
373
+ function compactFormat(tag) {
374
+ let format = compactFormats.get(tag);
375
+ if (format === undefined) {
376
+ format = new Intl.NumberFormat(tag, {
377
+ notation: "compact",
378
+ maximumFractionDigits: 1
379
+ });
380
+ compactFormats.set(tag, format);
381
+ }
382
+ return format;
383
+ }
384
+ /**
385
+ * @param value - token count.
386
+ * @param tag - BCP 47 locale.
387
+ * @returns compact text such as `1.7亿`, `174M`, or `—`.
388
+ */
389
+ function compactNumber(value, tag) {
390
+ const count = Number(value);
391
+ if (!Number.isFinite(count)) return "—";
392
+ if (count === 0) return "0";
393
+ return compactFormat(tag).format(count);
394
+ }
395
+ /**
396
+ * @param today - today's total.
397
+ * @param yesterday - yesterday's total.
398
+ * @returns percentage change, or null when no comparison is meaningful.
399
+ */
400
+ function percentDelta(today, yesterday) {
401
+ const current = Number(today);
402
+ const previous = Number(yesterday);
403
+ if (!Number.isFinite(current) || !Number.isFinite(previous) || previous <= 0) return null;
404
+ const delta = (current - previous) / previous * 100;
405
+ return Number.isFinite(delta) ? delta : null;
406
+ }
407
+ /**
408
+ * @param delta - percentage change.
409
+ * @returns signed percent text, `±0%` when it rounds to nothing.
410
+ */
411
+ function formatPercent(delta) {
412
+ const value = Number(delta);
413
+ if (!Number.isFinite(value)) return "—";
414
+ if (Math.abs(value) < 0.1) return "±0%";
415
+ const digits = Math.abs(value) >= 100 ? 0 : 1;
416
+ return (value > 0 ? "+" : "-") + Math.abs(value).toFixed(digits) + "%";
417
+ }
418
+ /**
419
+ * @param instant - epoch milliseconds.
420
+ * @returns Beijing wall-clock fields for that instant.
421
+ */
422
+ function beijingParts(instant) {
423
+ const shifted = new Date(Number(instant) + BEIJING_OFFSET_MINUTES * 60000);
424
+ const year = shifted.getUTCFullYear();
425
+ const month = shifted.getUTCMonth() + 1;
426
+ const day = shifted.getUTCDate();
427
+ const pad = (value) => value < 10 ? "0" + value : String(value);
428
+ return {
429
+ year,
430
+ month,
431
+ day,
432
+ weekday: shifted.getUTCDay(),
433
+ minuteOfDay: shifted.getUTCHours() * 60 + shifted.getUTCMinutes(),
434
+ dateKey: year + "-" + pad(month) + "-" + pad(day),
435
+ dayStart: Date.UTC(year, month - 1, day) - BEIJING_OFFSET_MINUTES * 60000
436
+ };
437
+ }
438
+ /**
439
+ * @param instant - epoch milliseconds.
440
+ * @returns true inside a Beijing weekday peak window that is not a holiday.
441
+ */
442
+ function isPeakAt(instant) {
443
+ const parts = beijingParts(instant);
444
+ if (parts.weekday === 0 || parts.weekday === 6) return false;
445
+ if (HOLIDAYS.has(parts.dateKey)) return false;
446
+ return PEAK_WINDOWS.some(([start, end]) => parts.minuteOfDay >= start && parts.minuteOfDay < end);
447
+ }
448
+ /**
449
+ * Everything the rows need to describe the current price period.
450
+ * @param instant - epoch milliseconds.
451
+ * @returns period, the next flip, countdown, holiday context, and hour bands.
452
+ */
453
+ function tariffStatus(instant) {
454
+ const at = Number.isFinite(Number(instant)) ? Number(instant) : Date.now();
455
+ const parts = beijingParts(at);
456
+ const weekend = parts.weekday === 0 || parts.weekday === 6;
457
+ const holiday = HOLIDAYS.has(parts.dateKey);
458
+ const peak = !weekend && !holiday && PEAK_WINDOWS.some(([start, end]) => parts.minuteOfDay >= start && parts.minuteOfDay < end);
459
+ // The next boundary belongs to the next period by construction: window
460
+ // starts are peak, window ends are off-peak, and the day edges are off.
461
+ let next = null;
462
+ for (let day = 0; day < 21 && next === null; day += 1) {
463
+ const base = parts.dayStart + day * 86400000;
464
+ const edges = [];
465
+ for (const [start, end] of PEAK_WINDOWS) {
466
+ edges.push(base + start * 60000, base + end * 60000);
467
+ }
468
+ edges.sort((left, right) => left - right);
469
+ for (const edge of edges) {
470
+ if (edge <= at) continue;
471
+ if (isPeakAt(edge) !== peak) {
472
+ next = edge;
473
+ break;
474
+ }
475
+ }
476
+ }
477
+ // The hour strip buckets by the browser offset, so peak shading only
478
+ // lines up when the browser clock is Beijing time.
479
+ const beijingClock = -new Date(at).getTimezoneOffset() === BEIJING_OFFSET_MINUTES;
480
+ const peakDay = !weekend && !holiday;
481
+ return {
482
+ period: peak ? "peak" : "off-peak",
483
+ nextSwitchAt: next,
484
+ msUntilSwitch: next === null ? null : Math.max(0, next - at),
485
+ weekend,
486
+ holiday,
487
+ beijingClock,
488
+ bands: peakDay && beijingClock ? PEAK_WINDOWS.map(([start, end]) => ({
489
+ start: start / 60,
490
+ end: end / 60
491
+ })) : [],
492
+ covered: HOLIDAY_YEARS.includes(parts.year),
493
+ year: parts.year,
494
+ dateKey: parts.dateKey,
495
+ minuteOfDay: parts.minuteOfDay
496
+ };
497
+ }
498
+ /**
499
+ * @param ms - remaining time in milliseconds.
500
+ * @param t - translator.
501
+ * @returns compact remaining time, never a negative clock.
502
+ */
503
+ function formatCountdown(ms, t) {
504
+ const duration = Number(ms);
505
+ if (!Number.isFinite(duration)) return t("tariffSoon");
506
+ const minutes = Math.ceil(Math.max(0, duration) / 60000);
507
+ if (minutes <= 0) return t("tariffSoon");
508
+ if (minutes < 60) return t("tariffMinutes", { count: minutes });
509
+ const hours = Math.floor(minutes / 60);
510
+ const rest = minutes % 60;
511
+ return rest === 0 ? t("tariffHours", { count: hours }) : t("tariffHoursMinutes", {
512
+ count: hours,
513
+ minutes: rest
514
+ });
515
+ }
516
+ /**
517
+ * @param instant - epoch milliseconds.
518
+ * @returns `HH:MM` on the Beijing clock.
519
+ */
520
+ function switchClock(instant) {
521
+ const shifted = new Date(Number(instant) + BEIJING_OFFSET_MINUTES * 60000);
522
+ return String(shifted.getUTCHours()).padStart(2, "0") + ":" + String(shifted.getUTCMinutes()).padStart(2, "0");
523
+ }
524
+ /**
525
+ * @param status - from {@link tariffStatus}.
526
+ * @param t - translator.
527
+ * @returns the short price-period headline.
528
+ */
529
+ function tariffHeadline(status, t) {
530
+ return status.period === "peak" ? t("tariffPeakShort") : t("tariffOffShort");
531
+ }
532
+ /**
533
+ * @param status - from {@link tariffStatus}.
534
+ * @param t - translator.
535
+ * @returns the countdown sentence, or an empty string when nothing flips.
536
+ */
537
+ function tariffCountdown(status, t) {
538
+ if (status.nextSwitchAt === null || status.msUntilSwitch === null) return "";
539
+ return t(status.period === "peak" ? "tariffToOff" : "tariffToPeak", {
540
+ time: formatCountdown(status.msUntilSwitch, t)
541
+ });
542
+ }
543
+ /**
544
+ * Keep the price period fresh without polling the Host.
545
+ * @returns the current {@link tariffStatus}, refreshed every 15 seconds.
546
+ */
547
+ function useTariff() {
548
+ const [status, setStatus] = React.useState(() => tariffStatus(Date.now()));
549
+ React.useEffect(() => {
550
+ const tick = () => setStatus(tariffStatus(Date.now()));
551
+ const timer = window.setInterval(tick, 15000);
552
+ document.addEventListener("visibilitychange", tick);
553
+ window.addEventListener("focus", tick);
554
+ return () => {
555
+ window.clearInterval(timer);
556
+ document.removeEventListener("visibilitychange", tick);
557
+ window.removeEventListener("focus", tick);
558
+ };
559
+ }, []);
560
+ return status;
561
+ }
562
+ /**
563
+ * @param value - bar value.
564
+ * @param max - tallest value in the series.
565
+ * @param height - chart height in pixels.
566
+ * @returns a visible bar height; zero stays flat.
567
+ */
568
+ function barHeight(value, max, height) {
569
+ const current = Number(value);
570
+ const ceiling = Number(max);
571
+ if (!Number.isFinite(current) || current <= 0 || !Number.isFinite(ceiling) || ceiling <= 0) return 0;
572
+ return Math.max(2, Math.round(current / ceiling * height));
573
+ }
574
+ /**
575
+ * @param date - `YYYY-MM-DD`.
576
+ * @returns `MM-DD`, or the input when it does not match.
577
+ */
578
+ function shortDate(date) {
579
+ return typeof date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(date) ? date.slice(5) : String(date ?? "");
580
+ }
581
+ /**
582
+ * @param date - `YYYY-MM-DD`.
583
+ * @returns the same calendar day at UTC midnight.
584
+ */
585
+ function parseIsoDate(date) {
586
+ return new Date(String(date) + "T00:00:00Z");
587
+ }
588
+ /**
589
+ * @param date - UTC-midnight date.
590
+ * @returns `YYYY-MM-DD`.
591
+ */
592
+ function isoDate(date) {
593
+ return date.toISOString().slice(0, 10);
594
+ }
595
+ /**
596
+ * @param date - UTC-midnight date.
597
+ * @param days - signed day count.
598
+ * @returns the shifted date.
599
+ */
600
+ function addDays(date, days) {
601
+ return new Date(date.getTime() + days * 86400000);
602
+ }
603
+ /**
604
+ * @param date - UTC-midnight date.
605
+ * @returns ISO weekday, Monday 1 through Sunday 7.
606
+ */
607
+ function isoWeekday(date) {
608
+ const day = date.getUTCDay();
609
+ return day === 0 ? 7 : day;
610
+ }
611
+ /**
612
+ * Build the 53-week calendar grid ending with the Host's local "today".
613
+ * Columns are weeks (Monday first); each column holds seven day cells.
614
+ * @param data - Host usage payload.
615
+ * @returns `[{ start, cells }]` where a cell is a day entry or null.
616
+ */
617
+ function buildCalendar(data) {
618
+ const todayDate = typeof data?.today?.date === "string" ? parseIsoDate(data.today.date) : null;
619
+ if (todayDate === null || Number.isNaN(todayDate.getTime())) return [];
620
+ const byDate = new Map();
621
+ for (const entry of Array.isArray(data?.days) ? data.days : []) {
622
+ if (entry !== null && typeof entry === "object" && typeof entry.date === "string") byDate.set(entry.date, entry);
623
+ }
624
+ const currentMonday = addDays(todayDate, -(isoWeekday(todayDate) - 1));
625
+ const gridStart = addDays(currentMonday, -(CALENDAR_WEEKS - 1) * 7);
626
+ const weeks = [];
627
+ for (let column = 0; column < CALENDAR_WEEKS; column += 1) {
628
+ const cells = [];
629
+ for (let row = 0; row < 7; row += 1) {
630
+ const cellDate = addDays(gridStart, column * 7 + row);
631
+ if (cellDate.getTime() > todayDate.getTime()) {
632
+ cells.push(null);
633
+ continue;
634
+ }
635
+ const key = isoDate(cellDate);
636
+ cells.push(byDate.get(key) ?? {
637
+ date: key,
638
+ input: 0,
639
+ output: 0,
640
+ cacheRead: 0,
641
+ cacheWrite: 0,
642
+ total: 0,
643
+ requests: 0,
644
+ sessions: 0
645
+ });
646
+ }
647
+ weeks.push({
648
+ start: isoDate(addDays(gridStart, column * 7)),
649
+ cells
650
+ });
651
+ }
652
+ return weeks;
653
+ }
654
+ /**
655
+ * Resolve each cell's heat value for the active mode.
656
+ * @param weeks - grid from {@link buildCalendar}.
657
+ * @param mode - `day`, `week`, or `cumulative`.
658
+ * @returns per-column values plus each column's own total.
659
+ */
660
+ function calendarMetric(weeks, mode) {
661
+ const weekTotals = weeks.map((week) => week.cells.reduce((sum, cell) => sum + (cell === null ? 0 : Number(cell.total) || 0), 0));
662
+ let running = 0;
663
+ const values = weeks.map((week, column) => week.cells.map((cell) => {
664
+ if (cell === null) return null;
665
+ const total = Number(cell.total) || 0;
666
+ if (mode === "week") return weekTotals[column];
667
+ if (mode === "cumulative") {
668
+ running += total;
669
+ return running;
670
+ }
671
+ return total;
672
+ }));
673
+ return {
674
+ values,
675
+ weekTotals
676
+ };
677
+ }
678
+ /**
679
+ * Quartile thresholds over the positive heat values.
680
+ * @param values - flattened cell values.
681
+ * @returns three ascending thresholds, or null when nothing is nonzero.
682
+ */
683
+ function levelThresholds(values) {
684
+ const positive = values.filter((value) => Number.isFinite(value) && value > 0).sort((left, right) => left - right);
685
+ if (positive.length === 0) return null;
686
+ const at = (share) => positive[Math.min(positive.length - 1, Math.floor((positive.length - 1) * share))];
687
+ return [at(0.25), at(0.5), at(0.75)];
688
+ }
689
+ /**
690
+ * @param value - cell heat value.
691
+ * @param thresholds - from {@link levelThresholds}.
692
+ * @returns heat level 0 through 4.
693
+ */
694
+ function levelOf(value, thresholds) {
695
+ if (thresholds === null || !Number.isFinite(value) || value <= 0) return 0;
696
+ if (value <= thresholds[0]) return 1;
697
+ if (value <= thresholds[1]) return 2;
698
+ if (value <= thresholds[2]) return 3;
699
+ return 4;
700
+ }
701
+ /**
702
+ * Month labels for the calendar's bottom axis, one per month boundary.
703
+ * @param weeks - grid from {@link buildCalendar}.
704
+ * @param tag - BCP 47 locale.
705
+ * @returns `[{ column, label }]`.
706
+ */
707
+ function calendarMonths(weeks, tag) {
708
+ const format = new Intl.DateTimeFormat(tag, {
709
+ month: "short",
710
+ timeZone: "UTC"
711
+ });
712
+ const labels = [];
713
+ let previousMonth = null;
714
+ let lastColumn = -10;
715
+ weeks.forEach((week, column) => {
716
+ week.cells.forEach((cell) => {
717
+ if (cell === null) return;
718
+ const month = cell.date.slice(0, 7);
719
+ if (previousMonth === null) {
720
+ previousMonth = month;
721
+ return;
722
+ }
723
+ if (month === previousMonth) return;
724
+ previousMonth = month;
725
+ // A boundary one or two columns after the previous label would collide.
726
+ if (column - lastColumn < 3) return;
727
+ labels.push({
728
+ column,
729
+ label: format.format(parseIsoDate(cell.date))
730
+ });
731
+ lastColumn = column;
732
+ });
733
+ });
734
+ return labels;
735
+ }
736
+ /**
737
+ * @param ctx - client plugin context.
738
+ * @returns the BCP 47 tag for the active language.
739
+ */
740
+ function localeTag(ctx) {
741
+ return ctx.locale.getSnapshot().active === "zh" ? "zh-CN" : "en-US";
742
+ }
743
+ /** @returns a zeroed usage bucket. */
744
+ function zeroUsage() {
745
+ return {
746
+ input: 0,
747
+ output: 0,
748
+ cacheRead: 0,
749
+ cacheWrite: 0,
750
+ total: 0,
751
+ requests: 0,
752
+ sessions: 0
753
+ };
754
+ }
755
+ /**
756
+ * @param usage - a usage bucket from the Host payload.
757
+ * @returns the same shape with numeric fields filled in.
758
+ */
759
+ function usageBucket(usage) {
760
+ if (usage === null || typeof usage !== "object") return zeroUsage();
761
+ return {
762
+ input: Number(usage.input) || 0,
763
+ output: Number(usage.output) || 0,
764
+ cacheRead: Number(usage.cacheRead) || 0,
765
+ cacheWrite: Number(usage.cacheWrite) || 0,
766
+ total: Number(usage.total) || 0,
767
+ requests: Number(usage.requests) || 0,
768
+ sessions: Number(usage.sessions) || 0
769
+ };
770
+ }
771
+ /**
772
+ * Build the request identity one account call carries.
773
+ * @param ctx - client plugin context.
774
+ * @returns version, active language, and UTC offset in seconds.
775
+ */
776
+ function accountMetadata(ctx) {
777
+ const boot = typeof window !== "undefined" ? window.__DSH_BOOT__ : void 0;
778
+ const version = boot && boot.release && typeof boot.release.version === "string" ? boot.release.version : "0.0.0";
779
+ const snapshot = ctx.locale.getSnapshot();
780
+ return {
781
+ version,
782
+ locale: snapshot.active,
783
+ timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60
784
+ };
785
+ }
786
+ /**
787
+ * The bottom-pinned balance row.
788
+ * @param props - slot props plus this plugin's context and translator.
789
+ * @returns the row, or nothing on the collapsed rail.
790
+ */
791
+ function BalanceRow({ ctx, t, wide }) {
792
+ const [view, setView] = React.useState({
793
+ phase: "loading",
794
+ wallets: [],
795
+ bonusWallets: [],
796
+ at: 0
797
+ });
798
+ const [signedIn, setSignedIn] = React.useState(null);
799
+ const [, setLocaleRevision] = React.useState(0);
800
+ const alive = React.useRef(true);
801
+ const sequence = React.useRef(0);
802
+ const signedInRef = React.useRef(signedIn);
803
+ signedInRef.current = signedIn;
804
+ const read = React.useCallback(() => {
805
+ const run = ++sequence.current;
806
+ const publish = (next) => {
807
+ if (alive.current && run === sequence.current) setView(next);
808
+ };
809
+ Promise.resolve()
810
+ .then(() => ctx.remote.account.getBalance(accountMetadata(ctx)))
811
+ .then((result) => {
812
+ if (!result || !result.ok) {
813
+ publish({
814
+ phase: signedInRef.current === false ? "signed-out" : "failed",
815
+ wallets: [],
816
+ bonusWallets: [],
817
+ at: 0
818
+ });
819
+ return;
820
+ }
821
+ const balance = result.value ?? {};
822
+ if (balance.status !== "ready") {
823
+ publish({
824
+ phase: "failed",
825
+ wallets: [],
826
+ bonusWallets: [],
827
+ at: 0
828
+ });
829
+ return;
830
+ }
831
+ publish({
832
+ phase: "ready",
833
+ wallets: Array.isArray(balance.value) ? balance.value : [],
834
+ bonusWallets: Array.isArray(balance.bonusWallets) ? balance.bonusWallets : [],
835
+ at: Date.now()
836
+ });
837
+ if (signedInRef.current === null) setSignedIn(true);
838
+ })
839
+ .catch(() => {
840
+ publish({
841
+ phase: signedInRef.current === false ? "signed-out" : "failed",
842
+ wallets: [],
843
+ bonusWallets: [],
844
+ at: 0
845
+ });
846
+ });
847
+ }, [ctx]);
848
+ // Follow the account state stream: it names sign-in/sign-out and asks for a fresh read on every frame.
849
+ React.useEffect(() => {
850
+ alive.current = true;
851
+ let disposed = false;
852
+ let stream;
853
+ try {
854
+ stream = ctx.remote.$stream({
855
+ name: "account",
856
+ open: (signal) => ctx.remote.account.watch(signal),
857
+ ended: () => new Error("account stream ended")
858
+ });
859
+ } catch (_error) {
860
+ return () => {
861
+ alive.current = false;
862
+ };
863
+ }
864
+ (async () => {
865
+ try {
866
+ for await (const frame of stream) {
867
+ if (disposed) break;
868
+ const status = frame?.value?.status;
869
+ setSignedIn(status === "credential-stored");
870
+ if (status === "credential-stored") read();
871
+ try {
872
+ frame.accept();
873
+ } catch (_error) {}
874
+ }
875
+ } catch (_error) {}
876
+ })();
877
+ return () => {
878
+ disposed = true;
879
+ alive.current = false;
880
+ try {
881
+ stream.dispose();
882
+ } catch (_error) {}
883
+ };
884
+ }, [read]);
885
+ // Poll while visible; re-read on focus and on returning to the page.
886
+ React.useEffect(() => {
887
+ read();
888
+ const timer = window.setInterval(() => {
889
+ // The account stream triggers a read when a credential appears, so a signed-out page stays quiet.
890
+ if (signedInRef.current === false) return;
891
+ if (document.visibilityState !== "hidden") read();
892
+ }, POLL_MS);
893
+ const onVisible = () => {
894
+ if (document.visibilityState === "visible") read();
895
+ };
896
+ document.addEventListener("visibilitychange", onVisible);
897
+ window.addEventListener("focus", onVisible);
898
+ return () => {
899
+ window.clearInterval(timer);
900
+ document.removeEventListener("visibilitychange", onVisible);
901
+ window.removeEventListener("focus", onVisible);
902
+ };
903
+ }, [read]);
904
+ // Re-render with the active language without re-reading the balance.
905
+ React.useEffect(() => ctx.locale.subscribe(() => setLocaleRevision((value) => value + 1)), [ctx]);
906
+ const tariff = useTariff();
907
+ if (!wide) return null;
908
+ const phase = signedIn === false ? "signed-out" : view.phase;
909
+ const bonusWallets = phase === "ready" ? positiveBonusWallets(view.bonusWallets) : [];
910
+ let amount;
911
+ if (phase === "signed-out") amount = t("signedOut");
912
+ else if (phase === "failed") amount = t("retry");
913
+ else if (phase === "loading") amount = t("loading");
914
+ else amount = formatWallets(view.wallets);
915
+ const lines = [];
916
+ const countdown = tariffCountdown(tariff, t);
917
+ lines.push(tariffHeadline(tariff, t) + (countdown === "" ? "" : " · " + countdown));
918
+ if (tariff.holiday) lines.push(t("tariffHoliday"));
919
+ else if (tariff.weekend) lines.push(t("tariffWeekend"));
920
+ if (tariff.nextSwitchAt !== null) lines.push(t("tariffClock", { clock: switchClock(tariff.nextSwitchAt) }) + " · " + t("tariffRuleShort"));
921
+ else lines.push(t("tariffRuleShort"));
922
+ if (!tariff.covered) lines.push(t("tariffEstimate", { year: tariff.year }));
923
+ if (phase === "ready") {
924
+ lines.push(t("recharge") + ": " + formatWallets(view.wallets));
925
+ if (bonusWallets.length > 0) lines.push(t("bonus") + ": " + formatWallets(bonusWallets));
926
+ if (view.at > 0) lines.push(t("updated") + " " + new Date(view.at).toLocaleTimeString(ctx.locale.getSnapshot().active === "zh" ? "zh-CN" : "en-US", { hour12: false }));
927
+ } else if (phase === "signed-out") lines.push(t("signedOutHint"));
928
+ else if (phase === "failed") lines.push(t("failed"));
929
+ lines.push(t("refresh"));
930
+ const title = lines.join("\n");
931
+ return React.createElement("button", {
932
+ type: "button",
933
+ className: "dsb_row",
934
+ title,
935
+ "aria-label": t("label") + ": " + amount + " · " + t(tariff.period === "peak" ? "tariffPeak" : "tariffOff"),
936
+ "data-balance-phase": phase,
937
+ "data-tariff-period": tariff.period,
938
+ onClick: () => read()
939
+ }, React.createElement("span", { className: "dsb_label" }, t("label")), React.createElement("span", { className: "dsb_amounts" }, React.createElement("span", {
940
+ className: "dsb_phase",
941
+ "data-period": tariff.period
942
+ }, t(tariff.period === "peak" ? "tariffPeak" : "tariffOff")), React.createElement("span", {
943
+ className: "dsb_value",
944
+ "data-phase": phase
945
+ }, amount), bonusWallets.length > 0 ? React.createElement("span", { className: "dsb_bonus" }, "+" + formatWallets(bonusWallets)) : null));
946
+ }
947
+ /**
948
+ * Inline SVG icon.
949
+ * @param props - viewBox, size, and child paths.
950
+ * @returns the svg element.
951
+ */
952
+ function Icon({ viewBox, size, children }) {
953
+ return React.createElement("svg", {
954
+ viewBox,
955
+ width: size,
956
+ height: size,
957
+ fill: "none",
958
+ stroke: "currentColor",
959
+ strokeWidth: 1.4,
960
+ strokeLinecap: "round",
961
+ strokeLinejoin: "round",
962
+ "aria-hidden": "true",
963
+ focusable: "false"
964
+ }, children);
965
+ }
966
+ const MODE_STORAGE_KEY = "dsh-balance/usage-mode";
967
+ /**
968
+ * @returns the remembered calendar mode, or `day`.
969
+ */
970
+ function rememberedMode() {
971
+ try {
972
+ const stored = typeof window !== "undefined" && window.localStorage !== void 0 ? window.localStorage.getItem(MODE_STORAGE_KEY) : null;
973
+ if (stored === "week" || stored === "cumulative") return stored;
974
+ } catch (_error) {}
975
+ return "day";
976
+ }
977
+ /**
978
+ * @param mode - calendar mode to remember.
979
+ */
980
+ function rememberMode(mode) {
981
+ try {
982
+ if (typeof window !== "undefined" && window.localStorage !== void 0) window.localStorage.setItem(MODE_STORAGE_KEY, mode);
983
+ } catch (_error) {}
984
+ }
985
+ /**
986
+ * @returns the remembered usage source, or `local`.
987
+ */
988
+ function rememberedSource() {
989
+ try {
990
+ const stored = typeof window !== "undefined" && window.localStorage !== void 0 ? window.localStorage.getItem(SOURCE_STORAGE_KEY) : null;
991
+ if (stored === "account") return stored;
992
+ } catch (_error) {}
993
+ return "local";
994
+ }
995
+ /**
996
+ * @param source - usage source to remember.
997
+ */
998
+ function rememberSource(source) {
999
+ try {
1000
+ if (typeof window !== "undefined" && window.localStorage !== void 0) window.localStorage.setItem(SOURCE_STORAGE_KEY, source);
1001
+ } catch (_error) {}
1002
+ }
1003
+ const moneyFormats = new Map();
1004
+ /**
1005
+ * @param value - amount in the platform currency.
1006
+ * @param currency - ISO currency code.
1007
+ * @param tag - BCP 47 locale.
1008
+ * @returns `¥12.34`, `$12.34`, or `—`.
1009
+ */
1010
+ function formatMoney(value, currency, tag) {
1011
+ const amount = Number(value);
1012
+ if (!Number.isFinite(amount)) return "—";
1013
+ let format = moneyFormats.get(tag);
1014
+ if (format === undefined) {
1015
+ format = new Intl.NumberFormat(tag, {
1016
+ minimumFractionDigits: 2,
1017
+ maximumFractionDigits: 2
1018
+ });
1019
+ moneyFormats.set(tag, format);
1020
+ }
1021
+ const symbol = currency === "USD" ? "$" : currency === "CNY" ? "¥" : String(currency ?? "") + " ";
1022
+ return symbol + format.format(amount);
1023
+ }
1024
+ /**
1025
+ * @param reason - account failure reason from the Host.
1026
+ * @param t - translator.
1027
+ * @returns the message to show.
1028
+ */
1029
+ function accountFailureText(reason, t) {
1030
+ if (reason === "missing") return t("usageAccountMissing");
1031
+ if (reason === "auth") return t("usageAccountAuth");
1032
+ return t("usageAccountNetwork");
1033
+ }
1034
+ /**
1035
+ * The token-activity panel: a 53-week contribution graph plus today's hour
1036
+ * strip and numeric breakdown. Anchored above its row and portaled to
1037
+ * `document.body` when a portal renderer is available.
1038
+ * @param props - payload, translator, locale tag, anchor ref, and callbacks.
1039
+ * @returns the floating panel.
1040
+ */
1041
+ function UsagePanel({ t, tag, data, source, phase, reason, anchorRef, onClose, onRefresh, onSourceChange, busy, error }) {
1042
+ const panelRef = React.useRef(null);
1043
+ const [pos, setPos] = React.useState(null);
1044
+ const [mode, setMode] = React.useState(rememberedMode);
1045
+ const [hover, setHover] = React.useState(null);
1046
+ const [hoverHour, setHoverHour] = React.useState(null);
1047
+ const tariff = useTariff();
1048
+ // Place above the row, clamped into the viewport; re-place on resize,
1049
+ // scroll, and any panel size change (data arrival, locale switch).
1050
+ React.useLayoutEffect(() => {
1051
+ const place = () => {
1052
+ const anchor = anchorRef.current;
1053
+ const panel = panelRef.current;
1054
+ if (anchor === null || panel === null || typeof window === "undefined") return;
1055
+ const anchorRect = anchor.getBoundingClientRect();
1056
+ const width = panel.offsetWidth || 680;
1057
+ const height = panel.offsetHeight || 380;
1058
+ const maxHeight = Math.max(180, anchorRect.top - PANEL_GAP - PANEL_MARGIN);
1059
+ const visibleHeight = Math.min(height, maxHeight);
1060
+ const maxLeft = Math.max(PANEL_MARGIN, window.innerWidth - width - PANEL_MARGIN);
1061
+ const left = Math.min(Math.max(anchorRect.left, PANEL_MARGIN), maxLeft);
1062
+ const top = Math.max(PANEL_MARGIN, anchorRect.top - PANEL_GAP - visibleHeight);
1063
+ setPos({
1064
+ left,
1065
+ top,
1066
+ maxHeight
1067
+ });
1068
+ };
1069
+ place();
1070
+ let observer = null;
1071
+ if (typeof ResizeObserver === "function") {
1072
+ observer = new ResizeObserver(place);
1073
+ if (panelRef.current !== null) observer.observe(panelRef.current);
1074
+ // A sidebar drag resizes the row without a window resize event.
1075
+ if (anchorRef.current !== null) observer.observe(anchorRef.current);
1076
+ }
1077
+ window.addEventListener("resize", place);
1078
+ window.addEventListener("scroll", place, true);
1079
+ return () => {
1080
+ if (observer !== null) observer.disconnect();
1081
+ window.removeEventListener("resize", place);
1082
+ window.removeEventListener("scroll", place, true);
1083
+ };
1084
+ }, [anchorRef, data, mode]);
1085
+ // Dismiss on Escape and on any pointer press outside the panel and row.
1086
+ React.useEffect(() => {
1087
+ const onKeyDown = (event) => {
1088
+ if (event.key === "Escape") onClose();
1089
+ };
1090
+ const onPointerDown = (event) => {
1091
+ const target = event.target;
1092
+ if (!(target instanceof Node)) return;
1093
+ if (panelRef.current?.contains(target) === true) return;
1094
+ if (anchorRef.current?.contains(target) === true) return;
1095
+ onClose();
1096
+ };
1097
+ document.addEventListener("keydown", onKeyDown);
1098
+ document.addEventListener("pointerdown", onPointerDown, true);
1099
+ return () => {
1100
+ document.removeEventListener("keydown", onKeyDown);
1101
+ document.removeEventListener("pointerdown", onPointerDown, true);
1102
+ };
1103
+ }, [anchorRef, onClose]);
1104
+ const chooseMode = (next) => {
1105
+ setHover(null);
1106
+ setMode(next);
1107
+ rememberMode(next);
1108
+ };
1109
+ const today = usageBucket(data?.today);
1110
+ const yesterday = usageBucket(data?.yesterday);
1111
+ const week = usageBucket(data?.week);
1112
+ const month = usageBucket(data?.month);
1113
+ const all = usageBucket(data?.total);
1114
+ const hours = Array.isArray(data?.hours) ? data.hours : [];
1115
+ const hourMax = Math.max(1, ...hours.map((entry) => Number(entry?.total) || 0));
1116
+ const hourSum = hours.reduce((sum, entry) => sum + (Number(entry?.total) || 0), 0);
1117
+ const delta = percentDelta(today.total, yesterday.total);
1118
+ const weeks = buildCalendar(data);
1119
+ const metric = calendarMetric(weeks, mode);
1120
+ const thresholds = levelThresholds(metric.values.flat());
1121
+ const months = calendarMonths(weeks, tag);
1122
+ const dayRangeTotal = metric.values.flat().reduce((sum, value) => sum + (Number.isFinite(value) ? value : 0), 0);
1123
+ const rangeTotal = dayRangeTotal;
1124
+ const hoveredValue = hover === null ? null : hover.value;
1125
+ const captionLabel = hover === null ? t("usageLastMonths") : hover.label;
1126
+ const captionValue = compactNumber(hover === null ? rangeTotal : hoveredValue, tag);
1127
+ const captionMeta = hover === null ? t("usageSum") : t("usageRequests", { count: hover.requests });
1128
+ const cellNodes = [];
1129
+ weeks.forEach((weekEntry, column) => {
1130
+ weekEntry.cells.forEach((cell, row) => {
1131
+ if (cell === null) {
1132
+ cellNodes.push(React.createElement("div", {
1133
+ className: "dsu_cell",
1134
+ key: "empty-" + column + "-" + row,
1135
+ "data-empty": "true"
1136
+ }));
1137
+ return;
1138
+ }
1139
+ const value = metric.values[column][row];
1140
+ const level = levelOf(value, thresholds);
1141
+ cellNodes.push(React.createElement("div", {
1142
+ className: "dsu_cell",
1143
+ key: cell.date,
1144
+ "data-level": level > 0 ? String(level) : void 0,
1145
+ title: cell.date + " · " + compactNumber(value, tag),
1146
+ onMouseEnter: () => setHover({
1147
+ label: cell.date,
1148
+ value,
1149
+ requests: Number(cell.requests) || 0
1150
+ }),
1151
+ onMouseLeave: () => setHover(null)
1152
+ }));
1153
+ });
1154
+ });
1155
+ const monthAxis = React.createElement("div", {
1156
+ className: "dsu_months",
1157
+ style: { gridTemplateColumns: "repeat(" + Math.max(weeks.length, 1) + ",1fr)" }
1158
+ }, months.map((entry) => React.createElement("span", {
1159
+ key: "month-" + entry.column,
1160
+ style: {
1161
+ gridColumn: String(entry.column + 1),
1162
+ justifySelf: entry.column >= weeks.length - 2 ? "end" : "start"
1163
+ }
1164
+ }, entry.label)));
1165
+ const legend = React.createElement("div", { className: "dsu_legend" }, React.createElement("span", null, t("usageLess")), [0, 1, 2, 3, 4].map((level) => React.createElement("i", {
1166
+ key: "swatch-" + level,
1167
+ className: "dsu_swatch",
1168
+ "data-level": level > 0 ? String(level) : void 0
1169
+ })), React.createElement("span", null, t("usageMore")));
1170
+ const modeButtons = [
1171
+ ["day", t("usageModeDay")],
1172
+ ["week", t("usageModeWeek")],
1173
+ ["cumulative", t("usageModeTotal")]
1174
+ ].map(([value, label]) => React.createElement("button", {
1175
+ type: "button",
1176
+ key: value,
1177
+ className: "dsu_mode",
1178
+ "data-active": mode === value ? "true" : "false",
1179
+ "aria-pressed": mode === value,
1180
+ onClick: () => chooseMode(value)
1181
+ }, label));
1182
+ const hourBars = hours.map((entry, index) => React.createElement("div", {
1183
+ className: "dsu_col",
1184
+ key: "hour-" + String(entry?.hour ?? index),
1185
+ title: String(Number(entry?.hour) || 0).padStart(2, "0") + ":00 · " + compactNumber(entry?.total, tag),
1186
+ onMouseEnter: () => setHoverHour({
1187
+ label: String(Number(entry?.hour) || 0).padStart(2, "0") + ":00",
1188
+ value: Number(entry?.total) || 0,
1189
+ requests: Number(entry?.requests) || 0
1190
+ }),
1191
+ onMouseLeave: () => setHoverHour(null)
1192
+ }, React.createElement("div", {
1193
+ className: "dsu_bar",
1194
+ "data-peak": Number(entry?.total) === hourMax && hourMax > 1 ? "true" : void 0,
1195
+ style: { height: barHeight(entry?.total, hourMax, HOUR_CHART_HEIGHT) + "px" }
1196
+ })));
1197
+ const stat = (label, value) => React.createElement("div", {
1198
+ className: "dsu_pair",
1199
+ key: label
1200
+ }, React.createElement("span", null, label), React.createElement("b", null, value));
1201
+ const accountCell = (key, label, value, emphasis) => React.createElement("div", {
1202
+ className: "dsu_accountCell",
1203
+ key,
1204
+ "data-emphasis": emphasis === true ? "true" : void 0
1205
+ }, React.createElement("span", null, label), React.createElement("b", null, value));
1206
+ const hasData = data !== null && typeof data === "object";
1207
+ const isAccount = source === "account" || data?.granularity === "day";
1208
+ const cost = data?.cost ?? {};
1209
+ const todayLabel = isAccount ? t("usageTodayUtc") : t("usageToday");
1210
+ const monthKey = typeof data?.today?.date === "string" ? data.today.date.slice(0, 7) : null;
1211
+ const calendarMonthTotal = monthKey === null || !Array.isArray(data?.days) ? 0 : data.days.reduce((sum, entry) => entry !== null && typeof entry?.date === "string" && entry.date.slice(0, 7) === monthKey ? sum + (Number(entry.total) || 0) : sum, 0);
1212
+ const sourceButtons = [["local", t("usageSourceLocal")], ["account", t("usageSourceAccount")]].map(([value, label]) => React.createElement("button", {
1213
+ type: "button",
1214
+ key: value,
1215
+ className: "dsu_mode",
1216
+ "data-active": source === value ? "true" : "false",
1217
+ "aria-pressed": source === value,
1218
+ onClick: () => onSourceChange(value)
1219
+ }, label));
1220
+ const bands = Array.isArray(tariff.bands) ? tariff.bands : [];
1221
+ const hourChart = React.createElement("div", { className: "dsu_chartWrap" }, bands.length === 0 ? null : React.createElement("div", {
1222
+ className: "dsu_bands",
1223
+ "aria-hidden": "true"
1224
+ }, bands.map((band, index) => React.createElement("i", {
1225
+ className: "dsu_band",
1226
+ key: "band-" + index,
1227
+ style: {
1228
+ left: band.start / 24 * 100 + "%",
1229
+ width: (band.end - band.start) / 24 * 100 + "%"
1230
+ }
1231
+ }))), React.createElement("div", {
1232
+ className: "dsu_chart",
1233
+ style: { "--dsu-chart-height": HOUR_CHART_HEIGHT + "px" }
1234
+ }, hourBars));
1235
+ const localBody = React.createElement("div", {
1236
+ className: "dsu_body",
1237
+ key: "body"
1238
+ }, React.createElement("div", { className: "dsu_left" }, React.createElement("div", { className: "dsu_caption", style: { marginTop: "0" } }, React.createElement("span", null, hoverHour === null ? t("usageHours") : hoverHour.label), React.createElement("span", null, React.createElement("b", null, compactNumber(hoverHour === null ? hourSum : hoverHour.value, tag)), hoverHour === null ? "" : " · " + t("usageRequests", { count: hoverHour.requests }))), hourChart, React.createElement("div", { className: "dsu_axis" }, React.createElement("span", null, "00"), React.createElement("span", null, "06"), React.createElement("span", null, "12"), React.createElement("span", null, "18"), React.createElement("span", null, "23")), bands.length === 0 ? null : React.createElement("div", { className: "dsu_chartNote" }, t("tariffBand"))), React.createElement("div", { className: "dsu_right" }, React.createElement("div", { className: "dsu_headline" }, React.createElement("span", { className: "dsu_big" }, compactNumber(today.total, tag)), React.createElement("span", { className: "dsu_unit" }, t("usageToday")), delta === null ? null : React.createElement("span", {
1239
+ className: "dsu_delta",
1240
+ "data-dir": delta > 0 ? "up" : delta < 0 ? "down" : "flat"
1241
+ }, formatPercent(delta))), React.createElement("div", { className: "dsu_grid" }, stat(t("usageInput"), compactNumber(today.input, tag)), stat(t("usageOutput"), compactNumber(today.output, tag)), stat(t("usageCacheRead"), compactNumber(today.cacheRead, tag)), stat(t("usageCacheWrite"), compactNumber(today.cacheWrite, tag)))));
1242
+ const accountBody = React.createElement("div", {
1243
+ className: "dsu_accountBody",
1244
+ key: "account"
1245
+ }, React.createElement("div", { className: "dsu_statGrid" }, accountCell("today", todayLabel, compactNumber(today.total, tag), true), accountCell("month", t("usageAccountMonth"), compactNumber(calendarMonthTotal, tag), true), accountCell("costToday", t("usageAccountCostToday"), formatMoney(cost.today, cost.currency, tag)), accountCell("costMonth", t("usageAccountCostMonth"), formatMoney(cost.month, cost.currency, tag)), accountCell("input", t("usageInput"), compactNumber(today.input, tag)), accountCell("output", t("usageOutput"), compactNumber(today.output, tag)), accountCell("cache", t("usageCacheRead"), compactNumber(today.cacheRead, tag)), accountCell("requests", t("usageRequestsLabel"), t("usageRequests", { count: today.requests }))), React.createElement("div", { className: "dsu_note", style: { marginTop: "0" } }, t("usageAccountNote") + (data?.partial === true ? " · " + t("usageAccountPartial") : "")));
1246
+ const footerTariff = tariffHeadline(tariff, t) + (tariffCountdown(tariff, t) === "" ? "" : " · " + tariffCountdown(tariff, t));
1247
+ const footer = React.createElement("div", {
1248
+ className: "dsu_footer",
1249
+ key: "footer"
1250
+ }, React.createElement("span", {
1251
+ className: "dsu_tariff",
1252
+ key: "tariff",
1253
+ "data-period": tariff.period,
1254
+ title: t("tariffRule") + " " + t("tariffSource") + " " + PRICING_URL
1255
+ }, React.createElement("i", { "aria-hidden": "true" }), footerTariff), isAccount ? null : React.createElement("span", null, t("usageRequestsLabel") + " ", React.createElement("b", null, t("usageRequests", { count: today.requests }))), isAccount ? null : React.createElement("span", null, t("usageSessionsLabel") + " ", React.createElement("b", null, t("usageSessions", { count: today.sessions }))), React.createElement("span", null, t("usageLast7") + " ", React.createElement("b", null, compactNumber(week.total, tag))), React.createElement("span", null, t("usageLast30") + " ", React.createElement("b", null, compactNumber(month.total, tag))), React.createElement("span", null, (isAccount ? t("usageLastMonths") : t("usageTotal")) + " ", React.createElement("b", null, compactNumber(isAccount ? rangeTotal : all.total, tag))));
1256
+ const showEmpty = hasData && all.total === 0 && data?.scanning !== true;
1257
+ const notes = [];
1258
+ if (hasData && error === true) notes.push(isAccount ? accountFailureText(reason, t) : t("usageRefreshFailed"));
1259
+ if (hasData && data?.scanning === true) notes.push(t("usageScanning"));
1260
+ const content = !hasData ? React.createElement("div", {
1261
+ className: "dsu_empty",
1262
+ key: "placeholder"
1263
+ }, phase === "failed" ? (isAccount ? accountFailureText(reason, t) : t("usageFailed")) : t("usageScanning")) : showEmpty ? React.createElement("div", {
1264
+ className: "dsu_empty",
1265
+ key: "empty"
1266
+ }, t("usageEmpty")) : [React.createElement("div", {
1267
+ className: "dsu_caption",
1268
+ key: "caption"
1269
+ }, React.createElement("span", null, captionLabel), React.createElement("span", null, React.createElement("b", null, captionValue), " · " + captionMeta)), React.createElement("div", {
1270
+ className: "dsu_calendar",
1271
+ key: "calendar",
1272
+ style: {
1273
+ gridTemplateColumns: "repeat(" + Math.max(weeks.length, 1) + ",1fr)",
1274
+ gridTemplateRows: "repeat(7,1fr)",
1275
+ aspectRatio: Math.max(weeks.length, 1) + " / 7"
1276
+ }
1277
+ }, cellNodes), monthAxis, React.createElement("div", {
1278
+ className: "dsu_legendRow",
1279
+ key: "legend"
1280
+ }, legend), isAccount ? accountBody : localBody, footer];
1281
+ return React.createElement("div", {
1282
+ ref: panelRef,
1283
+ className: "dsu_panel",
1284
+ role: "dialog",
1285
+ "aria-label": t("usageTitle"),
1286
+ style: pos === null ? {
1287
+ visibility: "hidden",
1288
+ left: 0,
1289
+ top: 0
1290
+ } : {
1291
+ left: pos.left,
1292
+ top: pos.top,
1293
+ maxHeight: pos.maxHeight
1294
+ }
1295
+ }, React.createElement("div", { className: "dsu_header" }, React.createElement("span", { className: "dsu_title" }, t("usageTitle")), React.createElement("div", {
1296
+ className: "dsu_modes",
1297
+ role: "group",
1298
+ "aria-label": t("usageTitle")
1299
+ }, sourceButtons), React.createElement("span", { className: "dsu_divider", "aria-hidden": "true" }), React.createElement("div", {
1300
+ className: "dsu_modes",
1301
+ role: "group",
1302
+ "aria-label": t("usageTitle")
1303
+ }, modeButtons), React.createElement("button", {
1304
+ type: "button",
1305
+ className: "dsu_icon",
1306
+ title: t("usageRefresh"),
1307
+ "aria-label": t("usageRefresh"),
1308
+ "data-busy": busy === true ? "true" : "false",
1309
+ onClick: onRefresh
1310
+ }, React.createElement(Icon, { viewBox: "0 0 16 16", size: 14 }, React.createElement("path", { d: "M13 8a5 5 0 1 1-1.46-3.54" }), React.createElement("path", { d: "M13 3.2v3.1H9.9" }))), React.createElement("button", {
1311
+ type: "button",
1312
+ className: "dsu_icon",
1313
+ title: t("usageClose"),
1314
+ "aria-label": t("usageClose"),
1315
+ onClick: onClose
1316
+ }, React.createElement(Icon, { viewBox: "0 0 16 16", size: 14 }, React.createElement("path", { d: "M4 4l8 8M12 4l-8 8" })))), content, notes.length === 0 ? null : React.createElement("div", { className: "dsu_note" }, notes.join(" · ")));
1317
+ }
1318
+ /**
1319
+ * The usage row. Its value is today's token total; clicking opens the panel.
1320
+ * @param props - slot props plus this plugin's context and translator.
1321
+ * @returns the row plus its portaled panel, or nothing on the collapsed rail.
1322
+ */
1323
+ function UsageRow({ ctx, t, wide }) {
1324
+ const [source, setSource] = React.useState(rememberedSource);
1325
+ const [view, setView] = React.useState(() => ({
1326
+ phase: "loading",
1327
+ source: rememberedSource(),
1328
+ data: null,
1329
+ at: 0,
1330
+ error: false,
1331
+ reason: null
1332
+ }));
1333
+ const [open, setOpen] = React.useState(false);
1334
+ const [busy, setBusy] = React.useState(false);
1335
+ const [, setLocaleRevision] = React.useState(0);
1336
+ const rowRef = React.useRef(null);
1337
+ const alive = React.useRef(true);
1338
+ const sequence = React.useRef(0);
1339
+ const viewRef = React.useRef(view);
1340
+ viewRef.current = view;
1341
+ const sourceRef = React.useRef(source);
1342
+ sourceRef.current = source;
1343
+ const cacheRef = React.useRef({ local: null, account: null });
1344
+ const scanTries = React.useRef(0);
1345
+ const read = React.useCallback((requested) => {
1346
+ const next = requested === "account" || requested === "local" ? requested : sourceRef.current;
1347
+ const run = ++sequence.current;
1348
+ const publish = (nextView) => {
1349
+ if (!alive.current || run !== sequence.current) return;
1350
+ setBusy(false);
1351
+ setView(nextView);
1352
+ };
1353
+ if (alive.current) setBusy(true);
1354
+ const query = USAGE_ROUTE + "?days=" + USAGE_DAYS + "&offset=" + String(-new Date().getTimezoneOffset() * 60) + "&source=" + next;
1355
+ Promise.resolve()
1356
+ .then(() => fetch(query, {
1357
+ headers: { accept: "application/json" },
1358
+ cache: "no-store",
1359
+ credentials: "same-origin"
1360
+ }))
1361
+ .then(async (response) => {
1362
+ if (response !== null && typeof response === "object" && response.ok === true) return {
1363
+ ok: true,
1364
+ data: await response.json()
1365
+ };
1366
+ let reason = null;
1367
+ try {
1368
+ const body = await response.json();
1369
+ if (typeof body?.reason === "string") reason = body.reason;
1370
+ } catch (_error) {}
1371
+ return {
1372
+ ok: false,
1373
+ reason
1374
+ };
1375
+ })
1376
+ .then((result) => {
1377
+ if (result === null || typeof result !== "object" || result.ok !== true || result.data === null || typeof result.data !== "object") {
1378
+ const previous = viewRef.current;
1379
+ if (previous.source === next && previous.data !== null) publish({
1380
+ ...previous,
1381
+ error: true,
1382
+ reason: result?.reason ?? null
1383
+ });
1384
+ else publish({
1385
+ phase: "failed",
1386
+ source: next,
1387
+ data: null,
1388
+ at: 0,
1389
+ error: true,
1390
+ reason: result?.reason ?? null
1391
+ });
1392
+ return;
1393
+ }
1394
+ const at = Date.now();
1395
+ // A stale Host build answers account requests with local data;
1396
+ // refuse to mislabel it instead of showing the wrong source.
1397
+ if (next === "account" && result.data.source !== "account") {
1398
+ publish({
1399
+ phase: "failed",
1400
+ source: next,
1401
+ data: null,
1402
+ at: 0,
1403
+ error: true,
1404
+ reason: "stale-host"
1405
+ });
1406
+ return;
1407
+ }
1408
+ cacheRef.current[next] = {
1409
+ data: result.data,
1410
+ at
1411
+ };
1412
+ publish({
1413
+ phase: "ready",
1414
+ source: next,
1415
+ data: result.data,
1416
+ at,
1417
+ error: false,
1418
+ reason: null
1419
+ });
1420
+ })
1421
+ .catch(() => {
1422
+ const previous = viewRef.current;
1423
+ if (previous.source === next && previous.data !== null) publish({
1424
+ ...previous,
1425
+ error: true,
1426
+ reason: null
1427
+ });
1428
+ else publish({
1429
+ phase: "failed",
1430
+ source: next,
1431
+ data: null,
1432
+ at: 0,
1433
+ error: true,
1434
+ reason: null
1435
+ });
1436
+ });
1437
+ }, []);
1438
+ const chooseSource = React.useCallback((next) => {
1439
+ if (next !== "local" && next !== "account") return;
1440
+ if (next === sourceRef.current) return;
1441
+ setSource(next);
1442
+ rememberSource(next);
1443
+ const cached = cacheRef.current[next];
1444
+ if (cached !== null && cached !== undefined) setView({
1445
+ phase: "ready",
1446
+ source: next,
1447
+ data: cached.data,
1448
+ at: cached.at,
1449
+ error: false,
1450
+ reason: null
1451
+ });
1452
+ else setView({
1453
+ phase: "loading",
1454
+ source: next,
1455
+ data: null,
1456
+ at: 0,
1457
+ error: false,
1458
+ reason: null
1459
+ });
1460
+ read(next);
1461
+ }, [read]);
1462
+ // Poll while visible; re-read on focus and on returning to the page.
1463
+ React.useEffect(() => {
1464
+ alive.current = true;
1465
+ read();
1466
+ const timer = window.setInterval(() => {
1467
+ if (document.visibilityState !== "hidden") read();
1468
+ }, USAGE_POLL_MS);
1469
+ const onVisible = () => {
1470
+ if (document.visibilityState === "visible") read();
1471
+ };
1472
+ document.addEventListener("visibilitychange", onVisible);
1473
+ window.addEventListener("focus", onVisible);
1474
+ return () => {
1475
+ alive.current = false;
1476
+ window.clearInterval(timer);
1477
+ document.removeEventListener("visibilitychange", onVisible);
1478
+ window.removeEventListener("focus", onVisible);
1479
+ };
1480
+ }, [read]);
1481
+ // Refresh on open when the cached payload is old.
1482
+ React.useEffect(() => {
1483
+ if (!open) return;
1484
+ if (Date.now() - viewRef.current.at > 30000) read();
1485
+ }, [open, read]);
1486
+ // While the Host is still indexing history, poll quickly until it settles.
1487
+ React.useEffect(() => {
1488
+ if (view.data === null || view.data.scanning !== true) {
1489
+ scanTries.current = 0;
1490
+ return;
1491
+ }
1492
+ if (scanTries.current >= USAGE_SCAN_RETRIES) return;
1493
+ const timer = window.setTimeout(() => {
1494
+ scanTries.current += 1;
1495
+ read();
1496
+ }, USAGE_SCAN_RETRY_MS);
1497
+ return () => window.clearTimeout(timer);
1498
+ }, [view.data, read]);
1499
+ // Re-render with the active language without re-reading usage.
1500
+ React.useEffect(() => ctx.locale.subscribe(() => setLocaleRevision((value) => value + 1)), [ctx]);
1501
+ const close = React.useCallback(() => setOpen(false), []);
1502
+ if (!wide) return null;
1503
+ const tag = localeTag(ctx);
1504
+ const active = view.source === source;
1505
+ const phase = active ? view.phase : "loading";
1506
+ const data = active ? view.data : null;
1507
+ const today = usageBucket(data?.today);
1508
+ const isAccount = source === "account";
1509
+ const amount = phase === "ready" && data !== null ? compactNumber(today.total, tag) : phase === "failed" ? t("usageRetry") : t("loading");
1510
+ const lines = [];
1511
+ if (phase === "ready" && data !== null) {
1512
+ const todayLabel = data.dayBasis === "utc" ? t("usageTodayUtc") : t("usageToday");
1513
+ lines.push((isAccount ? t("usageSourceAccount") : t("usageSourceLocal")) + " · " + todayLabel + " " + compactNumber(today.total, tag));
1514
+ lines.push(t("usageInput") + " " + compactNumber(today.input, tag) + " · " + t("usageOutput") + " " + compactNumber(today.output, tag) + " · " + t("usageCacheRead") + " " + compactNumber(today.cacheRead, tag));
1515
+ lines.push(t("usageLast7") + " " + compactNumber(usageBucket(data.week).total, tag) + " · " + t("usageLast30") + " " + compactNumber(usageBucket(data.month).total, tag));
1516
+ if (data.scanning === true) lines.push(t("usageScanning"));
1517
+ else if (view.at > 0) lines.push(t("updated") + " " + new Date(view.at).toLocaleTimeString(tag, { hour12: false }));
1518
+ if (view.error === true) lines.push(isAccount ? accountFailureText(view.reason, t) : t("usageRefreshFailed"));
1519
+ } else if (phase === "failed") lines.push(isAccount ? accountFailureText(view.reason, t) : t("usageFailed"));
1520
+ else lines.push(t("usageScanning"));
1521
+ lines.push(t("usageHint"));
1522
+ const title = lines.join("\n");
1523
+ const onClick = () => {
1524
+ setOpen((value) => !value);
1525
+ if (phase === "failed") read(source);
1526
+ };
1527
+ const panel = open ? React.createElement(UsagePanel, {
1528
+ t,
1529
+ tag,
1530
+ data,
1531
+ phase,
1532
+ reason: view.reason,
1533
+ source,
1534
+ anchorRef: rowRef,
1535
+ onClose: close,
1536
+ onRefresh: () => read(source),
1537
+ onSourceChange: chooseSource,
1538
+ busy,
1539
+ error: active ? view.error : false
1540
+ }) : null;
1541
+ const panelNode = panel === null ? null : ReactDOM !== null && typeof ReactDOM.createPortal === "function" && typeof document !== "undefined" ? ReactDOM.createPortal(panel, document.body) : panel;
1542
+ return React.createElement(React.Fragment, null, React.createElement("button", {
1543
+ type: "button",
1544
+ ref: rowRef,
1545
+ className: "dsb_row",
1546
+ title,
1547
+ "aria-label": t("usageLabel") + ": " + amount,
1548
+ "aria-haspopup": "dialog",
1549
+ "aria-expanded": open,
1550
+ "data-usage-phase": phase,
1551
+ onClick
1552
+ }, React.createElement("span", { className: "dsb_label" }, t("usageLabel")), React.createElement("span", { className: "dsb_amounts" }, React.createElement("span", {
1553
+ className: "dsb_value",
1554
+ "data-phase": phase
1555
+ }, amount))), panelNode);
1556
+ }
1557
+ /**
1558
+ * Both footer rows in one slot entry: `sidebar.footer.action` is a row flex
1559
+ * container, so a single column wrapper keeps usage above balance on every
1560
+ * layout (including a future layout change in the sidebar).
1561
+ * @param props - slot props plus this plugin's context and translator.
1562
+ * @returns the stacked rows, or nothing on the collapsed rail.
1563
+ */
1564
+ function SidebarRows({ ctx, t, wide }) {
1565
+ if (!wide) return null;
1566
+ return React.createElement("div", { className: "dsb_rows" }, React.createElement(UsageRow, {
1567
+ ctx,
1568
+ t,
1569
+ wide
1570
+ }), React.createElement(BalanceRow, {
1571
+ ctx,
1572
+ t,
1573
+ wide
1574
+ }));
1575
+ }
1576
+ /** Services required by the sidebar rows. */
1577
+ const inject = ["slots", "locale", "remote", "remote.account"];
1578
+ /**
1579
+ * Register the usage and balance rows into the sidebar's footer list seat.
1580
+ * @param ctx - client root context.
1581
+ */
1582
+ function apply(ctx) {
1583
+ ctx.effect(() => ctx.locale.register(NS, {
1584
+ zh,
1585
+ en
1586
+ }), "balance: dictionaries");
1587
+ const t = ctx.locale.bind(NS);
1588
+ ctx.slots.inject(SLOT, () => ctx.slots.register({
1589
+ name: SLOT,
1590
+ id: "balance",
1591
+ order: 100
1592
+ }, (props) => React.createElement(SidebarRows, {
1593
+ ...props,
1594
+ ctx,
1595
+ t
1596
+ })));
1597
+ }
1598
+ exports.apply = apply;
1599
+ exports.inject = inject;
1600
+ // Formatting helpers exposed for offline checks only; nothing imports this member at runtime.
1601
+ exports.__test = {
1602
+ formatAmount,
1603
+ formatWallets,
1604
+ positiveBonusWallets,
1605
+ compactNumber,
1606
+ percentDelta,
1607
+ formatPercent,
1608
+ barHeight,
1609
+ shortDate,
1610
+ usageBucket,
1611
+ buildCalendar,
1612
+ calendarMetric,
1613
+ levelThresholds,
1614
+ levelOf,
1615
+ calendarMonths,
1616
+ formatMoney,
1617
+ accountFailureText,
1618
+ tariffStatus,
1619
+ isPeakAt,
1620
+ formatCountdown,
1621
+ switchClock,
1622
+ tariffHeadline,
1623
+ UsagePanel
1624
+ };
1625
+ return module.exports;
1626
+ }
1627
+ });