spendbyteam 0.0.0-stage → 0.2.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.
@@ -0,0 +1,164 @@
1
+ import { HOOK_COMMAND, HOOK_COMMAND_RE, HOOK_EVENTS, HOOK_TIMEOUT_SECONDS } from './constants.js';
2
+ import { MANAGED_ENV_KEYS } from './env.js';
3
+ import { isPlainObject, JsonFileError } from './fsutil.js';
4
+ export function hookEntry() {
5
+ return { type: 'command', command: HOOK_COMMAND, async: true, timeout: HOOK_TIMEOUT_SECONDS };
6
+ }
7
+ function isOurHook(h) {
8
+ return isPlainObject(h) && typeof h.command === 'string' && HOOK_COMMAND_RE.test(h.command.trim());
9
+ }
10
+ function clone(v) {
11
+ return JSON.parse(JSON.stringify(v));
12
+ }
13
+ function envOf(settings, file = 'settings.json') {
14
+ if (settings.env === undefined)
15
+ return {};
16
+ if (!isPlainObject(settings.env))
17
+ throw new JsonFileError(`"env" in ${file} must be an object.`);
18
+ return settings.env;
19
+ }
20
+ function hooksOf(settings, file = 'settings.json') {
21
+ if (settings.hooks === undefined)
22
+ return {};
23
+ if (!isPlainObject(settings.hooks))
24
+ throw new JsonFileError(`"hooks" in ${file} must be an object.`);
25
+ return settings.hooks;
26
+ }
27
+ /**
28
+ * Merge our env block and hooks into existing settings without touching anything else.
29
+ * Idempotent: merging twice yields identical output. `prior` (from state.json) makes re-runs keep the
30
+ * original pre-install values and drops keys a previous run applied but this run no longer wants.
31
+ */
32
+ export function mergeSettings(current, env, prior) {
33
+ const next = clone(current);
34
+ const curEnv = { ...envOf(next) };
35
+ const previousEnv = {};
36
+ const overwritten = [];
37
+ if (prior) {
38
+ for (const [key, applied] of Object.entries(prior.appliedEnv)) {
39
+ if (key in env || curEnv[key] !== applied)
40
+ continue;
41
+ const prev = prior.previousEnv[key];
42
+ if (prev === null || prev === undefined)
43
+ delete curEnv[key];
44
+ else
45
+ curEnv[key] = prev;
46
+ }
47
+ }
48
+ for (const [key, value] of Object.entries(env)) {
49
+ if (prior && key in prior.appliedEnv && key in prior.previousEnv) {
50
+ previousEnv[key] = prior.previousEnv[key] ?? null;
51
+ continue;
52
+ }
53
+ const has = Object.prototype.hasOwnProperty.call(curEnv, key);
54
+ previousEnv[key] = has ? String(curEnv[key]) : null;
55
+ if (has && String(curEnv[key]) !== value)
56
+ overwritten.push(key);
57
+ }
58
+ next.env = { ...curEnv, ...env };
59
+ const hooks = hooksOf(next);
60
+ for (const event of HOOK_EVENTS) {
61
+ const groups = hooks[event];
62
+ if (groups !== undefined && !Array.isArray(groups)) {
63
+ throw new JsonFileError(`"hooks.${event}" in settings.json must be an array.`);
64
+ }
65
+ const list = groups ? [...groups] : [];
66
+ let found = false;
67
+ for (let i = 0; i < list.length; i++) {
68
+ const g = list[i];
69
+ if (!isPlainObject(g) || !Array.isArray(g.hooks))
70
+ continue;
71
+ if (!g.hooks.some(isOurHook))
72
+ continue;
73
+ const inner = g.hooks
74
+ .map((h) => {
75
+ if (!isOurHook(h))
76
+ return h;
77
+ if (found)
78
+ return undefined; // drop duplicates of our hook
79
+ found = true;
80
+ return hookEntry();
81
+ })
82
+ .filter((h) => h !== undefined);
83
+ list[i] = inner.length > 0 ? { ...g, hooks: inner } : undefined;
84
+ }
85
+ if (!found)
86
+ list.push({ hooks: [hookEntry()] });
87
+ hooks[event] = list.filter((g) => g !== undefined);
88
+ }
89
+ next.hooks = hooks;
90
+ return { settings: next, previousEnv, overwritten };
91
+ }
92
+ /**
93
+ * Undo mergeSettings: remove our hooks and restore/remove our env keys.
94
+ * Without state (state.json lost) env keys are only removed when the OTLP headers carry an
95
+ * SpendByTeam token, so we never strip a different collector's configuration.
96
+ */
97
+ export function removeSettings(current, opts = {}) {
98
+ const next = clone(current);
99
+ if (next.env !== undefined && isPlainObject(next.env)) {
100
+ const env = next.env;
101
+ if (opts.previousEnv && opts.appliedEnv) {
102
+ for (const [key, applied] of Object.entries(opts.appliedEnv)) {
103
+ if (!Object.prototype.hasOwnProperty.call(env, key))
104
+ continue;
105
+ if (String(env[key]) !== applied)
106
+ continue; // user changed it after install; keep
107
+ const prev = opts.previousEnv[key];
108
+ if (prev === null || prev === undefined)
109
+ delete env[key];
110
+ else
111
+ env[key] = prev;
112
+ }
113
+ }
114
+ else if (typeof env.OTEL_EXPORTER_OTLP_HEADERS === 'string' && env.OTEL_EXPORTER_OTLP_HEADERS.includes('sbt_ing_')) {
115
+ for (const key of MANAGED_ENV_KEYS)
116
+ delete env[key];
117
+ }
118
+ if (Object.keys(env).length === 0)
119
+ delete next.env;
120
+ }
121
+ if (next.hooks !== undefined && isPlainObject(next.hooks)) {
122
+ const hooks = next.hooks;
123
+ for (const event of HOOK_EVENTS) {
124
+ const groups = hooks[event];
125
+ if (!Array.isArray(groups))
126
+ continue;
127
+ const kept = groups
128
+ .map((g) => {
129
+ if (!isPlainObject(g) || !Array.isArray(g.hooks))
130
+ return g;
131
+ const had = g.hooks.length;
132
+ const inner = g.hooks.filter((h) => !isOurHook(h));
133
+ if (inner.length === had)
134
+ return g;
135
+ return inner.length === 0 ? undefined : { ...g, hooks: inner };
136
+ })
137
+ .filter((g) => g !== undefined);
138
+ if (kept.length === 0)
139
+ delete hooks[event];
140
+ else
141
+ hooks[event] = kept;
142
+ }
143
+ if (Object.keys(hooks).length === 0)
144
+ delete next.hooks;
145
+ }
146
+ return next;
147
+ }
148
+ /** Compare current settings to the env we expect (status/doctor). */
149
+ export function inspectSettings(current, expectedEnv) {
150
+ const env = isPlainObject(current.env) ? current.env : {};
151
+ const mismatchedKeys = [];
152
+ if (expectedEnv) {
153
+ for (const [k, v] of Object.entries(expectedEnv))
154
+ if (env[k] !== v)
155
+ mismatchedKeys.push(k);
156
+ }
157
+ const hooks = isPlainObject(current.hooks) ? current.hooks : {};
158
+ const hookEvents = {};
159
+ for (const event of HOOK_EVENTS) {
160
+ const groups = hooks[event];
161
+ hookEvents[event] = Array.isArray(groups) && groups.some((g) => isPlainObject(g) && Array.isArray(g.hooks) && g.hooks.some(isOurHook));
162
+ }
163
+ return { envMatches: expectedEnv !== undefined && mismatchedKeys.length === 0, mismatchedKeys, hookEvents };
164
+ }
package/dist/state.js ADDED
@@ -0,0 +1,35 @@
1
+ import fs from 'node:fs';
2
+ import { paths } from './paths.js';
3
+ import { isPlainObject, readJsonObject, toJson, writeFileAtomic } from './fsutil.js';
4
+ export function ensureSbtDir() {
5
+ const { sbtDir } = paths();
6
+ fs.mkdirSync(sbtDir, { recursive: true, mode: 0o700 });
7
+ fs.chmodSync(sbtDir, 0o700);
8
+ }
9
+ /** config.json is read by hook.sh; it holds the token, so it is always chmod 600. */
10
+ export function writeConfig(cfg) {
11
+ ensureSbtDir();
12
+ writeFileAtomic(paths().config, toJson({ token: cfg.token, endpoint: cfg.endpoint }), 0o600);
13
+ }
14
+ export function readConfig() {
15
+ const data = readJsonObject(paths().config);
16
+ if (!data || typeof data.token !== 'string' || typeof data.endpoint !== 'string')
17
+ return undefined;
18
+ return { token: data.token, endpoint: data.endpoint };
19
+ }
20
+ export function writeState(state) {
21
+ ensureSbtDir();
22
+ writeFileAtomic(paths().state, toJson(state), 0o600);
23
+ }
24
+ export function readState() {
25
+ let data;
26
+ try {
27
+ data = readJsonObject(paths().state);
28
+ }
29
+ catch {
30
+ return undefined;
31
+ }
32
+ if (!data || !isPlainObject(data.previous_env) || !isPlainObject(data.applied_env))
33
+ return undefined;
34
+ return data;
35
+ }
package/dist/status.js ADDED
@@ -0,0 +1,83 @@
1
+ import { buildEnv, maskToken } from './env.js';
2
+ import { paths } from './paths.js';
3
+ import { fileMode, readJsonObject } from './fsutil.js';
4
+ import { inspectSettings } from './settings.js';
5
+ import { readConfig, readState } from './state.js';
6
+ import { HOOK_EVENTS } from './constants.js';
7
+ import { consoleLogger } from './log.js';
8
+ export function collectStatus() {
9
+ const p = paths();
10
+ let config;
11
+ try {
12
+ config = readConfig();
13
+ }
14
+ catch {
15
+ config = undefined;
16
+ }
17
+ const hookMode = fileMode(p.hook);
18
+ const report = {
19
+ installed: false,
20
+ config,
21
+ configMode: fileMode(p.config),
22
+ hookInstalled: hookMode !== undefined,
23
+ hookExecutable: hookMode !== undefined && (hookMode & 0o100) !== 0,
24
+ };
25
+ let settings;
26
+ try {
27
+ settings = readJsonObject(p.settings) ?? {};
28
+ }
29
+ catch (err) {
30
+ report.settingsError = err.message;
31
+ }
32
+ if (settings) {
33
+ // Prefer what init actually applied (includes team id); fall back to config.
34
+ const state = readState();
35
+ let expected = state?.applied_env;
36
+ if (!expected && config) {
37
+ try {
38
+ expected = buildEnv({ token: config.token, endpoint: config.endpoint });
39
+ }
40
+ catch {
41
+ expected = undefined;
42
+ }
43
+ }
44
+ report.inspection = inspectSettings(settings, expected);
45
+ }
46
+ report.installed = Boolean(config && report.hookInstalled && report.inspection?.envMatches && HOOK_EVENTS.every((e) => report.inspection?.hookEvents[e]));
47
+ return report;
48
+ }
49
+ export function status(opts = {}) {
50
+ const log = opts.logger ?? consoleLogger;
51
+ const p = paths();
52
+ const r = collectStatus();
53
+ if (!r.config && !r.hookInstalled && !r.inspection?.hookEvents.SessionStart) {
54
+ log.info('SpendByTeam is not installed. Run: npx spendbyteam init --token=sbt_ing_...');
55
+ return r;
56
+ }
57
+ if (r.config)
58
+ log.ok(`Config ${p.config}: endpoint ${r.config.endpoint}, token ${maskToken(r.config.token)}`);
59
+ else
60
+ log.error(`Config ${p.config} missing or invalid`);
61
+ if (r.configMode !== undefined && r.configMode !== 0o600)
62
+ log.warn(`Config mode is ${r.configMode.toString(8)}, expected 600`);
63
+ if (r.settingsError)
64
+ log.error(r.settingsError);
65
+ if (r.inspection) {
66
+ if (r.inspection.envMatches)
67
+ log.ok('OTel env in ~/.claude/settings.json');
68
+ else
69
+ log.error(`OTel env in ~/.claude/settings.json missing or changed: ${r.inspection.mismatchedKeys.join(', ') || 'unknown'}`);
70
+ for (const e of HOOK_EVENTS) {
71
+ if (r.inspection.hookEvents[e])
72
+ log.ok(`${e} hook registered`);
73
+ else
74
+ log.error(`${e} hook not registered`);
75
+ }
76
+ }
77
+ if (r.hookExecutable)
78
+ log.ok(`Hook script ${p.hook}`);
79
+ else
80
+ log.error(`Hook script ${p.hook} ${r.hookInstalled ? 'is not executable' : 'missing'}`);
81
+ log.info(r.installed ? 'Status: installed' : 'Status: incomplete — run "npx spendbyteam init" again or "npx spendbyteam doctor"');
82
+ return r;
83
+ }
@@ -0,0 +1,34 @@
1
+ import fs from 'node:fs';
2
+ import { paths } from './paths.js';
3
+ import { fileMode, readJsonObject, toJson, writeFileAtomic } from './fsutil.js';
4
+ import { removeSettings } from './settings.js';
5
+ import { readState } from './state.js';
6
+ import { consoleLogger } from './log.js';
7
+ export function uninstall(opts = {}) {
8
+ const log = opts.logger ?? consoleLogger;
9
+ const p = paths();
10
+ const state = readState();
11
+ let settingsChanged = false;
12
+ let backupPath;
13
+ const existing = readJsonObject(p.settings);
14
+ if (existing !== undefined) {
15
+ const next = removeSettings(existing, state ? { previousEnv: state.previous_env, appliedEnv: state.applied_env } : {});
16
+ const after = toJson(next);
17
+ if (after !== toJson(existing)) {
18
+ fs.copyFileSync(p.settings, p.settingsBackup);
19
+ backupPath = p.settingsBackup;
20
+ writeFileAtomic(p.settings, after, fileMode(p.settings) ?? 0o600);
21
+ settingsChanged = true;
22
+ log.ok(`Removed SpendByTeam settings from ${p.settings} (backup: ${backupPath})`);
23
+ }
24
+ else {
25
+ log.ok(`${p.settings} has no SpendByTeam settings`);
26
+ }
27
+ }
28
+ const removedDir = fs.existsSync(p.sbtDir);
29
+ fs.rmSync(p.sbtDir, { recursive: true, force: true });
30
+ if (removedDir)
31
+ log.ok(`Removed ${p.sbtDir}`);
32
+ log.info('SpendByTeam is uninstalled. Restart Claude Code sessions to stop sending metrics.');
33
+ return { settingsChanged, backupPath, removedDir };
34
+ }
package/hook/hook.sh ADDED
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env bash
2
+ # SpendByTeam context hook — açık kaynak, sadece aşağıdaki alanları gönderir.
3
+ set -u
4
+ CFG="$HOME/.spendbyteam/config.json"
5
+ [ -r "$CFG" ] || exit 0
6
+
7
+ INPUT=$(cat)
8
+ SESSION_ID=$(printf '%s' "$INPUT" | jq -r '.session_id // empty')
9
+ CWD=$(printf '%s' "$INPUT" | jq -r '.cwd // empty')
10
+ EVENT=$(printf '%s' "$INPUT" | jq -r '.hook_event_name // empty')
11
+ [ -n "$SESSION_ID" ] && [ -n "$CWD" ] || exit 0
12
+
13
+ TOKEN=$(jq -r '.token // empty' "$CFG"); ENDPOINT=$(jq -r '.endpoint // empty' "$CFG")
14
+ # Token yalnızca güvenli karakterler (header enjeksiyonu yok); endpoint https (http sadece localhost).
15
+ printf '%s' "$TOKEN" | grep -qE '^sbt_ing_[A-Za-z0-9_-]{1,120}$' || exit 0
16
+ printf '%s' "$ENDPOINT" | grep -qE '^(https://[^[:space:]]+|http://(localhost|127\.0\.0\.1|\[::1\])(:[0-9]+)?(/[^[:space:]]*)?)$' || exit 0
17
+
18
+ REMOTE=$(git -C "$CWD" config --get remote.origin.url 2>/dev/null || true)
19
+ # Commit'siz repo ve detached HEAD'de rev-parse "HEAD" döner: branch yok say.
20
+ BRANCH=$(git -C "$CWD" rev-parse --abbrev-ref HEAD 2>/dev/null) || BRANCH=""
21
+ [ "$BRANCH" = "HEAD" ] && BRANCH=""
22
+ TICKET=$(printf '%s' "$BRANCH" | grep -oE '[A-Z][A-Z0-9]+-[0-9]+' | head -1 || true)
23
+
24
+ # Remote URL'den kimlik bilgisini (scheme://user:token@host/...), query ve fragment'ı temizle.
25
+ REMOTE=$(printf '%s' "$REMOTE" | sed -E 's#^([A-Za-z][A-Za-z0-9+.-]*://)[^/]*@#\1#; s#[?\#].*$##')
26
+ # Yerel yol / file:// remote'u gönderme: kullanıcı adı ve klasör yapısı sızar (cwd kuralı).
27
+ printf '%s' "$REMOTE" | grep -qE '^(([A-Za-z][A-Za-z0-9+.-]*://[^/]+)|([^/:@[:space:]]+@[^/:[:space:]]+:)|([A-Za-z0-9-]+\.[A-Za-z0-9.-]+:))' \
28
+ && ! printf '%s' "$REMOTE" | grep -qiE '^file://' || REMOTE=""
29
+
30
+ # Token argv'de değil (ps ile diğer kullanıcılar göremesin): header bir fd'den okunur.
31
+ jq -n --arg s "$SESSION_ID" --arg e "$EVENT" --arg r "$REMOTE" \
32
+ --arg b "$BRANCH" --arg t "$TICKET" --arg ts "$(date -u +%FT%TZ)" \
33
+ '{session_id:$s, event:$e, repo_url:$r, branch:$b, ticket:$t, at:$ts}' |
34
+ curl -sS -m 5 -X POST "$ENDPOINT/v1/context" \
35
+ -H @<(printf 'Authorization: Bearer %s\n' "$TOKEN") -H "Content-Type: application/json" \
36
+ --data-binary @- >/dev/null 2>&1 || true
37
+ exit 0
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "spendbyteam",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "See what Claude Code costs per project, model, branch or day (offline), and connect it to SpendByTeam for your team.",
5
+ "license": "MIT",
6
+ "homepage": "https://spendbyteam.com/docs/install",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/spendbyteam/cli.git"
10
+ },
11
+ "bugs": {
12
+ "email": "support@spendbyteam.com"
13
+ },
14
+ "type": "module",
15
+ "bin": {
16
+ "spendbyteam": "dist/cli.js"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "hook/hook.sh",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "engines": {
25
+ "node": ">=18.17"
26
+ },
27
+ "scripts": {
28
+ "build": "tsc -p tsconfig.json && chmod +x dist/cli.js",
29
+ "typecheck": "tsc -p tsconfig.json --noEmit",
30
+ "test": "npm run test:unit && npm run test:hook",
31
+ "test:unit": "vitest run",
32
+ "test:hook": "bash test/hook.test.sh",
33
+ "prepublishOnly": "npm run build && npm test"
34
+ },
35
+ "keywords": [
36
+ "claude-code",
37
+ "opentelemetry",
38
+ "cost",
39
+ "usage",
40
+ "tokens",
41
+ "spendbyteam"
42
+ ],
43
+ "devDependencies": {
44
+ "@types/node": "^22.10.0",
45
+ "typescript": "^5.7.0",
46
+ "vitest": "^5.1.0"
47
+ }
48
+ }