react-doctor 0.2.15-dev.01ec05c → 0.2.15-dev.17e722e

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.
package/README.md CHANGED
@@ -96,14 +96,14 @@ Prefer JSON? Use `doctor.config.json`:
96
96
 
97
97
  ## Telemetry
98
98
 
99
- The CLI reports crashes and basic run traces to [Sentry](https://sentry.io) to help us fix bugs. Events include the version, platform, Node version, how the CLI was invoked (which command, package manager, and whether it ran locally vs. CI vs. a coding agent), the detected project shape (framework, React version, TypeScript, project size — never the contents of your files), and de-minified stack traces.
99
+ The CLI reports crashes, basic run traces, and anonymous usage counters to [Sentry](https://sentry.io) to help us fix bugs and prioritize what to build. Events and metrics include the version, platform, Node version, how the CLI was invoked (which command, package manager, and whether it ran locally vs. CI vs. a coding agent), the detected project shape (framework, React version, TypeScript, project size — never the contents of your files), which rules fired (rule names only, e.g. `react-doctor/no-array-index-as-key`, with counts — never your code or specific findings), and de-minified stack traces.
100
100
 
101
101
  Telemetry is **anonymized** before it leaves your machine: no IP address is collected, your hostname and machine name are stripped, your OS username is removed from every path (your home directory is replaced with `~`), captured local variables are dropped, and known secrets/API keys/emails are masked. No source code or diagnostic findings are sent.
102
102
 
103
103
  Opt out at any time:
104
104
 
105
- - `npx react-doctor@latest --no-telemetry` disables Sentry entirely (crash reporting and tracing) for that run, alongside the hosted score API.
106
- - `SENTRY_TRACES_SAMPLE_RATE=0` keeps crash reporting but turns off performance tracing.
105
+ - `npx react-doctor@latest --no-telemetry` disables Sentry entirely (crash reporting, tracing, and usage counters) for that run, alongside the hosted score API.
106
+ - `SENTRY_TRACES_SAMPLE_RATE=0` keeps crash reporting and usage counters but turns off performance tracing.
107
107
 
108
108
  ## Contributing
109
109
 
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="540e80ff-13a0-5cd7-8313-53bd820f256d")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="bd9bed01-711f-553b-b228-212598cc6e87")}catch(e){}}();
3
3
  import { createRequire } from "node:module";
4
4
  import { execFileSync, spawn, spawnSync } from "node:child_process";
5
5
  import * as Path from "node:path";
@@ -7254,15 +7254,6 @@ const formatReactDoctorError = (error) => error.reason.message;
7254
7254
  const isSplittableReactDoctorError = (error) => error instanceof ReactDoctorError && error.reason._tag === "OxlintBatchExceeded";
7255
7255
  const isReactDoctorError = (error) => error instanceof ReactDoctorError;
7256
7256
  /**
7257
- * Diff-base failures stem from the caller's `--diff` argument or local
7258
- * git state — a malformed ref/range, or a base branch that simply hasn't
7259
- * been fetched — not from a bug in react-doctor. The CLI renders these
7260
- * as a plain message and exits non-zero WITHOUT capturing them to Sentry
7261
- * or pointing the user at a bug report: they're expected, user-actionable
7262
- * conditions, not crashes to triage.
7263
- */
7264
- const isUserInputError = (error) => error instanceof ReactDoctorError && (error.reason._tag === "GitBaseBranchInvalid" || error.reason._tag === "GitBaseBranchMissing");
7265
- /**
7266
7257
  * Tagged-reason → legacy thrown-class boundary shared by every public
7267
7258
  * shell (`inspect()` in `react-doctor`, `diagnose()` in `@react-doctor/api`).
7268
7259
  *
@@ -8984,11 +8975,6 @@ const trimOrNull = (value) => {
8984
8975
  * `@{` reflog suffix, or any character outside `[A-Za-z0-9_./-]`.
8985
8976
  */
8986
8977
  const SAFE_GIT_REVISION_PATTERN = /^[A-Za-z0-9_./-]+$/;
8987
- /** Human-readable summary of the `isSafeGitRevision` contract, reused across error details. */
8988
- const GIT_REF_NAME_RULE = "must match [A-Za-z0-9_./-] without leading '-', '..', or '@{'";
8989
- /** git's two range operators: two-dot (direct) and three-dot (merge-base). */
8990
- const DIFF_RANGE_OPERATOR = "..";
8991
- const SYMMETRIC_DIFF_RANGE_OPERATOR = "...";
8992
8978
  const isSafeGitRevision = (candidate) => {
8993
8979
  if (candidate.length === 0) return false;
8994
8980
  if (candidate.startsWith("-")) return false;
@@ -8996,31 +8982,6 @@ const isSafeGitRevision = (candidate) => {
8996
8982
  if (candidate.includes("..") || candidate.includes("@{")) return false;
8997
8983
  return SAFE_GIT_REVISION_PATTERN.test(candidate);
8998
8984
  };
8999
- /**
9000
- * Splits a git revision range into its endpoints: three-dot `A...B`
9001
- * (symmetric, merge-base) or two-dot `A..B` (direct). Returns `null`
9002
- * when `value` carries no range operator so the caller falls back to
9003
- * single-base resolution.
9004
- *
9005
- * Only the first operator is split on; any leftover `..` stays inside an
9006
- * endpoint so `isSafeGitRevision` rejects malformed input like
9007
- * `A..B..C` instead of silently guessing which pair the user meant.
9008
- */
9009
- const parseGitDiffRange = (value) => {
9010
- const symmetricIndex = value.indexOf(SYMMETRIC_DIFF_RANGE_OPERATOR);
9011
- if (symmetricIndex !== -1) return {
9012
- base: value.slice(0, symmetricIndex),
9013
- head: value.slice(symmetricIndex + 3),
9014
- symmetric: true
9015
- };
9016
- const rangeIndex = value.indexOf(DIFF_RANGE_OPERATOR);
9017
- if (rangeIndex !== -1) return {
9018
- base: value.slice(0, rangeIndex),
9019
- head: value.slice(rangeIndex + 2),
9020
- symmetric: false
9021
- };
9022
- return null;
9023
- };
9024
8985
  const parseGithubRepoFromRemoteUrl = (remoteUrl) => {
9025
8986
  const withoutGitSuffix = remoteUrl.trim().replace(/\.git$/, "");
9026
8987
  const sshMatch = /^git@github\.com:([^/\s]+)\/([^/\s]+)$/.exec(withoutGitSuffix);
@@ -9172,49 +9133,6 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
9172
9133
  if (result.status !== 0) return null;
9173
9134
  return parseGithubViewerPermission(result.stdout);
9174
9135
  }).pipe(Effect.catch(() => Effect.succeed(null)));
