@tokenboard/cli 0.1.2 → 0.1.3

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/dist/cli.js CHANGED
@@ -598,8 +598,15 @@ function resolveProjectsRoot(homedir3) {
598
598
 
599
599
  // src/collectors/claude-code-source.ts
600
600
  init_esm_shims();
601
- import { readdirSync, readFileSync } from "fs";
601
+ import { readdirSync, readFileSync as readFileSync2 } from "fs";
602
+ import { join as join3 } from "path";
603
+
604
+ // src/collectors/claude-code-cache.ts
605
+ init_esm_shims();
606
+ import { readFileSync, statSync } from "fs";
607
+ import { mkdirSync, writeFileSync, renameSync } from "fs";
602
608
  import { join as join2 } from "path";
609
+ import { randomBytes } from "crypto";
603
610
 
604
611
  // src/collectors/claude-code-filter.ts
605
612
  init_esm_shims();
@@ -609,6 +616,88 @@ function isCountableAssistantLine(line) {
609
616
  return l?.["type"] === "assistant" && message?.["usage"] != null && message?.["model"] !== "<synthetic>" && l?.["isApiErrorMessage"] !== true;
610
617
  }
611
618
 
619
+ // src/collectors/claude-code-cache.ts
620
+ var CACHE_VERSION = 1;
621
+ function parseFileLines(file, text) {
622
+ const out2 = [];
623
+ const lines = text.split("\n");
624
+ for (let i = 0; i < lines.length; i++) {
625
+ const raw = lines[i];
626
+ if (!raw) continue;
627
+ let parsed;
628
+ try {
629
+ parsed = JSON.parse(raw);
630
+ } catch {
631
+ continue;
632
+ }
633
+ if (!isCountableAssistantLine(parsed)) continue;
634
+ const line = parsed;
635
+ out2.push({
636
+ messageId: line.message.id ?? null,
637
+ model: line.message.model ?? "",
638
+ usage: line.message.usage,
639
+ timestamp: line.timestamp ?? null,
640
+ sourcePath: file,
641
+ lineIndex: i
642
+ });
643
+ }
644
+ return out2;
645
+ }
646
+ function cachePath(configDir) {
647
+ return join2(configDir, "parse-cache.json");
648
+ }
649
+ function loadCache(configDir) {
650
+ try {
651
+ const c = JSON.parse(readFileSync(cachePath(configDir), "utf8"));
652
+ if (c.version !== CACHE_VERSION || typeof c.files !== "object" || c.files === null) {
653
+ return { version: CACHE_VERSION, files: {} };
654
+ }
655
+ return c;
656
+ } catch {
657
+ return { version: CACHE_VERSION, files: {} };
658
+ }
659
+ }
660
+ function saveCache(configDir, cache) {
661
+ try {
662
+ mkdirSync(configDir, { recursive: true });
663
+ const tmp = join2(configDir, `.parse-cache.json.${randomBytes(6).toString("hex")}.tmp`);
664
+ writeFileSync(tmp, JSON.stringify(cache), "utf8");
665
+ renameSync(tmp, cachePath(configDir));
666
+ } catch {
667
+ }
668
+ }
669
+ function linesForFile(file, prev, next) {
670
+ let st;
671
+ try {
672
+ const s = statSync(file);
673
+ st = { mtimeMs: s.mtimeMs, size: s.size };
674
+ } catch {
675
+ return [];
676
+ }
677
+ const hit = prev.files[file];
678
+ if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) {
679
+ next.files[file] = hit;
680
+ return hit.lines;
681
+ }
682
+ let text;
683
+ try {
684
+ text = readFileSync(file, "utf8");
685
+ } catch {
686
+ return [];
687
+ }
688
+ const lines = parseFileLines(file, text);
689
+ next.files[file] = { mtimeMs: st.mtimeMs, size: st.size, lines };
690
+ return lines;
691
+ }
692
+ function collectClaudeCodeLinesCached(files, configDir) {
693
+ const prev = loadCache(configDir);
694
+ const next = { version: CACHE_VERSION, files: {} };
695
+ const out2 = [];
696
+ for (const file of files) out2.push(...linesForFile(file, prev, next));
697
+ saveCache(configDir, next);
698
+ return out2;
699
+ }
700
+
612
701
  // src/collectors/claude-code-source.ts
