claude-rpc 1.5.4 → 1.6.0

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/src/png.js ADDED
@@ -0,0 +1,135 @@
1
+ // SVG → PNG with whatever the machine already has, so claude-rpc stays at zero
2
+ // dependencies: rsvg-convert, then a Chromium-family browser in headless mode
3
+ // (Chrome, Edge, Brave, Chromium — Edge ships with every Windows 10/11), then
4
+ // ImageMagick or Inkscape. CLAUDE_RPC_BROWSER points at a browser binary
5
+ // explicitly.
6
+
7
+ import { existsSync, mkdtempSync, writeFileSync, readFileSync, rmSync, statSync, openSync, closeSync } from 'node:fs';
8
+ import { tmpdir } from 'node:os';
9
+ import { join, delimiter } from 'node:path';
10
+ import { pathToFileURL } from 'node:url';
11
+
12
+ const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
13
+
14
+ // Width/height of the root <svg>, from width/height or the viewBox.
15
+ export function svgSize(svg) {
16
+ const tag = (svg.match(/<svg\b[^>]*>/i) || [''])[0];
17
+ const num = (name) => {
18
+ const m = tag.match(new RegExp(`\\s${name}="([\\d.]+)(px)?"`, 'i'));
19
+ return m ? Number(m[1]) : null;
20
+ };
21
+ let w = num('width');
22
+ let h = num('height');
23
+ if (!w || !h) {
24
+ const vb = tag.match(/viewBox="[\d.-]+[\s,]+[\d.-]+[\s,]+([\d.]+)[\s,]+([\d.]+)"/i);
25
+ if (vb) { w = w || Number(vb[1]); h = h || Number(vb[2]); }
26
+ }
27
+ return { width: Math.ceil(w || 600), height: Math.ceil(h || 300) };
28
+ }
29
+
30
+ function onPath(name, env = process.env, platform = process.platform) {
31
+ const exts = platform === 'win32' ? (env.PATHEXT || '.EXE;.CMD;.BAT').split(';') : [''];
32
+ for (const dir of (env.PATH || env.Path || '').split(delimiter)) {
33
+ if (!dir) continue;
34
+ for (const ext of exts) {
35
+ const p = join(dir, name + ext);
36
+ try { if (statSync(p).isFile()) return p; } catch { /* not here */ }
37
+ }
38
+ }
39
+ return null;
40
+ }
41
+
42
+ function browserCandidates(env = process.env, platform = process.platform) {
43
+ if (platform === 'darwin') {
44
+ return ['Google Chrome', 'Microsoft Edge', 'Brave Browser', 'Chromium']
45
+ .map((app) => `/Applications/${app}.app/Contents/MacOS/${app}`);
46
+ }
47
+ if (platform === 'win32') {
48
+ const roots = [env.ProgramFiles, env['ProgramFiles(x86)'], env.LOCALAPPDATA].filter(Boolean);
49
+ const rel = ['Microsoft\\Edge\\Application\\msedge.exe', 'Google\\Chrome\\Application\\chrome.exe',
50
+ 'BraveSoftware\\Brave-Browser\\Application\\brave.exe'];
51
+ return roots.flatMap((r) => rel.map((p) => join(r, p)));
52
+ }
53
+ return [];
54
+ }
55
+
56
+ // The first available renderer as { kind, bin }, or null.
57
+ export function findRasterizer(env = process.env, platform = process.platform) {
58
+ if (env.CLAUDE_RPC_BROWSER) return existsSync(env.CLAUDE_RPC_BROWSER) ? { kind: 'browser', bin: env.CLAUDE_RPC_BROWSER } : null;
59
+ const rsvg = onPath('rsvg-convert', env, platform);
60
+ if (rsvg) return { kind: 'rsvg', bin: rsvg };
61
+ for (const p of browserCandidates(env, platform)) if (existsSync(p)) return { kind: 'browser', bin: p };
62
+ for (const name of ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser', 'microsoft-edge', 'brave-browser', 'msedge', 'chrome']) {
63
+ const p = onPath(name, env, platform);
64
+ if (p) return { kind: 'browser', bin: p };
65
+ }
66
+ const magick = onPath('magick', env, platform);
67
+ if (magick) return { kind: 'magick', bin: magick };
68
+ const inkscape = onPath('inkscape', env, platform);
69
+ if (inkscape) return { kind: 'inkscape', bin: inkscape };
70
+ return null;
71
+ }
72
+
73
+ // The argv for one renderer. Exported for tests.
74
+ export function rasterArgs(kind, { svgFile, htmlFile, out, width, height, scale, profileDir, root = false }) {
75
+ switch (kind) {
76
+ case 'rsvg': return ['-z', String(scale), '-b', 'none', '-o', out, svgFile];
77
+ case 'magick': return ['-background', 'none', '-density', String(96 * scale), svgFile, out];
78
+ case 'inkscape': return ['--export-type=png', `--export-filename=${out}`, `--export-dpi=${96 * scale}`, svgFile];
79
+ case 'browser': return [
80
+ '--headless=new', '--disable-gpu', '--hide-scrollbars', '--no-first-run', '--no-default-browser-check',
81
+ `--user-data-dir=${profileDir}`, '--default-background-color=00000000',
82
+ `--force-device-scale-factor=${scale}`, `--window-size=${width},${height}`,
83
+ `--screenshot=${out}`, ...(root ? ['--no-sandbox'] : []), pathToFileURL(htmlFile).href,
84
+ ];
85
+ default: throw new Error(`unknown rasterizer ${kind}`);
86
+ }
87
+ }
88
+
89
+ // Render `svg` to a PNG at `out` (2× by default). Throws with a readable
90
+ // message when nothing on the machine can do it.
91
+ export async function svgToPng(svg, out, { scale = 2, env = process.env } = {}) {
92
+ const r = findRasterizer(env);
93
+ if (!r) {
94
+ const e = new Error('no SVG renderer found');
95
+ e.hint = process.platform === 'darwin'
96
+ ? 'install Chrome, or `brew install librsvg` — or use --svg / --link instead'
97
+ : process.platform === 'win32'
98
+ ? 'Microsoft Edge does it — or set CLAUDE_RPC_BROWSER to a Chrome/Edge exe; --svg / --link work without one'
99
+ : 'install librsvg (rsvg-convert) or Chromium — or use --svg / --link instead';
100
+ throw e;
101
+ }
102
+ const { spawnSync } = await import('node:child_process');
103
+ const dir = mkdtempSync(join(tmpdir(), 'claude-rpc-png-'));
104
+ try {
105
+ const { width, height } = svgSize(svg);
106
+ const svgFile = join(dir, 'card.svg');
107
+ const htmlFile = join(dir, 'card.html');
108
+ writeFileSync(svgFile, svg);
109
+ writeFileSync(htmlFile, `<!doctype html><meta charset="utf-8"><style>html,body{margin:0;background:transparent;overflow:hidden}svg{display:block}</style>${svg}`);
110
+ const args = rasterArgs(r.kind, {
111
+ svgFile, htmlFile, out, width, height, scale,
112
+ profileDir: join(dir, 'profile'), root: typeof process.getuid === 'function' && process.getuid() === 0,
113
+ });
114
+ // stdio to a file, not a pipe: Chrome's crashpad helper inherits the pipe
115
+ // and outlives the browser, so spawnSync would wait on it until timeout.
116
+ const errFile = join(dir, 'err.log');
117
+ const fd = openSync(errFile, 'w');
118
+ let res;
119
+ try { res = spawnSync(r.bin, args, { stdio: ['ignore', fd, fd], timeout: 45_000, windowsHide: true }); } finally { closeSync(fd); }
120
+ try { res.stderr = readFileSync(errFile, 'utf8'); } catch { /* keep whatever spawnSync had */ }
121
+ let ok = false;
122
+ try { ok = readFileSync(out).subarray(0, 4).equals(PNG_MAGIC); } catch { /* not written */ }
123
+ if (!ok) {
124
+ const why = (res.error?.message || res.stderr || '').trim().split('\n').slice(-2).join(' ');
125
+ throw new Error(`${basenameOf(r.bin)} could not render the PNG${why ? `: ${why.slice(0, 200)}` : ''}`);
126
+ }
127
+ return { out, via: basenameOf(r.bin), width: width * scale, height: height * scale };
128
+ } finally {
129
+ try { rmSync(dir, { recursive: true, force: true }); } catch { /* temp cleanup is best-effort */ }
130
+ }
131
+ }
132
+
133
+ function basenameOf(p) {
134
+ return String(p).split(/[\\/]/).pop();
135
+ }
package/src/pricing.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // what your Claude Code subscription actually charges. Treat the resulting
4
4
  // `costEstimate` as a usage-weighted rough order of magnitude, not a bill.