9175
- /**
9176
- * Resolves a `--diff A..B` / `A...B` commit range into a changed-file
9177
- * selection. Each endpoint is validated with `isSafeGitRevision`
9178
- * BEFORE it reaches `git` (so the range syntax can't smuggle a
9179
- * `--upload-pack=…`-style option past the CVE-2018-17456 guard) and
9180
- * verified to exist, then the diff runs between the two commits with
9181
- * the same `--diff-filter=ACMR` shape the single-base path uses.
9182
- */
9183
- const resolveDiffRange = (input) => Effect.gen(function* () {
9184
- if (input.range.base.length === 0 && input.range.head.length === 0) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: `Diff range "${input.raw}" must name at least one commit (e.g. "main..feature").` }) }));
9185
- const baseRef = input.range.base.length === 0 ? "HEAD" : input.range.base;
9186
- const headRef = input.range.head.length === 0 ? "HEAD" : input.range.head;
9187
- for (const endpoint of [baseRef, headRef]) if (!isSafeGitRevision(endpoint)) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: `Diff range "${input.raw}" has an invalid endpoint "${endpoint}" (${GIT_REF_NAME_RULE}).` }) }));
9188
- for (const endpoint of [baseRef, headRef]) if (!(yield* branchExists(input.directory, endpoint))) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchMissing({ branch: endpoint }) }));
9189
- let diffBaseRef = baseRef;
9190
- if (input.range.symmetric) {
9191
- const mergeBase = yield* runGit(input.directory, [
9192
- "merge-base",
9193
- baseRef,
9194
- headRef
9195
- ]);
9196
- if (mergeBase.status !== 0) return null;
9197
- const mergeBaseRef = trimOrNull(mergeBase.stdout);
9198
- if (mergeBaseRef === null) return null;
9199
- diffBaseRef = mergeBaseRef;
9200
- }
9201
- const diff = yield* runGit(input.directory, [
9202
- "diff",
9203
- "-z",
9204
- "--name-only",
9205
- "--diff-filter=ACMR",
9206
- "--relative",
9207
- diffBaseRef,
9208
- headRef
9209
- ]);
9210
- if (diff.status !== 0) return null;
9211
- return {
9212
- currentBranch: headRef,
9213
- baseBranch: baseRef,
9214
- changedFiles: splitNullSeparated(diff.stdout),
9215
- isCurrentChanges: false
9216
- };
9217
- });
9218
9136
  return Git.of({
9219
9137
  currentBranch,
9220
9138
  defaultBranch,
@@ -9224,15 +9142,7 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
9224
9142
  branchExists,
9225
9143
  diffSelection: ({ directory, explicitBaseBranch }) => Effect.gen(function* () {
9226
9144
  if (explicitBaseBranch !== void 0 && explicitBaseBranch.trim().length === 0) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: "Diff base branch cannot be empty." }) }));
9227
- if (explicitBaseBranch !== void 0) {
9228
- const range = parseGitDiffRange(explicitBaseBranch);
9229
- if (range !== null) return yield* resolveDiffRange({
9230
- directory,
9231
- range,
9232
- raw: explicitBaseBranch
9233
- });
9234
- if (!isSafeGitRevision(explicitBaseBranch)) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: `Diff base branch "${explicitBaseBranch}" is not a valid git ref name (${GIT_REF_NAME_RULE}).` }) }));
9235
- }
9145
+ if (explicitBaseBranch !== void 0 && !isSafeGitRevision(explicitBaseBranch)) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: `Diff base branch "${explicitBaseBranch}" is not a valid git ref name (must match [A-Za-z0-9_./-] without leading '-', '..', or '@{').` }) }));
9236
9146
  const resolvedCurrentBranch = yield* currentBranch(directory);
9237
9147
  if (resolvedCurrentBranch === null && explicitBaseBranch === void 0) return null;
9238
9148
  const baseBranch = explicitBaseBranch ?? (yield* defaultBranch(directory));
@@ -11614,13 +11524,12 @@ const buildSkippedChecks = (input) => {
11614
11524
  * Git service runs through Effect's `ChildProcess` (true subprocess
11615
11525
  * spawn, not `spawnSync`).
11616
11526
  *
11617
- * Failures propagate as the tagged `ReactDoctorError` (rejected by
11618
- * `Effect.runPromise`) rather than being flattened into a plain
11619
- * `Error`. The message is unchanged — `ReactDoctorError.message`
11620
- * defers to `reason.message` — so message-matching callers keep
11621
- * working, while the CLI can now dispatch on `error.reason._tag` to
11622
- * render diff-base mistakes (`GitBaseBranchInvalid` /
11623
- * `GitBaseBranchMissing`) as clean user errors instead of crashes.
11527
+ * Tagged-reason errors are dispatched via `Effect.catchReasons`
11528
+ * (a v4-native API for narrowing inside a `Schema.TaggedErrorClass`
11529
+ * union without manual `instanceof` checks). The recovered branches
11530
+ * raise plain `Error`s so existing thrown-class consumers continue
11531
+ * to work — anything else (real `GitInvocationFailed`, etc.)
11532
+ * propagates as the tagged `ReactDoctorError` through `Effect.runPromise`.
11624
11533
  */
11625
11534
  const getDiffInfo = (directory, explicitBaseBranch) => Effect.runPromise(Effect.gen(function* () {
11626
11535
  const selection = yield* (yield* Git).diffSelection({
@@ -11634,7 +11543,10 @@ const getDiffInfo = (directory, explicitBaseBranch) => Effect.runPromise(Effect.
11634
11543
  changedFiles: [...selection.changedFiles],
11635
11544
  ...selection.isCurrentChanges ? { isCurrentChanges: true } : {}
11636
11545
  };
11637
- }).pipe(Effect.provide(Git.layerNode)));
11546
+ }).pipe(Effect.provide(Git.layerNode), Effect.catchReasons("ReactDoctorError", {
11547
+ GitBaseBranchInvalid: (reason) => Effect.die(new Error(reason.detail)),
11548
+ GitBaseBranchMissing: (reason) => Effect.die(new Error(reason.message))
11549
+ })));
11638
11550
  const filterSourceFiles = (filePaths) => filePaths.filter(isLintableSourceFile);
11639
11551
  var import_picocolors = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
11640
11552
  let p = process || {}, argv = p.argv || [], env = p.env || {};
@@ -11848,6 +11760,33 @@ const STAGED_FILES_TEMP_DIR_PREFIX = "react-doctor-staged-";
11848
11760
  const INTERNAL_ERROR_JSON_FALLBACK = "{\"schemaVersion\":1,\"ok\":false,\"error\":{\"message\":\"Internal error\",\"name\":\"Error\",\"chain\":[]}}\n";
11849
11761
  const SENTRY_FLUSH_TIMEOUT_MS = 2e3;
11850
11762
  const NANOSECONDS_PER_SECOND = 1000000000n;
11763
+ const METRIC = {
11764
+ cliInvoked: "cli.invoked",
11765
+ cliError: "cli.error",
11766
+ projectDetected: "project.detected",
11767
+ scanCompleted: "scan.completed",
11768
+ scanDuration: "scan.duration",
11769
+ scanPhaseDuration: "scan.phase_duration",
11770
+ scanFiles: "scan.files",
11771
+ scanScore: "scan.score",
11772
+ scanClean: "scan.clean",
11773
+ scanCheckSkipped: "scan.check_skipped",
11774
+ ruleFired: "rule.fired",
11775
+ lintFailed: "lint.failed",
11776
+ deadCodeFailed: "deadcode.failed",
11777
+ scoreUnavailable: "score.unavailable",
11778
+ oxlintWorkers: "oxlint.workers",
11779
+ agentHandoff: "agent.handoff",
11780
+ agentInstallHintShown: "agent.install_hint_shown",
11781
+ installCompleted: "install.completed",
11782
+ installAgent: "install.agent",
11783
+ installGitHook: "install.git_hook",
11784
+ installWorkflow: "install.workflow",
11785
+ installAgentHooks: "install.agent_hooks",
11786
+ installDependency: "install.dependency",
11787
+ rulesChanged: "rules.changed",
11788
+ rulesQueried: "rules.queried"
11789
+ };
11851
11790
  //#endregion
11852
11791
  //#region src/cli/utils/noop-console.ts