613
702
  function findJsonlFiles(dir) {
614
703
  let entries;
@@ -619,65 +708,30 @@ function findJsonlFiles(dir) {
619
708
  }
620
709
  const out2 = [];
621
710
  for (const entry of entries) {
622
- const full = join2(dir, entry.name);
711
+ const full = join3(dir, entry.name);
623
712
  if (entry.isDirectory()) out2.push(...findJsonlFiles(full));
624
713
  else if (entry.isFile() && entry.name.endsWith(".jsonl")) out2.push(full);
625
714
  }
626
715
  return out2;
627
716
  }
628
- function collectClaudeCodeLines(projectsRoot) {
629
- const files = findJsonlFiles(projectsRoot);
630
- const out2 = [];
631
- for (const file of files) {
632
- let text;
633
- try {
634
- text = readFileSync(file, "utf8");
635
- } catch {
636
- continue;
637
- }
638
- const lines = text.split("\n");
639
- for (let i = 0; i < lines.length; i++) {
640
- const raw = lines[i];
641
- if (!raw) continue;
642
- let parsed;
643
- try {
644
- parsed = JSON.parse(raw);
645
- } catch {
646
- continue;
647
- }
648
- if (!isCountableAssistantLine(parsed)) continue;
649
- const line = parsed;
650
- out2.push({
651
- messageId: line.message.id ?? null,
652
- model: line.message.model ?? "",
653
- usage: line.message.usage,
654
- timestamp: line.timestamp ?? null,
655
- sourcePath: file,
656
- lineIndex: i
657
- });
658
- }
659
- }
660
- return out2;
661
- }
662
717
 
663
718
  // src/collectors/dedup.ts
664
719
  init_esm_shims();
720
+ function outputOf(line) {
721
+ return line.usage.output_tokens ?? 0;
722
+ }
665
723
  function dedupeByMessageId(lines) {
666
- const ordered = [...lines].sort(
667
- (a, b) => a.sourcePath < b.sourcePath ? -1 : a.sourcePath > b.sourcePath ? 1 : a.lineIndex - b.lineIndex
668
- );
669
- const seen = /* @__PURE__ */ new Set();
670
- const kept = [];
671
- for (const line of ordered) {
724
+ const best = /* @__PURE__ */ new Map();
725
+ const idless = [];
726
+ for (const line of lines) {
672
727
  if (line.messageId == null || line.messageId === "") {
673
- kept.push(line);
728
+ idless.push(line);
674
729
  continue;
675
730
  }
676
- if (seen.has(line.messageId)) continue;
677
- seen.add(line.messageId);
678
- kept.push(line);
731
+ const cur = best.get(line.messageId);
732
+ if (cur === void 0 || outputOf(line) > outputOf(cur)) best.set(line.messageId, line);
679
733
  }
680
- return kept;
734
+ return [...best.values(), ...idless];
681
735
  }
682
736
 
683
737
  // src/collectors/claude-code-map.ts
@@ -990,7 +1044,10 @@ function summarize(records, prices) {
990
1044
  unpricedTokens += tokens;
991
1045
  unpricedModels.add(r.model);
992
1046
  }
993
- perDay.set(r.date, (perDay.get(r.date) ?? 0) + tokens);
1047
+ const d = perDay.get(r.date) ?? { tokens: 0, costUsd: 0 };
1048
+ d.tokens += tokens;
1049
+ d.costUsd += costUsd;
1050
+ perDay.set(r.date, d);
994
1051
  const t = perTool.get(r.tool) ?? { tokens: 0, costUsd: 0 };
995
1052
  t.tokens += tokens;
996
1053
  t.costUsd += costUsd;
@@ -1007,7 +1064,7 @@ function summarize(records, prices) {
1007
1064
  anyUnpriced: unpricedModels.size > 0,
1008
1065
  unpricedTokens,
1009
1066
  unpricedModels: [...unpricedModels].sort(),
1010
- perDay: [...perDay.entries()].map(([date, tokens]) => ({ date, tokens })).sort((a, b) => a.date < b.date ? -1 : 1),
1067
+ perDay: [...perDay.entries()].map(([date, v]) => ({ date, ...v })).sort((a, b) => a.date < b.date ? -1 : 1),
1011
1068
  perTool: [...perTool.entries()].map(([tool, v]) => ({ tool, ...v })).sort((a, b) => b.tokens - a.tokens),
1012
1069
  perModel: [...perModel.entries()].map(([model, v]) => ({ model, ...v })).sort((a, b) => b.tokens - a.tokens)
1013
1070
  };
@@ -1035,6 +1092,38 @@ function styler(style) {
1035
1092
  };
1036
1093
  }
