@prisma-next/cli-telemetry 0.10.0 → 0.11.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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/endpoint.ts","../../src/user-config.ts","../../src/gating.ts","../../src/payload.ts","../../src/sanitize.ts","../../src/spawn.ts"],"mappings":";;;;AAIA;cAAa,qBAAA;;;;cAKA,uBAAA;;;;;AAab;;;;;;;iBAAgB,wBAAA,CACd,GAAA,GAAK,QAAA,CAAS,MAAA;;;;;;AAnBhB;;;;;AAKA;UCKiB,UAAA;EAAA,SACN,eAAA;EAAA,SACA,cAAA;EAAA,UACC,GAAA;AAAA;;;;;iBA0CI,cAAA,CAAA;;;;;;iBASA,cAAA,CAAA,GAAkB,UAAA;AAtDlC;;;;;;;;;AA6CA;;;;AA7CA,iBAkFgB,eAAA,CAAgB,OAAA,EAAS,OAAA,CAAQ,UAAA;;;;;AD5FjD;;KEEY,oBAAA;AAAA,KAEA,gBAAA;EAAA,SACG,OAAA;AAAA;EAAA,SACA,OAAA;EAAA,SAAyB,MAAA,EAAQ,oBAAA;AAAA;AAAA,UAE/B,YAAA;EFUD;;;;;;EAAA,SEHL,GAAA,EAAK,QAAA,CAAS,MAAA;EFIwC;EAAA,SEFtD,MAAA,EAAQ,UAAA;AAAA;;;ADPnB;;;;;;;;;AA6CA;;;;;iBCHgB,aAAA,CAAc,MAAA,EAAQ,YAAA,GAAe,gBAAA;;;;;;AFpDrD;;;;;AAKA;;;UGIiB,qBAAA;EAAA,SACN,cAAA;EAAA,SACA,OAAA;EAAA,SACA,OAAA;EAAA,SACA,KAAA;EAAA,SACA,cAAA;EAAA,SACA,UAAA;EHIK;EAAA,SGFL,WAAA;EHEsD;EAAA,SGAtD,QAAA;AAAA;AFTX;;;;AAAA,UE6CiB,cAAA;EAAA,SACN,cAAA;EAAA,SACA,OAAA;EAAA,SACA,OAAA;EAAA,SACA,KAAA;EAAA,SACA,WAAA;EAAA,SACA,cAAA;EAAA,SACA,EAAA;EAAA,SACA,IAAA;EAAA,SACA,cAAA;EAAA,SACA,cAAA;EAAA,SACA,SAAA;EAAA,SACA,KAAA;EAAA,SACA,UAAA;AAAA;;;UCxEM,oBAAA;;WAEN,aAAA;EJEE;EAAA,SIAF,QAAA;;WAEA,MAAA;AAAA;AJGX;;;;;AAaA;AAbA,UIMiB,oBAAA;;;;;;WAMN,WAAA;EJEsD;;;;ACTjE;;EDSiE,SIKtD,cAAA;EHdgB;;;;;;EAAA,SGqBhB,OAAA,WAAkB,oBAAA;AAAA;;;;AHiC7B;;UGzBiB,gBAAA;EAAA,SACN,OAAA;EAAA,SACA,KAAA;AAAA;;;;;;;;;;;;AFvCX;;;;iBE+DgB,uBAAA,CAAwB,KAAA,EAAO,oBAAA,GAAuB,gBAAA;;;;AJjEtE;;;;;AAKA;UKMiB,kBAAA;;WAEN,OAAA,EAAS,oBAAA;ELRgB;EAAA,SKUzB,OAAA;ELG6B;EAAA,SKD7B,cAAA;ELEI;EAAA,SKAJ,UAAA;ELAK;EAAA,SKEL,WAAA;ELFsD;;;;;ACTjE;EDSiE,SKStD,UAAA;;;;;;WAMA,IAAA;EJrBY;EAAA,SIuBZ,GAAA,GAAM,QAAA,CAAS,MAAA;EJmBI;EAAA,SIjBnB,UAAA,GAAa,UAAA;AAAA;;AJ0BxB;;;;;AA4BA;;;;;KIxCY,mBAAA;EAAA,SACG,OAAA;AAAA;EAAA,SACA,OAAA;EAAA,SAAyB,MAAA;AAAA;AAAA,iBAExB,YAAA,CAAa,MAAA,EAAQ,kBAAA,GAAqB,mBAAA;AHtD1D;;;;;AAEA;;AAFA,iBGmHgB,eAAA,CAAgB,aAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/endpoint.ts","../../src/payload.ts","../../src/enrich.ts","../../src/user-config.ts","../../src/gating.ts","../../src/sanitize.ts","../../src/spawn.ts"],"mappings":";;;;AAIA;cAAa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B;;;;;;;;;;;;;AA4DA;iBGnCgB,aAAA,CAAc,MAAA,EAAQ,YAAA,GAAe,gBAAA;;;UCxDpC,oBAAA;;WAEN,aAAA;ELEE;EAAA,SKAF,QAAA;;WAEA,MAAA;AAAA;ALGX;;;;;AAaA;AAbA,UKMiB,oBAAA;;;;;;WAMN,WAAA;ELEsD;;;;ACQjE;;EDRiE,SKKtD,cAAA;EJG2B;;;;;;EAAA,SII3B,OAAA,WAAkB,oBAAA;AAAA;;;AJwD7B;;;UIhDiB,gBAAA;EAAA,SACN,OAAA;EAAA,SACA,KAAA;AAAA;;;;;;;;;;;;;;;;iBAwBK,uBAAA,CAAwB,KAAA,EAAO,oBAAA,GAAuB,gBAAA;;;;ALjEtE;;;;;AAKA;;;;;AAaA;;;;;UMGiB,kBAAA;ENFf;EAAA,SMIS,OAAA,EAAS,oBAAA;ENJ6C;EAAA,SMMtD,OAAA;;WAEA,WAAA;ELAM;;;;;EAAA,SKMN,cAAA;ELHA;;;;;;EAAA,SKUA,UAAA;EL+CM;;;;;EAAA,SKzCN,IAAA;EL4CA;EAAA,SK1CA,GAAA,GAAM,QAAA,CAAS,MAAA;EL4Cf;EAAA,SK1CA,UAAA,GAAa,UAAA;AAAA;;;;;;;;;;;;KAcZ,mBAAA;EAAA,SACG,OAAA;AAAA;EAAA,SACA,OAAA;EAAA,SAAyB,MAAA;AAAA;AAAA,iBAExB,YAAA,CAAa,MAAA,EAAQ,kBAAA,GAAqB,mBAAA;;;;;;;;iBA4D1C,eAAA,CAAgB,aAAA"}
@@ -1,9 +1,11 @@
1
+ import { n as loadProjectConfig } from "../enrich-CGZ8Za8Y.mjs";
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "pathe";
1
4
  import { fork } from "node:child_process";
2
5
  import { fileURLToPath } from "node:url";
6
+ import { ifDefined } from "@prisma-next/utils/defined";
3
7
  import { randomUUID } from "node:crypto";
4
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
5
8
  import { homedir } from "node:os";
6
- import { dirname, join } from "pathe";
7
9
  //#region src/endpoint.ts