11853
11792
  /**
@@ -11889,7 +11828,7 @@ const makeNoopConsole = () => ({
11889
11828
  });
11890
11829
  //#endregion
11891
11830
  //#region src/cli/utils/version.ts
11892
- const VERSION = "0.2.15-dev.01ec05c";
11831
+ const VERSION = "0.2.15-dev.17e722e";
11893
11832
  //#endregion
11894
11833
  //#region src/cli/utils/json-mode.ts
11895
11834
  let context = null;
@@ -12113,13 +12052,20 @@ const buildSentryScope = (runContext = buildRunContext()) => {
12113
12052
  };
12114
12053
  };
12115
12054
  //#endregion
12116
- //#region src/cli/utils/scrub-sentry-event.ts
12055
+ //#region src/cli/utils/anonymize-text.ts
12056
+ /**
12057
+ * Free-text fields can carry both a home-directory path (the OS username) and a
12058
+ * secret/email echoed from user code, so run both scrubbers: strip the username
12059
+ * from paths, then mask any known credential/PII shape. Shared by the Sentry
12060
+ * event scrubber ({@link scrubSentryEvent}) and metric scrubber
12061
+ * ({@link scrubSentryMetric}).
12062
+ */
12117
12063
  const anonymizeText = (text) => redactSensitiveText(scrubSensitivePaths(text));
12118
12064
  /**
12119
12065
  * Recursively rewrites every string within an arbitrary value (object / array /
12120
12066
  * primitive) through {@link anonymizeText}, mutating in place. Used to sweep the
12121
- * unstructured corners of an event (contexts, extra, tags, breadcrumb data,
12122
- * span attributes) where a path or secret could hide.
12067
+ * unstructured corners of a Sentry payload (event contexts/extra/tags, breadcrumb
12068
+ * data, span attributes, metric attributes) where a path or secret could hide.
12123
12069
  */