1037
1094
 
1095
+ // src/render/spinner.ts
1096
+ init_esm_shims();
1097
+ var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
1098
+ var FRAMES_ASCII = ["|", "/", "-", "\\"];
1099
+ var INTERVAL_MS = 80;
1100
+ function startSpinner(label, ascii = false) {
1101
+ if (!process.stderr.isTTY) return { stop: () => {
1102
+ } };
1103
+ const frames = ascii ? FRAMES_ASCII : FRAMES;
1104
+ let i = 0;
1105
+ const write = (s) => process.stderr.write(s);
1106
+ write("\x1B[?25l");
1107
+ const render = () => {
1108
+ const frame = frames[i % frames.length];
1109
+ i += 1;
1110
+ write(`\r${frame} ${label}`);
1111
+ };
1112
+ render();
1113
+ const timer = setInterval(render, INTERVAL_MS);
1114
+ timer.unref?.();
1115
+ let stopped = false;
1116
+ return {
1117
+ stop: () => {
1118
+ if (stopped) return;
1119
+ stopped = true;
1120
+ clearInterval(timer);
1121
+ write("\r\x1B[2K");
1122
+ write("\x1B[?25h");
1123
+ }
1124
+ };
1125
+ }
1126
+
1038
1127
  // src/render/local-preview.ts
1039
1128
  init_esm_shims();
1040
1129
 
@@ -1675,31 +1764,34 @@ function renderLocalPreview(summary, style) {
1675
1764
  c.bold(`you burned ${humanizeTokens(summary.totalTokens)} tokens`) + ` \xB7 ${formatApproxUsd(summary.totalCostUsd)} est`
1676
1765
  );
1677
1766
  lines.push("");