5
5
  //
6
- // To customize: edit this file and run `claude-rpc rescan`.
6
+ // To customize: edit this file and run `claude-rpc scan --force`.
7
7
 
8
8
  const PRICING = {
9
9
  // Fable family — Anthropic's frontier tier above Opus. 5.1 cut cache reads 4x.
package/src/select.js ADDED
@@ -0,0 +1,60 @@
1
+ // A small arrow-key menu for interactive commands. ↑/↓ (or j/k) move, 1–9
2
+ // jump, Enter picks, Esc / q / Ctrl-C cancels (→ null). Disabled options are
3
+ // shown dimmed with their reason and skipped. Only call on a TTY.
4
+
5
+ import { c } from './ui.js';
6
+
7
+ export function select({ title, options, initial = 0, input = process.stdin, output = process.stdout }) {
8
+ const enabled = (i) => options[i] && !options[i].disabled;
9
+ let at = enabled(initial) ? initial : options.findIndex((o) => !o.disabled);
10
+ if (at === -1) return Promise.resolve(null);
11
+ let drawn = 0;
12
+ const labelW = options.reduce((m, o) => Math.max(m, o.label.length), 0);
13
+
14
+ const draw = () => {
15
+ if (drawn) output.write(`\x1b[${drawn}A`);
16
+ const lines = [` ${c.bold}${title}${c.reset} ${c.gray}↑↓ move · enter pick · esc cancel${c.reset}`];
17
+ options.forEach((o, i) => {
18
+ const n = i < 9 ? `${i + 1}` : ' ';
19
+ const hint = o.disabled ? o.disabled : (o.hint || '');
20
+ if (o.disabled) lines.push(` ${c.gray} ${n} ${o.label.padEnd(labelW)} ${hint}${c.reset}`);
21
+ else if (i === at) lines.push(` ${c.magenta}❯${c.reset} ${c.bold}${n} ${c.cyan}${o.label.padEnd(labelW)}${c.reset} ${c.dim}${hint}${c.reset}`);
22
+ else lines.push(` ${c.dim}${n}${c.reset} ${o.label.padEnd(labelW)} ${c.dim}${hint}${c.reset}`);
23
+ });
24
+ for (const l of lines) output.write(`\x1b[2K${l}\n`);
25
+ drawn = lines.length;
26
+ };
27
+
28
+ return new Promise((resolve) => {
29
+ const move = (d) => {
30
+ for (let i = 1; i <= options.length; i++) {
31
+ const j = (at + d * i + options.length * i) % options.length;
32
+ if (enabled(j)) { at = j; break; }
33
+ }
34
+ };
35
+ const done = (v) => {
36
+ input.off('data', onKey);
37
+ try { input.setRawMode(false); } catch { /* not a tty */ }
38
+ input.pause();
39
+ output.write('\x1b[?25h');
40
+ // Collapse the menu to one line showing the choice.
41
+ output.write(`\x1b[${drawn}A\x1b[0J`);
42
+ output.write(` ${c.bold}${title}${c.reset} ${v === null ? `${c.gray}cancelled${c.reset}` : `${c.cyan}${options[v].label}${c.reset}`}\n`);
43
+ resolve(v);
44
+ };
45
+ const onKey = (buf) => {
46
+ const k = buf.toString();
47
+ if (k === '\x03' || k === '\x1b' || k === 'q') return done(null);
48
+ if (k === '\r' || k === '\n') return done(at);
49
+ if (k === '\x1b[A' || k === 'k') move(-1);
50
+ else if (k === '\x1b[B' || k === 'j' || k === '\t') move(1);
51
+ else if (/^[1-9]$/.test(k) && enabled(Number(k) - 1)) { at = Number(k) - 1; draw(); return done(at); }
52
+ draw();
53
+ };
54
+ output.write('\x1b[?25l');
55
+ draw();
56
+ try { input.setRawMode(true); } catch { /* not a tty */ }
57
+ input.resume();
58
+ input.on('data', onKey);
59
+ });
60
+ }
@@ -0,0 +1,278 @@
1
+ // `claude-rpc statcards` — every shareable card in one place, each to a live
2
+ // link (served by the worker, refreshes itself as you work), a PNG, or an SVG.
3
+ //
4
+ // claude-rpc statcards menu: pick a card, then where it goes
5
+ // claude-rpc statcards stats --link --md Markdown for a README, to stdout
6
+ // claude-rpc statcards poster --png ./claude-poster.png
7
+ // claude-rpc statcards badge --metric streak --svg streak.svg
8
+ // claude-rpc statcards list what exists and where it can go
9
+ //
10
+ // Live links need a public profile (the worker renders from what it has
11
+ // published). PNG/SVG render locally from the aggregate when the card has a
12
+ // local renderer, otherwise from the live link. The older one-card commands
13
+ // (badge, card, github-stat, calendar, session-card, readme) still work
14
+ // unchanged.
15
+
16
+ import { writeFileSync } from 'node:fs';
17
+ import { resolve, relative } from 'node:path';
18
+ import { c, fail, EX_USER_ERROR, EX_BAD_STATE, EX_SYS_ERROR } from './ui.js';
19
+ import { isValidHandle } from './leaderboard.js';
20
+
21
+ const SITE = 'https://claude-rpc.com';
22
+ const DEFAULT_ENDPOINT = 'https://claude-rpc-totals.claude-rpc.workers.dev';
23
+
24
+ const q = (metric, fallback) => (metric && metric !== fallback ? `?metric=${metric}` : '');
25
+
26
+ export const CARDS = [
27
+ { id: 'stats', title: 'Stats + heatmap', blurb: 'totals over your year heatmap — the README hero',
28
+ metrics: ['tokens', 'hours'],
29
+ hosted: (h, o) => `/stats/${h}.svg${q(o.metric, 'tokens')}`, page: (h) => `${SITE}/u/${h}`,
30
+ local: async (ctx, o) => (await import('./calendar.js')).renderCalendarCard(ctx.aggregate(), { metric: o.metric || 'tokens', handle: ctx.handle }) },
31
+ { id: 'profile', title: 'Profile card', blurb: 'tokens, sessions, hours and streak on one card',
32
+ hosted: (h) => `/card/${h}.svg`, page: (h) => `${SITE}/u/${h}`,
33
+ local: async (ctx) => (await import('./profile.js')).renderProfileCard(ctx.aggregate(), { handle: ctx.handle }) },
34
+ { id: 'badge', title: 'Badge', blurb: 'a small shields-style badge',
35
+ metrics: ['hours', 'tokens', 'streak', 'sessions'], localMetrics: ['hours', 'tokens', 'streak', 'prompts', 'cost', 'lines', 'files'],
36
+ hosted: (h, o) => `/badge/${h}.svg?metric=${o.metric || 'hours'}`, page: () => `${SITE}/?ref=badge`,
37
+ local: async (ctx, o) => (await import('./badge.js')).badgeSvg({ aggregate: ctx.aggregate(), metric: o.metric || 'hours', range: o.range || '7d' }) },
38
+ { id: 'heatmap', title: 'Year heatmap', blurb: 'just the GitHub-style year grid',
39
+ metrics: ['tokens', 'hours'],
40
+ hosted: (h, o) => `/heatmap/${h}.svg${q(o.metric, 'tokens')}`, page: (h) => `${SITE}/u/${h}`,
41
+ local: async (ctx, o) => (await import('./calendar.js')).renderCalendar(ctx.aggregate(), { metric: o.metric || 'tokens' }) },
42
+ { id: 'poster', title: 'Poster', blurb: 'the big summary poster (great in Discord)',
43
+ ranges: ['year', 'month', 'week', 'all'],
44
+ local: async (ctx, o) => (await import('./card.js')).renderCard(ctx.aggregate(), { range: o.range || 'year' }) },
45
+ { id: 'session', title: 'This session', blurb: 'recap of the session you are in',
46
+ local: async (ctx) => (await import('./session-card.js')).renderSessionCard(ctx.liveVars(), {}) },
47
+ { id: 'wrapped', title: 'Wrapped card', blurb: 'your year in review (after wrapped --publish)',
48
+ hosted: (h, o) => `/wrapped/${h}.svg${o.year ? `?year=${o.year}` : ''}`, page: (h) => `${SITE}/wrapped/${h}` },
49
+ ];
50
+
51
+ export const OUTPUTS = ['link', 'png', 'svg'];
52
+ const cardById = (id) => CARDS.find((k) => k.id === id) || null;
53
+
54
+ // Parse statcards' argv. `--png`/`--svg` take an optional path: the next token,
55
+ // unless it is a flag or a card name.
56
+ export function parseArgs(argv) {
57
+ const o = { card: null, out: null, path: null, md: false, html: false, copy: false, metric: null, range: null, year: null };
58
+ for (let i = 0; i < argv.length; i++) {
59
+ let a = argv[i];
60
+ let val = null;
61
+ const eq = a.indexOf('=');
62
+ if (a.startsWith('--') && eq !== -1) { val = a.slice(eq + 1); a = a.slice(0, eq); }
63
+ const next = () => val ?? (argv[i + 1] && !argv[i + 1].startsWith('-') ? argv[++i] : null);
64
+ if (a === '--link' || a === '--url') o.out = 'link';
65
+ else if (a === '--png' || a === '--svg') {
66
+ o.out = a.slice(2);
67
+ const n = val ?? argv[i + 1];
68
+ if (n && !n.startsWith('-') && !cardById(n)) { o.path = n; if (val === null) i++; }
69
+ } else if (a === '--md' || a === '--markdown') { o.md = true; o.out = o.out || 'link'; }
70
+ else if (a === '--html') { o.html = true; o.out = o.out || 'link'; }
71
+ else if (a === '--copy') o.copy = true;
72
+ else if (a === '--metric' || a === '-m') o.metric = next();
73
+ else if (a === '--range' || a === '-r') o.range = next();
74
+ else if (a === '--year') o.year = next();
75
+ else if (!a.startsWith('-') && !o.card) o.card = a;
76
+ else return { error: `unknown option ${argv[i]}` };
77
+ }
78
+ return o;
79
+ }
80
+
81
+ export function snippets(card, handle, opts, endpoint = DEFAULT_ENDPOINT) {
82
+ const url = endpoint.replace(/\/+$/, '') + card.hosted(handle, opts);
83
+ const page = card.page(handle);
84
+ const alt = card.id === 'badge' ? `Claude Code ${opts.metric || 'hours'}` : 'Claude Code stats';
85
+ return {
86
+ url,
87
+ md: `[![${alt}](${url})](${page})`,
88
+ html: `<a href="${page}"><img src="${url}" alt="${alt}" /></a>`,
89
+ };
90
+ }
91
+
92
+ // Copy text to the system clipboard. Returns the tool used, or null.
93
+ export async function copyToClipboard(text, platform = process.platform, env = process.env) {
94
+ const { spawnSync } = await import('node:child_process');
95
+ const tries = platform === 'darwin' ? [['pbcopy', []]]
96
+ : platform === 'win32' ? [['clip', []]]
97
+ : [...(env.WAYLAND_DISPLAY ? [['wl-copy', []]] : []), ['xclip', ['-selection', 'clipboard']], ['xsel', ['--clipboard', '--input']]];
98
+ for (const [bin, args] of tries) {
99
+ try {
100
+ const r = spawnSync(bin, args, { input: text, timeout: 3000, windowsHide: true, stdio: ['pipe', 'ignore', 'ignore'] });
101
+ if (r.status === 0) return bin;
102
+ } catch { /* not installed — next */ }
103
+ }
104
+ return null;
105
+ }
106
+
107
+ function printList(ctx) {
108
+ const live = ctx.live;
109
+ console.log('');
110
+ console.log(` ${c.bold}${c.magenta}◆ Stat cards${c.reset} ${c.dim}— claude-rpc statcards <card> [--link|--png|--svg]${c.reset}`);
111
+ console.log('');
112
+ const w = CARDS.reduce((m, k) => Math.max(m, k.id.length), 0);
113
+ for (const k of CARDS) {
114
+ const where = [k.hosted ? 'link' : null, 'png', 'svg'].filter(Boolean).join(' · ');
115
+ const extra = k.metrics ? ` ${c.gray}--metric ${(k.localMetrics ? [...new Set([...k.metrics, ...k.localMetrics])] : k.metrics).join('|')}${c.reset}`
116
+ : k.ranges ? ` ${c.gray}--range ${k.ranges.join('|')}${c.reset}` : '';
117
+ console.log(` ${c.cyan}${k.id.padEnd(w)}${c.reset} ${k.blurb} ${c.dim}[${where}]${c.reset}${extra}`);
118
+ }
119
+ console.log('');
120
+ console.log(live
121
+ ? ` ${c.green}●${c.reset} ${c.dim}live links on — public profile ${c.reset}${c.cyan}@${ctx.handle}${c.reset}`
122
+ : ` ${c.yellow}○${c.reset} ${c.dim}live links need a public profile: ${c.reset}${c.cyan}claude-rpc profile set --handle <name>${c.reset}${c.dim} then ${c.reset}${c.cyan}claude-rpc profile on${c.reset}`);
123
+ console.log('');
124
+ }
125
+
126
+ async function renderSvg(card, ctx, opts) {
127
+ if (card.local) return card.local(ctx, opts);
128
+ // Hosted-only card: fetch what the worker serves.
129
+ const { url } = snippets(card, ctx.handle, opts, ctx.endpoint);
130
+ const res = await fetch(url, { headers: { 'user-agent': 'claude-rpc statcards' } });
131
+ if (!res.ok) throw new Error(`${url} answered HTTP ${res.status}`);
132
+ return res.text();
133
+ }
134
+
135
+ // ctx: { aggregate(), liveVars(), config, prompt(q), enableProfile() }
136
+ export async function runStatcards(argv, ctx) {
137
+ const o = parseArgs(argv);
138
+ if (o.error) return fail(o.error, { hint: 'claude-rpc help statcards', code: EX_USER_ERROR });
139
+ const cfg = ctx.config;
140
+ const profile = cfg.profile || {};
141
+ ctx.handle = isValidHandle(profile.handle) ? profile.handle : '';
142
+ ctx.live = !!profile.enabled && !!ctx.handle;
143
+ ctx.endpoint = (cfg.community?.endpoint || DEFAULT_ENDPOINT).replace(/\/+$/, '');
144
+ const tty = !!(process.stdout.isTTY && process.stdin.isTTY);
145
+ const { select } = tty ? await import('./select.js') : {};
146
+
147
+ if (o.card === 'list') return printList(ctx);
148
+
149
+ // 1. Which card.
150
+ let card = o.card ? cardById(o.card) : null;
151
+ if (o.card && !card) {
152
+ return fail(`no card called "${o.card}"`, { hint: `cards: ${CARDS.map((k) => k.id).join(', ')}`, code: EX_USER_ERROR });
153
+ }
154
+ if (!card) {
155
+ if (!tty) return printList(ctx);
156
+ console.log('');
157
+ const i = await select({
158
+ title: 'Which card?',
159
+ options: CARDS.map((k) => ({ label: k.title, hint: k.blurb })),
160
+ });
161
+ if (i === null) return;
162
+ card = CARDS[i];
163
+ }
164
+
165
+ // 2. Where it goes.
166
+ let out = o.out;
167
+ if (out === 'link' && !card.hosted) {
168
+ return fail(`the ${card.id} card has no live link`, { hint: `save it instead: claude-rpc statcards ${card.id} --png`, code: EX_USER_ERROR });
169
+ }
170
+ if (!out && !tty) out = 'svg';
171
+ if (!out) {
172
+ const linkWhy = !card.hosted ? 'only renders on this machine' : !ctx.live ? 'needs a public profile — you can turn it on next' : '';
173
+ const i = await select({
174
+ title: 'Where to?',
175
+ options: [
176
+ { label: 'Live link', hint: 'paste once in a README or site; it keeps itself up to date', disabled: !card.hosted ? linkWhy : '' },
177
+ { label: 'PNG image', hint: 'for Discord, X, LinkedIn, slides' },
178
+ { label: 'SVG file', hint: 'crisp at any size' },
179
+ ],
180
+ initial: card.hosted && ctx.live ? 0 : 1,
181
+ });
182
+ if (i === null) return;
183
+ out = OUTPUTS[i];
184
+ }
185
+
186
+ // 3. Options the card takes.
187
+ const metrics = out === 'link' || !card.local ? card.metrics : (card.localMetrics || card.metrics);
188
+ if (o.metric && metrics && !metrics.includes(o.metric)) {
189
+ return fail(`--metric ${o.metric} isn't available for the ${card.id} card${out === 'link' ? ' as a live link' : ''}`,
190
+ { hint: `use one of: ${metrics.join(', ')}`, code: EX_USER_ERROR });
191
+ }
192
+ if (o.metric && !metrics) return fail(`the ${card.id} card has no --metric`, { code: EX_USER_ERROR });
193
+ if (o.range && !(card.ranges || card.id === 'badge')) return fail(`the ${card.id} card has no --range`, { code: EX_USER_ERROR });
194
+ if (tty && !o.metric && metrics) {
195
+ const list = metrics;
196
+ const i = await select({ title: 'Counting?', options: list.map((m) => ({ label: m })) });
197
+ if (i === null) return;
198
+ o.metric = list[i];
199
+ }
200
+ if (tty && !o.range && card.ranges && out !== 'link') {
201
+ const i = await select({ title: 'Covering?', options: card.ranges.map((r) => ({ label: r === 'all' ? 'all time' : `this ${r}` })) });
202
+ if (i === null) return;
203
+ o.range = card.ranges[i];
204
+ }
205
+
206
+ // Live link (or a hosted-only card's file) needs the public profile.
207
+ if ((out === 'link' || !card.local) && !ctx.live) {
208
+ if (!ctx.handle) {
209
+ return fail('live cards need a public profile', {
210
+ hint: ['claude-rpc profile set --handle <name>', 'claude-rpc profile on — then run this again'], code: EX_BAD_STATE,
211
+ });
212
+ }
213
+ if (!tty) return fail(`your profile @${ctx.handle} is private`, { hint: 'claude-rpc profile on', code: EX_BAD_STATE });
214
+ const answer = (await ctx.prompt(` Make @${ctx.handle} public so the link works? ${c.dim}[y/N]${c.reset} `)).trim().toLowerCase();
215
+ if (answer !== 'y' && answer !== 'yes') {
216
+ console.log(` ${c.dim}left private — PNG and SVG work without it.${c.reset}`);
217
+ return;
218
+ }
219
+ await ctx.enableProfile();
220
+ ctx.live = true;
221
+ }
222
+
223
+ if (out === 'link') return emitLink(card, ctx, o, tty);
224
+ return emitFile(card, ctx, o, out, tty);
225
+ }
226
+
227
+ async function emitLink(card, ctx, o, tty) {
228
+ const s = snippets(card, ctx.handle, o, ctx.endpoint);
229
+ // Pipe-friendly: just the one thing asked for.
230
+ if (!tty) {
231
+ const text = o.md ? s.md : o.html ? s.html : s.url;
232
+ if (o.copy) await copyToClipboard(text);
233
+ process.stdout.write(text + '\n');
234
+ return;
235
+ }
236
+
237
+ console.log('');
238
+ console.log(` ${c.green}✓${c.reset} ${c.bold}${card.title}${c.reset} ${c.dim}— live; it refreshes itself as you work${c.reset}`);
239
+ console.log('');
240
+ console.log(` ${c.dim}link ${c.reset}${c.cyan}${s.url}${c.reset}`);
241
+ console.log(` ${c.dim}markdown ${c.reset}${s.md}`);
242
+ console.log(` ${c.dim}html ${c.reset}${s.html}`);
243
+ console.log('');
244
+ const which = o.html ? 'html' : 'md';
245
+ const tool = await copyToClipboard(s[which]);
246
+ if (tool) console.log(` ${c.magenta}⧉${c.reset} ${c.dim}${which === 'html' ? 'HTML' : 'Markdown'} copied — paste it into your README${c.reset}`);
247
+ if (card.id === 'wrapped') console.log(` ${c.dim}shows your year once it's published: ${c.reset}${c.cyan}claude-rpc wrapped --publish${c.reset}`);
248
+ console.log('');
249
+ }
250
+
251
+ async function emitFile(card, ctx, o, out, tty) {
252
+ let svg;
253
+ try {
254
+ svg = await renderSvg(card, ctx, o);
255
+ } catch (e) {
256
+ return fail(`couldn't render the ${card.id} card: ${e.message}`, { code: EX_SYS_ERROR });
257
+ }
258
+ const suffix = [card.id, o.metric && card.metrics && o.metric !== card.metrics[0] ? o.metric : null, o.range && o.range !== 'year' ? o.range : null]
259
+ .filter(Boolean).join('-');
260
+ const path = resolve(o.path || `claude-${suffix}.${out}`);
261
+ const shown = relative(process.cwd(), path) || path;
262
+
263
+ if (out === 'svg') {
264
+ if (!o.path && !tty && !o.out) { process.stdout.write(svg); return; }
265
+ writeFileSync(path, svg);
266
+ console.log(` ${c.green}✓${c.reset} saved ${c.cyan}${shown}${c.reset} ${c.dim}(${svg.length} bytes)${c.reset}`);
267
+ return;
268
+ }
269
+
270
+ const { svgToPng } = await import('./png.js');
271
+ try {
272
+ const r = await svgToPng(svg, path);
273
+ console.log(` ${c.green}✓${c.reset} saved ${c.cyan}${shown}${c.reset} ${c.dim}(${r.width}×${r.height}, via ${r.via})${c.reset}`);
274
+ if (tty) console.log(` ${c.dim}drag it into Discord, X or a slide — it's 2× for sharp screens${c.reset}`);
275
+ } catch (e) {
276
+ return fail(e.message, { hint: e.hint || '', code: EX_SYS_ERROR });
277
+ }
278
+ }
package/src/version.js CHANGED
@@ -11,7 +11,7 @@ import { readFileSync } from 'node:fs';
11
11
  import { join } from 'node:path';
12
12
  import { ROOT } from './paths.js';
13
13
 
14
- const BAKED = '1.5.4';
14
+ const BAKED = '1.6.0';
15
15
 
16
16
  function readPkgVersion() {
17
17
  try {