12124
12070
  const anonymizeInPlace = (value) => {
12125
12071
  if (Array.isArray(value)) {
@@ -12137,6 +12083,8 @@ const anonymizeInPlace = (value) => {
12137
12083
  else anonymizeInPlace(inner);
12138
12084
  }
12139
12085
  };
12086
+ //#endregion
12087
+ //#region src/cli/utils/scrub-sentry-event.ts
12140
12088
  /**
12141
12089
  * Anonymizes a Sentry event (error or transaction) before it leaves the
12142
12090
  * machine. Strips identity the SDK attaches automatically — the IP-bearing
@@ -12184,6 +12132,27 @@ const scrubSentryEvent = (event) => {
12184
12132
  }
12185
12133
  };
12186
12134
  //#endregion
12135
+ //#region src/cli/utils/scrub-sentry-metric.ts
12136
+ /**
12137
+ * Anonymizes a Sentry metric before it leaves the machine, mirroring
12138
+ * {@link scrubSentryEvent}. Drops the `server.address` default attribute (the
12139
+ * hostname) and scrubs home-directory paths + known secrets/emails from every
12140
+ * remaining attribute value (metric names are our own constants, so they're
12141
+ * left intact to avoid splitting a series). Returns `null` on any failure so an
12142
+ * un-anonymized metric is never sent. Wired into `beforeSendMetric`.
12143
+ */
12144
+ const scrubSentryMetric = (metric) => {
12145
+ try {
12146
+ if (metric.attributes) {
12147
+ delete metric.attributes["server.address"];
12148
+ anonymizeInPlace(metric.attributes);
12149
+ }
12150
+ return metric;
12151
+ } catch {
12152
+ return null;
12153
+ }
12154
+ };
12155
+ //#endregion
12187
12156
  //#region src/instrument.ts
12188
12157
  let isInitialized = false;
12189
12158
  let resolvedTracesSampleRate = 0;
@@ -12205,13 +12174,13 @@ const isDevVersion = (version) => version === "0.0.0" || version.includes("-");
12205
12174
  * uploads source-map artifacts under, so stack frames symbolicate. Honors the
12206
12175
  * standard `SENTRY_RELEASE` override.
12207
12176
  */
12208
- const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.2.15-dev.01ec05c`;
12177
+ const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.2.15-dev.17e722e`;
12209
12178
  /**
12210
12179
  * Deployment environment shown in Sentry's environment filter. Defaults to
12211
12180
  * `production` for tagged releases and `development` for dev/unbuilt versions,
12212
12181
  * overridable via the standard `SENTRY_ENVIRONMENT` env var.
12213
12182
  */
12214
- const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.2.15-dev.01ec05c") ? "development" : "production");
12183
+ const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.2.15-dev.17e722e") ? "development" : "production");
12215
12184
  /**
12216
12185
  * Performance-tracing sample rate in `[0, 1]`. Reads `SENTRY_TRACES_SAMPLE_RATE`
12217
12186
  * (set to `0` to disable tracing) and falls back to
@@ -12279,7 +12248,8 @@ const initializeSentry = () => {
12279
12248
  contexts
12280
12249
  },
12281
12250
  beforeSend: (event) => scrubSentryEvent(event),
12282
- beforeSendTransaction: (event) => scrubSentryEvent(event)
12251
+ beforeSendTransaction: (event) => scrubSentryEvent(event),
12252
+ beforeSendMetric: (metric) => scrubSentryMetric(metric)
12283
12253
  });
12284
12254
  };
12285
12255
  //#endregion
@@ -15551,6 +15521,122 @@ const recordSentryProjectContext = (projectInfo, rootSpan) => {
15551
15521
  rootSpan?.setAttributes(toSpanAttributes(buildSentryProjectContext(projectInfo).tags));
15552
15522
  };
15553
15523
  //#endregion
15524
+ //#region src/cli/utils/record-metric.ts
15525
+ const cleanAttributes = (attributes) => {
15526
+ const cleaned = {};
15527
+ if (!attributes) return cleaned;
15528
+ for (const [key, value] of Object.entries(attributes)) if (value !== null && value !== void 0) cleaned[key] = value;
15529
+ return cleaned;
15530
+ };
15531
+ const withRunAttributes = (attributes) => ({
15532
+ ...toSpanAttributes(buildSentryScope().tags),
15533
+ ...cleanAttributes(attributes)
15534
+ });
15535
+ /**
15536
+ * Emits a Sentry counter. A guarded, swallow-on-throw no-op unless the CLI's
15537
+ * Sentry SDK is live, so it's inert under `--no-score`, tests, and the
15538
+ * programmatic `@react-doctor/api` library (none of which initialize Sentry).
15539
+ * Metrics flow independently of performance tracing, so counters are still
15540
+ * recorded when `SENTRY_TRACES_SAMPLE_RATE=0`.
15541
+ */
15542
+ const recordCount = (name, value = 1, attributes) => {
15543
+ if (!Sentry.isInitialized()) return;
15544
+ try {
15545
+ Sentry.metrics.count(name, value, { attributes: withRunAttributes(attributes) });
15546
+ } catch {}
15547
+ };
15548
+ /**
15549
+ * Emits a Sentry distribution (value ranges — durations, sizes, scores). Same
15550
+ * gating and run-attribute handling as {@link recordCount}.
15551
+ */
15552
+ const recordDistribution = (name, value, options = {}) => {
15553
+ if (!Sentry.isInitialized()) return;
15554
+ try {
15555
+ Sentry.metrics.distribution(name, value, {
15556
+ unit: options.unit,
15557
+ attributes: withRunAttributes(options.attributes)
15558
+ });
15559
+ } catch {}
15560
+ };
15561
+ //#endregion
15562
+ //#region src/cli/utils/record-scan-metrics.ts
15563
+ /**
15564
+ * Aggregates diagnostics into per-`(rule, severity)` firing counts, reusing the
15565
+ * canonical `getDiagnosticRuleIdentity` so the `<plugin>/<rule>` key and
15566
+ * category match every other rule-keyed surface. Pure and exported so the
15567
+ * bucketing is unit-testable without an active Sentry client (the emit helpers
15568
+ * no-op under tests). Grouping the emitted `rule.fired` counter by `category`
15569
+ * or `severity` in Sentry reproduces a coarser breakdown.
15570
+ */
15571
+ const summarizeRuleFirings = (diagnostics) => {
15572
+ const firings = /* @__PURE__ */ new Map();
15573
+ for (const diagnostic of diagnostics) {
15574
+ const { ruleKey, category } = getDiagnosticRuleIdentity(diagnostic);
15575
+ const firingKey = `${ruleKey}\u0000${diagnostic.severity}`;
15576
+ const existing = firings.get(firingKey);
15577
+ firings.set(firingKey, existing ? {
15578
+ ...existing,
15579
+ count: existing.count + 1
15580
+ } : {
15581
+ rule: ruleKey,
15582
+ plugin: diagnostic.plugin,
15583
+ category,
15584
+ severity: diagnostic.severity,
15585
+ count: 1
15586
+ });
15587
+ }
15588
+ return [...firings.values()];
15589
+ };
15590
+ /**
15591
+ * Emits the per-scan engineering + product counters/distributions for one
15592
+ * `inspect()` run (fires once per project in a workspace scan). Every emission
15593
+ * is a no-op unless Sentry is live, and the shared run/project attributes ride
15594
+ * along from the global scope, so call sites only pass scan-specific dimensions.
15595
+ */
15596
+ const recordScanMetrics = (input) => {
15597
+ const { result } = input;
15598
+ const hasSkippedChecks = result.skippedChecks.length > 0;
15599
+ recordCount(METRIC.scanCompleted, 1, {
15600
+ mode: input.mode,
15601
+ lint: input.lint,
15602
+ deadCode: input.deadCode,
15603
+ parallel: input.parallel,
15604
+ scoreOnly: input.scoreOnly,
15605
+ didLintFail: input.didLintFail,
15606
+ didDeadCodeFail: input.didDeadCodeFail,
15607
+ hasSkippedChecks
15608
+ });
15609
+ recordDistribution(METRIC.scanDuration, result.elapsedMilliseconds, {
15610
+ unit: "millisecond",
15611
+ attributes: {
15612
+ mode: input.mode,
15613
+ parallel: input.parallel,
15614
+ scoreOnly: input.scoreOnly
15615
+ }
15616
+ });
15617
+ if (result.scanElapsedMilliseconds !== void 0) recordDistribution(METRIC.scanPhaseDuration, result.scanElapsedMilliseconds, {
15618
+ unit: "millisecond",
15619
+ attributes: { mode: input.mode }
15620
+ });
15621
+ if (result.scannedFileCount !== void 0) recordDistribution(METRIC.scanFiles, result.scannedFileCount, { attributes: { mode: input.mode } });
15622
+ if (input.workerCount !== void 0) recordDistribution(METRIC.oxlintWorkers, input.workerCount, { attributes: { mode: input.mode } });
15623
+ for (const firing of summarizeRuleFirings(result.diagnostics)) recordCount(METRIC.ruleFired, firing.count, {
15624
+ rule: firing.rule,
15625
+ plugin: firing.plugin,
15626
+ category: firing.category,
15627
+ severity: firing.severity
15628
+ });
15629
+ if (result.diagnostics.length === 0 && !hasSkippedChecks) recordCount(METRIC.scanClean, 1, { mode: input.mode });
15630
+ if (result.score) recordDistribution(METRIC.scanScore, result.score.score, { attributes: { mode: input.mode } });
15631
+ else if (!input.noScore && !input.didLintFail) recordCount(METRIC.scoreUnavailable, 1, { mode: input.mode });
15632
+ if (input.didLintFail) recordCount(METRIC.lintFailed, 1, { reasonKind: input.lintFailureReasonKind });
15633
+ if (input.didDeadCodeFail) recordCount(METRIC.deadCodeFailed, 1);
15634
+ for (const check of result.skippedChecks) recordCount(METRIC.scanCheckSkipped, 1, {
15635
+ check,
15636
+ reason: result.skippedCheckReasons?.[check] ?? null
15637
+ });
15638
+ };
15639
+ //#endregion
15554
15640
  //#region src/cli/utils/build-no-score-message.ts
15555
15641
  const ENTERPRISE_CONTACT_HINT = `Want something custom to your company? Contact us at ${ENTERPRISE_CONTACT_URL}.`;
15556
15642
  const buildNoScoreMessage = (isScoreDisabled) => {
@@ -16458,6 +16544,7 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
16458
16544
  suppressScanSummary: options.suppressRendering
16459
16545
  }, { beforeLint: (projectInfo, lintIncludePaths) => Effect.gen(function* () {
16460
16546
  recordSentryProjectContext(projectInfo, rootSentrySpan);
16547
+ recordCount(METRIC.projectDetected, 1);
16461
16548
  if (options.scoreOnly || options.suppressRendering) return;
16462
16549
  const lintSourceFileCount = lintIncludePaths?.length ?? projectInfo.sourceFileCount;
16463
16550
  yield* printProjectDetection({
@@ -16493,7 +16580,21 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
16493
16580
  scannedFilePaths: output.scannedFilePaths,
16494
16581
  scanElapsedMilliseconds: output.scanElapsedMilliseconds
16495
16582
  };
16496
- return await Effect.runPromise(finalizeAndRender(finalizeInput).pipe(options.silent ? Effect.provideService(Console.Console, silentConsole) : (program) => program));
16583
+ const result = await Effect.runPromise(finalizeAndRender(finalizeInput).pipe(options.silent ? Effect.provideService(Console.Console, silentConsole) : (program) => program));
16584
+ recordScanMetrics({
16585
+ result,
16586
+ mode: isDiffMode ? "diff" : "full",
16587
+ parallel: options.concurrency !== void 0,
16588
+ workerCount: options.concurrency,
16589
+ lint: options.lint,
16590
+ deadCode: options.deadCode,
16591
+ scoreOnly: options.scoreOnly,
16592
+ noScore: options.noScore,
16593
+ didLintFail,
16594
+ lintFailureReasonKind: lintBindingMissing ? "native-binding-missing" : output.lintFailureReasonKind,
16595
+ didDeadCodeFail: output.didDeadCodeFail
16596
+ });
16597
+ return result;
16497
16598
  };
16498
16599
  const finalizeAndRender = (input) => Effect.gen(function* () {
16499
16600
  const { options, elapsedMilliseconds, diagnostics, score, project, userConfig, didLintFail, lintFailureReason, lintPartialFailures, didDeadCodeFail, deadCodeFailureReason, directory, scannedFileCount, scannedFilePaths, scanElapsedMilliseconds } = input;
@@ -16677,21 +16778,6 @@ const handleError = (error, options = {}) => {
16677
16778
  if (options.shouldExit !== false) process.exit(1);
16678
16779
  process.exitCode = 1;
16679
16780
  };
16680
- /**
16681
- * Renderer for expected, user-actionable failures (see `isUserInputError`):
16682
- * a bad `--diff` value or a base branch that isn't fetched. Prints just the
16683
- * (already human-readable) message — no "Something went wrong", prefilled
16684
- * issue, Discord link, or Sentry reference — because there is no bug to report.
16685
- */
16686
- const handleUserError = (error, options = {}) => {
16687
- Effect.runSync(Effect.gen(function* () {
16688
- yield* Console.error("");
16689
- yield* Console.error(highlighter.error(formatErrorForReport(error)));
16690
- yield* Console.error("");
16691
- }));
16692
- if (options.shouldExit !== false) process.exit(1);
16693
- process.exitCode = 1;
16694
- };
16695
16781
  //#endregion
16696
16782
  //#region src/cli/utils/build-handoff-payload.ts
16697
16783
  const buildHandoffPayload = (input) => {
@@ -17700,11 +17786,17 @@ const installReactDoctorPackageSetup = async (projectRoot, dependencyRunner) =>
17700
17786
  projectRoot,
17701
17787
  runner: dependencyRunner
17702
17788
  });
17789
+ recordCount(METRIC.installDependency, 1, {
17790
+ status: dependencyResult.dependencyStatus,
17791
+ reason: dependencyResult.dependencyReason ?? null,
17792
+ packageManager: detectPackageManager(projectRoot)
17793
+ });
17703
17794
  if (dependencyResult.dependencyStatus === "skipped") {
17704
17795
  dependencySpinner.fail(formatDependencyInstallMessage(dependencyResult));
17705
- return;
17796
+ return dependencyResult;
17706
17797
  }
17707
17798
  dependencySpinner.succeed(formatDependencyInstallMessage(dependencyResult));
17799
+ return dependencyResult;
17708
17800
  } catch (error) {
17709
17801
  dependencySpinner.fail("Failed to install React Doctor package.");
17710
17802
  throw error;
@@ -17872,7 +17964,7 @@ const runInstallReactDoctor = async (options = {}) => {
17872
17964
  } catch {
17873
17965
  cliLogger.dim(" Skipped bundled sibling skills (install error).");
17874
17966
  }
17875
- await installReactDoctorPackageSetup(projectRoot, options.installDependencyRunner);
17967
+ const dependencyResult = await installReactDoctorPackageSetup(projectRoot, options.installDependencyRunner);
17876
17968
  if (shouldInstallGitHook && gitHookTarget !== null && gitHookTarget !== void 0) {
17877
17969
  const hookSpinner = spinner("Installing React Doctor pre-commit hook...").start();
17878
17970
  try {
@@ -17883,6 +17975,7 @@ const runInstallReactDoctor = async (options = {}) => {
17883
17975
  hooksPathConfig: gitHookTarget.hooksPathConfig
17884
17976
  });
17885
17977
  hookSpinner.succeed(formatGitHookInstallMessage(hookResult));
17978
+ recordCount(METRIC.installGitHook, 1, { kind: hookResult.kind });
17886
17979
  } catch (error) {
17887
17980
  hookSpinner.fail("Failed to install React Doctor pre-commit hook.");
17888
17981
  throw error;
@@ -17896,7 +17989,10 @@ const runInstallReactDoctor = async (options = {}) => {
17896
17989
  agents: selectedAgents
17897
17990
  });
17898
17991
  if (hookResult.installedAgents.length === 0) hookSpinner.succeed("No supported native agent hook targets selected.");
17899
- else hookSpinner.succeed(`React Doctor agent hooks installed for ${hookResult.installedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
17992
+ else {
17993
+ hookSpinner.succeed(`React Doctor agent hooks installed for ${hookResult.installedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
17994
+ recordCount(METRIC.installAgentHooks, 1, { agentsCount: hookResult.installedAgents.length });
17995
+ }
17900
17996
  } catch (error) {
17901
17997
  hookSpinner.fail("Failed to install React Doctor agent hooks.");
17902
17998
  throw error;
@@ -17908,11 +18004,21 @@ const runInstallReactDoctor = async (options = {}) => {
17908
18004
  try {
17909
18005
  writeFileSync(workflowTargetPath, buildWorkflowContent());
17910
18006
  workflowSpinner.succeed(`GitHub Actions workflow added at ${path.relative(projectRoot, workflowTargetPath)}.`);
18007
+ recordCount(METRIC.installWorkflow, 1);
17911
18008
  } catch (error) {
17912
18009
  workflowSpinner.fail("Failed to add GitHub Actions workflow.");
17913
18010
  throw error;
17914
18011
  }
17915
18012
  }
18013
+ recordCount(METRIC.installCompleted, 1, {
18014
+ agentsCount: selectedAgents.length,
18015
+ gitHook: shouldInstallGitHook,
18016
+ agentHooks: shouldInstallAgentHooks,
18017
+ workflow: shouldInstallWorkflow,
18018
+ dependencyStatus: dependencyResult.dependencyStatus,
18019
+ packageManager: detectPackageManager(projectRoot)
18020
+ });
18021
+ for (const agent of selectedAgents) recordCount(METRIC.installAgent, 1, { agent });
17916
18022
  };
17917
18023
  //#endregion
17918
18024
  //#region src/cli/utils/install-skill-for-agent.ts
@@ -18025,6 +18131,16 @@ const handoffToAgent = async (input) => {
18025
18131
  ],
18026
18132
  initial: 0
18027
18133
  }, { onCancel: () => true });
18134
+ let handoffOutcome = "launch";
18135
+ if (handoffTarget === void 0) handoffOutcome = "cancel";
18136
+ else if (handoffTarget === SKIP_CHOICE) handoffOutcome = "skip";
18137
+ else if (handoffTarget === PRINT_CHOICE) handoffOutcome = "print";
18138
+ else if (handoffTarget === CLIPBOARD_CHOICE) handoffOutcome = "clipboard";
18139
+ recordCount(METRIC.agentHandoff, 1, {
18140
+ outcome: handoffOutcome,
18141
+ agent: handoffOutcome === "launch" ? handoffTarget : void 0,
18142
+ diagnosticsCount: input.diagnostics.length
18143
+ });
18028
18144
  if (handoffTarget === void 0 || handoffTarget === SKIP_CHOICE) return;
18029
18145
  const payload = buildHandoffPayload({
18030
18146
  diagnostics: input.diagnostics,
@@ -18170,6 +18286,13 @@ const reportErrorToSentry = async (error) => {
18170
18286
  if (!Sentry.isInitialized()) return void 0;
18171
18287
  try {
18172
18288
  const { tags, contexts } = buildSentryScope();
18289
+ let reason = "unknown";
18290
+ if (isReactDoctorError(error)) reason = error.reason._tag;
18291
+ else if (error instanceof Error) reason = error.name;
18292
+ recordCount(METRIC.cliError, 1, {
18293
+ command: typeof tags.command === "string" ? tags.command : void 0,
18294
+ reason
18295
+ });
18173
18296
  const runTrace = getActiveRunTrace();
18174
18297
  const eventId = Sentry.withScope((scope) => {
18175
18298
  for (const [name, context] of Object.entries(contexts)) scope.setContext(name, context);
@@ -18715,6 +18838,7 @@ const inspectAction = async (directory, flags) => {
18715
18838
  compact: Boolean(flags.jsonCompact),
18716
18839
  directory: requestedDirectory
18717
18840
  });
18841
+ recordCount(METRIC.cliInvoked, 1, { command: "inspect" });
18718
18842
  try {
18719
18843
  validateModeFlags(flags);
18720
18844
  maybeMigrateLegacyConfig(requestedDirectory, {
@@ -18892,26 +19016,25 @@ const inspectAction = async (directory, flags) => {
18892
19016
  isJsonMode,
18893
19017
  isScoreOnly,
18894
19018
  isStaged: Boolean(flags.staged)
18895
- })) printAgentInstallHint();
19019
+ })) {
19020
+ printAgentInstallHint();
19021
+ recordCount(METRIC.agentInstallHintShown, 1);
19022
+ }
18896
19023
  }
18897
19024
  } catch (error) {
18898
- const isUserError = isUserInputError(error);
18899
- const sentryEventId = isUserError ? void 0 : await reportErrorToSentry(error);
19025
+ const sentryEventId = await reportErrorToSentry(error);
18900
19026
  if (isJsonMode) {
18901
19027
  writeJsonErrorReport(error);
18902
19028
  process.exitCode = 1;
18903
19029
  return;
18904
19030
  }
18905
- if (isUserError) {
18906
- handleUserError(error);
18907
- return;
18908
- }
18909
19031
  handleError(error, { sentryEventId });
18910
19032
  }
18911
19033
  };
18912
19034
  //#endregion
18913
19035
  //#region src/cli/commands/install.ts
18914
19036
  const installAction = async (options, command) => {
19037
+ recordCount(METRIC.cliInvoked, 1, { command: "install" });
18915
19038
  Effect.runSync(printBrandedHeader);
18916
19039
  try {
18917
19040
  const parentOptions = command?.parent?.opts?.();
@@ -19232,6 +19355,7 @@ const SEVERITY_VALUES = [
19232
19355
  "warn",
19233
19356
  "error"
19234
19357
  ];
19358
+ const recordRulesInvocation = () => recordCount(METRIC.cliInvoked, 1, { command: "rules" });
19235
19359
  const resolveProjectRoot = (options) => {
19236
19360
  const requestedDirectory = path.resolve(options.cwd ?? process.cwd());
19237
19361
  return findNearestPackageDirectory(requestedDirectory) ?? requestedDirectory;
@@ -19274,6 +19398,11 @@ const reportManualEdit = (target, nextConfig) => {
19274
19398
  process.exitCode = 1;
19275
19399
  };
19276
19400
  const rulesListAction = async (options) => {
19401
+ recordRulesInvocation();
19402
+ recordCount(METRIC.rulesQueried, 1, {
19403
+ subcommand: "list",
19404
+ hadFilter: Boolean(options.category || options.tag || options.framework || options.configured)
19405
+ });
19277
19406
  const catalog = buildRuleCatalog();
19278
19407
  const config = validateConfigTypes((await resolveRuleConfigTarget(resolveProjectRoot(options))).config);
19279
19408
  const categoryFilter = options.category?.toLowerCase();
@@ -19305,6 +19434,8 @@ const rulesListAction = async (options) => {
19305
19434
  cliLogger.log(renderRuleCatalog(rows));
19306
19435
  };
19307
19436
  const rulesExplainAction = async (ruleQuery, options) => {
19437
+ recordRulesInvocation();
19438
+ recordCount(METRIC.rulesQueried, 1, { subcommand: "explain" });
19308
19439
  const entry = findRuleInCatalog(buildRuleCatalog(), ruleQuery);
19309
19440
  if (!entry) {
19310
19441
  reportRuleNotFound(ruleQuery);
@@ -19332,7 +19463,7 @@ const rulesExplainAction = async (ruleQuery, options) => {
19332
19463
  effective
19333
19464
  }));
19334
19465
  };
19335
- const setRuleSeverityAndReport = async (entry, severity, options) => {
19466
+ const setRuleSeverityAndReport = async (entry, severity, options, action) => {
19336
19467
  const { target, nextConfig, written } = await applyConfigChange(options, (config) => setRuleSeverity(config, entry.key, severity));
19337
19468
  if (!written) {
19338
19469
  reportManualEdit(target, nextConfig);
@@ -19340,8 +19471,14 @@ const setRuleSeverityAndReport = async (entry, severity, options) => {
19340
19471
  }
19341
19472
  cliLogger.success(`Set ${entry.key} → ${severity}`);
19342
19473
  cliLogger.dim(` Updated ${describeTargetPath(target)}`);
19474
+ recordCount(METRIC.rulesChanged, 1, {
19475
+ action,
19476
+ severity,
19477
+ target: entry.key
19478
+ });
19343
19479
  };
19344
19480
  const rulesSetAction = async (ruleQuery, severityValue, options) => {
19481
+ recordRulesInvocation();
19345
19482
  const severity = parseSeverity(severityValue);
19346
19483
  if (!severity) {
19347
19484
  reportInvalidSeverity(severityValue);
@@ -19352,16 +19489,17 @@ const rulesSetAction = async (ruleQuery, severityValue, options) => {
19352
19489
  reportRuleNotFound(ruleQuery);
19353
19490
  return;
19354
19491
  }
19355
- await setRuleSeverityAndReport(entry, severity, options);
19492
+ await setRuleSeverityAndReport(entry, severity, options, "set");
19356
19493
  };
19357
19494
  const rulesEnableAction = async (ruleQuery, options) => {
19495
+ recordRulesInvocation();
19358
19496
  const entry = findRuleInCatalog(buildRuleCatalog(), ruleQuery);
19359
19497
  if (!entry) {
19360
19498
  reportRuleNotFound(ruleQuery);
19361
19499
  return;
19362
19500
  }
19363
19501
  if (options.severity === void 0) {
19364
- await setRuleSeverityAndReport(entry, entry.defaultSeverity, options);
19502
+ await setRuleSeverityAndReport(entry, entry.defaultSeverity, options, "enable");
19365
19503
  return;
19366
19504
  }
19367
19505
  const severity = parseSeverity(options.severity);
@@ -19374,17 +19512,19 @@ const rulesEnableAction = async (ruleQuery, options) => {
19374
19512
  process.exitCode = 1;
19375
19513
  return;
19376
19514
  }
19377
- await setRuleSeverityAndReport(entry, severity, options);
19515
+ await setRuleSeverityAndReport(entry, severity, options, "enable");
19378
19516
  };
19379
19517
  const rulesDisableAction = async (ruleQuery, options) => {
19518
+ recordRulesInvocation();
19380
19519
  const entry = findRuleInCatalog(buildRuleCatalog(), ruleQuery);
19381
19520
  if (!entry) {
19382
19521
  reportRuleNotFound(ruleQuery);
19383
19522
  return;
19384
19523
  }
19385
- await setRuleSeverityAndReport(entry, "off", options);
19524
+ await setRuleSeverityAndReport(entry, "off", options, "disable");
19386
19525
  };
19387
19526
  const rulesCategoryAction = async (categoryQuery, severityValue, options) => {
19527
+ recordRulesInvocation();
19388
19528
  const severity = parseSeverity(severityValue);
19389
19529
  if (!severity) {
19390
19530
  reportInvalidSeverity(severityValue);
@@ -19405,8 +19545,14 @@ const rulesCategoryAction = async (categoryQuery, severityValue, options) => {
19405
19545
  }
19406
19546
  cliLogger.success(`Set category "${matchedCategory}" → ${severity}`);
19407
19547
  cliLogger.dim(` Updated ${describeTargetPath(target)}`);
19548
+ recordCount(METRIC.rulesChanged, 1, {
19549
+ action: "category",
19550
+ severity,
19551
+ target: matchedCategory
19552
+ });
19408
19553
  };
19409
19554
  const rulesIgnoreTagAction = async (tag, options) => {
19555
+ recordRulesInvocation();
19410
19556
  const knownTags = listRuleTags(buildRuleCatalog());
19411
19557
  if (!knownTags.includes(tag)) {
19412
19558
  cliLogger.error(`Unknown tag "${tag}".`);
@@ -19421,8 +19567,13 @@ const rulesIgnoreTagAction = async (tag, options) => {
19421
19567
  }
19422
19568
  cliLogger.success(`Ignoring tag "${tag}" (rules with this tag are skipped before linting)`);
19423
19569
  cliLogger.dim(` Updated ${describeTargetPath(target)}`);
19570
+ recordCount(METRIC.rulesChanged, 1, {
19571
+ action: "ignoreTag",
19572
+ target: tag
19573
+ });
19424
19574
  };
19425
19575
  const rulesUnignoreTagAction = async (tag, options) => {
19576
+ recordRulesInvocation();
19426
19577
  const target = await resolveRuleConfigTarget(resolveProjectRoot(options));
19427
19578
  if (!(target.config.ignore?.tags ?? []).includes(tag)) {
19428
19579
  cliLogger.dim(`Tag "${tag}" was not being ignored; nothing to change.`);
@@ -19436,6 +19587,10 @@ const rulesUnignoreTagAction = async (tag, options) => {
19436
19587
  }
19437
19588
  cliLogger.success(`Tag "${tag}" is no longer ignored`);
19438
19589
  cliLogger.dim(` Updated ${describeTargetPath(target)}`);
19590
+ recordCount(METRIC.rulesChanged, 1, {
19591
+ action: "unignoreTag",
19592
+ target: tag
19593
+ });
19439
19594
  };
19440
19595
  //#endregion
19441
19596
  //#region src/cli/commands/version.ts
@@ -19448,6 +19603,7 @@ const rulesUnignoreTagAction = async (tag, options) => {
19448
19603
  */
19449
19604
  const buildVersionString = () => `react-doctor/${VERSION} ${process.platform}-${process.arch} node-${process.version}`;
19450
19605
  const versionAction = () => {
19606
+ recordCount(METRIC.cliInvoked, 1, { command: "version" });
19451
19607
  process.stdout.write(`${buildVersionString()}\n`);
19452
19608
  };
19453
19609
  //#endregion
@@ -19765,4 +19921,4 @@ program.parseAsync(argv).then(() => flushSentry()).catch(async (error) => {
19765
19921
  export {};
19766
19922
 
19767
19923
  //# sourceMappingURL=cli.js.map
19768
- //# debugId=540e80ff-13a0-5cd7-8313-53bd820f256d
19924
+ //# debugId=bd9bed01-711f-553b-b228-212598cc6e87
package/dist/index.d.ts CHANGED
@@ -726,12 +726,20 @@ declare class ReactDoctorError extends ReactDoctorError_base {
726
726
  }
727
727
  declare const isReactDoctorError: (error: unknown) => error is ReactDoctorError;
728
728
  /**
729
- * Diff-base failures stem from the caller's `--diff` argument or local
730
- * git state — a malformed ref/range, or a base branch that simply hasn't
731
- * been fetched — not from a bug in react-doctor. The CLI renders these
732
- * as a plain message and exits non-zero WITHOUT capturing them to Sentry
733
- * or pointing the user at a bug report: they're expected, user-actionable
734
- * conditions, not crashes to triage.
729
+ * Tagged-reason → legacy thrown-class boundary shared by every public
730
+ * shell (`inspect()` in `react-doctor`, `diagnose()` in `@react-doctor/api`).
731
+ *
732
+ * `Effect.catchReasons` dispatches on the tagged-error sub-channel
733
+ * without manual `instanceof` checks. Each handler converts a tagged
734
+ * reason into the historical thrown class advertised by the legacy
735
+ * public-API contract (via `Effect.die`, which `Effect.runPromise`
736
+ * re-throws unchanged). The `orElse` branch re-`die`s the original
737
+ * `ReactDoctorError` instance so advanced callers can still narrow on
738
+ * `error.reason._tag` while grep-stderr users keep the same
739
+ * `error.message` they always saw.
740
+ *
741
+ * Adding a new legacy thrown class is a one-line change on the
742
+ * `Effect.catchReasons` map — both shells pick it up automatically.
735
743
  */
736
744
  //#endregion
737
745
  //#region src/build-json-report-error.d.ts
@@ -764,13 +772,12 @@ declare const buildJsonReport: (input: BuildJsonReportInput) => JsonReport; //#e
764
772
  * Git service runs through Effect's `ChildProcess` (true subprocess
765
773
  * spawn, not `spawnSync`).
766
774
  *
767
- * Failures propagate as the tagged `ReactDoctorError` (rejected by
768
- * `Effect.runPromise`) rather than being flattened into a plain
769
- * `Error`. The message is unchanged — `ReactDoctorError.message`
770
- * defers to `reason.message` — so message-matching callers keep
771
- * working, while the CLI can now dispatch on `error.reason._tag` to
772
- * render diff-base mistakes (`GitBaseBranchInvalid` /
773
- * `GitBaseBranchMissing`) as clean user errors instead of crashes.
775
+ * Tagged-reason errors are dispatched via `Effect.catchReasons`
776
+ * (a v4-native API for narrowing inside a `Schema.TaggedErrorClass`
777
+ * union without manual `instanceof` checks). The recovered branches
778
+ * raise plain `Error`s so existing thrown-class consumers continue
779
+ * to work — anything else (real `GitInvocationFailed`, etc.)
780
+ * propagates as the tagged `ReactDoctorError` through `Effect.runPromise`.
774
781
  */
775
782
  declare const getDiffInfo: (directory: string, explicitBaseBranch?: string) => Promise<DiffInfo | null>;
776
783
  declare const filterSourceFiles: (filePaths: string[]) => string[]; //#endregion
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4536fc6c-0d5d-50d5-83e0-910624b3a687")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="df20b0d3-9e4e-52e0-8991-ce8a6349a04a")}catch(e){}}();
3
3
  import { createRequire } from "node:module";
4
4
  import * as Schema from "effect/Schema";
5
5
  import * as fs$1 from "node:fs";
@@ -5928,11 +5928,6 @@ const trimOrNull = (value) => {
5928
5928
  * `@{` reflog suffix, or any character outside `[A-Za-z0-9_./-]`.
5929
5929
  */
5930
5930
  const SAFE_GIT_REVISION_PATTERN = /^[A-Za-z0-9_./-]+$/;
5931
- /** Human-readable summary of the `isSafeGitRevision` contract, reused across error details. */
5932
- const GIT_REF_NAME_RULE = "must match [A-Za-z0-9_./-] without leading '-', '..', or '@{'";
5933
- /** git's two range operators: two-dot (direct) and three-dot (merge-base). */
5934
- const DIFF_RANGE_OPERATOR = "..";
5935
- const SYMMETRIC_DIFF_RANGE_OPERATOR = "...";
5936
5931
  const isSafeGitRevision = (candidate) => {
5937
5932
  if (candidate.length === 0) return false;
5938
5933
  if (candidate.startsWith("-")) return false;
@@ -5940,31 +5935,6 @@ const isSafeGitRevision = (candidate) => {
5940
5935
  if (candidate.includes("..") || candidate.includes("@{")) return false;
5941
5936
  return SAFE_GIT_REVISION_PATTERN.test(candidate);
5942
5937
  };
5943
- /**
5944
- * Splits a git revision range into its endpoints: three-dot `A...B`
5945
- * (symmetric, merge-base) or two-dot `A..B` (direct). Returns `null`
5946
- * when `value` carries no range operator so the caller falls back to
5947
- * single-base resolution.
5948
- *
5949
- * Only the first operator is split on; any leftover `..` stays inside an
5950
- * endpoint so `isSafeGitRevision` rejects malformed input like
5951
- * `A..B..C` instead of silently guessing which pair the user meant.
5952
- */
5953
- const parseGitDiffRange = (value) => {
5954
- const symmetricIndex = value.indexOf(SYMMETRIC_DIFF_RANGE_OPERATOR);
5955
- if (symmetricIndex !== -1) return {
5956
- base: value.slice(0, symmetricIndex),
5957
- head: value.slice(symmetricIndex + 3),
5958
- symmetric: true
5959
- };
5960
- const rangeIndex = value.indexOf(DIFF_RANGE_OPERATOR);
5961
- if (rangeIndex !== -1) return {
5962
- base: value.slice(0, rangeIndex),
5963
- head: value.slice(rangeIndex + 2),
5964
- symmetric: false
5965
- };
5966
- return null;
5967
- };
5968
5938
  const parseGithubRepoFromRemoteUrl = (remoteUrl) => {
5969
5939
  const withoutGitSuffix = remoteUrl.trim().replace(/\.git$/, "");
5970
5940
  const sshMatch = /^git@github\.com:([^/\s]+)\/([^/\s]+)$/.exec(withoutGitSuffix);
@@ -6116,49 +6086,6 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
6116
6086
  if (result.status !== 0) return null;
6117
6087
  return parseGithubViewerPermission(result.stdout);
6118
6088
  }).pipe(Effect.catch(() => Effect.succeed(null)));
6119
- /**
6120
- * Resolves a `--diff A..B` / `A...B` commit range into a changed-file
6121
- * selection. Each endpoint is validated with `isSafeGitRevision`
6122
- * BEFORE it reaches `git` (so the range syntax can't smuggle a
6123
- * `--upload-pack=…`-style option past the CVE-2018-17456 guard) and
6124
- * verified to exist, then the diff runs between the two commits with
6125
- * the same `--diff-filter=ACMR` shape the single-base path uses.
6126
- */
6127
- const resolveDiffRange = (input) => Effect.gen(function* () {
6128
- if (input.range.base.length === 0 && input.range.head.length === 0) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: `Diff range "${input.raw}" must name at least one commit (e.g. "main..feature").` }) }));
6129
- const baseRef = input.range.base.length === 0 ? "HEAD" : input.range.base;
6130
- const headRef = input.range.head.length === 0 ? "HEAD" : input.range.head;
6131
- for (const endpoint of [baseRef, headRef]) if (!isSafeGitRevision(endpoint)) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: `Diff range "${input.raw}" has an invalid endpoint "${endpoint}" (${GIT_REF_NAME_RULE}).` }) }));
6132
- for (const endpoint of [baseRef, headRef]) if (!(yield* branchExists(input.directory, endpoint))) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchMissing({ branch: endpoint }) }));
6133
- let diffBaseRef = baseRef;
6134
- if (input.range.symmetric) {
6135
- const mergeBase = yield* runGit(input.directory, [
6136
- "merge-base",
6137
- baseRef,
6138
- headRef
6139
- ]);
6140
- if (mergeBase.status !== 0) return null;
6141
- const mergeBaseRef = trimOrNull(mergeBase.stdout);
6142
- if (mergeBaseRef === null) return null;
6143
- diffBaseRef = mergeBaseRef;
6144
- }
6145
- const diff = yield* runGit(input.directory, [
6146
- "diff",
6147
- "-z",
6148
- "--name-only",
6149
- "--diff-filter=ACMR",
6150
- "--relative",
6151
- diffBaseRef,
6152
- headRef
6153
- ]);
6154
- if (diff.status !== 0) return null;
6155
- return {
6156
- currentBranch: headRef,
6157
- baseBranch: baseRef,
6158
- changedFiles: splitNullSeparated(diff.stdout),
6159
- isCurrentChanges: false
6160
- };
6161
- });
6162
6089
  return Git.of({
6163
6090
  currentBranch,
6164
6091
  defaultBranch,
@@ -6168,15 +6095,7 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
6168
6095
  branchExists,
6169
6096
  diffSelection: ({ directory, explicitBaseBranch }) => Effect.gen(function* () {
6170
6097
  if (explicitBaseBranch !== void 0 && explicitBaseBranch.trim().length === 0) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: "Diff base branch cannot be empty." }) }));
6171
- if (explicitBaseBranch !== void 0) {
6172
- const range = parseGitDiffRange(explicitBaseBranch);
6173
- if (range !== null) return yield* resolveDiffRange({
6174
- directory,
6175
- range,
6176
- raw: explicitBaseBranch
6177
- });
6178
- if (!isSafeGitRevision(explicitBaseBranch)) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: `Diff base branch "${explicitBaseBranch}" is not a valid git ref name (${GIT_REF_NAME_RULE}).` }) }));
6179
- }
6098
+ if (explicitBaseBranch !== void 0 && !isSafeGitRevision(explicitBaseBranch)) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: `Diff base branch "${explicitBaseBranch}" is not a valid git ref name (must match [A-Za-z0-9_./-] without leading '-', '..', or '@{').` }) }));
6180
6099
  const resolvedCurrentBranch = yield* currentBranch(directory);
