@prisma-next/cli-telemetry 0.10.0-dev.8

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,266 @@
1
+ import { fork } from "node:child_process";
2
+ import { fileURLToPath } from "node:url";
3
+ import { randomUUID } from "node:crypto";
4
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
5
+ import { homedir } from "node:os";
6
+ import { dirname, join } from "pathe";
7
+ //#region src/endpoint.ts
8
+ /**
9
+ * Production endpoint pinned to the deployed Prisma Compute backend.
10
+ * Compiled as a build-time constant; not user-configurable.
11
+ */
12
+ const TELEMETRY_BACKEND_URL = "https://cmpbfbsdp09hr3jf7pojjs5qs.ewr.prisma.build";
13
+ /**
14
+ * Path within the backend that accepts telemetry POSTs.
15
+ */
16
+ const TELEMETRY_ENDPOINT_PATH = "/events";
17
+ /**
18
+ * Resolve the full POST URL the sender targets. The
19
+ * `PRISMA_NEXT_TELEMETRY_ENDPOINT` env var is an integration-testing
20
+ * affordance only — it lets the test suite spin up a mock HTTP server
21
+ * on an ephemeral port and point the spawned sender at it. The override
22
+ * is intentionally undocumented in user-facing material.
23
+ *
24
+ * Fail-open: a malformed override (typo in a dev shell, bad CI config)
25
+ * silently falls back to the production backend rather than throwing,
26
+ * matching the telemetry layer's broader silent-on-failure contract.
27
+ */
28
+ function resolveTelemetryEndpoint(env = process.env) {
29
+ const override = env["PRISMA_NEXT_TELEMETRY_ENDPOINT"];
30
+ const base = override !== void 0 && override.length > 0 ? override : TELEMETRY_BACKEND_URL;
31
+ try {
32
+ return new URL(TELEMETRY_ENDPOINT_PATH, base).toString();
33
+ } catch {
34
+ return new URL(TELEMETRY_ENDPOINT_PATH, TELEMETRY_BACKEND_URL).toString();
35
+ }
36
+ }
37
+ //#endregion
38
+ //#region src/gating.ts
39
+ /**
40
+ * A `PRISMA_NEXT_DISABLE_TELEMETRY` value counts as an opt-out only if
41
+ * it parses as a truthy string. The set-but-falsy spellings (`''`,
42
+ * `'0'`, `'false'`) are intentionally treated as not-set so a parent
43
+ * shell that exports the variable to a benign value doesn't accidentally
44
+ * disable telemetry for child processes.
45
+ */
46
+ function isTruthyOptOut(raw) {
47
+ if (raw === void 0) return false;
48
+ const normalised = raw.trim().toLowerCase();
49
+ if (normalised === "") return false;
50
+ if (normalised === "0") return false;
51
+ if (normalised === "false") return false;
52
+ return true;
53
+ }
54
+ /**
55
+ * Pure-function resolution of the gating decision. Same input → same
56
+ * output; no I/O. The caller is responsible for reading the env and the
57
+ * user config.
58
+ *
59
+ * Decision order:
60
+ * 1. Env-var override (`PRISMA_NEXT_DISABLE_TELEMETRY` truthy, or
61
+ * `DO_NOT_TRACK=1`) → disabled.
62
+ * 2. Stored `enableTelemetry === true` → enabled.
63
+ * 3. Stored `enableTelemetry === false` → disabled (`stored-opt-out`).
64
+ * 4. Stored `enableTelemetry === undefined` (file missing, or field
65
+ * not set) → disabled (`default-off`).
66
+ *
67
+ * Telemetry is enabled only when no env override is active **and**
68
+ * `enableTelemetry` is explicitly `true`.
69
+ */
70
+ function resolveGating(inputs) {
71
+ if (isTruthyOptOut(inputs.env["PRISMA_NEXT_DISABLE_TELEMETRY"]) || inputs.env["DO_NOT_TRACK"] === "1") return {
72
+ enabled: false,
73
+ reason: "env-override"
74
+ };
75
+ if (inputs.config.enableTelemetry === true) return { enabled: true };
76
+ if (inputs.config.enableTelemetry === false) return {
77
+ enabled: false,
78
+ reason: "stored-opt-out"
79
+ };
80
+ return {
81
+ enabled: false,
82
+ reason: "default-off"
83
+ };
84
+ }
85
+ //#endregion
86
+ //#region src/sanitize.ts
87
+ function flagNameFromLongName(longName) {
88
+ if (longName === null || !longName.startsWith("--")) return null;
89
+ const withoutPrefix = longName.slice(2);
90
+ return withoutPrefix.length > 0 ? withoutPrefix : null;
91
+ }
92
+ /**
93
+ * Project commander's parsed result into the wire-shape command and
94
+ * flag-name list. Pure; the only allowed inputs are the fields of
95
+ * `CommanderResultShape`.
96
+ *
97
+ * Sanitiser contract — no flag values, no positionals, no raw argv:
98
+ * - Drop the root program name (`commandPath[0]`); the wire ships
99
+ * `migration new`, not `prisma-next migration new`.
100
+ * - Emit only options whose Commander source is `cli`.
101
+ * - Emit the long user-facing flag spelling without the `--` prefix;
102
+ * never emit Commander's camelCase attribute names.
103
+ * - `positionalArgs` is accepted but never consumed; the field exists
104
+ * in the input type to make it obvious at the call site that
105
+ * positionals were deliberately excluded.
106
+ */
107
+ function sanitizeCommanderResult(input) {
108
+ return {
109
+ command: input.commandPath.slice(1).join(" "),
110
+ flags: input.options.flatMap((option) => {
111
+ if (option.source !== "cli") return [];
112
+ const flagName = flagNameFromLongName(option.longName);
113
+ return flagName === null ? [] : [flagName];
114
+ })
115
+ };
116
+ }
117
+ //#endregion
118
+ //#region src/user-config.ts
119
+ const APP_DIR = "prisma-next";
120
+ const FILE_NAME = "config.json";
121
+ /**
122
+ * Resolves the user-level config directory:
123
+ * - Windows: `%APPDATA%\prisma-next\` (fallback: `%USERPROFILE%\AppData\Roaming\prisma-next\`).
124
+ * - Unix (incl. macOS): `$XDG_CONFIG_HOME/prisma-next/` if set, else
125
+ * `$HOME/.config/prisma-next/` per the XDG Base Directory Specification.
126
+ *
127
+ * The spec deliberately picks XDG over the macOS-native
128
+ * `~/Library/Preferences/` convention so the path resolution is
129
+ * test-overridable via `XDG_CONFIG_HOME` and matches the documented
130
+ * behaviour on all *nix platforms. We intentionally do not use
131
+ * `env-paths`: its macOS choice of `~/Library/Preferences` is for
132
+ * OS-managed plist preferences, not arbitrary JSON files. Apple documents
133
+ * that apps access that directory through system APIs such as
134
+ * `NSUserDefaults`, while cross-platform CLI and developer tools conventionally
135
+ * use `~/.config` on macOS too:
136
+ * https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/MacOSXDirectories/MacOSXDirectories.html
137
+ */
138
+ function configDir() {
139
+ if (process.platform === "win32") {
140
+ const appData = process.env["APPDATA"];
141
+ if (appData !== void 0 && appData.length > 0) return join(appData, APP_DIR);
142
+ return join(homedir(), "AppData", "Roaming", APP_DIR);
143
+ }
144
+ const xdg = process.env["XDG_CONFIG_HOME"];
145
+ if (xdg !== void 0 && xdg.length > 0) return join(xdg, APP_DIR);
146
+ return join(homedir(), ".config", APP_DIR);
147
+ }
148
+ /**
149
+ * Path to the user-level config file. Resolved per call so test
150
+ * harnesses can mutate `$XDG_CONFIG_HOME` between cases.
151
+ */
152
+ function userConfigPath() {
153
+ return join(configDir(), FILE_NAME);
154
+ }
155
+ /**
156
+ * Reads the user-level config. File-missing, unreadable, or malformed →
157
+ * `{}` (the absence of consent is the same answer in every error mode).
158
+ * Unknown fields from a future client are passed through verbatim.
159
+ */
160
+ function readUserConfig() {
161
+ const path = userConfigPath();
162
+ if (!existsSync(path)) return {};
163
+ try {
164
+ const raw = readFileSync(path, "utf-8");
165
+ const parsed = JSON.parse(raw);
166
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
167
+ return {};
168
+ } catch {
169
+ return {};
170
+ }
171
+ }
172
+ /**
173
+ * Merges `partial` into the current config and writes the result
174
+ * atomically (temp file + rename) so a crash mid-write never leaves a
175
+ * half-baked file readable on disk. Unknown fields already on disk are
176
+ * preserved.
177
+ *
178
+ * When `partial.enableTelemetry === true` and no `installationId` is
179
+ * stored yet, generates a v4 random UUID and persists both fields in
180
+ * the same write. An existing `installationId` is never rotated.
181
+ *
182
+ * `writeUserConfig({ enableTelemetry: false })` does *not* generate an
183
+ * installation id — only an affirmative consent answer produces one.
184
+ */
185
+ function writeUserConfig(partial) {
186
+ const merged = {
187
+ ...readUserConfig(),
188
+ ...partial
189
+ };
190
+ if (partial.enableTelemetry === true && merged["installationId"] === void 0) merged["installationId"] = randomUUID();
191
+ const path = userConfigPath();
192
+ const dir = dirname(path);
193
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
194
+ const tmpPath = `${path}.${process.pid}.tmp`;
195
+ writeFileSync(tmpPath, `${JSON.stringify(merged, null, 2)}\n`, "utf-8");
196
+ renameSync(tmpPath, path);
197
+ }
198
+ //#endregion
199
+ //#region src/spawn.ts
200
+ function runTelemetry(inputs) {
201
+ const env = inputs.env ?? process.env;
202
+ if (inputs.isCI) return {
203
+ spawned: false,
204
+ reason: "ci"
205
+ };
206
+ const config = inputs.userConfig ?? readUserConfig();
207
+ if (!resolveGating({
208
+ env,
209
+ config
210
+ }).enabled) return {
211
+ spawned: false,
212
+ reason: "gated-off"
213
+ };
214
+ const sanitised = sanitizeCommanderResult(inputs.command);
215
+ if (typeof config.installationId !== "string" || config.installationId.length === 0) return {
216
+ spawned: false,
217
+ reason: "gated-off"
218
+ };
219
+ const payload = {
220
+ installationId: config.installationId,
221
+ version: inputs.version,
222
+ command: sanitised.command,
223
+ flags: sanitised.flags,
224
+ databaseTarget: inputs.databaseTarget,
225
+ extensions: inputs.extensions,
226
+ projectRoot: inputs.projectRoot,
227
+ endpoint: resolveTelemetryEndpoint(env)
228
+ };
229
+ try {
230
+ const child = fork(inputs.senderPath, [], {
231
+ detached: true,
232
+ stdio: [
233
+ "pipe",
234
+ "ignore",
235
+ "ignore",
236
+ "ipc"
237
+ ]
238
+ });
239
+ child.send(payload, (err) => {
240
+ if (err !== null && process.env["PRISMA_NEXT_DEBUG"] === "1") process.stderr.write(`[cli-telemetry] parent send error: ${String(err)}\n`);
241
+ });
242
+ child.disconnect();
243
+ child.unref();
244
+ return { spawned: true };
245
+ } catch (err) {
246
+ if (process.env["PRISMA_NEXT_DEBUG"] === "1") process.stderr.write(`[cli-telemetry] parent fork failed: ${String(err)}\n`);
247
+ return {
248
+ spawned: false,
249
+ reason: "fork-failed"
250
+ };
251
+ }
252
+ }
253
+ /**
254
+ * Resolve the path to the compiled sender entry relative to a consumer
255
+ * that has captured its own `import.meta.url`. The CLI's
256
+ * `tsdown`-emitted entry sits at `<package>/dist/sender.mjs`; the
257
+ * consumer asks `senderModuleUrl()` and forwards the result to
258
+ * `runTelemetry({ senderPath })`.
259
+ */
260
+ function senderModuleUrl(importMetaUrl) {
261
+ return fileURLToPath(new URL("./sender.mjs", importMetaUrl));
262
+ }
263
+ //#endregion
264
+ export { TELEMETRY_BACKEND_URL, TELEMETRY_ENDPOINT_PATH, readUserConfig, resolveGating, resolveTelemetryEndpoint, runTelemetry, sanitizeCommanderResult, senderModuleUrl, userConfigPath, writeUserConfig };
265
+
266
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +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,OAAO;CACnC,OAAO;;;;;;;;;;;;;;;;;;AAmBT,SAAgB,cAAc,QAAwC;CACpE,IACE,eAAe,OAAO,IAAI,iCAAiC,IAC3D,OAAO,IAAI,oBAAoB,KAE/B,OAAO;EAAE,SAAS;EAAO,QAAQ;EAAgB;CAEnD,IAAI,OAAO,OAAO,oBAAoB,MACpC,OAAO,EAAE,SAAS,MAAM;CAE1B,IAAI,OAAO,OAAO,oBAAoB,OACpC,OAAO;EAAE,SAAS;EAAO,QAAQ;EAAkB;CAErD,OAAO;EAAE,SAAS;EAAO,QAAQ;EAAe;;;;ACrBlD,SAAS,qBAAqB,UAAwC;CACpE,IAAI,aAAa,QAAQ,CAAC,SAAS,WAAW,KAAK,EAAE,OAAO;CAC5D,MAAM,gBAAgB,SAAS,MAAM,EAAE;CACvC,OAAO,cAAc,SAAS,IAAI,gBAAgB;;;;;;;;;;;;;;;;;AAkBpD,SAAgB,wBAAwB,OAA+C;CAOrF,OAAO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Q,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"}
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,253 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "pathe";
3
+ 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
+ //#region src/payload.ts
163
+ /**
164
+ * Runtime validator for {@link ParentToSenderPayload}. The child sender
165
+ * uses this to gate `postEvent` so a payload missing a required field
166
+ * cannot silently produce a degraded telemetry event downstream.
167
+ *
168
+ * 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.
173
+ */
174
+ const requiredString = type.string.moreThanLength(0);
175
+ const stringArray = type.string.array();
176
+ const parentToSenderPayloadSchema = type({
177
+ installationId: requiredString,
178
+ version: requiredString,
179
+ command: requiredString,
180
+ flags: stringArray,
181
+ databaseTarget: type.string.or("null"),
182
+ extensions: stringArray,
183
+ projectRoot: requiredString,
184
+ endpoint: requiredString
185
+ });
186
+ function isParentToSenderPayload(value) {
187
+ return !(parentToSenderPayloadSchema(value) instanceof type.errors);
188
+ }
189
+ //#endregion
190
+ //#region src/sender.ts
191
+ /**
192
+ * Sender script entry — forked into a detached child by the parent CLI via
193
+ * `child_process.fork(senderPath, [], { detached: true, ... })`.
194
+ *
195
+ * Lifecycle:
196
+ * 1. Wait for the parent's IPC `message` event carrying a
197
+ * `ParentToSenderPayload`.
198
+ * 2. Enrich with the local-process probes (runtime, os, arch, agent,
199
+ * package manager, tsVersion).
200
+ * 3. POST the event to the endpoint URL with a hard 1.5 s timeout.
201
+ * 4. Exit 0 unconditionally — successful POST, network failure, server
202
+ * error, parse error of the response, anything else: same outcome.
203
+ *
204
+ * Every error is swallowed; the only escape valve for visibility is
205
+ * `PRISMA_NEXT_DEBUG=1`, which routes diagnostics to stderr. In normal
206
+ * operation no telemetry-originating output ever reaches the user — the
207
+ * parent's stdio map ignores our streams anyway, but we also gate
208
+ * stderr writes behind the debug flag so the same binary is safe to
209
+ * invoke directly outside the spawn flow.
210
+ */
211
+ const REQUEST_TIMEOUT_MS = 1500;
212
+ function debugLog(message, error) {
213
+ if (process.env["PRISMA_NEXT_DEBUG"] !== "1") return;
214
+ if (error !== void 0) process.stderr.write(`[cli-telemetry] ${message}: ${String(error)}\n`);
215
+ else process.stderr.write(`[cli-telemetry] ${message}\n`);
216
+ }
217
+ async function postEvent(payload) {
218
+ const event = buildTelemetryEventFromProcess(payload);
219
+ const controller = new AbortController();
220
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
221
+ try {
222
+ debugLog(`sent event: status=${(await fetch(payload.endpoint, {
223
+ method: "POST",
224
+ headers: { "content-type": "application/json" },
225
+ body: JSON.stringify(event),
226
+ signal: controller.signal
227
+ })).status}`);
228
+ } catch (err) {
229
+ debugLog("send failed", err);
230
+ } finally {
231
+ clearTimeout(timer);
232
+ }
233
+ }
234
+ function exitClean() {
235
+ try {
236
+ process.disconnect?.();
237
+ } catch {}
238
+ process.exit(0);
239
+ }
240
+ process.once("message", (message) => {
241
+ if (!isParentToSenderPayload(message)) {
242
+ debugLog("received malformed payload; exiting");
243
+ exitClean();
244
+ return;
245
+ }
246
+ postEvent(message).catch((err) => debugLog("post threw", err)).finally(exitClean);
247
+ });
248
+ const SENDER_IDLE_EXIT_MS = REQUEST_TIMEOUT_MS * 2;
249
+ setTimeout(exitClean, SENDER_IDLE_EXIT_MS).unref();
250
+ //#endregion
251
+ export {};
252
+
253
+ //# sourceMappingURL=sender.mjs.map
@@ -0,0 +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;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client for Prisma Next: detached subprocess sender, gating resolution, user-config store, and consent surface",
8
+ "files": [
9
+ "dist",
10
+ "src"
11
+ ],
12
+ "dependencies": {
13
+ "arktype": "^2.2.0",
14
+ "pathe": "^2.0.3"
15
+ },
16
+ "devDependencies": {
17
+ "@prisma-next/test-utils": "0.10.0-dev.8",
18
+ "@prisma-next/tsconfig": "0.10.0-dev.8",
19
+ "@prisma-next/tsdown": "0.10.0-dev.8",
20
+ "@types/node": "24.10.4",
21
+ "tsdown": "0.22.0",
22
+ "typescript": "5.9.3",
23
+ "vitest": "4.1.6"
24
+ },
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/exports/index.d.mts",
28
+ "import": "./dist/exports/index.mjs"
29
+ },
30
+ "./sender": {
31
+ "types": "./dist/sender.d.mts",
32
+ "import": "./dist/sender.mjs"
33
+ }
34
+ },
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "https://github.com/prisma/prisma-next.git",
38
+ "directory": "packages/1-framework/3-tooling/cli-telemetry"
39
+ },
40
+ "scripts": {
41
+ "build": "tsdown",
42
+ "test": "vitest run",
43
+ "test:coverage": "vitest run --coverage",
44
+ "typecheck": "tsc --project tsconfig.json --noEmit",
45
+ "lint": "biome check . --error-on-warnings",
46
+ "lint:fix": "biome check --write .",
47
+ "lint:fix:unsafe": "biome check --write --unsafe .",
48
+ "clean": "rm -rf dist dist-tsc dist-tsc-prod coverage .tmp-output"
49
+ }
50
+ }