1678
- lines.push(c.dim("\u{1FA99} tokenboard \xB7 your local usage"));
1679
- const dayTokens = summary.perDay.map((d) => d.tokens);
1680
- const spark = sparkline(dayTokens, style.ascii);
1681
- const headers = ["tool", "tokens", "~$ est", "daily burn"];
1682
- const aligns = ["left", "right", "right", "left"];
1683
- const bodyRows = summary.perTool.map((t) => [
1684
- t.tool,
1685
- humanizeTokens(t.tokens),
1686
- formatApproxUsd(t.costUsd),
1687
- spark
1688
- // same per-day series across the board in Phase 2 (per-tool series is Phase 6+)
1767
+ lines.push(c.dim("\u{1FA99} tokenboard \xB7 your local usage by day"));
1768
+ const headers = ["date", "tokens", "~$ est"];
1769
+ const aligns = ["left", "right", "right"];
1770
+ const bodyRows = summary.perDay.map((d) => [
1771
+ d.date,
1772
+ humanizeTokens(d.tokens),
1773
+ formatApproxUsd(d.costUsd)
1689
1774
  ]);
1690
- const allRows = [headers, ...bodyRows];
1775
+ const totalRow = ["TOTAL", humanizeTokens(summary.totalTokens), formatApproxUsd(summary.totalCostUsd)];
1776
+ const allRows = [headers, ...bodyRows, totalRow];
1691
1777
  const colWidths = headers.map(
1692
1778
  (_, col) => Math.max(...allRows.map((r) => [...r[col]].length), 1)
1693
1779
  );
1694
1780
  const cellAlign = (i) => aligns[i] ?? "left";
1695
1781
  const width = (i) => colWidths[i] ?? 1;
1782
+ const renderRow = (cells) => row(cells.map((cell, i) => padCell(cell, width(i), cellAlign(i))), g);
1696
1783
  lines.push(rule(colWidths, "top", g));
1697
- lines.push(row(headers.map((h, i) => padCell(h, width(i), cellAlign(i))), g));
1784
+ lines.push(renderRow(headers));
1698
1785
  lines.push(rule(colWidths, "mid", g));
1699
- for (const r of bodyRows) {
1700
- lines.push(row(r.map((cell, i) => padCell(cell, width(i), cellAlign(i))), g));
1701
- }
1786
+ for (const r of bodyRows) lines.push(renderRow(r));
1787
+ lines.push(rule(colWidths, "mid", g));
1788
+ lines.push(renderRow(totalRow));
1702
1789
  lines.push(rule(colWidths, "bottom", g));
1790
+ const spark = sparkline(
1791
+ summary.perDay.map((d) => d.tokens),
1792
+ style.ascii
1793
+ );
1794
+ if (spark) lines.push(c.dim("daily burn ") + spark);
1703
1795
  lines.push(
1704
1796
  c.dim("approx $ is a local estimate from a bundled LiteLLM snapshot \u2014 the server is authoritative")
1705
1797
  );
@@ -1714,26 +1806,26 @@ var CLAIM_HINT = "\u2192 Claim your spot anytime \u2192 tokenboard claim";
1714
1806
  // src/config/auth-store.ts
1715
1807
  init_esm_shims();
1716
1808
  import { homedir, platform } from "os";
1717
- import { join as join3, isAbsolute } from "path";
1809
+ import { join as join4, isAbsolute } from "path";
1718
1810
  import { mkdir, writeFile, chmod, rename, unlink, readFile } from "fs/promises";
1719
- import { randomBytes } from "crypto";
1811
+ import { randomBytes as randomBytes2 } from "crypto";
1720
1812
  function resolveConfigDir(env = process.env) {
1721
1813
  if (platform() === "win32") {
1722
- const appData = env.APPDATA && env.APPDATA.trim() !== "" ? env.APPDATA : join3(homedir(), "AppData", "Roaming");
1723
- return join3(appData, "tokenboard");
1814
+ const appData = env.APPDATA && env.APPDATA.trim() !== "" ? env.APPDATA : join4(homedir(), "AppData", "Roaming");
1815
+ return join4(appData, "tokenboard");
1724
1816
  }
1725
1817
  const xdg = env.XDG_CONFIG_HOME;
1726
- const base = xdg && isAbsolute(xdg) ? xdg : join3(homedir(), ".config");
1727
- return join3(base, "tokenboard");
1818
+ const base = xdg && isAbsolute(xdg) ? xdg : join4(homedir(), ".config");
1819
+ return join4(base, "tokenboard");
1728
1820
  }
1729
1821
  function resolveAuthPath(env = process.env) {
1730
- return join3(resolveConfigDir(env), "auth.json");
1822
+ return join4(resolveConfigDir(env), "auth.json");
1731
1823
  }
1732
1824
  async function writeAuthFile(auth, env = process.env) {
1733
1825
  const dir = resolveConfigDir(env);
1734
- const finalPath = join3(dir, "auth.json");
1826
+ const finalPath = join4(dir, "auth.json");
1735
1827
  await mkdir(dir, { recursive: true, mode: 448 });
1736
- const tmpPath = join3(dir, `.auth.json.${randomBytes(6).toString("hex")}.tmp`);
1828
+ const tmpPath = join4(dir, `.auth.json.${randomBytes2(6).toString("hex")}.tmp`);
1737
1829
  const body = `${JSON.stringify(auth, null, 2)}
1738
1830
  `;
1739
1831
  try {
@@ -2137,133 +2229,6 @@ function clientLabel() {
2137
2229
  return `${hostname()} (${platform3()})`;
2138
2230
  }
2139
2231
 
2140
- // src/commands/claim.ts
2141
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2142
- var out = (line) => process.stdout.write(`${line}
2143
- `);
2144
- async function runClaim() {
2145
- const base = resolveApiBase();
2146
- const grant = await startDeviceGrant(base, clientLabel(), machineHash());
2147
- if (process.stdout.isTTY) openInBrowser(grant.verification_url);
2148
- out("");
2149
- out(" Open this URL to approve this machine:");
2150
- out(` ${grant.verification_url}`);
2151
- out(` Code: ${grant.user_code}`);
2152
- out(" Waiting for approval...");
2153
- out("");
2154
- const deadline = Date.now() + grant.expires_in * 1e3;
2155
- let intervalMs = grant.interval * 1e3;
2156
- let first = true;
2157
- while (Date.now() < deadline) {
2158
- if (!first) await sleep(intervalMs);
2159
- first = false;
2160
- const result = await pollDeviceGrant(base, grant.device_code);
2161
- if (result.status === "complete") {
2162
- const path2 = await writeAuthFile({
2163
- token: result.ingest_token,
2164
- userId: result.userId,
2165
- handle: result.user.handle,
2166
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
2167
- });
2168
- out(` Claimed as @${result.user.handle}. Saved credentials to ${path2}`);
2169
- return;
2170
- }
2171
- if (result.status === "denied") {
2172
- throw new Error("Approval was denied in the browser.");
2173
- }
2174
- if (result.status === "expired") {
2175
- throw new Error("This claim request expired. Run `tokenboard claim` again.");
2176
- }
2177
- if (result.status === "slow_down") {
2178
- intervalMs += 5e3;
2179
- continue;
2180
- }
2181
- }
2182
- throw new Error("This claim request expired. Run `tokenboard claim` again.");
2183
- }
2184
-
2185
- // src/commands/preview.ts
2186
- async function collectLocalRecords() {
2187
- const tz = resolveTimeZone();
2188
- const claudeLines = dedupeByMessageId(collectClaudeCodeLines(resolveProjectsRoot(homedir2())));
2189
- const claudeRecords = claudeLines.map((l) => parsedLineToRecord(l, tz));
2190
- const ccusage = await collectCcusage();
2191
- const records = aggregateByKey([...claudeRecords, ...ccusage.records]);
2192
- return { records, ccusageSkipped: ccusage.skipped, npxAvailable: ccusage.npxAvailable };
2193
- }
2194
- async function runPreview(args) {
2195
- const prices = loadPriceTable();
2196
- const { records } = await collectLocalRecords();
2197
- const summary = summarize(records, prices);
2198
- if (args.json) {
2199
- process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
2200
- return;
2201
- }
2202
- const style = resolveStyle({
2203
- isTTY: Boolean(process.stdout.isTTY),
2204
- // Per the NO_COLOR spec (no-color.org), color is disabled when the var is PRESENT
2205
- // regardless of value — so `NO_COLOR=` (empty) still counts. Test presence, not truthiness.
2206
- noColorEnv: process.env["NO_COLOR"] !== void 0,
2207
- noColorFlag: args.noColor,
2208
- asciiFlag: args.ascii,
2209
- columns: process.stdout.columns
2210
- });
2211
- process.stdout.write(renderLocalPreview(summary, style) + "\n");
2212
- await offerClaim(style);
2213
- }
2214
- async function offerClaim(style) {
2215
- if (!process.stdin.isTTY || !process.stdout.isTTY) return;
2216
- const c = styler(style);
2217
- const auth = await readAuthFile();
2218
- if (auth) {
2219
- process.stdout.write("\n" + c.dim(`\u2713 claimed as @${auth.handle} \xB7 run \`tokenboard sync\` to upload`) + "\n");
2220
- return;
2221
- }
2222
- process.stdout.write("\n");
2223
- if (await confirm(c.cyan(CLAIM_PROMPT))) {
2224
- await runClaim();
2225
- return;
2226
- }
2227
- process.stdout.write(c.dim(CLAIM_HINT) + "\n");
2228
- }
2229
-
2230
- // src/commands/show-data.ts
2231
- init_esm_shims();
2232
- async function runShowData() {
2233
- const { records, ccusageSkipped, npxAvailable } = await collectLocalRecords();
2234
- const failures = [];
2235
- for (const rec of records) {
2236
- const result = normalizedRecordSchema.safeParse(rec);
2237
- if (!result.success) failures.push({ record: rec, issues: result.error.issues });
2238
- }
2239
- process.stdout.write(
2240
- " tokenboard show-data \u2014 dry run. This is EXACTLY what a future `sync` would upload.\n Counts only \u2014 no prompts, code, file paths, or repo names. NOTHING is uploaded in this release.\n\n"
2241
- );
2242
- if (failures.length > 0) {
2243
- process.stderr.write(
2244
- `show-data: ${failures.length} record(s) failed contract validation (parser bug):
2245
- ` + JSON.stringify(failures, null, 2) + "\n"
2246
- );
2247
- process.exitCode = 1;
2248
- return;
2249
- }
2250
- process.stdout.write(JSON.stringify(records, null, 2) + "\n");
2251
- if (!npxAvailable) {
2252
- process.stdout.write("\n (npx not found \u2014 ccusage long-tail skipped; Claude Code data shown above)\n");
2253
- } else if (ccusageSkipped.length > 0) {
2254
- process.stdout.write(`
2255
- (ccusage sources skipped: ${ccusageSkipped.join(", ")})
2256
- `);
2257
- }
2258
- }
2259
-
2260
- // src/commands/stub.ts
2261
- init_esm_shims();
2262
- function notAvailableYet(name, phase) {
2263
- process.stdout.write(` tokenboard ${name} \u2014 coming in a later release (${phase}).
2264
- `);
2265
- }
2266
-
2267
2232
  // src/commands/sync.ts
2268
2233
  init_esm_shims();
2269
2234
 
@@ -2339,7 +2304,7 @@ var CHUNK_SIZE = 500;
2339
2304
  var CLI_VERSION = "0.0.1";
2340
2305
  var IN_PROGRESS_RETRIES = 3;
2341
2306
  var IN_PROGRESS_BACKOFF_MS = 1e3;
2342
- var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
2307
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
2343
2308
  async function sendChunk(base, token, body) {
2344
2309
  const key = chunkIdempotencyKey(body);
2345
2310
  for (let attempt = 0; ; attempt++) {
@@ -2347,7 +2312,7 @@ async function sendChunk(base, token, body) {
2347
2312
  return await postSyncChunk(base, token, key, CLI_VERSION, body);
2348
2313
  } catch (err) {
2349
2314
  if (err instanceof SyncInProgressError && attempt < IN_PROGRESS_RETRIES) {
2350
- await sleep2(IN_PROGRESS_BACKOFF_MS * (attempt + 1));
2315
+ await sleep(IN_PROGRESS_BACKOFF_MS * (attempt + 1));
2351
2316
  continue;
2352
2317
  }
2353
2318
  throw err;
@@ -2393,6 +2358,148 @@ async function runSync() {
2393
2358
  `);
2394
2359
  }
2395
2360
 
2361
+ // src/commands/claim.ts
2362
+ var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2363
+ var out = (line) => process.stdout.write(`${line}
2364
+ `);
2365
+ async function runClaim() {
2366
+ const base = resolveApiBase();
2367
+ const grant = await startDeviceGrant(base, clientLabel(), machineHash());
2368
+ if (process.stdout.isTTY) openInBrowser(grant.verification_url);
2369
+ out("");
2370
+ out(" Open this URL to approve this machine:");
2371
+ out(` ${grant.verification_url}`);
2372
+ out(` Code: ${grant.user_code}`);
2373
+ out(" Waiting for approval...");
2374
+ out("");
2375
+ const deadline = Date.now() + grant.expires_in * 1e3;
2376
+ let intervalMs = grant.interval * 1e3;
2377
+ let first = true;
2378
+ while (Date.now() < deadline) {
2379
+ if (!first) await sleep2(intervalMs);
2380
+ first = false;
2381
+ const result = await pollDeviceGrant(base, grant.device_code);
2382
+ if (result.status === "complete") {
2383
+ const path2 = await writeAuthFile({
2384
+ token: result.ingest_token,
2385
+ userId: result.userId,
2386
+ handle: result.user.handle,
2387
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
2388
+ });
2389
+ out(` Claimed as @${result.user.handle}. Saved credentials to ${path2}`);
2390
+ out("");
2391
+ try {
2392
+ await runSync();
2393
+ } catch {
2394
+ out(" Couldn't sync usage just now \u2014 run `tokenboard sync` to appear on the board.");
2395
+ }
2396
+ return;
2397
+ }
2398
+ if (result.status === "denied") {
2399
+ throw new Error("Approval was denied in the browser.");
2400
+ }
2401
+ if (result.status === "expired") {
2402
+ throw new Error("This claim request expired. Run `tokenboard claim` again.");
2403
+ }
2404
+ if (result.status === "slow_down") {
2405
+ intervalMs += 5e3;
2406
+ continue;
2407
+ }
2408
+ }
2409
+ throw new Error("This claim request expired. Run `tokenboard claim` again.");
2410
+ }
2411
+
2412
+ // src/commands/preview.ts
2413
+ async function collectLocalRecords() {
2414
+ const tz = resolveTimeZone();
2415
+ const files = findJsonlFiles(resolveProjectsRoot(homedir2()));
2416
+ const [claudeLines, ccusage] = await Promise.all([
2417
+ Promise.resolve().then(() => dedupeByMessageId(collectClaudeCodeLinesCached(files, resolveConfigDir()))),
2418
+ collectCcusage()
2419
+ ]);
2420
+ const claudeRecords = claudeLines.map((l) => parsedLineToRecord(l, tz));
2421
+ const records = aggregateByKey([...claudeRecords, ...ccusage.records]);
2422
+ return { records, ccusageSkipped: ccusage.skipped, npxAvailable: ccusage.npxAvailable };
2423
+ }
2424
+ async function runPreview(args) {
2425
+ const prices = loadPriceTable();
2426
+ const spinner = args.json ? null : startSpinner("reading your local usage\u2026", args.ascii);
2427
+ let records;
2428
+ try {
2429
+ ({ records } = await collectLocalRecords());
2430
+ } finally {
2431
+ spinner?.stop();
2432
+ }
2433
+ const summary = summarize(records, prices);
2434
+ if (args.json) {
2435
+ process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
2436
+ return;
2437
+ }
2438
+ const style = resolveStyle({
2439
+ isTTY: Boolean(process.stdout.isTTY),
2440
+ // Per the NO_COLOR spec (no-color.org), color is disabled when the var is PRESENT
2441
+ // regardless of value — so `NO_COLOR=` (empty) still counts. Test presence, not truthiness.
2442
+ noColorEnv: process.env["NO_COLOR"] !== void 0,
2443
+ noColorFlag: args.noColor,
2444
+ asciiFlag: args.ascii,
2445
+ columns: process.stdout.columns
2446
+ });
2447
+ process.stdout.write(renderLocalPreview(summary, style) + "\n");
2448
+ await offerClaim(style);
2449
+ }
2450
+ async function offerClaim(style) {
2451
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return;
2452
+ const c = styler(style);
2453
+ const auth = await readAuthFile();
2454
+ if (auth) {
2455
+ process.stdout.write("\n" + c.dim(`\u2713 claimed as @${auth.handle} \xB7 run \`tokenboard sync\` to upload`) + "\n");
2456
+ return;
2457
+ }
2458
+ process.stdout.write("\n");
2459
+ if (await confirm(c.cyan(CLAIM_PROMPT))) {
2460
+ await runClaim();
2461
+ return;
2462
+ }
2463
+ process.stdout.write(c.dim(CLAIM_HINT) + "\n");
2464
+ }
2465
+
2466
+ // src/commands/show-data.ts
2467
+ init_esm_shims();
2468
+ async function runShowData() {
2469
+ const { records, ccusageSkipped, npxAvailable } = await collectLocalRecords();
2470
+ const failures = [];
2471
+ for (const rec of records) {
2472
+ const result = normalizedRecordSchema.safeParse(rec);
2473
+ if (!result.success) failures.push({ record: rec, issues: result.error.issues });
2474
+ }
2475
+ process.stdout.write(
2476
+ " tokenboard show-data \u2014 dry run. This is EXACTLY what a future `sync` would upload.\n Counts only \u2014 no prompts, code, file paths, or repo names. NOTHING is uploaded in this release.\n\n"
2477
+ );
2478
+ if (failures.length > 0) {
2479
+ process.stderr.write(
2480
+ `show-data: ${failures.length} record(s) failed contract validation (parser bug):
2481
+ ` + JSON.stringify(failures, null, 2) + "\n"
2482
+ );
2483
+ process.exitCode = 1;
2484
+ return;
2485
+ }
2486
+ process.stdout.write(JSON.stringify(records, null, 2) + "\n");
2487
+ if (!npxAvailable) {
2488
+ process.stdout.write("\n (npx not found \u2014 ccusage long-tail skipped; Claude Code data shown above)\n");
2489
+ } else if (ccusageSkipped.length > 0) {
2490
+ process.stdout.write(`
2491
+ (ccusage sources skipped: ${ccusageSkipped.join(", ")})
2492
+ `);
2493
+ }
2494
+ }
2495
+
2496
+ // src/commands/stub.ts
2497
+ init_esm_shims();
2498
+ function notAvailableYet(name, phase) {
2499
+ process.stdout.write(` tokenboard ${name} \u2014 coming in a later release (${phase}).
2500
+ `);
2501
+ }
2502
+
2396
2503
  // src/cli.ts
2397
2504
  var windowArgs = {
2398
2505
  "7d": { type: "boolean", description: "leaderboard window: last 7 days" },