6181
6100
  if (resolvedCurrentBranch === null && explicitBaseBranch === void 0) return null;
6182
6101
  const baseBranch = explicitBaseBranch ?? (yield* defaultBranch(directory));
@@ -8534,13 +8453,12 @@ const buildSkippedChecks = (input) => {
8534
8453
  * Git service runs through Effect's `ChildProcess` (true subprocess
8535
8454
  * spawn, not `spawnSync`).
8536
8455
  *
8537
- * Failures propagate as the tagged `ReactDoctorError` (rejected by
8538
- * `Effect.runPromise`) rather than being flattened into a plain
8539
- * `Error`. The message is unchanged — `ReactDoctorError.message`
8540
- * defers to `reason.message` — so message-matching callers keep
8541
- * working, while the CLI can now dispatch on `error.reason._tag` to
8542
- * render diff-base mistakes (`GitBaseBranchInvalid` /
8543
- * `GitBaseBranchMissing`) as clean user errors instead of crashes.
8456
+ * Tagged-reason errors are dispatched via `Effect.catchReasons`
8457
+ * (a v4-native API for narrowing inside a `Schema.TaggedErrorClass`
8458
+ * union without manual `instanceof` checks). The recovered branches
8459
+ * raise plain `Error`s so existing thrown-class consumers continue
8460
+ * to work — anything else (real `GitInvocationFailed`, etc.)
8461
+ * propagates as the tagged `ReactDoctorError` through `Effect.runPromise`.
8544
8462
  */
