|
| 1 | +import { execSync } from "node:child_process"; |
| 2 | +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; |
| 3 | +import { homedir } from "node:os"; |
| 4 | +import { join } from "node:path"; |
| 5 | +import { PostHog } from "posthog-node"; |
| 6 | +import packageJson from "../package.json"; |
| 7 | + |
| 8 | +const POSTHOG_API_KEY = "phc_uKMUhqYc5TLZ7NPNPnY3Bdnd29HKZ9du7BQepwsm8Wn"; |
| 9 | +const GIT_EXEC_OPTIONS = { encoding: "utf-8" as const, stdio: "pipe" as const }; |
| 10 | +const ANON_ID_PATH = join(homedir(), ".config", "verno", "anonymous-id"); |
| 11 | + |
| 12 | +export const isTelemetryEnabled = (): boolean => |
| 13 | + process.env["DO_NOT_TRACK"] !== "1" && process.env["VERNO_TELEMETRY_DISABLED"] !== "1"; |
| 14 | + |
| 15 | +interface GitIdentity { |
| 16 | + distinctId: string; |
| 17 | + email?: string; |
| 18 | + name?: string; |
| 19 | +} |
| 20 | + |
| 21 | +const getAnonymousId = (): string => { |
| 22 | + try { |
| 23 | + return readFileSync(ANON_ID_PATH, "utf-8").trim(); |
| 24 | + } catch { |
| 25 | + const id = crypto.randomUUID(); |
| 26 | + try { |
| 27 | + mkdirSync(join(homedir(), ".config", "verno"), { recursive: true }); |
| 28 | + writeFileSync(ANON_ID_PATH, id, "utf-8"); |
| 29 | + } catch { |
| 30 | + // read-only fs — use the id for this run only |
| 31 | + } |
| 32 | + return id; |
| 33 | + } |
| 34 | +}; |
| 35 | + |
| 36 | +const getGitIdentity = (): GitIdentity => { |
| 37 | + try { |
| 38 | + const email = execSync("git config user.email", GIT_EXEC_OPTIONS).trim(); |
| 39 | + if (email) { |
| 40 | + const name = execSync("git config user.name", GIT_EXEC_OPTIONS).trim(); |
| 41 | + return { distinctId: email, email, name: name || undefined }; |
| 42 | + } |
| 43 | + } catch { |
| 44 | + // git not available or not configured |
| 45 | + } |
| 46 | + return { distinctId: getAnonymousId() }; |
| 47 | +}; |
| 48 | + |
| 49 | +export const trackEvent = async ( |
| 50 | + event: string, |
| 51 | + properties: Record<string, unknown> = {}, |
| 52 | +): Promise<void> => { |
| 53 | + if (!isTelemetryEnabled()) { |
| 54 | + return; |
| 55 | + } |
| 56 | + try { |
| 57 | + const { distinctId, name, email } = getGitIdentity(); |
| 58 | + const client = new PostHog(POSTHOG_API_KEY, { |
| 59 | + flushAt: 1, |
| 60 | + flushInterval: 0, |
| 61 | + host: "https://us.i.posthog.com", |
| 62 | + }); |
| 63 | + if (email) { |
| 64 | + client.identify({ |
| 65 | + distinctId, |
| 66 | + properties: { email, name }, |
| 67 | + }); |
| 68 | + } |
| 69 | + client.capture({ |
| 70 | + distinctId, |
| 71 | + event, |
| 72 | + properties: { |
| 73 | + ...properties, |
| 74 | + cli_version: packageJson.version, |
| 75 | + node_version: process.version, |
| 76 | + platform: process.platform, |
| 77 | + }, |
| 78 | + }); |
| 79 | + await client.shutdown(); |
| 80 | + } catch { |
| 81 | + // silent — analytics must never break the CLI |
| 82 | + } |
| 83 | +}; |
0 commit comments