8
10
  /**
9
11
  * Production endpoint pinned to the deployed Prisma Compute backend.
@@ -221,10 +223,9 @@ function runTelemetry(inputs) {
221
223
  version: inputs.version,
222
224
  command: sanitised.command,
223
225
  flags: sanitised.flags,
224
- databaseTarget: inputs.databaseTarget,
225
- extensions: inputs.extensions,
226
226
  projectRoot: inputs.projectRoot,
227
- endpoint: resolveTelemetryEndpoint(env)
227
+ endpoint: resolveTelemetryEndpoint(env),
228
+ ...ifDefined("databaseTarget", inputs.databaseTarget)
228
229
  };
229
230
  try {
230
231
  const child = fork(inputs.senderPath, [], {
@@ -261,6 +262,6 @@ function senderModuleUrl(importMetaUrl) {
261
262
  return fileURLToPath(new URL("./sender.mjs", importMetaUrl));
262
263
  }
263
264
  //#endregion
264
- export { TELEMETRY_BACKEND_URL, TELEMETRY_ENDPOINT_PATH, readUserConfig, resolveGating, resolveTelemetryEndpoint, runTelemetry, sanitizeCommanderResult, senderModuleUrl, userConfigPath, writeUserConfig };
265
+ export { TELEMETRY_BACKEND_URL, TELEMETRY_ENDPOINT_PATH, loadProjectConfig, readUserConfig, resolveGating, resolveTelemetryEndpoint, runTelemetry, sanitizeCommanderResult, senderModuleUrl, userConfigPath, writeUserConfig };
265
266
 
266
267
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/endpoint.ts","../../src/gating.ts","../../src/sanitize.ts","../../src/user-config.ts","../../src/spawn.ts"],"sourcesContent":["/**\n * Production endpoint pinned to the deployed Prisma Compute backend.\n * Compiled as a build-time constant; not user-configurable.\n */\nexport const TELEMETRY_BACKEND_URL = 'https://cmpbfbsdp09hr3jf7pojjs5qs.ewr.prisma.build';\n\n/**\n * Path within the backend that accepts telemetry POSTs.\n */\nexport const TELEMETRY_ENDPOINT_PATH = '/events';\n\n/**\n * Resolve the full POST URL the sender targets. The\n * `PRISMA_NEXT_TELEMETRY_ENDPOINT` env var is an integration-testing\n * affordance only — it lets the test suite spin up a mock HTTP server\n * on an ephemeral port and point the spawned sender at it. The override\n * is intentionally undocumented in user-facing material.\n *\n * Fail-open: a malformed override (typo in a dev shell, bad CI config)\n * silently falls back to the production backend rather than throwing,\n * matching the telemetry layer's broader silent-on-failure contract.\n */\nexport function resolveTelemetryEndpoint(\n env: Readonly<Record<string, string | undefined>> = process.env,\n): string {\n const override = env['PRISMA_NEXT_TELEMETRY_ENDPOINT'];\n const base = override !== undefined && override.length > 0 ? override : TELEMETRY_BACKEND_URL;\n try {\n return new URL(TELEMETRY_ENDPOINT_PATH, base).toString();\n } catch {\n return new URL(TELEMETRY_ENDPOINT_PATH, TELEMETRY_BACKEND_URL).toString();\n }\n}\n","import type { UserConfig } from './user-config';\n\n/**\n * Why telemetry was disabled. Useful for debug-mode logging in the\n * parent; never surfaces to users.\n */\nexport type GatingDisabledReason = 'env-override' | 'stored-opt-out' | 'default-off';\n\nexport type GatingResolution =\n | { readonly enabled: true }\n | { readonly enabled: false; readonly reason: GatingDisabledReason };\n\nexport interface GatingInputs {\n /**\n * Environment-variable lookups the resolver consults. Tests pass a\n * literal record; production passes `process.env`. The two opt-out\n * signals are `PRISMA_NEXT_DISABLE_TELEMETRY` (Prisma-specific) and\n * `DO_NOT_TRACK` (community convention).\n */\n readonly env: Readonly<Record<string, string | undefined>>;\n /** Result of `readUserConfig()` — file-missing tolerated as `{}`. */\n readonly config: UserConfig;\n}\n\n/**\n * A `PRISMA_NEXT_DISABLE_TELEMETRY` value counts as an opt-out only if\n * it parses as a truthy string. The set-but-falsy spellings (`''`,\n * `'0'`, `'false'`) are intentionally treated as not-set so a parent\n * shell that exports the variable to a benign value doesn't accidentally\n * disable telemetry for child processes.\n */\nfunction isTruthyOptOut(raw: string | undefined): boolean {\n if (raw === undefined) return false;\n const normalised = raw.trim().toLowerCase();\n if (normalised === '') return false;\n if (normalised === '0') return false;\n if (normalised === 'false') return false;\n return true;\n}\n\n/**\n * Pure-function resolution of the gating decision. Same input → same\n * output; no I/O. The caller is responsible for reading the env and the\n * user config.\n *\n * Decision order:\n * 1. Env-var override (`PRISMA_NEXT_DISABLE_TELEMETRY` truthy, or\n * `DO_NOT_TRACK=1`) → disabled.\n * 2. Stored `enableTelemetry === true` → enabled.\n * 3. Stored `enableTelemetry === false` → disabled (`stored-opt-out`).\n * 4. Stored `enableTelemetry === undefined` (file missing, or field\n * not set) → disabled (`default-off`).\n *\n * Telemetry is enabled only when no env override is active **and**\n * `enableTelemetry` is explicitly `true`.\n */\nexport function resolveGating(inputs: GatingInputs): GatingResolution {\n if (\n isTruthyOptOut(inputs.env['PRISMA_NEXT_DISABLE_TELEMETRY']) ||\n inputs.env['DO_NOT_TRACK'] === '1'\n ) {\n return { enabled: false, reason: 'env-override' };\n }\n if (inputs.config.enableTelemetry === true) {\n return { enabled: true };\n }\n if (inputs.config.enableTelemetry === false) {\n return { enabled: false, reason: 'stored-opt-out' };\n }\n return { enabled: false, reason: 'default-off' };\n}\n","export interface CommanderOptionShape {\n /** Commander's option attribute name, e.g. `dryRun` for `--dry-run`. */\n readonly attributeName: string;\n /** Commander's long, user-facing flag spelling, e.g. `--dry-run` or `--no-install`. */\n readonly longName: string | null;\n /** Commander's value source for this option. Only `cli` is user-supplied. */\n readonly source: string | null;\n}\n\n/**\n * Input shape: a thin projection of commander's parsed-result surface.\n * The parent extracts the command path, positional args, and per-option\n * metadata from the leaf command. The sanitiser never consumes raw\n * argv, never reads `process.argv`, and never sees flag values.\n */\nexport interface CommanderResultShape {\n /**\n * The full command path from the root program to the leaf, including\n * the root program name as the first element (the sanitiser drops it).\n * Example: `['prisma-next', 'migration', 'new']`.\n */\n readonly commandPath: readonly string[];\n /**\n * Positional arguments commander parsed for the leaf command.\n * **Intentionally never read.** Accepted so the call site doesn't have\n * to think about whether to pass it; the sanitiser's contract is that\n * positionals never leave the parent process.\n */\n readonly positionalArgs: readonly string[];\n /**\n * Per-option Commander metadata. The sanitiser emits only options whose\n * source is `cli`, and uses `longName` so telemetry sees user-facing\n * names (`dry-run`, `connection-string`, `no-install`) rather than\n * Commander's internal camelCase attribute names or defaulted options.\n */\n readonly options: readonly CommanderOptionShape[];\n}\n\n/**\n * Output shape: the sanitised projection that flows into the telemetry\n * payload. Two fields only — command name (space-delimited subcommand\n * path) and flag names (in commander's option declaration order).\n */\nexport interface SanitisedCommand {\n readonly command: string;\n readonly flags: readonly string[];\n}\n\nfunction flagNameFromLongName(longName: string | null): string | null {\n if (longName === null || !longName.startsWith('--')) return null;\n const withoutPrefix = longName.slice(2);\n return withoutPrefix.length > 0 ? withoutPrefix : null;\n}\n\n/**\n * Project commander's parsed result into the wire-shape command and\n * flag-name list. Pure; the only allowed inputs are the fields of\n * `CommanderResultShape`.\n *\n * Sanitiser contract — no flag values, no positionals, no raw argv:\n * - Drop the root program name (`commandPath[0]`); the wire ships\n * `migration new`, not `prisma-next migration new`.\n * - Emit only options whose Commander source is `cli`.\n * - Emit the long user-facing flag spelling without the `--` prefix;\n * never emit Commander's camelCase attribute names.\n * - `positionalArgs` is accepted but never consumed; the field exists\n * in the input type to make it obvious at the call site that\n * positionals were deliberately excluded.\n */\nexport function sanitizeCommanderResult(input: CommanderResultShape): SanitisedCommand {\n const command = input.commandPath.slice(1).join(' ');\n const flags = input.options.flatMap((option) => {\n if (option.source !== 'cli') return [];\n const flagName = flagNameFromLongName(option.longName);\n return flagName === null ? [] : [flagName];\n });\n return { command, flags };\n}\n","import { randomUUID } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'pathe';\n\n/**\n * The user-level config file. Persists the consent flag and the\n * installation UUID together so an env-var opt-out never mutates disk,\n * and so an opt-in → opt-out → opt-in cycle keeps the same UUID (correct\n * for MAU continuity).\n *\n * Readers tolerate unknown fields for forward compat; writers merge\n * partials into the existing object so unknown fields are preserved.\n */\nexport interface UserConfig {\n readonly enableTelemetry?: boolean;\n readonly installationId?: string;\n readonly [key: string]: unknown;\n}\n\nconst APP_DIR = 'prisma-next';\nconst FILE_NAME = 'config.json';\n\n/**\n * Resolves the user-level config directory:\n * - Windows: `%APPDATA%\\prisma-next\\` (fallback: `%USERPROFILE%\\AppData\\Roaming\\prisma-next\\`).\n * - Unix (incl. macOS): `$XDG_CONFIG_HOME/prisma-next/` if set, else\n * `$HOME/.config/prisma-next/` per the XDG Base Directory Specification.\n *\n * The spec deliberately picks XDG over the macOS-native\n * `~/Library/Preferences/` convention so the path resolution is\n * test-overridable via `XDG_CONFIG_HOME` and matches the documented\n * behaviour on all *nix platforms. We intentionally do not use\n * `env-paths`: its macOS choice of `~/Library/Preferences` is for\n * OS-managed plist preferences, not arbitrary JSON files. Apple documents\n * that apps access that directory through system APIs such as\n * `NSUserDefaults`, while cross-platform CLI and developer tools conventionally\n * use `~/.config` on macOS too:\n * https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/MacOSXDirectories/MacOSXDirectories.html\n */\nfunction configDir(): string {\n if (process.platform === 'win32') {\n const appData = process.env['APPDATA'];\n if (appData !== undefined && appData.length > 0) {\n return join(appData, APP_DIR);\n }\n return join(homedir(), 'AppData', 'Roaming', APP_DIR);\n }\n const xdg = process.env['XDG_CONFIG_HOME'];\n if (xdg !== undefined && xdg.length > 0) {\n return join(xdg, APP_DIR);\n }\n return join(homedir(), '.config', APP_DIR);\n}\n\n/**\n * Path to the user-level config file. Resolved per call so test\n * harnesses can mutate `$XDG_CONFIG_HOME` between cases.\n */\nexport function userConfigPath(): string {\n return join(configDir(), FILE_NAME);\n}\n\n/**\n * Reads the user-level config. File-missing, unreadable, or malformed →\n * `{}` (the absence of consent is the same answer in every error mode).\n * Unknown fields from a future client are passed through verbatim.\n */\nexport function readUserConfig(): UserConfig {\n const path = userConfigPath();\n if (!existsSync(path)) return {};\n try {\n const raw = readFileSync(path, 'utf-8');\n const parsed: unknown = JSON.parse(raw);\n if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return parsed as UserConfig;\n }\n return {};\n } catch {\n return {};\n }\n}\n\n/**\n * Merges `partial` into the current config and writes the result\n * atomically (temp file + rename) so a crash mid-write never leaves a\n * half-baked file readable on disk. Unknown fields already on disk are\n * preserved.\n *\n * When `partial.enableTelemetry === true` and no `installationId` is\n * stored yet, generates a v4 random UUID and persists both fields in\n * the same write. An existing `installationId` is never rotated.\n *\n * `writeUserConfig({ enableTelemetry: false })` does *not* generate an\n * installation id — only an affirmative consent answer produces one.\n */\nexport function writeUserConfig(partial: Partial<UserConfig>): void {\n const current = readUserConfig();\n const merged: Record<string, unknown> = { ...current, ...partial };\n if (partial.enableTelemetry === true && merged['installationId'] === undefined) {\n merged['installationId'] = randomUUID();\n }\n const path = userConfigPath();\n const dir = dirname(path);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n const tmpPath = `${path}.${process.pid}.tmp`;\n writeFileSync(tmpPath, `${JSON.stringify(merged, null, 2)}\\n`, 'utf-8');\n renameSync(tmpPath, path);\n}\n","import { fork } from 'node:child_process';\nimport { fileURLToPath } from 'node:url';\nimport { resolveTelemetryEndpoint } from './endpoint';\nimport { resolveGating } from './gating';\nimport type { ParentToSenderPayload } from './payload';\nimport { type CommanderResultShape, sanitizeCommanderResult } from './sanitize';\nimport { readUserConfig, type UserConfig } from './user-config';\n\n/**\n * Inputs the CLI entry point hands the telemetry layer at command\n * start. The CLI is responsible for stitching commander's result, the\n * loaded config, and the project root together; the telemetry module\n * does no I/O of its own except for the user-config read (skipped when\n * `userConfig` is provided).\n */\nexport interface RunTelemetryInputs {\n /** Sanitised commander snapshot — see `CommanderResultShape`. */\n readonly command: CommanderResultShape;\n /** This CLI's own version (from its `package.json`). */\n readonly version: string;\n /** Resolved `config.target.targetId`, or `null` when the config could not be loaded. */\n readonly databaseTarget: string | null;\n /** Declared extension-pack IDs, in any deterministic order. */\n readonly extensions: readonly string[];\n /** Absolute path of the project root (typically `process.cwd()`). */\n readonly projectRoot: string;\n /**\n * Path to the sender entry compiled into this package's `dist/`.\n * Resolved by the caller because the compiled sender lives at\n * `<package>/dist/sender.mjs` and only the consumer knows its own\n * `import.meta.url`.\n */\n readonly senderPath: string;\n /**\n * `isCI()` result from the consumer. Telemetry is suppressed when\n * `true` regardless of the stored consent answer — CI environments\n * never emit (matches the colour-output convention's CI suppression).\n */\n readonly isCI: boolean;\n /** Process env to read for opt-out signals. Defaults to `process.env`. */\n readonly env?: Readonly<Record<string, string | undefined>>;\n /** Cached user config when the caller already read it to resolve gates before other work. */\n readonly userConfig?: UserConfig;\n}\n\n/**\n * Best-effort telemetry spawn at command start. Returns synchronously —\n * the fork runs in the background and never blocks the parent. Every\n * failure mode is swallowed; the parent's stdout/stderr is untouched in\n * normal operation, the only escape valve being\n * `PRISMA_NEXT_DEBUG=1` which routes diagnostics to stderr.\n *\n * Returns the spawn outcome so debug-mode logging and the test-harness\n * probe (which verifies test runs short-circuit the fork) can inspect\n * the decision without scraping stderr.\n */\nexport type TelemetryRunOutcome =\n | { readonly spawned: true }\n | { readonly spawned: false; readonly reason: 'gated-off' | 'ci' | 'fork-failed' };\n\nexport function runTelemetry(inputs: RunTelemetryInputs): TelemetryRunOutcome {\n const env = inputs.env ?? process.env;\n\n if (inputs.isCI) {\n return { spawned: false, reason: 'ci' };\n }\n\n const config = inputs.userConfig ?? readUserConfig();\n const gating = resolveGating({ env, config });\n if (!gating.enabled) {\n return { spawned: false, reason: 'gated-off' };\n }\n\n const sanitised = sanitizeCommanderResult(inputs.command);\n // Gating already confirmed enableTelemetry === true, so installationId\n // must be set (writeUserConfig generates it alongside that field).\n // Defence-in-depth: if a stale config has the flag but no id, skip\n // rather than send a junk event.\n if (typeof config.installationId !== 'string' || config.installationId.length === 0) {\n return { spawned: false, reason: 'gated-off' };\n }\n\n const payload: ParentToSenderPayload = {\n installationId: config.installationId,\n version: inputs.version,\n command: sanitised.command,\n flags: sanitised.flags,\n databaseTarget: inputs.databaseTarget,\n extensions: inputs.extensions,\n projectRoot: inputs.projectRoot,\n endpoint: resolveTelemetryEndpoint(env),\n };\n\n try {\n const child = fork(inputs.senderPath, [], {\n detached: true,\n stdio: ['pipe', 'ignore', 'ignore', 'ipc'],\n });\n child.send(payload, (err) => {\n if (err !== null && process.env['PRISMA_NEXT_DEBUG'] === '1') {\n process.stderr.write(`[cli-telemetry] parent send error: ${String(err)}\\n`);\n }\n });\n child.disconnect();\n child.unref();\n return { spawned: true };\n } catch (err) {\n if (process.env['PRISMA_NEXT_DEBUG'] === '1') {\n process.stderr.write(`[cli-telemetry] parent fork failed: ${String(err)}\\n`);\n }\n return { spawned: false, reason: 'fork-failed' };\n }\n}\n\n/**\n * Resolve the path to the compiled sender entry relative to a consumer\n * that has captured its own `import.meta.url`. The CLI's\n * `tsdown`-emitted entry sits at `<package>/dist/sender.mjs`; the\n * consumer asks `senderModuleUrl()` and forwards the result to\n * `runTelemetry({ senderPath })`.\n */\nexport function senderModuleUrl(importMetaUrl: string): string {\n return fileURLToPath(new URL('./sender.mjs', importMetaUrl));\n}\n"],"mappings":";;;;;;;;;;;AAIA,MAAa,wBAAwB;;;;AAKrC,MAAa,0BAA0B;;;;;;;;;;;;AAavC,SAAgB,yBACd,MAAoD,QAAQ,KACpD;CACR,MAAM,WAAW,IAAI;CACrB,MAAM,OAAO,aAAa,KAAA,KAAa,SAAS,SAAS,IAAI,WAAW;CACxE,IAAI;EACF,OAAO,IAAI,IAAI,yBAAyB,KAAK,CAAC,UAAU;SAClD;EACN,OAAO,IAAI,IAAI,yBAAyB,sBAAsB,CAAC,UAAU;;;;;;;;;;;;ACC7E,SAAS,eAAe,KAAkC;CACxD,IAAI,QAAQ,KAAA,GAAW,OAAO;CAC9B,MAAM,aAAa,IAAI,MAAM,CAAC,aAAa;CAC3C,IAAI,eAAe,IAAI,OAAO;CAC9B,IAAI,eAAe,KAAK,OAAO;CAC/B,IAAI,eAAe,SAAS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Ae,WAAW,GAChF,OAAO;EAAE,SAAS;EAAO,QAAQ;EAAa;CAGhD,MAAM,UAAiC;EACrC,gBAAgB,OAAO;EACvB,SAAS,OAAO;EAChB,SAAS,UAAU;EACnB,OAAO,UAAU;EACjB,gBAAgB,OAAO;EACvB,YAAY,OAAO;EACnB,aAAa,OAAO;EACpB,UAAU,yBAAyB,IAAI;EACxC;CAED,IAAI;EACF,MAAM,QAAQ,KAAK,OAAO,YAAY,EAAE,EAAE;GACxC,UAAU;GACV,OAAO;IAAC;IAAQ;IAAU;IAAU;IAAM;GAC3C,CAAC;EACF,MAAM,KAAK,UAAU,QAAQ;GAC3B,IAAI,QAAQ,QAAQ,QAAQ,IAAI,yBAAyB,KACvD,QAAQ,OAAO,MAAM,sCAAsC,OAAO,IAAI,CAAC,IAAI;IAE7E;EACF,MAAM,YAAY;EAClB,MAAM,OAAO;EACb,OAAO,EAAE,SAAS,MAAM;UACjB,KAAK;EACZ,IAAI,QAAQ,IAAI,yBAAyB,KACvC,QAAQ,OAAO,MAAM,uCAAuC,OAAO,IAAI,CAAC,IAAI;EAE9E,OAAO;GAAE,SAAS;GAAO,QAAQ;GAAe;;;;;;;;;;AAWpD,SAAgB,gBAAgB,eAA+B;CAC7D,OAAO,cAAc,IAAI,IAAI,gBAAgB,cAAc,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/endpoint.ts","../../src/gating.ts","../../src/sanitize.ts","../../src/user-config.ts","../../src/spawn.ts"],"sourcesContent":["/**\n * Production endpoint pinned to the deployed Prisma Compute backend.\n * Compiled as a build-time constant; not user-configurable.\n */\nexport const TELEMETRY_BACKEND_URL = 'https://cmpbfbsdp09hr3jf7pojjs5qs.ewr.prisma.build';\n\n/**\n * Path within the backend that accepts telemetry POSTs.\n */\nexport const TELEMETRY_ENDPOINT_PATH = '/events';\n\n/**\n * Resolve the full POST URL the sender targets. The\n * `PRISMA_NEXT_TELEMETRY_ENDPOINT` env var is an integration-testing\n * affordance only — it lets the test suite spin up a mock HTTP server\n * on an ephemeral port and point the spawned sender at it. The override\n * is intentionally undocumented in user-facing material.\n *\n * Fail-open: a malformed override (typo in a dev shell, bad CI config)\n * silently falls back to the production backend rather than throwing,\n * matching the telemetry layer's broader silent-on-failure contract.\n */\nexport function resolveTelemetryEndpoint(\n env: Readonly<Record<string, string | undefined>> = process.env,\n): string {\n const override = env['PRISMA_NEXT_TELEMETRY_ENDPOINT'];\n const base = override !== undefined && override.length > 0 ? override : TELEMETRY_BACKEND_URL;\n try {\n return new URL(TELEMETRY_ENDPOINT_PATH, base).toString();\n } catch {\n return new URL(TELEMETRY_ENDPOINT_PATH, TELEMETRY_BACKEND_URL).toString();\n }\n}\n","import type { UserConfig } from './user-config';\n\n/**\n * Why telemetry was disabled. Useful for debug-mode logging in the\n * parent; never surfaces to users.\n */\nexport type GatingDisabledReason = 'env-override' | 'stored-opt-out' | 'default-off';\n\nexport type GatingResolution =\n | { readonly enabled: true }\n | { readonly enabled: false; readonly reason: GatingDisabledReason };\n\nexport interface GatingInputs {\n /**\n * Environment-variable lookups the resolver consults. Tests pass a\n * literal record; production passes `process.env`. The two opt-out\n * signals are `PRISMA_NEXT_DISABLE_TELEMETRY` (Prisma-specific) and\n * `DO_NOT_TRACK` (community convention).\n */\n readonly env: Readonly<Record<string, string | undefined>>;\n /** Result of `readUserConfig()` — file-missing tolerated as `{}`. */\n readonly config: UserConfig;\n}\n\n/**\n * A `PRISMA_NEXT_DISABLE_TELEMETRY` value counts as an opt-out only if\n * it parses as a truthy string. The set-but-falsy spellings (`''`,\n * `'0'`, `'false'`) are intentionally treated as not-set so a parent\n * shell that exports the variable to a benign value doesn't accidentally\n * disable telemetry for child processes.\n */\nfunction isTruthyOptOut(raw: string | undefined): boolean {\n if (raw === undefined) return false;\n const normalised = raw.trim().toLowerCase();\n if (normalised === '') return false;\n if (normalised === '0') return false;\n if (normalised === 'false') return false;\n return true;\n}\n\n/**\n * Pure-function resolution of the gating decision. Same input → same\n * output; no I/O. The caller is responsible for reading the env and the\n * user config.\n *\n * Decision order:\n * 1. Env-var override (`PRISMA_NEXT_DISABLE_TELEMETRY` truthy, or\n * `DO_NOT_TRACK=1`) → disabled.\n * 2. Stored `enableTelemetry === true` → enabled.\n * 3. Stored `enableTelemetry === false` → disabled (`stored-opt-out`).\n * 4. Stored `enableTelemetry === undefined` (file missing, or field\n * not set) → disabled (`default-off`).\n *\n * Telemetry is enabled only when no env override is active **and**\n * `enableTelemetry` is explicitly `true`.\n */\nexport function resolveGating(inputs: GatingInputs): GatingResolution {\n if (\n isTruthyOptOut(inputs.env['PRISMA_NEXT_DISABLE_TELEMETRY']) ||\n inputs.env['DO_NOT_TRACK'] === '1'\n ) {\n return { enabled: false, reason: 'env-override' };\n }\n if (inputs.config.enableTelemetry === true) {\n return { enabled: true };\n }\n if (inputs.config.enableTelemetry === false) {\n return { enabled: false, reason: 'stored-opt-out' };\n }\n return { enabled: false, reason: 'default-off' };\n}\n","export interface CommanderOptionShape {\n /** Commander's option attribute name, e.g. `dryRun` for `--dry-run`. */\n readonly attributeName: string;\n /** Commander's long, user-facing flag spelling, e.g. `--dry-run` or `--no-install`. */\n readonly longName: string | null;\n /** Commander's value source for this option. Only `cli` is user-supplied. */\n readonly source: string | null;\n}\n\n/**\n * Input shape: a thin projection of commander's parsed-result surface.\n * The parent extracts the command path, positional args, and per-option\n * metadata from the leaf command. The sanitiser never consumes raw\n * argv, never reads `process.argv`, and never sees flag values.\n */\nexport interface CommanderResultShape {\n /**\n * The full command path from the root program to the leaf, including\n * the root program name as the first element (the sanitiser drops it).\n * Example: `['prisma-next', 'migration', 'new']`.\n */\n readonly commandPath: readonly string[];\n /**\n * Positional arguments commander parsed for the leaf command.\n * **Intentionally never read.** Accepted so the call site doesn't have\n * to think about whether to pass it; the sanitiser's contract is that\n * positionals never leave the parent process.\n */\n readonly positionalArgs: readonly string[];\n /**\n * Per-option Commander metadata. The sanitiser emits only options whose\n * source is `cli`, and uses `longName` so telemetry sees user-facing\n * names (`dry-run`, `connection-string`, `no-install`) rather than\n * Commander's internal camelCase attribute names or defaulted options.\n */\n readonly options: readonly CommanderOptionShape[];\n}\n\n/**\n * Output shape: the sanitised projection that flows into the telemetry\n * payload. Two fields only — command name (space-delimited subcommand\n * path) and flag names (in commander's option declaration order).\n */\nexport interface SanitisedCommand {\n readonly command: string;\n readonly flags: readonly string[];\n}\n\nfunction flagNameFromLongName(longName: string | null): string | null {\n if (longName === null || !longName.startsWith('--')) return null;\n const withoutPrefix = longName.slice(2);\n return withoutPrefix.length > 0 ? withoutPrefix : null;\n}\n\n/**\n * Project commander's parsed result into the wire-shape command and\n * flag-name list. Pure; the only allowed inputs are the fields of\n * `CommanderResultShape`.\n *\n * Sanitiser contract — no flag values, no positionals, no raw argv:\n * - Drop the root program name (`commandPath[0]`); the wire ships\n * `migration new`, not `prisma-next migration new`.\n * - Emit only options whose Commander source is `cli`.\n * - Emit the long user-facing flag spelling without the `--` prefix;\n * never emit Commander's camelCase attribute names.\n * - `positionalArgs` is accepted but never consumed; the field exists\n * in the input type to make it obvious at the call site that\n * positionals were deliberately excluded.\n */\nexport function sanitizeCommanderResult(input: CommanderResultShape): SanitisedCommand {\n const command = input.commandPath.slice(1).join(' ');\n const flags = input.options.flatMap((option) => {\n if (option.source !== 'cli') return [];\n const flagName = flagNameFromLongName(option.longName);\n return flagName === null ? [] : [flagName];\n });\n return { command, flags };\n}\n","import { randomUUID } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'pathe';\n\n/**\n * The user-level config file. Persists the consent flag and the\n * installation UUID together so an env-var opt-out never mutates disk,\n * and so an opt-in → opt-out → opt-in cycle keeps the same UUID (correct\n * for MAU continuity).\n *\n * Readers tolerate unknown fields for forward compat; writers merge\n * partials into the existing object so unknown fields are preserved.\n */\nexport interface UserConfig {\n readonly enableTelemetry?: boolean;\n readonly installationId?: string;\n readonly [key: string]: unknown;\n}\n\nconst APP_DIR = 'prisma-next';\nconst FILE_NAME = 'config.json';\n\n/**\n * Resolves the user-level config directory:\n * - Windows: `%APPDATA%\\prisma-next\\` (fallback: `%USERPROFILE%\\AppData\\Roaming\\prisma-next\\`).\n * - Unix (incl. macOS): `$XDG_CONFIG_HOME/prisma-next/` if set, else\n * `$HOME/.config/prisma-next/` per the XDG Base Directory Specification.\n *\n * The spec deliberately picks XDG over the macOS-native\n * `~/Library/Preferences/` convention so the path resolution is\n * test-overridable via `XDG_CONFIG_HOME` and matches the documented\n * behaviour on all *nix platforms. We intentionally do not use\n * `env-paths`: its macOS choice of `~/Library/Preferences` is for\n * OS-managed plist preferences, not arbitrary JSON files. Apple documents\n * that apps access that directory through system APIs such as\n * `NSUserDefaults`, while cross-platform CLI and developer tools conventionally\n * use `~/.config` on macOS too:\n * https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/MacOSXDirectories/MacOSXDirectories.html\n */\nfunction configDir(): string {\n if (process.platform === 'win32') {\n const appData = process.env['APPDATA'];\n if (appData !== undefined && appData.length > 0) {\n return join(appData, APP_DIR);\n }\n return join(homedir(), 'AppData', 'Roaming', APP_DIR);\n }\n const xdg = process.env['XDG_CONFIG_HOME'];\n if (xdg !== undefined && xdg.length > 0) {\n return join(xdg, APP_DIR);\n }\n return join(homedir(), '.config', APP_DIR);\n}\n\n/**\n * Path to the user-level config file. Resolved per call so test\n * harnesses can mutate `$XDG_CONFIG_HOME` between cases.\n */\nexport function userConfigPath(): string {\n return join(configDir(), FILE_NAME);\n}\n\n/**\n * Reads the user-level config. File-missing, unreadable, or malformed →\n * `{}` (the absence of consent is the same answer in every error mode).\n * Unknown fields from a future client are passed through verbatim.\n */\nexport function readUserConfig(): UserConfig {\n const path = userConfigPath();\n if (!existsSync(path)) return {};\n try {\n const raw = readFileSync(path, 'utf-8');\n const parsed: unknown = JSON.parse(raw);\n if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return parsed as UserConfig;\n }\n return {};\n } catch {\n return {};\n }\n}\n\n/**\n * Merges `partial` into the current config and writes the result\n * atomically (temp file + rename) so a crash mid-write never leaves a\n * half-baked file readable on disk. Unknown fields already on disk are\n * preserved.\n *\n * When `partial.enableTelemetry === true` and no `installationId` is\n * stored yet, generates a v4 random UUID and persists both fields in\n * the same write. An existing `installationId` is never rotated.\n *\n * `writeUserConfig({ enableTelemetry: false })` does *not* generate an\n * installation id — only an affirmative consent answer produces one.\n */\nexport function writeUserConfig(partial: Partial<UserConfig>): void {\n const current = readUserConfig();\n const merged: Record<string, unknown> = { ...current, ...partial };\n if (partial.enableTelemetry === true && merged['installationId'] === undefined) {\n merged['installationId'] = randomUUID();\n }\n const path = userConfigPath();\n const dir = dirname(path);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n const tmpPath = `${path}.${process.pid}.tmp`;\n writeFileSync(tmpPath, `${JSON.stringify(merged, null, 2)}\\n`, 'utf-8');\n renameSync(tmpPath, path);\n}\n","import { fork } from 'node:child_process';\nimport { fileURLToPath } from 'node:url';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { resolveTelemetryEndpoint } from './endpoint';\nimport { resolveGating } from './gating';\nimport type { ParentToSenderPayload } from './payload';\nimport { type CommanderResultShape, sanitizeCommanderResult } from './sanitize';\nimport { readUserConfig, type UserConfig } from './user-config';\n\n/**\n * Inputs the CLI entry point hands the telemetry layer at command\n * start. The CLI is responsible for stitching commander's result and\n * the project root together; the telemetry module does no I/O of its\n * own except for the user-config read (skipped when `userConfig` is\n * provided). `extensions` is deliberately absent: the detached child\n * loads `prisma-next.config.*` via c12 itself and derives the\n * extension-pack ids from the validated config — see the rationale\n * on `ParentToSenderPayload` for why c12 lives in the child rather\n * than on the parent's hot path.\n *\n * `databaseTarget` is an optional parent-side override forwarded to\n * the child. Set by `fireTelemetryAfterInitConsent` (where the\n * config file does not yet exist on disk); left unset by the\n * preAction-hook path so the child's c12 load supplies the value.\n */\nexport interface RunTelemetryInputs {\n /** Sanitised commander snapshot — see `CommanderResultShape`. */\n readonly command: CommanderResultShape;\n /** This CLI's own version (from its `package.json`). */\n readonly version: string;\n /** Absolute path of the project root (typically `process.cwd()`). */\n readonly projectRoot: string;\n /**\n * Optional parent-side override for the c12-derived database target,\n * forwarded verbatim to the child sender. Wins over the child's\n * c12-derived value when present; `undefined` means \"no override\".\n */\n readonly databaseTarget?: string;\n /**\n * Path to the sender entry compiled into this package's `dist/`.\n * Resolved by the caller because the compiled sender lives at\n * `<package>/dist/sender.mjs` and only the consumer knows its own\n * `import.meta.url`.\n */\n readonly senderPath: string;\n /**\n * `isCI()` result from the consumer. Telemetry is suppressed when\n * `true` regardless of the stored consent answer — CI environments\n * never emit (matches the colour-output convention's CI suppression).\n */\n readonly isCI: boolean;\n /** Process env to read for opt-out signals. Defaults to `process.env`. */\n readonly env?: Readonly<Record<string, string | undefined>>;\n /** Cached user config when the caller already read it to resolve gates before other work. */\n readonly userConfig?: UserConfig;\n}\n\n/**\n * Best-effort telemetry spawn at command start. Returns synchronously —\n * the fork runs in the background and never blocks the parent. Every\n * failure mode is swallowed; the parent's stdout/stderr is untouched in\n * normal operation, the only escape valve being\n * `PRISMA_NEXT_DEBUG=1` which routes diagnostics to stderr.\n *\n * Returns the spawn outcome so debug-mode logging and the test-harness\n * probe (which verifies test runs short-circuit the fork) can inspect\n * the decision without scraping stderr.\n */\nexport type TelemetryRunOutcome =\n | { readonly spawned: true }\n | { readonly spawned: false; readonly reason: 'gated-off' | 'ci' | 'fork-failed' };\n\nexport function runTelemetry(inputs: RunTelemetryInputs): TelemetryRunOutcome {\n const env = inputs.env ?? process.env;\n\n if (inputs.isCI) {\n return { spawned: false, reason: 'ci' };\n }\n\n const config = inputs.userConfig ?? readUserConfig();\n const gating = resolveGating({ env, config });\n if (!gating.enabled) {\n return { spawned: false, reason: 'gated-off' };\n }\n\n const sanitised = sanitizeCommanderResult(inputs.command);\n // Gating already confirmed enableTelemetry === true, so installationId\n // must be set (writeUserConfig generates it alongside that field).\n // Defence-in-depth: if a stale config has the flag but no id, skip\n // rather than send a junk event.\n if (typeof config.installationId !== 'string' || config.installationId.length === 0) {\n return { spawned: false, reason: 'gated-off' };\n }\n\n const payload: ParentToSenderPayload = {\n installationId: config.installationId,\n version: inputs.version,\n command: sanitised.command,\n flags: sanitised.flags,\n projectRoot: inputs.projectRoot,\n endpoint: resolveTelemetryEndpoint(env),\n ...ifDefined('databaseTarget', inputs.databaseTarget),\n };\n\n try {\n const child = fork(inputs.senderPath, [], {\n detached: true,\n stdio: ['pipe', 'ignore', 'ignore', 'ipc'],\n });\n child.send(payload, (err) => {\n if (err !== null && process.env['PRISMA_NEXT_DEBUG'] === '1') {\n process.stderr.write(`[cli-telemetry] parent send error: ${String(err)}\\n`);\n }\n });\n child.disconnect();\n child.unref();\n return { spawned: true };\n } catch (err) {\n if (process.env['PRISMA_NEXT_DEBUG'] === '1') {\n process.stderr.write(`[cli-telemetry] parent fork failed: ${String(err)}\\n`);\n }\n return { spawned: false, reason: 'fork-failed' };\n }\n}\n\n/**\n * Resolve the path to the compiled sender entry relative to a consumer\n * that has captured its own `import.meta.url`. The CLI's\n * `tsdown`-emitted entry sits at `<package>/dist/sender.mjs`; the\n * consumer asks `senderModuleUrl()` and forwards the result to\n * `runTelemetry({ senderPath })`.\n */\nexport function senderModuleUrl(importMetaUrl: string): string {\n return fileURLToPath(new URL('./sender.mjs', importMetaUrl));\n}\n"],"mappings":";;;;;;;;;;;;;AAIA,MAAa,wBAAwB;;;;AAKrC,MAAa,0BAA0B;;;;;;;;;;;;AAavC,SAAgB,yBACd,MAAoD,QAAQ,KACpD;CACR,MAAM,WAAW,IAAI;CACrB,MAAM,OAAO,aAAa,KAAA,KAAa,SAAS,SAAS,IAAI,WAAW;CACxE,IAAI;EACF,OAAO,IAAI,IAAI,yBAAyB,KAAK,CAAC,UAAU;SAClD;EACN,OAAO,IAAI,IAAI,yBAAyB,sBAAsB,CAAC,UAAU;;;;;;;;;;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,gBAAgB;CAEpD,IAAI,CADW,cAAc;EAAE;EAAK;EAAQ,CACjC,CAAC,SACV,OAAO;EAAE,SAAS;EAAO,QAAQ;EAAa;CAGhD,MAAM,YAAY,wBAAwB,OAAO,QAAQ;CAKzD,IAAI,OAAO,OAAO,mBAAmB,YAAY,OAAO,eAAe,WAAW,GAChF,OAAO;EAAE,SAAS;EAAO,QAAQ;EAAa;CAGhD,MAAM,UAAiC;EACrC,gBAAgB,OAAO;EACvB,SAAS,OAAO;EAChB,SAAS,UAAU;EACnB,OAAO,UAAU;EACjB,aAAa,OAAO;EACpB,UAAU,yBAAyB,IAAI;EACvC,GAAG,UAAU,kBAAkB,OAAO,eAAe;EACtD;CAED,IAAI;EACF,MAAM,QAAQ,KAAK,OAAO,YAAY,EAAE,EAAE;GACxC,UAAU;GACV,OAAO;IAAC;IAAQ;IAAU;IAAU;IAAM;GAC3C,CAAC;EACF,MAAM,KAAK,UAAU,QAAQ;GAC3B,IAAI,QAAQ,QAAQ,QAAQ,IAAI,yBAAyB,KACvD,QAAQ,OAAO,MAAM,sCAAsC,OAAO,IAAI,CAAC,IAAI;IAE7E;EACF,MAAM,YAAY;EAClB,MAAM,OAAO;EACb,OAAO,EAAE,SAAS,MAAM;UACjB,KAAK;EACZ,IAAI,QAAQ,IAAI,yBAAyB,KACvC,QAAQ,OAAO,MAAM,uCAAuC,OAAO,IAAI,CAAC,IAAI;EAE9E,OAAO;GAAE,SAAS;GAAO,QAAQ;GAAe;;;;;;;;;;AAWpD,SAAgB,gBAAgB,eAA+B;CAC7D,OAAO,cAAc,IAAI,IAAI,gBAAgB,cAAc,CAAC"}
package/dist/sender.mjs CHANGED
@@ -1,164 +1,5 @@
1
- import { readFileSync } from "node:fs";
2
- import { join } from "pathe";
1
+ import { t as buildTelemetryEventFromProcess } from "./enrich-CGZ8Za8Y.mjs";
3
2
  import { type } from "arktype";
4
- //#region src/detect-agent.ts
5
- const AGENT_MARKERS = [
6
- {
7
- envVar: "CLAUDECODE",
8
- agent: "Claude Code"
9
- },
10
- {
11
- envVar: "CURSOR_AGENT",
12
- agent: "Cursor"
13
- },
14
- {
15
- envVar: "CODEX_SANDBOX",
16
- agent: "Codex CLI"
17
- },
18
- {
19
- envVar: "GEMINI_CLI",
20
- agent: "Gemini CLI"
21
- },
22
- {
23
- envVar: "WINDSURF",
24
- agent: "Windsurf"
25
- },
26
- {
27
- envVar: "AIDER",
28
- agent: "Aider"
29
- },
30
- {
31
- envVar: "CODY",
32
- agent: "Cody"
33
- },
34
- {
35
- envVar: "CONTINUE",
36
- agent: "Continue"
37
- }
38
- ];
39
- function isTruthyMarker(raw) {
40
- if (raw === void 0) return false;
41
- const normalised = raw.trim().toLowerCase();
42
- if (normalised === "") return false;
43
- if (normalised === "0") return false;
44
- if (normalised === "false") return false;
45
- return true;
46
- }
47
- /**
48
- * Resolve the agent label from an env snapshot, or `null` if no marker
49
- * is set. Returns the **first** matching marker in `AGENT_MARKERS`
50
- * order, so when multiple markers are set the agent label is
51
- * deterministic and the allowlist's first entry wins.
52
- *
53
- * Pure: takes an env record, returns a string or null. No I/O.
54
- */
55
- function detectAgent(env) {
56
- for (const marker of AGENT_MARKERS) if (isTruthyMarker(env[marker.envVar])) return marker.agent;
57
- return null;
58
- }
59
- //#endregion
60
- //#region src/enrich.ts
61
- /**
62
- * Identify the runtime the sender is running in. Same-runtime as the
63
- * parent is a correctness requirement: the parent forked us via
64
- * `child_process.fork`, which inherits the parent's runtime. Detection
65
- * keys on the runtime-specific version field rather than env vars so a
66
- * spoofed env can't lie about the actual interpreter.
67
- */
68
- function resolveRuntime(versions) {
69
- if (versions.bun !== void 0) return {
70
- name: "bun",
71
- version: versions.bun
72
- };
73
- if (versions.deno !== void 0) return {
74
- name: "deno",
75
- version: versions.deno
76
- };
77
- return {
78
- name: "node",
79
- version: versions.node
80
- };
81
- }
82
- /**
83
- * Parse `npm_config_user_agent` into a `<pm>/<version>` token. The
84
- * value, when present, looks like
85
- * `"pnpm/10.27.0 npm/? node/v24.13.0 darwin arm64"` — we take the first
86
- * whitespace-separated token. Any failure → `null`.
87
- */
88
- function parsePackageManager(userAgent) {
89
- if (userAgent === void 0) return null;
90
- const first = userAgent.split(/\s+/)[0];
91
- if (first === void 0 || first.length === 0) return null;
92
- if (!first.includes("/")) return null;
93
- return first;
94
- }
95
- /**
96
- * Read the user's project `package.json` and resolve a TypeScript
97
- * version from `devDependencies.typescript` (preferred) or
98
- * `dependencies.typescript`. Strips a leading `^` or `~` semver
99
- * prefix. Returns `null` on any failure mode — file missing,
100
- * unreadable, malformed JSON, key absent, not a string.
101
- */
102
- function readTsVersionFromPackageJson(raw) {
103
- if (raw === null) return null;
104
- let parsed;
105
- try {
106
- parsed = JSON.parse(raw);
107
- } catch {
108
- return null;
109
- }
110
- const candidate = pickStringDep(parsed["devDependencies"]) ?? pickStringDep(parsed["dependencies"]);
111
- if (candidate === null) return null;
112
- return candidate.replace(/^[\^~]/, "");
113
- }
114
- function pickStringDep(deps) {
115
- if (deps === null || typeof deps !== "object" || Array.isArray(deps)) return null;
116
- const value = deps["typescript"];
117
- return typeof value === "string" ? value : null;
118
- }
119
- /**
120
- * Build the full backend event from the parent's payload and the
121
- * child's per-process snapshot. Pure given an `EnrichEnvironment`.
122
- */
123
- function buildTelemetryEvent(payload, env) {
124
- const runtime = resolveRuntime(env.versions);
125
- return {
126
- installationId: payload.installationId,
127
- version: payload.version,
128
- command: payload.command,
129
- flags: payload.flags,
130
- runtimeName: runtime.name,
131
- runtimeVersion: runtime.version,
132
- os: env.platform,
133
- arch: env.arch,
134
- packageManager: parsePackageManager(env.env["npm_config_user_agent"]),
135
- databaseTarget: payload.databaseTarget,
136
- tsVersion: readTsVersionFromPackageJson(env.readProjectPackageJson()),
137
- agent: detectAgent(env.env),
138
- extensions: payload.extensions
139
- };
140
- }
141
- /**
142
- * Convenience for the sender entry: build the event from the live
143
- * `process` plus a real project-package.json reader, swallowing any
144
- * I/O errors in the file read.
145
- */
146
- function buildTelemetryEventFromProcess(payload) {
147
- return buildTelemetryEvent(payload, {
148
- platform: process.platform,
149
- arch: process.arch,
150
- versions: process.versions,
151
- env: process.env,
152
- readProjectPackageJson: () => {
153
- try {
154
- return readFileSync(join(payload.projectRoot, "package.json"), "utf-8");
155
- } catch {
156
- return null;
157
- }
158
- }
159
- });
160
- }
161
- //#endregion
162
3
  //#region src/payload.ts
163
4
  /**
164
5
  * Runtime validator for {@link ParentToSenderPayload}. The child sender
@@ -166,22 +7,21 @@ function buildTelemetryEventFromProcess(payload) {
166
7
  * cannot silently produce a degraded telemetry event downstream.
167
8
  *
168
9
  * Mirrors the backend's own arktype schema in spirit: required scalars
169
- * must be non-empty strings; `databaseTarget` is `string | null`; the
170
- * two string arrays are validated element-by-element. Size caps are
171
- * enforced by the backend, not here IPC is structured-cloned and
172
- * the parent/child agree on the schema by version-coupling.
10
+ * must be non-empty strings; the optional `databaseTarget` override is
11
+ * `string` when present (no `null` see the type's doc-block); the
12
+ * string array is validated element-by-element. Size caps are enforced
13
+ * by the backend, not here IPC is structured-cloned and the
14
+ * parent/child agree on the schema by version-coupling.
173
15
  */
174
16
  const requiredString = type.string.moreThanLength(0);
175
- const stringArray = type.string.array();
176
17
  const parentToSenderPayloadSchema = type({
177
18
  installationId: requiredString,
178
19
  version: requiredString,
179
20
  command: requiredString,
180
- flags: stringArray,
181
- databaseTarget: type.string.or("null"),
182
- extensions: stringArray,
21
+ flags: type.string.array(),
183
22
  projectRoot: requiredString,
184
- endpoint: requiredString
23
+ endpoint: requiredString,
24
+ "databaseTarget?": type.string
185
25
  });
186
26
  function isParentToSenderPayload(value) {
187
27
  return !(parentToSenderPayloadSchema(value) instanceof type.errors);
@@ -215,7 +55,7 @@ function debugLog(message, error) {
215
55
  else process.stderr.write(`[cli-telemetry] ${message}\n`);
216
56
  }
217
57
  async function postEvent(payload) {
218
- const event = buildTelemetryEventFromProcess(payload);
58
+ const event = await buildTelemetryEventFromProcess(payload);
219
59
  const controller = new AbortController();
220
60
  const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
221
61
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"sender.mjs","names":[],"sources":["../src/detect-agent.ts","../src/enrich.ts","../src/payload.ts","../src/sender.ts"],"sourcesContent":["/**\n * Best-effort identification of AI coding-agent sessions from an\n * env-var allowlist. Detector property: false positives are negligible\n * (a marker present ⇒ confidently an agent); false negatives are\n * expected and documented in the user-facing telemetry docs. New\n * entries should land here, not in per-CLI hand-rolls.\n *\n * Each entry is a `(envVar, agent)` pair with uniform comparison shape:\n * the marker counts as \"present\" when `process.env[envVar]` is set to a\n * truthy string. Truthy = anything other than the empty string, `'0'`,\n * or `'false'` (case-insensitive); see `gating.isTruthyOptOut` for the\n * same convention applied to opt-out env vars.\n *\n * The detector runs in the **child** sender process, never the parent;\n * the parent does not probe env at command start.\n *\n * Codex CLI note: `CODEX_SANDBOX` is the only clear marker available here.\n * Non-sandboxed Codex sessions may be false negatives.\n *\n * TODO: a ci-info-for-agents would be nice — this allowlist drifts the\n * moment a new agent ships its env marker, and consolidating with the\n * other ecosystems that need the same lookup (rate-limited LLM\n * gateways, agent-aware metrics, etc.) would let one library carry the\n * matrix instead of every consumer re-doing it.\n */\nexport interface AgentMarker {\n /** The env-var name to read. Exact-match; no prefix or fuzzy logic. */\n readonly envVar: string;\n /** The agent label written to the `agent` field of the telemetry event. */\n readonly agent: string;\n}\n\nexport const AGENT_MARKERS: readonly AgentMarker[] = [\n { envVar: 'CLAUDECODE', agent: 'Claude Code' },\n { envVar: 'CURSOR_AGENT', agent: 'Cursor' },\n { envVar: 'CODEX_SANDBOX', agent: 'Codex CLI' },\n { envVar: 'GEMINI_CLI', agent: 'Gemini CLI' },\n { envVar: 'WINDSURF', agent: 'Windsurf' },\n { envVar: 'AIDER', agent: 'Aider' },\n { envVar: 'CODY', agent: 'Cody' },\n { envVar: 'CONTINUE', agent: 'Continue' },\n];\n\nfunction isTruthyMarker(raw: string | undefined): boolean {\n if (raw === undefined) return false;\n const normalised = raw.trim().toLowerCase();\n if (normalised === '') return false;\n if (normalised === '0') return false;\n if (normalised === 'false') return false;\n return true;\n}\n\n/**\n * Resolve the agent label from an env snapshot, or `null` if no marker\n * is set. Returns the **first** matching marker in `AGENT_MARKERS`\n * order, so when multiple markers are set the agent label is\n * deterministic and the allowlist's first entry wins.\n *\n * Pure: takes an env record, returns a string or null. No I/O.\n */\nexport function detectAgent(env: Readonly<Record<string, string | undefined>>): string | null {\n for (const marker of AGENT_MARKERS) {\n if (isTruthyMarker(env[marker.envVar])) {\n return marker.agent;\n }\n }\n return null;\n}\n","import { readFileSync } from 'node:fs';\nimport { join } from 'pathe';\nimport { detectAgent } from './detect-agent';\nimport type { ParentToSenderPayload, TelemetryEvent } from './payload';\n\n/**\n * Versions surface the enrichment cares about. Modelled as a structural\n * record with a required `node` field so tests can pass a literal object\n * without faking every field of `NodeJS.ProcessVersions` (which adds\n * properties between Node versions and includes a long tail the\n * enrichment never touches). Both `bun` and `deno` are read on the\n * runtime-resolution path; everything else is ignored.\n */\nexport interface VersionsSnapshot {\n readonly node: string;\n readonly bun?: string;\n readonly deno?: string;\n}\n\n/**\n * Snapshot of process-level inputs the enrichment reads. Tests pass an\n * explicit snapshot so the enrichment is deterministic per case; the\n * sender entry point passes a fresh snapshot from `process`.\n */\nexport interface EnrichEnvironment {\n readonly platform: NodeJS.Platform;\n readonly arch: string;\n readonly versions: VersionsSnapshot;\n /**\n * Included because package-manager and agent detection intentionally read\n * environment variables from the same process snapshot as platform/versions.\n */\n readonly env: Readonly<Record<string, string | undefined>>;\n /**\n * Best-effort reader for the project's `package.json`, used only to derive\n * the optional `tsVersion` telemetry field. Returning `null` means unknown.\n */\n readonly readProjectPackageJson: () => string | null;\n}\n\n/**\n * Identify the runtime the sender is running in. Same-runtime as the\n * parent is a correctness requirement: the parent forked us via\n * `child_process.fork`, which inherits the parent's runtime. Detection\n * keys on the runtime-specific version field rather than env vars so a\n * spoofed env can't lie about the actual interpreter.\n */\nfunction resolveRuntime(versions: VersionsSnapshot): {\n readonly name: 'node' | 'bun' | 'deno';\n readonly version: string;\n} {\n if (versions.bun !== undefined) {\n return { name: 'bun', version: versions.bun };\n }\n if (versions.deno !== undefined) {\n return { name: 'deno', version: versions.deno };\n }\n return { name: 'node', version: versions.node };\n}\n\n/**\n * Parse `npm_config_user_agent` into a `<pm>/<version>` token. The\n * value, when present, looks like\n * `\"pnpm/10.27.0 npm/? node/v24.13.0 darwin arm64\"` — we take the first\n * whitespace-separated token. Any failure → `null`.\n */\nexport function parsePackageManager(userAgent: string | undefined): string | null {\n if (userAgent === undefined) return null;\n const first = userAgent.split(/\\s+/)[0];\n if (first === undefined || first.length === 0) return null;\n if (!first.includes('/')) return null;\n return first;\n}\n\n/**\n * Read the user's project `package.json` and resolve a TypeScript\n * version from `devDependencies.typescript` (preferred) or\n * `dependencies.typescript`. Strips a leading `^` or `~` semver\n * prefix. Returns `null` on any failure mode — file missing,\n * unreadable, malformed JSON, key absent, not a string.\n */\nexport function readTsVersionFromPackageJson(raw: string | null): string | null {\n if (raw === null) return null;\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(raw) as Record<string, unknown>;\n } catch {\n return null;\n }\n const candidate =\n pickStringDep(parsed['devDependencies']) ?? pickStringDep(parsed['dependencies']);\n if (candidate === null) return null;\n return candidate.replace(/^[\\^~]/, '');\n}\n\nfunction pickStringDep(deps: unknown): string | null {\n if (deps === null || typeof deps !== 'object' || Array.isArray(deps)) return null;\n const value = (deps as Record<string, unknown>)['typescript'];\n return typeof value === 'string' ? value : null;\n}\n\n/**\n * Build the full backend event from the parent's payload and the\n * child's per-process snapshot. Pure given an `EnrichEnvironment`.\n */\nexport function buildTelemetryEvent(\n payload: ParentToSenderPayload,\n env: EnrichEnvironment,\n): TelemetryEvent {\n const runtime = resolveRuntime(env.versions);\n return {\n installationId: payload.installationId,\n version: payload.version,\n command: payload.command,\n flags: payload.flags,\n runtimeName: runtime.name,\n runtimeVersion: runtime.version,\n os: env.platform,\n arch: env.arch,\n packageManager: parsePackageManager(env.env['npm_config_user_agent']),\n databaseTarget: payload.databaseTarget,\n tsVersion: readTsVersionFromPackageJson(env.readProjectPackageJson()),\n agent: detectAgent(env.env),\n extensions: payload.extensions,\n };\n}\n\n/**\n * Convenience for the sender entry: build the event from the live\n * `process` plus a real project-package.json reader, swallowing any\n * I/O errors in the file read.\n */\nexport function buildTelemetryEventFromProcess(payload: ParentToSenderPayload): TelemetryEvent {\n return buildTelemetryEvent(payload, {\n platform: process.platform,\n arch: process.arch,\n versions: process.versions,\n env: process.env,\n readProjectPackageJson: () => {\n try {\n return readFileSync(join(payload.projectRoot, 'package.json'), 'utf-8');\n } catch {\n return null;\n }\n },\n });\n}\n","import { type } from 'arktype';\n\n/**\n * Wire-shape payload the parent IPC-sends to the forked child sender.\n * Mirrors the fields the parent has naturally in hand at command start\n * (installation id, sanitised command + flags, CLI version, db target,\n * extension-pack ids, project root for TS-version lookup). The child\n * fills in the rest (runtime/os/arch, package manager, ts version,\n * agent) on its side.\n *\n * Both sides version-couple on this shape because the IPC carrier is\n * structured-cloned by Node and there's no on-wire compat to maintain.\n */\nexport interface ParentToSenderPayload {\n readonly installationId: string;\n readonly version: string;\n readonly command: string;\n readonly flags: readonly string[];\n readonly databaseTarget: string | null;\n readonly extensions: readonly string[];\n /** Absolute path of the user's project. The child reads `<projectRoot>/package.json` for `tsVersion`. */\n readonly projectRoot: string;\n /** Resolved endpoint URL (already includes the `/events` path). */\n readonly endpoint: string;\n}\n\n/**\n * Runtime validator for {@link ParentToSenderPayload}. The child sender\n * uses this to gate `postEvent` so a payload missing a required field\n * cannot silently produce a degraded telemetry event downstream.\n *\n * Mirrors the backend's own arktype schema in spirit: required scalars\n * must be non-empty strings; `databaseTarget` is `string | null`; the\n * two string arrays are validated element-by-element. Size caps are\n * enforced by the backend, not here — IPC is structured-cloned and\n * the parent/child agree on the schema by version-coupling.\n */\nconst requiredString = type.string.moreThanLength(0);\nconst stringArray = type.string.array();\n\nexport const parentToSenderPayloadSchema = type({\n installationId: requiredString,\n version: requiredString,\n command: requiredString,\n flags: stringArray,\n databaseTarget: type.string.or('null'),\n extensions: stringArray,\n projectRoot: requiredString,\n endpoint: requiredString,\n});\n\nexport function isParentToSenderPayload(value: unknown): value is ParentToSenderPayload {\n return !(parentToSenderPayloadSchema(value) instanceof type.errors);\n}\n\n/**\n * The full event the child POSTs to the backend. Shape matches the\n * backend's arktype schema (`apps/telemetry-backend/src/schema.ts`).\n */\nexport interface TelemetryEvent {\n readonly installationId: string;\n readonly version: string;\n readonly command: string;\n readonly flags: readonly string[];\n readonly runtimeName: string;\n readonly runtimeVersion: string;\n readonly os: string;\n readonly arch: string;\n readonly packageManager: string | null;\n readonly databaseTarget: string | null;\n readonly tsVersion: string | null;\n readonly agent: string | null;\n readonly extensions: readonly string[];\n}\n","/**\n * Sender script entry — forked into a detached child by the parent CLI via\n * `child_process.fork(senderPath, [], { detached: true, ... })`.\n *\n * Lifecycle:\n * 1. Wait for the parent's IPC `message` event carrying a\n * `ParentToSenderPayload`.\n * 2. Enrich with the local-process probes (runtime, os, arch, agent,\n * package manager, tsVersion).\n * 3. POST the event to the endpoint URL with a hard 1.5 s timeout.\n * 4. Exit 0 unconditionally — successful POST, network failure, server\n * error, parse error of the response, anything else: same outcome.\n *\n * Every error is swallowed; the only escape valve for visibility is\n * `PRISMA_NEXT_DEBUG=1`, which routes diagnostics to stderr. In normal\n * operation no telemetry-originating output ever reaches the user — the\n * parent's stdio map ignores our streams anyway, but we also gate\n * stderr writes behind the debug flag so the same binary is safe to\n * invoke directly outside the spawn flow.\n */\nimport { buildTelemetryEventFromProcess } from './enrich';\nimport { isParentToSenderPayload, type ParentToSenderPayload } from './payload';\n\nconst REQUEST_TIMEOUT_MS = 1500;\n\nfunction debugLog(message: string, error?: unknown): void {\n if (process.env['PRISMA_NEXT_DEBUG'] !== '1') return;\n if (error !== undefined) {\n process.stderr.write(`[cli-telemetry] ${message}: ${String(error)}\\n`);\n } else {\n process.stderr.write(`[cli-telemetry] ${message}\\n`);\n }\n}\n\nasync function postEvent(payload: ParentToSenderPayload): Promise<void> {\n const event = buildTelemetryEventFromProcess(payload);\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);\n try {\n const response = await fetch(payload.endpoint, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(event),\n signal: controller.signal,\n });\n debugLog(`sent event: status=${response.status}`);\n } catch (err) {\n debugLog('send failed', err);\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction exitClean(): void {\n // `process.disconnect()` lets the parent's `.disconnect()` complete\n // without lingering IPC handles when the parent is fast.\n try {\n process.disconnect?.();\n } catch {\n // ignore\n }\n process.exit(0);\n}\n\nprocess.once('message', (message: unknown) => {\n if (!isParentToSenderPayload(message)) {\n debugLog('received malformed payload; exiting');\n exitClean();\n return;\n }\n postEvent(message)\n .catch((err) => debugLog('post threw', err))\n .finally(exitClean);\n});\n\n// Defensive: if the parent never sends a payload (or the IPC channel\n// closes before `message` arrives), exit after a generous grace period\n// so the child process is not stuck holding a handle.\nconst SENDER_IDLE_EXIT_MS = REQUEST_TIMEOUT_MS * 2;\nsetTimeout(exitClean, SENDER_IDLE_EXIT_MS).unref();\n"],"mappings":";;;;AAgCA,MAAa,gBAAwC;CACnD;EAAE,QAAQ;EAAc,OAAO;EAAe;CAC9C;EAAE,QAAQ;EAAgB,OAAO;EAAU;CAC3C;EAAE,QAAQ;EAAiB,OAAO;EAAa;CAC/C;EAAE,QAAQ;EAAc,OAAO;EAAc;CAC7C;EAAE,QAAQ;EAAY,OAAO;EAAY;CACzC;EAAE,QAAQ;EAAS,OAAO;EAAS;CACnC;EAAE,QAAQ;EAAQ,OAAO;EAAQ;CACjC;EAAE,QAAQ;EAAY,OAAO;EAAY;CAC1C;AAED,SAAS,eAAe,KAAkC;CACxD,IAAI,QAAQ,KAAA,GAAW,OAAO;CAC9B,MAAM,aAAa,IAAI,MAAM,CAAC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,+BAA+B,QAAQ;CACrD,MAAM,aAAa,IAAI,iBAAiB;CACxC,MAAM,QAAQ,iBAAiB,WAAW,OAAO,EAAE,mBAAmB;CACtE,IAAI;EAOF,SAAS,uBAAsB,MANR,MAAM,QAAQ,UAAU;GAC7C,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAC/C,MAAM,KAAK,UAAU,MAAM;GAC3B,QAAQ,WAAW;GACpB,CAAC,EACsC,SAAS;UAC1C,KAAK;EACZ,SAAS,eAAe,IAAI;WACpB;EACR,aAAa,MAAM;;;AAIvB,SAAS,YAAkB;CAGzB,IAAI;EACF,QAAQ,cAAc;SAChB;CAGR,QAAQ,KAAK,EAAE;;AAGjB,QAAQ,KAAK,YAAY,YAAqB;CAC5C,IAAI,CAAC,wBAAwB,QAAQ,EAAE;EACrC,SAAS,sCAAsC;EAC/C,WAAW;EACX;;CAEF,UAAU,QAAQ,CACf,OAAO,QAAQ,SAAS,cAAc,IAAI,CAAC,CAC3C,QAAQ,UAAU;EACrB;AAKF,MAAM,sBAAsB,qBAAqB;AACjD,WAAW,WAAW,oBAAoB,CAAC,OAAO"}
1
+ {"version":3,"file":"sender.mjs","names":[],"sources":["../src/payload.ts","../src/sender.ts"],"sourcesContent":["import { type } from 'arktype';\n\n/**\n * Wire-shape payload the parent IPC-sends to the forked child sender.\n * Mirrors only the fields the parent has naturally in hand at command\n * start: installation id, sanitised command + flags, CLI version, and\n * the project root the child uses to discover everything else. The\n * child probes its own process (runtime/os/arch, package manager, ts\n * version, agent) and reads the user's `prisma-next.config.*` via\n * c12 to derive `databaseTarget` and `extensions`.\n *\n * Loading c12 on the parent side would put a `loadConfig()` await on\n * the command's hot path between gate resolution and `fork()`,\n * opening a race against any CLI command that throws synchronously\n * before that await resolves (the parent exits before forking the\n * sender, and the telemetry event is lost). Moving the load into the\n * detached child eliminates that race; the trade is that the child\n * now evaluates user TS config code, so it's gated behind the same\n * privacy checks the parent already resolved before forking.\n *\n * `databaseTarget` is an optional parent-side override for the\n * c12-derived value: the first-`init` invocation supplies the\n * prompt-chosen target via this field because the config file does\n * not yet exist on disk at that moment. Every other invocation\n * leaves it unset (`undefined`) and the child's c12 load determines\n * the value — there is no third state, so the field's type is\n * `string | undefined`, not `string | null | undefined`.\n *\n * Both sides version-couple on this shape because the IPC carrier is\n * structured-cloned by Node and there's no on-wire compat to maintain.\n */\nexport interface ParentToSenderPayload {\n readonly installationId: string;\n readonly version: string;\n readonly command: string;\n readonly flags: readonly string[];\n /**\n * Absolute path of the user's project. The child reads\n * `<projectRoot>/package.json` for `tsVersion` and loads\n * `<projectRoot>/prisma-next.config.*` via c12 for `databaseTarget`\n * + `extensions`.\n */\n readonly projectRoot: string;\n /** Resolved endpoint URL (already includes the `/events` path). */\n readonly endpoint: string;\n /**\n * Optional parent-side override for the c12-derived database target.\n * Set by `fireTelemetryAfterInitConsent` (the first-`init` path,\n * where the config file is about to be written but doesn't exist\n * yet); left undefined by `fireTelemetryFromPreAction` (steady\n * state, child resolves the value via c12). The wire-format\n * `TelemetryEvent.databaseTarget: string | null` keeps `null` as\n * the on-the-wire \"no target known\" marker, but the IPC override\n * channel only needs two states so it's `string | undefined`.\n */\n readonly databaseTarget?: string;\n}\n\n/**\n * Runtime validator for {@link ParentToSenderPayload}. The child sender\n * uses this to gate `postEvent` so a payload missing a required field\n * cannot silently produce a degraded telemetry event downstream.\n *\n * Mirrors the backend's own arktype schema in spirit: required scalars\n * must be non-empty strings; the optional `databaseTarget` override is\n * `string` when present (no `null` — see the type's doc-block); the\n * string array is validated element-by-element. Size caps are enforced\n * by the backend, not here — IPC is structured-cloned and the\n * parent/child agree on the schema by version-coupling.\n */\nconst requiredString = type.string.moreThanLength(0);\nconst stringArray = type.string.array();\n\nexport const parentToSenderPayloadSchema = type({\n installationId: requiredString,\n version: requiredString,\n command: requiredString,\n flags: stringArray,\n projectRoot: requiredString,\n endpoint: requiredString,\n 'databaseTarget?': type.string,\n});\n\nexport function isParentToSenderPayload(value: unknown): value is ParentToSenderPayload {\n return !(parentToSenderPayloadSchema(value) instanceof type.errors);\n}\n\n/**\n * The full event the child POSTs to the backend. Shape matches the\n * backend's arktype schema (`apps/telemetry-backend/src/schema.ts`).\n */\nexport interface TelemetryEvent {\n readonly installationId: string;\n readonly version: string;\n readonly command: string;\n readonly flags: readonly string[];\n readonly runtimeName: string;\n readonly runtimeVersion: string;\n readonly os: string;\n readonly arch: string;\n readonly packageManager: string | null;\n readonly databaseTarget: string | null;\n readonly tsVersion: string | null;\n readonly agent: string | null;\n readonly extensions: readonly string[];\n}\n","/**\n * Sender script entry — forked into a detached child by the parent CLI via\n * `child_process.fork(senderPath, [], { detached: true, ... })`.\n *\n * Lifecycle:\n * 1. Wait for the parent's IPC `message` event carrying a\n * `ParentToSenderPayload`.\n * 2. Enrich with the local-process probes (runtime, os, arch, agent,\n * package manager, tsVersion).\n * 3. POST the event to the endpoint URL with a hard 1.5 s timeout.\n * 4. Exit 0 unconditionally — successful POST, network failure, server\n * error, parse error of the response, anything else: same outcome.\n *\n * Every error is swallowed; the only escape valve for visibility is\n * `PRISMA_NEXT_DEBUG=1`, which routes diagnostics to stderr. In normal\n * operation no telemetry-originating output ever reaches the user — the\n * parent's stdio map ignores our streams anyway, but we also gate\n * stderr writes behind the debug flag so the same binary is safe to\n * invoke directly outside the spawn flow.\n */\nimport { buildTelemetryEventFromProcess } from './enrich';\nimport { isParentToSenderPayload, type ParentToSenderPayload } from './payload';\n\nconst REQUEST_TIMEOUT_MS = 1500;\n\nfunction debugLog(message: string, error?: unknown): void {\n if (process.env['PRISMA_NEXT_DEBUG'] !== '1') return;\n if (error !== undefined) {\n process.stderr.write(`[cli-telemetry] ${message}: ${String(error)}\\n`);\n } else {\n process.stderr.write(`[cli-telemetry] ${message}\\n`);\n }\n}\n\nasync function postEvent(payload: ParentToSenderPayload): Promise<void> {\n const event = await buildTelemetryEventFromProcess(payload);\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);\n try {\n const response = await fetch(payload.endpoint, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(event),\n signal: controller.signal,\n });\n debugLog(`sent event: status=${response.status}`);\n } catch (err) {\n debugLog('send failed', err);\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction exitClean(): void {\n // `process.disconnect()` lets the parent's `.disconnect()` complete\n // without lingering IPC handles when the parent is fast.\n try {\n process.disconnect?.();\n } catch {\n // ignore\n }\n process.exit(0);\n}\n\nprocess.once('message', (message: unknown) => {\n if (!isParentToSenderPayload(message)) {\n debugLog('received malformed payload; exiting');\n exitClean();\n return;\n }\n postEvent(message)\n .catch((err) => debugLog('post threw', err))\n .finally(exitClean);\n});\n\n// Defensive: if the parent never sends a payload (or the IPC channel\n// closes before `message` arrives), exit after a generous grace period\n// so the child process is not stuck holding a handle.\nconst SENDER_IDLE_EXIT_MS = REQUEST_TIMEOUT_MS * 2;\nsetTimeout(exitClean, SENDER_IDLE_EXIT_MS).unref();\n"],"mappings":";;;;;;;;;;;;;;;AAsEA,MAAM,iBAAiB,KAAK,OAAO,eAAe,EAAE;AAGpD,MAAa,8BAA8B,KAAK;CAC9C,gBAAgB;CAChB,SAAS;CACT,SAAS;CACT,OANkB,KAAK,OAAO,OAMvB;CACP,aAAa;CACb,UAAU;CACV,mBAAmB,KAAK;CACzB,CAAC;AAEF,SAAgB,wBAAwB,OAAgD;CACtF,OAAO,EAAE,4BAA4B,MAAM,YAAY,KAAK;;;;;;;;;;;;;;;;;;;;;;;;AC7D9D,MAAM,qBAAqB;AAE3B,SAAS,SAAS,SAAiB,OAAuB;CACxD,IAAI,QAAQ,IAAI,yBAAyB,KAAK;CAC9C,IAAI,UAAU,KAAA,GACZ,QAAQ,OAAO,MAAM,mBAAmB,QAAQ,IAAI,OAAO,MAAM,CAAC,IAAI;MAEtE,QAAQ,OAAO,MAAM,mBAAmB,QAAQ,IAAI;;AAIxD,eAAe,UAAU,SAA+C;CACtE,MAAM,QAAQ,MAAM,+BAA+B,QAAQ;CAC3D,MAAM,aAAa,IAAI,iBAAiB;CACxC,MAAM,QAAQ,iBAAiB,WAAW,OAAO,EAAE,mBAAmB;CACtE,IAAI;EAOF,SAAS,uBAAsB,MANR,MAAM,QAAQ,UAAU;GAC7C,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAC/C,MAAM,KAAK,UAAU,MAAM;GAC3B,QAAQ,WAAW;GACpB,CAAC,EACsC,SAAS;UAC1C,KAAK;EACZ,SAAS,eAAe,IAAI;WACpB;EACR,aAAa,MAAM;;;AAIvB,SAAS,YAAkB;CAGzB,IAAI;EACF,QAAQ,cAAc;SAChB;CAGR,QAAQ,KAAK,EAAE;;AAGjB,QAAQ,KAAK,YAAY,YAAqB;CAC5C,IAAI,CAAC,wBAAwB,QAAQ,EAAE;EACrC,SAAS,sCAAsC;EAC/C,WAAW;EACX;;CAEF,UAAU,QAAQ,CACf,OAAO,QAAQ,SAAS,cAAc,IAAI,CAAC,CAC3C,QAAQ,UAAU;EACrB;AAKF,MAAM,sBAAsB,qBAAqB;AACjD,WAAW,WAAW,oBAAoB,CAAC,OAAO"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma-next/cli-telemetry",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -9,28 +9,21 @@
9
9
  "dist",
10
10
  "src"
11
11
  ],
12
- "scripts": {
13
- "build": "tsdown",
14
- "test": "vitest run",
15
- "test:coverage": "vitest run --coverage",
16
- "typecheck": "tsc --project tsconfig.json --noEmit",
17
- "lint": "biome check . --error-on-warnings",
18
- "lint:fix": "biome check --write .",
19
- "lint:fix:unsafe": "biome check --write --unsafe .",
20
- "clean": "rm -rf dist dist-tsc dist-tsc-prod coverage .tmp-output"
21
- },
22
12
  "dependencies": {
23
- "arktype": "catalog:",
13
+ "@prisma-next/config": "0.11.0",
14
+ "@prisma-next/utils": "0.11.0",
15
+ "arktype": "^2.2.0",
16
+ "c12": "^3.3.4",
24
17
  "pathe": "^2.0.3"
25
18
  },
26
19
  "devDependencies": {
27
- "@prisma-next/test-utils": "workspace:0.10.0",
28
- "@prisma-next/tsconfig": "workspace:0.10.0",
29
- "@prisma-next/tsdown": "workspace:0.10.0",
30
- "@types/node": "catalog:",
31
- "tsdown": "catalog:",
32
- "typescript": "catalog:",
33
- "vitest": "catalog:"
20
+ "@prisma-next/test-utils": "0.11.0",
21
+ "@prisma-next/tsconfig": "0.11.0",
22
+ "@prisma-next/tsdown": "0.11.0",
23
+ "@types/node": "24.10.4",
24
+ "tsdown": "0.22.0",
25
+ "typescript": "5.9.3",
26
+ "vitest": "4.1.6"
34
27
  },
35
28
  "exports": {
36
29
  ".": {
@@ -46,5 +39,15 @@
46
39
  "type": "git",
47
40
  "url": "https://github.com/prisma/prisma-next.git",
48
41
  "directory": "packages/1-framework/3-tooling/cli-telemetry"
42
+ },
43
+ "scripts": {
44
+ "build": "tsdown",
45
+ "test": "vitest run",
46
+ "test:coverage": "vitest run --coverage",
47
+ "typecheck": "tsc --project tsconfig.json --noEmit",
48
+ "lint": "biome check . --error-on-warnings",
49
+ "lint:fix": "biome check --write .",
50
+ "lint:fix:unsafe": "biome check --write --unsafe .",
51
+ "clean": "rm -rf dist dist-tsc dist-tsc-prod coverage .tmp-output"
49
52
  }
50
- }
53
+ }
package/src/enrich.ts CHANGED
@@ -1,8 +1,75 @@
1
1
  import { readFileSync } from 'node:fs';
2
+ import type { PrismaNextConfig } from '@prisma-next/config/config-types';
2
3
  import { join } from 'pathe';
3
4
  import { detectAgent } from './detect-agent';
4
5
  import type { ParentToSenderPayload, TelemetryEvent } from './payload';
5
6
 
7
+ /**
8
+ * Subset of the user's `prisma-next.config.*` the telemetry event
9
+ * surfaces. Loaded inside the detached child via {@link loadProjectConfig}
10
+ * — see the design rationale on {@link ParentToSenderPayload} for why
11
+ * this side runs c12 instead of the parent CLI.
12
+ */
13
+ export interface ProjectConfigFields {
14
+ readonly databaseTarget: string | null;
15
+ readonly extensions: readonly string[];
16
+ }
17
+
18
+ const EMPTY_PROJECT_CONFIG: ProjectConfigFields = {
19
+ databaseTarget: null,
20
+ extensions: [],
21
+ };
22
+
23
+ /**
24
+ * Best-effort load of `prisma-next.config.*` from `projectRoot`,
25
+ * validated against the canonical `@prisma-next/config` schema.
26
+ * Returns `{ databaseTarget: null, extensions: [] }` on any failure
27
+ * mode — missing config file (e.g. before `prisma-next init`), c12
28
+ * throws while evaluating user TS, validator rejects a malformed
29
+ * shape, etc. Telemetry is non-blocking and best-effort; an empty
30
+ * result is the only downside of an unloadable or invalid config.
31
+ *
32
+ * Both `c12` and `@prisma-next/config/config-validation` are imported
33
+ * lazily so the detached sender's cold-start cost is paid only when
34
+ * telemetry actually fires, not on every fork even when gates
35
+ * short-circuit before reaching this code path.
36
+ */
37
+ export async function loadProjectConfig(projectRoot: string): Promise<ProjectConfigFields> {
38
+ try {
39
+ const { loadConfig } = await import('c12');
40
+ const result = await loadConfig<Record<string, unknown>>({
41
+ name: 'prisma-next',
42
+ cwd: projectRoot,
43
+ dotenv: false,
44
+ rcFile: false,
45
+ globalRc: false,
46
+ });
47
+ const config = result.config ?? null;
48
+ // c12 returns an empty object when no config file exists in the
49
+ // search path — distinct from "file existed but parsed to an empty
50
+ // object". Either way, the canonical validator below would reject
51
+ // it on the first required field (`family`), so short-circuit
52
+ // without paying the import cost.
53
+ if (config === null || Object.keys(config).length === 0) {
54
+ return EMPTY_PROJECT_CONFIG;
55
+ }
56
+ const validation = await import('@prisma-next/config/config-validation');
57
+ // TS 4.7+ only flows `asserts cfg is X` narrowing when the
58
+ // assertion function is called via a directly-declared name with
59
+ // an explicit signature. The dynamic-import binding doesn't
60
+ // satisfy that, so wrap the call in a local declaration that
61
+ // re-asserts the signature.
62
+ const validate: (cfg: unknown) => asserts cfg is PrismaNextConfig = validation.validateConfig;
63
+ validate(config);
64
+ return {
65
+ databaseTarget: config.target.targetId,
66
+ extensions: (config.extensionPacks ?? []).map((pack) => pack.id),
67
+ };
68
+ } catch {
69
+ return EMPTY_PROJECT_CONFIG;
70
+ }
71
+ }
72
+
6
73
  /**
7
74
  * Versions surface the enrichment cares about. Modelled as a structural
8
75
  * record with a required `node` field so tests can pass a literal object
@@ -100,11 +167,13 @@ function pickStringDep(deps: unknown): string | null {
100
167
  }
101
168
 
102
169
  /**
103
- * Build the full backend event from the parent's payload and the
104
- * child's per-process snapshot. Pure given an `EnrichEnvironment`.
170
+ * Build the full backend event from the parent's payload, the
171
+ * c12-loaded project-config slice, and the child's per-process
172
+ * snapshot. Pure given a `projectConfig` + `EnrichEnvironment`.
105
173
  */
106
174
  export function buildTelemetryEvent(
107
175
  payload: ParentToSenderPayload,
176
+ projectConfig: ProjectConfigFields,
108
177
  env: EnrichEnvironment,
109
178
  ): TelemetryEvent {
110
179
  const runtime = resolveRuntime(env.versions);
@@ -118,20 +187,34 @@ export function buildTelemetryEvent(
118
187
  os: env.platform,
119
188
  arch: env.arch,
120
189
  packageManager: parsePackageManager(env.env['npm_config_user_agent']),
121
- databaseTarget: payload.databaseTarget,
190
+ databaseTarget: projectConfig.databaseTarget,
122
191
  tsVersion: readTsVersionFromPackageJson(env.readProjectPackageJson()),
123
192
  agent: detectAgent(env.env),
124
- extensions: payload.extensions,
193
+ extensions: projectConfig.extensions,
125
194
  };
126
195
  }
127
196
 
128
197
  /**
129
198
  * Convenience for the sender entry: build the event from the live
130
- * `process` plus a real project-package.json reader, swallowing any
131
- * I/O errors in the file read.
199
+ * `process` plus a c12 load of `prisma-next.config.*` from
200
+ * `payload.projectRoot` plus a real project-package.json reader,
201
+ * swallowing any I/O errors in the file read.
202
+ *
203
+ * The parent's `payload.databaseTarget` (when present) wins over the
204
+ * c12-derived value. The parent sets this for the first-`init` run,
205
+ * where the config file does not exist on disk yet but the user has
206
+ * just declared a target via the consent prompt; every other
207
+ * invocation leaves it unset and the c12 load supplies the value.
132
208
  */
133
- export function buildTelemetryEventFromProcess(payload: ParentToSenderPayload): TelemetryEvent {
134
- return buildTelemetryEvent(payload, {
209
+ export async function buildTelemetryEventFromProcess(
210
+ payload: ParentToSenderPayload,
211
+ ): Promise<TelemetryEvent> {
212
+ const loadedConfig = await loadProjectConfig(payload.projectRoot);
213
+ const projectConfig: ProjectConfigFields = {
214
+ databaseTarget: payload.databaseTarget ?? loadedConfig.databaseTarget,
215
+ extensions: loadedConfig.extensions,
216
+ };
217
+ return buildTelemetryEvent(payload, projectConfig, {
135
218
  platform: process.platform,
136
219
  arch: process.arch,
137
220
  versions: process.versions,
@@ -3,6 +3,8 @@ export {
3
3
  TELEMETRY_BACKEND_URL,
4
4
  TELEMETRY_ENDPOINT_PATH,
5
5
  } from '../endpoint';
6
+ export type { ProjectConfigFields } from '../enrich';
7
+ export { loadProjectConfig } from '../enrich';
6
8
  export type { GatingDisabledReason, GatingInputs, GatingResolution } from '../gating';
7
9
  export { resolveGating } from '../gating';
8
10
  export type { ParentToSenderPayload, TelemetryEvent } from '../payload';