8545
8463
  const getDiffInfo = (directory, explicitBaseBranch) => Effect.runPromise(Effect.gen(function* () {
8546
8464
  const selection = yield* (yield* Git).diffSelection({
@@ -8554,7 +8472,10 @@ const getDiffInfo = (directory, explicitBaseBranch) => Effect.runPromise(Effect.
8554
8472
  changedFiles: [...selection.changedFiles],
8555
8473
  ...selection.isCurrentChanges ? { isCurrentChanges: true } : {}
8556
8474
  };
8557
- }).pipe(Effect.provide(Git.layerNode)));
8475
+ }).pipe(Effect.provide(Git.layerNode), Effect.catchReasons("ReactDoctorError", {
8476
+ GitBaseBranchInvalid: (reason) => Effect.die(new Error(reason.detail)),
8477
+ GitBaseBranchMissing: (reason) => Effect.die(new Error(reason.message))
8478
+ })));
8558
8479
  const filterSourceFiles = (filePaths) => filePaths.filter(isLintableSourceFile);
8559
8480
  var import_picocolors = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
8560
8481
  let p = process || {}, argv = p.argv || [], env = p.env || {};
@@ -8699,4 +8620,4 @@ const toJsonReport = (result, options) => buildJsonReport({
8699
8620
  export { AmbiguousProjectError, NoReactDependencyError, NotADirectoryError, PackageJsonNotFoundError, ProjectNotFoundError, ReactDoctorError, buildJsonReport, buildJsonReportError, clearCaches, diagnose, filterSourceFiles, getDiffInfo, isProjectDiscoveryError, isReactDoctorError, summarizeDiagnostics, toJsonReport };
8700
8621
 
8701
8622
  //# sourceMappingURL=index.js.map
8702
- //# debugId=4536fc6c-0d5d-50d5-83e0-910624b3a687
8623
+ //# debugId=df20b0d3-9e4e-52e0-8991-ce8a6349a04a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-doctor",
3
- "version": "0.2.15-dev.01ec05c",
3
+ "version": "0.2.15-dev.17e722e",
4
4
  "description": "Diagnose and fix React codebases for security, performance, correctness, accessibility, bundle-size, and architecture issues",
5
5
  "keywords": [
6
6
  "accessibility",
@@ -63,7 +63,7 @@
63
63
  "oxlint": "^1.66.0",
64
64
  "prompts": "^2.4.2",
65
65
  "typescript": ">=5.0.4 <7",
66
- "oxlint-plugin-react-doctor": "0.2.15-dev.01ec05c"
66
+ "oxlint-plugin-react-doctor": "0.2.15-dev.17e722e"
67
67
  },
68
68
  "devDependencies": {
69
69
  "@types/babel__code-frame": "^7.27.0",