@tokenboard/cli 0.1.0 → 0.1.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/dist/cli.js CHANGED
@@ -587,7 +587,7 @@ function _getBuiltinFlags(long, short, userNames, userAliases) {
587
587
 
588
588
  // src/commands/preview.ts
589
589
  init_esm_shims();
590
- import { homedir } from "os";
590
+ import { homedir as homedir2 } from "os";
591
591
 
592
592
  // src/config/home.ts
593
593
  init_esm_shims();
@@ -793,6 +793,7 @@ function ccusageDailyToRecords(source, daily) {
793
793
 
794
794
  // src/collectors/ccusage-source.ts
795
795
  var SPAWN_TIMEOUT_MS = 3e4;
796
+ var CLAUDE_AGENT = "claude";
796
797
  function hasNpx() {
797
798
  try {
798
799
  const r = spawnSync("npx", ["--version"], { stdio: "ignore" });
@@ -801,11 +802,9 @@ function hasNpx() {
801
802
  return false;
802
803
  }
803
804
  }
804
- function runSource(source) {
805
+ function runCcusage(args) {
805
806
  return new Promise((resolve, reject) => {
806
- const child = spawn("npx", ["-y", "ccusage@20", source, "daily", "--json", "--offline"], {
807
- stdio: ["ignore", "pipe", "ignore"]
808
- });
807
+ const child = spawn("npx", ["-y", "ccusage@20", ...args], { stdio: ["ignore", "pipe", "ignore"] });
809
808
  let stdout = "";
810
809
  const killer = setTimeout(() => child.kill("SIGKILL"), SPAWN_TIMEOUT_MS);
811
810
  child.stdout.on("data", (chunk2) => {
@@ -818,22 +817,51 @@ function runSource(source) {
818
817
  child.on("close", (code) => {
819
818
  clearTimeout(killer);
820
819
  if (code !== 0) {
821
- reject(new Error(`ccusage ${source} exited ${code}`));
820
+ reject(new Error(`ccusage ${args.join(" ")} exited ${code}`));
822
821
  return;
823
822
  }
824
- try {
825
- const parsed = JSON.parse(stdout);
826
- resolve(parsed.daily ?? []);
827
- } catch (err) {
828
- reject(err);
829
- }
823
+ resolve(stdout);
830
824
  });
831
825
  });
832
826
  }
827
+ function runSource(source) {
828
+ return runCcusage([source, "daily", "--json", "--offline"]).then((stdout) => {
829
+ const parsed = JSON.parse(stdout);
830
+ return parsed.daily ?? [];
831
+ });
832
+ }
833
+ function agentsFromDailyPayload(parsed) {
834
+ const rows = typeof parsed === "object" && parsed !== null && Array.isArray(parsed.daily) ? parsed.daily : [];
835
+ const agents = /* @__PURE__ */ new Set();
836
+ for (const row2 of rows) {
837
+ const list = row2?.metadata?.agents;
838
+ if (Array.isArray(list)) {
839
+ for (const a of list) if (typeof a === "string") agents.add(a.toLowerCase());
840
+ }
841
+ }
842
+ if (rows.length > 0 && agents.size === 0) return null;
843
+ return agents;
844
+ }
845
+ async function detectAgentsWithData() {
846
+ try {
847
+ const stdout = await runCcusage(["daily", "--json", "--offline"]);
848
+ return agentsFromDailyPayload(JSON.parse(stdout));
849
+ } catch {
850
+ return null;
851
+ }
852
+ }
853
+ function canSkipFanOut(agents) {
854
+ if (agents === null) return false;
855
+ return [...agents].every((a) => a === CLAUDE_AGENT);
856
+ }
833
857
  async function collectCcusage() {
834
858
  if (!hasNpx()) {
835
859
  return { records: [], skipped: [], npxAvailable: false };
836
860
  }
861
+ const agents = await detectAgentsWithData();
862
+ if (canSkipFanOut(agents)) {
863
+ return { records: [], skipped: [], npxAvailable: true };
864
+ }
837
865
  const records = [];
838
866
  const skipped = [];
839
867
  await Promise.all(
@@ -1680,42 +1708,95 @@ function renderLocalPreview(summary, style) {
1680
1708
  }
1681
1709
  return lines.join("\n");
1682
1710
  }
1683
- var CLAIM_CTA = "\u2192 Sign in with GitHub to claim your spot \u2192 tokenboard claim";
1711
+ var CLAIM_PROMPT = "Sign in with GitHub to claim your spot?";
1712
+ var CLAIM_HINT = "\u2192 Claim your spot anytime \u2192 tokenboard claim";
1684
1713
 
1685
- // src/commands/preview.ts
1686
- async function collectLocalRecords() {
1687
- const tz = resolveTimeZone();
1688
- const claudeLines = dedupeByMessageId(collectClaudeCodeLines(resolveProjectsRoot(homedir())));
1689
- const claudeRecords = claudeLines.map((l) => parsedLineToRecord(l, tz));
1690
- const ccusage = await collectCcusage();
1691
- const records = aggregateByKey([...claudeRecords, ...ccusage.records]);
1692
- return { records, ccusageSkipped: ccusage.skipped, npxAvailable: ccusage.npxAvailable };
1714
+ // src/config/auth-store.ts
1715
+ init_esm_shims();
1716
+ import { homedir, platform } from "os";
1717
+ import { join as join3, isAbsolute } from "path";
1718
+ import { mkdir, writeFile, chmod, rename, unlink, readFile } from "fs/promises";
1719
+ import { randomBytes } from "crypto";
1720
+ function resolveConfigDir(env = process.env) {
1721
+ if (platform() === "win32") {
1722
+ const appData = env.APPDATA && env.APPDATA.trim() !== "" ? env.APPDATA : join3(homedir(), "AppData", "Roaming");
1723
+ return join3(appData, "tokenboard");
1724
+ }
1725
+ const xdg = env.XDG_CONFIG_HOME;
1726
+ const base = xdg && isAbsolute(xdg) ? xdg : join3(homedir(), ".config");
1727
+ return join3(base, "tokenboard");
1693
1728
  }
1694
- async function runPreview(args) {
1695
- const prices = loadPriceTable();
1696
- const { records } = await collectLocalRecords();
1697
- const summary = summarize(records, prices);
1698
- if (args.json) {
1699
- process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
1700
- return;
1729
+ function resolveAuthPath(env = process.env) {
1730
+ return join3(resolveConfigDir(env), "auth.json");
1731
+ }
1732
+ async function writeAuthFile(auth, env = process.env) {
1733
+ const dir = resolveConfigDir(env);
1734
+ const finalPath = join3(dir, "auth.json");
1735
+ await mkdir(dir, { recursive: true, mode: 448 });
1736
+ const tmpPath = join3(dir, `.auth.json.${randomBytes(6).toString("hex")}.tmp`);
1737
+ const body = `${JSON.stringify(auth, null, 2)}
1738
+ `;
1739
+ try {
1740
+ await writeFile(tmpPath, body, { mode: 384, flag: "wx" });
1741
+ await chmod(tmpPath, 384);
1742
+ await rename(tmpPath, finalPath);
1743
+ await chmod(finalPath, 384);
1744
+ } catch (err) {
1745
+ await unlink(tmpPath).catch(() => {
1746
+ });
1747
+ throw err;
1701
1748
  }
1702
- const style = resolveStyle({
1703
- isTTY: Boolean(process.stdout.isTTY),
1704
- // Per the NO_COLOR spec (no-color.org), color is disabled when the var is PRESENT
1705
- // regardless of value — so `NO_COLOR=` (empty) still counts. Test presence, not truthiness.
1706
- noColorEnv: process.env["NO_COLOR"] !== void 0,
1707
- noColorFlag: args.noColor,
1708
- asciiFlag: args.ascii,
1709
- columns: process.stdout.columns
1710
- });
1711
- process.stdout.write(renderLocalPreview(summary, style) + "\n");
1712
- if (process.stdout.isTTY) {
1713
- const c = styler(style);
1714
- process.stdout.write("\n" + c.cyan(CLAIM_CTA) + "\n");
1749
+ return finalPath;
1750
+ }
1751
+ async function readAuthFile(env = process.env) {
1752
+ try {
1753
+ return JSON.parse(await readFile(resolveAuthPath(env), "utf8"));
1754
+ } catch (err) {
1755
+ if (err.code === "ENOENT") return null;
1756
+ throw err;
1715
1757
  }
1716
1758
  }
1717
1759
 
1718
- // src/commands/show-data.ts
1760
+ // src/prompt/confirm.ts
1761
+ init_esm_shims();
1762
+ import { createInterface } from "readline/promises";
1763
+ function parseYesNo(answer) {
1764
+ const a = answer.trim().toLowerCase();
1765
+ return a === "y" || a === "yes";
1766
+ }
1767
+ async function confirm(question) {
1768
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return false;
1769
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1770
+ try {
1771
+ const answer = await rl.question(`${question} [y/N] `);
1772
+ return parseYesNo(answer);
1773
+ } finally {
1774
+ rl.close();
1775
+ }
1776
+ }
1777
+
1778
+ // src/commands/claim.ts
1779
+ init_esm_shims();
1780
+
1781
+ // src/claim/api-base.ts
1782
+ init_esm_shims();
1783
+ var DEFAULT_API_BASE = "https://tokenboard.sh";
1784
+ function resolveApiBase(env = process.env) {
1785
+ const raw = env.TOKENBOARD_API_URL?.trim();
1786
+ const base = raw && raw !== "" ? raw : DEFAULT_API_BASE;
1787
+ let parsed;
1788
+ try {
1789
+ parsed = new URL(base);
1790
+ } catch {
1791
+ throw new Error(`TOKENBOARD_API_URL is not a valid URL: ${base}`);
1792
+ }
1793
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
1794
+ throw new Error(`TOKENBOARD_API_URL must be http(s): ${base}`);
1795
+ }
1796
+ return base.replace(/\/+$/, "");
1797
+ }
1798
+
1799
+ // src/claim/transport.ts
1719
1800
  init_esm_shims();
1720
1801
 
1721
1802
  // ../packages/contracts/src/index.ts
@@ -1983,65 +2064,7 @@ var profileUpdateResponseSchema = z8.object({
1983
2064
  social_links: z8.record(z8.string(), z8.string())
1984
2065
  });
1985
2066
 
1986
- // src/commands/show-data.ts
1987
- async function runShowData() {
1988
- const { records, ccusageSkipped, npxAvailable } = await collectLocalRecords();
1989
- const failures = [];
1990
- for (const rec of records) {
1991
- const result = normalizedRecordSchema.safeParse(rec);
1992
- if (!result.success) failures.push({ record: rec, issues: result.error.issues });
1993
- }
1994
- process.stdout.write(
1995
- " 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"
1996
- );
1997
- if (failures.length > 0) {
1998
- process.stderr.write(
1999
- `show-data: ${failures.length} record(s) failed contract validation (parser bug):
2000
- ` + JSON.stringify(failures, null, 2) + "\n"
2001
- );
2002
- process.exitCode = 1;
2003
- return;
2004
- }
2005
- process.stdout.write(JSON.stringify(records, null, 2) + "\n");
2006
- if (!npxAvailable) {
2007
- process.stdout.write("\n (npx not found \u2014 ccusage long-tail skipped; Claude Code data shown above)\n");
2008
- } else if (ccusageSkipped.length > 0) {
2009
- process.stdout.write(`
2010
- (ccusage sources skipped: ${ccusageSkipped.join(", ")})
2011
- `);
2012
- }
2013
- }
2014
-
2015
- // src/commands/stub.ts
2016
- init_esm_shims();
2017
- function notAvailableYet(name, phase) {
2018
- process.stdout.write(` tokenboard ${name} \u2014 coming in a later release (${phase}).
2019
- `);
2020
- }
2021
-
2022
- // src/commands/claim.ts
2023
- init_esm_shims();
2024
-
2025
- // src/claim/api-base.ts
2026
- init_esm_shims();
2027
- var DEFAULT_API_BASE = "https://tokenboard.sh";
2028
- function resolveApiBase(env = process.env) {
2029
- const raw = env.TOKENBOARD_API_URL?.trim();
2030
- const base = raw && raw !== "" ? raw : DEFAULT_API_BASE;
2031
- let parsed;
2032
- try {
2033
- parsed = new URL(base);
2034
- } catch {
2035
- throw new Error(`TOKENBOARD_API_URL is not a valid URL: ${base}`);
2036
- }
2037
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
2038
- throw new Error(`TOKENBOARD_API_URL must be http(s): ${base}`);
2039
- }
2040
- return base.replace(/\/+$/, "");
2041
- }
2042
-
2043
2067
  // src/claim/transport.ts
2044
- init_esm_shims();
2045
2068
  var REQUEST_TIMEOUT_MS = 15e3;
2046
2069
  async function postJson(url, body) {
2047
2070
  const res = await fetch(url, {
@@ -2074,14 +2097,14 @@ async function pollDeviceGrant(base, deviceCode) {
2074
2097
  // src/claim/browser.ts
2075
2098
  init_esm_shims();
2076
2099
  import { spawn as spawn2 } from "child_process";
2077
- import { platform } from "os";
2100
+ import { platform as platform2 } from "os";
2078
2101
  function openInBrowser(url) {
2079
2102
  let command;
2080
2103
  let args;
2081
- if (platform() === "darwin") {
2104
+ if (platform2() === "darwin") {
2082
2105
  command = "open";
2083
2106
  args = [url];
2084
- } else if (platform() === "win32") {
2107
+ } else if (platform2() === "win32") {
2085
2108
  command = "cmd";
2086
2109
  args = ["/c", "start", "", url];
2087
2110
  } else {
@@ -2099,7 +2122,7 @@ function openInBrowser(url) {
2099
2122
 
2100
2123
  // src/claim/machine.ts
2101
2124
  init_esm_shims();
2102
- import { hostname, platform as platform2, arch, userInfo } from "os";
2125
+ import { hostname, platform as platform3, arch, userInfo } from "os";
2103
2126
  import { createHash } from "crypto";
2104
2127
  function machineHash() {
2105
2128
  let user = "";
@@ -2107,57 +2130,11 @@ function machineHash() {
2107
2130
  user = userInfo().username;
2108
2131
  } catch {
2109
2132
  }
2110
- const stable = [hostname(), platform2(), arch(), user].join(" ");
2133
+ const stable = [hostname(), platform3(), arch(), user].join(" ");
2111
2134
  return createHash("sha256").update(stable).digest("hex");
2112
2135
  }
2113
2136
  function clientLabel() {
2114
- return `${hostname()} (${platform2()})`;
2115
- }
2116
-
2117
- // src/config/auth-store.ts
2118
- init_esm_shims();
2119
- import { homedir as homedir2, platform as platform3 } from "os";
2120
- import { join as join3, isAbsolute } from "path";
2121
- import { mkdir, writeFile, chmod, rename, unlink, readFile } from "fs/promises";
2122
- import { randomBytes } from "crypto";
2123
- function resolveConfigDir(env = process.env) {
2124
- if (platform3() === "win32") {
2125
- const appData = env.APPDATA && env.APPDATA.trim() !== "" ? env.APPDATA : join3(homedir2(), "AppData", "Roaming");
2126
- return join3(appData, "tokenboard");
2127
- }
2128
- const xdg = env.XDG_CONFIG_HOME;
2129
- const base = xdg && isAbsolute(xdg) ? xdg : join3(homedir2(), ".config");
2130
- return join3(base, "tokenboard");
2131
- }
2132
- function resolveAuthPath(env = process.env) {
2133
- return join3(resolveConfigDir(env), "auth.json");
2134
- }
2135
- async function writeAuthFile(auth, env = process.env) {
2136
- const dir = resolveConfigDir(env);
2137
- const finalPath = join3(dir, "auth.json");
2138
- await mkdir(dir, { recursive: true, mode: 448 });
2139
- const tmpPath = join3(dir, `.auth.json.${randomBytes(6).toString("hex")}.tmp`);
2140
- const body = `${JSON.stringify(auth, null, 2)}
2141
- `;
2142
- try {
2143
- await writeFile(tmpPath, body, { mode: 384, flag: "wx" });
2144
- await chmod(tmpPath, 384);
2145
- await rename(tmpPath, finalPath);
2146
- await chmod(finalPath, 384);
2147
- } catch (err) {
2148
- await unlink(tmpPath).catch(() => {
2149
- });
2150
- throw err;
2151
- }
2152
- return finalPath;
2153
- }
2154
- async function readAuthFile(env = process.env) {
2155
- try {
2156
- return JSON.parse(await readFile(resolveAuthPath(env), "utf8"));
2157
- } catch (err) {
2158
- if (err.code === "ENOENT") return null;
2159
- throw err;
2160
- }
2137
+ return `${hostname()} (${platform3()})`;
2161
2138
  }
2162
2139
 
2163
2140
  // src/commands/claim.ts
@@ -2205,6 +2182,88 @@ async function runClaim() {
2205
2182
  throw new Error("This claim request expired. Run `tokenboard claim` again.");
2206
2183
  }
2207
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
+
2208
2267
  // src/commands/sync.ts
2209
2268
  init_esm_shims();
2210
2269