|
| 1 | +import { getVersion } from '../../utils/get-version.js'; |
| 2 | +import type { MigrationInstallResult } from './copy-migrations.js'; |
| 3 | + |
| 4 | +const ENDPOINT = 'https://pgflow-telemetry.workers.dev/'; |
| 5 | +const SEMVER_RE = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/; |
| 6 | + |
| 7 | +type Environment = Record<string, string | undefined>; |
| 8 | +type Send = typeof globalThis.fetch; |
| 9 | + |
| 10 | +const isSet = (value: string | undefined) => { |
| 11 | + const normalized = value?.toLowerCase(); |
| 12 | + return normalized !== undefined |
| 13 | + && normalized !== '' |
| 14 | + && normalized !== '0' |
| 15 | + && normalized !== 'false'; |
| 16 | +}; |
| 17 | + |
| 18 | +function telemetryDisabled(env: Environment): boolean { |
| 19 | + return env.NODE_ENV === 'test' |
| 20 | + || isSet(env.CI) |
| 21 | + || isSet(env.DO_NOT_TRACK) |
| 22 | + || isSet(env.PGFLOW_TELEMETRY_DISABLED); |
| 23 | +} |
| 24 | + |
| 25 | +function bucketCount(value: number): string { |
| 26 | + if (value === 0) return '0'; |
| 27 | + if (value === 1) return '1'; |
| 28 | + if (value <= 3) return '2-3'; |
| 29 | + if (value <= 7) return '4-7'; |
| 30 | + if (value <= 15) return '8-15'; |
| 31 | + if (value <= 31) return '16-31'; |
| 32 | + if (value <= 63) return '32-63'; |
| 33 | + if (value <= 127) return '64-127'; |
| 34 | + if (value <= 255) return '128-255'; |
| 35 | + return '256+'; |
| 36 | +} |
| 37 | + |
| 38 | +export async function reportInstallTelemetry( |
| 39 | + result: MigrationInstallResult, |
| 40 | + { |
| 41 | + env = process.env, |
| 42 | + version = getVersion(), |
| 43 | + send = globalThis.fetch, |
| 44 | + }: { env?: Environment; version?: string; send?: Send } = {}, |
| 45 | +): Promise<void> { |
| 46 | + if (telemetryDisabled(env) || version.length > 32 || !SEMVER_RE.test(version)) { |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + try { |
| 51 | + await send(ENDPOINT, { |
| 52 | + method: 'POST', |
| 53 | + headers: { 'content-type': 'application/json' }, |
| 54 | + body: JSON.stringify({ |
| 55 | + schema: 1, |
| 56 | + contributions: [{ |
| 57 | + metric: `cli_install_${result.kind}`, |
| 58 | + bucket: version, |
| 59 | + count: bucketCount(result.copied), |
| 60 | + }], |
| 61 | + }), |
| 62 | + signal: AbortSignal.timeout(500), |
| 63 | + }); |
| 64 | + } catch { |
| 65 | + // Telemetry must never delay or fail installation. |
| 66 | + } |
| 67 | +} |
0 commit comments