react-doctor 0.5.1-dev.fee3fc4 → 0.5.2-dev.022790b

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/dist/lsp.js CHANGED
@@ -10,10 +10,11 @@ import { spawn, spawnSync } from "node:child_process";
10
10
  import * as ts from "typescript";
11
11
  import reactDoctorPlugin, { ALL_REACT_DOCTOR_RULE_KEYS, FRAMEWORK_SPECIFIC_RULE_KEYS, MOTION_LIBRARY_PACKAGES, REACT_COMPILER_RULES, REACT_DOCTOR_RULES } from "oxlint-plugin-react-doctor";
12
12
  import { parseJSON5 } from "confbox";
13
+ import * as NodeUrl from "node:url";
14
+ import { fileURLToPath } from "node:url";
13
15
  import { createJiti } from "jiti";
14
16
  import * as Crypto from "node:crypto";
15
17
  import crypto from "node:crypto";
16
- import * as NodeUrl from "node:url";
17
18
  import { gzipSync } from "node:zlib";
18
19
  import { CodeActionKind, CodeActionTriggerKind, DidChangeWatchedFilesNotification, DocumentDiagnosticReportKind, FileChangeType, TextDocumentSyncKind, TextDocuments, createConnection } from "vscode-languageserver/node.js";
19
20
  import { TextDocument } from "vscode-languageserver-textdocument";
@@ -19283,6 +19284,7 @@ var Diagnostic = class extends Class("Diagnostic")({
19283
19284
  endLine: optional(Number$1),
19284
19285
  endColumn: optional(Number$1),
19285
19286
  category: String$1,
19287
+ fileContext: optional(Literals(["test", "story"])),
19286
19288
  suppressionHint: optional(String$1),
19287
19289
  relatedLocations: optional(ArraySchema(DiagnosticRelatedLocation))
19288
19290
  }) {};
@@ -34630,8 +34632,10 @@ const isFileIgnoredByPatterns = (filePath, rootDirectory, patterns) => {
34630
34632
  const relativePath = toRelativePath(filePath, rootDirectory);
34631
34633
  return patterns.some((pattern) => pattern.test(relativePath));
34632
34634
  };
34635
+ const SCRIPT_EXTENSION_FRAGMENT = "[cm]?[jt]sx?";
34636
+ const STORY_FILE_SUFFIX_PATTERN = new RegExp(`\\.(?:stories|story)\\.(?:${SCRIPT_EXTENSION_FRAGMENT})$`);
34637
+ const TEST_FILE_SUFFIX_PATTERN = new RegExp(`\\.(?:test|spec|fixture|fixtures)\\.(?:${SCRIPT_EXTENSION_FRAGMENT})$`);
34633
34638
  const TEST_FILE_DIRECTORY_PATTERN = /(?:^|\/)(?:__tests__|__test__|tests|test|__mocks__|cypress|e2e|playwright)\//;
34634
- const TEST_FILE_SUFFIX_PATTERN = /\.(?:test|spec|stories|story|fixture|fixtures)\.(?:[cm]?[jt]sx?)$/;
34635
34639
  const FIXTURE_PROJECT_PATTERN = /\/(?:fixtures|__fixtures__)\//;
34636
34640
  const SOURCE_ROOT_PATTERN = /\/(?:src|app|lib|components|pages|features|modules|packages|apps|frontend|client)\//g;
34637
34641
  const stripAboveSourceRoot = (relativePath) => {
@@ -34642,12 +34646,23 @@ const stripAboveSourceRoot = (relativePath) => {
34642
34646
  if (lastIdx >= 0) return relativePath.slice(lastIdx);
34643
34647
  return relativePath.slice(fixtureMatch.index + fixtureMatch[0].length - 1);
34644
34648
  };
34645
- const isTestFilePath = (relativePath) => {
34646
- if (relativePath.length === 0) return false;
34649
+ /**
34650
+ * Classifies where a file sits relative to shipped code. A finding in a
34651
+ * `.stories.tsx` or `.spec.ts` file never runs in front of users, so
34652
+ * renderers label those sites instead of framing them as production
34653
+ * impact (`rn-no-raw-text` in a spec doesn't say users crash).
34654
+ *
34655
+ * `"story"` is the `.stories.*` / `.story.*` suffix; `"test"` is the
34656
+ * test/spec/fixture suffixes and test directories; `"production"` is
34657
+ * the default.
34658
+ */
34659
+ const classifyFileContext = (relativePath) => {
34660
+ if (relativePath.length === 0) return "production";
34647
34661
  const forwardSlashed = relativePath.replaceAll("\\", "/");
34648
- if (TEST_FILE_SUFFIX_PATTERN.test(forwardSlashed)) return true;
34662
+ if (STORY_FILE_SUFFIX_PATTERN.test(forwardSlashed)) return "story";
34663
+ if (TEST_FILE_SUFFIX_PATTERN.test(forwardSlashed)) return "test";
34649
34664
  const scoped = stripAboveSourceRoot(forwardSlashed);
34650
- return TEST_FILE_DIRECTORY_PATTERN.test(scoped);
34665
+ return TEST_FILE_DIRECTORY_PATTERN.test(scoped) ? "test" : "production";
34651
34666
  };
34652
34667
  /**
34653
34668
  * Resolves the user-configured severity override for a rule.
@@ -34867,6 +34882,8 @@ const collectStringSet = (values) => {
34867
34882
  * 5. `rn-no-raw-text` suppression via configured `textComponents` and
34868
34883
  * `rawTextWrapperComponents` (config-driven JSX enclosure checks)
34869
34884
  * 6. inline suppressions (`// react-doctor-disable-next-line ...`)
34885
+ * 7. file-context stamping (`fileContext: "test" | "story"` on
34886
+ * survivors in non-production files, so renderers can label them)
34870
34887
  *
34871
34888
  * Returns `null` when the diagnostic is dropped, the (possibly
34872
34889
  * severity-restamped) diagnostic otherwise.
@@ -34886,7 +34903,7 @@ const buildDiagnosticPipeline = (input) => {
34886
34903
  const hasTextComponents = textComponentNames.size > 0;
34887
34904
  const hasRawTextWrappers = rawTextWrapperComponentNames.size > 0;
34888
34905
  const fileLinesCache = /* @__PURE__ */ new Map();
34889
- const testFileCache = /* @__PURE__ */ new Map();
34906
+ const fileContextCache = /* @__PURE__ */ new Map();
34890
34907
  const libraryFileCache = /* @__PURE__ */ new Map();
34891
34908
  const isLibraryFile = (filePath) => {
34892
34909
  let cached = libraryFileCache.get(filePath);
@@ -34903,11 +34920,11 @@ const buildDiagnosticPipeline = (input) => {
34903
34920
  fileLinesCache.set(filePath, lines);
34904
34921
  return lines;
34905
34922
  };
34906
- const isTest = (filePath) => {
34907
- let cached = testFileCache.get(filePath);
34923
+ const getFileContext = (filePath) => {
34924
+ let cached = fileContextCache.get(filePath);
34908
34925
  if (cached === void 0) {
34909
- cached = isTestFilePath(filePath);
34910
- testFileCache.set(filePath, cached);
34926
+ cached = classifyFileContext(filePath);
34927
+ fileContextCache.set(filePath, cached);
34911
34928
  }
34912
34929
  return cached;
34913
34930
  };
@@ -34916,7 +34933,7 @@ const buildDiagnosticPipeline = (input) => {
34916
34933
  const rule = reactDoctorPlugin.rules[diagnostic.rule];
34917
34934
  if (!rule?.tags?.includes("test-noise")) return false;
34918
34935
  if (rule.tags.includes("migration-hint")) return false;
34919
- return isTest(diagnostic.filePath);
34936
+ return getFileContext(diagnostic.filePath) !== "production";
34920
34937
  };
34921
34938
  const isRuleIgnored = (ruleIdentifier) => {
34922
34939
  for (const ignored of ignoredRules) if (isSameRuleKey(ignored, ruleIdentifier)) return true;
@@ -34973,6 +34990,11 @@ const buildDiagnosticPipeline = (input) => {
34973
34990
  };
34974
34991
  }
34975
34992
  }
34993
+ const fileContext = getFileContext(current.filePath);
34994
+ if (fileContext !== "production") current = {
34995
+ ...current,
34996
+ fileContext
34997
+ };
34976
34998
  return current;
34977
34999
  } };
34978
35000
  };
@@ -35347,10 +35369,41 @@ const PACKAGE_JSON_CONFIG_KEY = "reactDoctor";
35347
35369
  const LEGACY_CONFIG_FILENAME = "react-doctor.config.json";
35348
35370
  const jiti = createJiti(import.meta.url);
35349
35371
  const formatError = (error) => error instanceof Error ? error.message : String(error);
35350
- const loadModuleConfig = async (filePath) => {
35351
- const imported = await jiti.import(filePath);
35372
+ const importDefaultExport = async (jitiInstance, filePath) => {
35373
+ const imported = await jitiInstance.import(filePath);
35352
35374
  return imported?.default ?? imported;
35353
35375
  };
35376
+ const SELF_PACKAGE_IMPORT_SPECIFIER = "react-doctor/api";
35377
+ const SELF_PACKAGE_RESOLVE_TARGETS = ["react-doctor/api", "@react-doctor/core"];
35378
+ const MODULE_NOT_FOUND_ERROR_CODES = new Set(["MODULE_NOT_FOUND", "ERR_MODULE_NOT_FOUND"]);
35379
+ let selfAliasJiti;
35380
+ const getSelfAliasJiti = () => {
35381
+ if (selfAliasJiti !== void 0) return selfAliasJiti;
35382
+ for (const resolveTarget of SELF_PACKAGE_RESOLVE_TARGETS) try {
35383
+ const aliasTargetPath = fileURLToPath(jiti.esmResolve(resolveTarget));
35384
+ selfAliasJiti = createJiti(import.meta.url, { alias: { [SELF_PACKAGE_IMPORT_SPECIFIER]: aliasTargetPath } });
35385
+ return selfAliasJiti;
35386
+ } catch {
35387
+ continue;
35388
+ }
35389
+ selfAliasJiti = null;
35390
+ return selfAliasJiti;
35391
+ };
35392
+ const isSelfPackageResolutionError = (error) => error instanceof Error && "code" in error && typeof error.code === "string" && MODULE_NOT_FOUND_ERROR_CODES.has(error.code) && error.message.includes(SELF_PACKAGE_IMPORT_SPECIFIER);
35393
+ const loadModuleConfig = async (filePath) => {
35394
+ try {
35395
+ return await importDefaultExport(jiti, filePath);
35396
+ } catch (error) {
35397
+ if (!isSelfPackageResolutionError(error)) throw error;
35398
+ const aliasJiti = getSelfAliasJiti();
35399
+ if (!aliasJiti) throw error;
35400
+ try {
35401
+ return await importDefaultExport(aliasJiti, filePath);
35402
+ } catch (retryError) {
35403
+ throw new Error(`${formatError(error)} (retry with ${SELF_PACKAGE_IMPORT_SPECIFIER} aliased to the running react-doctor package also failed: ${formatError(retryError)})`, { cause: retryError });
35404
+ }
35405
+ }
35406
+ };
35354
35407
  const readDataConfig = (filePath) => parseJSON5(NFS.readFileSync(filePath, "utf-8"));
35355
35408
  const readEmbeddedPackageJsonConfig = (directory) => {
35356
35409
  const packageJsonPath = Path.join(directory, PACKAGE_JSON_FILENAME);
@@ -36010,6 +36063,17 @@ const checkPnpmHardening = (rootDirectory) => {
36010
36063
  }));
36011
36064
  return diagnostics;
36012
36065
  };
36066
+ const buildReactNativeDiagnostic = (input) => ({
36067
+ filePath: input.filePath,
36068
+ plugin: "react-doctor",
36069
+ rule: input.rule,
36070
+ severity: input.severity ?? "warning",
36071
+ message: input.message,
36072
+ help: input.help,
36073
+ line: input.line ?? 0,
36074
+ column: input.column ?? 0,
36075
+ category: input.category ?? "Correctness"
36076
+ });
36013
36077
  const BUILDER_BOB_PACKAGE = "react-native-builder-bob";
36014
36078
  const isBuilderBobLibrary = (packageJson) => {
36015
36079
  const bobConfig = packageJson[BUILDER_BOB_PACKAGE];
@@ -36021,17 +36085,12 @@ const checkReactNativeLibraryDependencies = (rootDirectory) => {
36021
36085
  const misplaced = ["react", "react-native"].filter((name) => packageJson.dependencies?.[name] !== void 0);
36022
36086
  if (misplaced.length === 0) return [];
36023
36087
  const quoted = misplaced.map((name) => `"${name}"`).join(" and ");
36024
- return [{
36088
+ return [buildReactNativeDiagnostic({
36025
36089
  filePath: "package.json",
36026
- plugin: "react-doctor",
36027
36090
  rule: "rn-library-react-in-dependencies",
36028
- severity: "warning",
36029
36091
  message: `This react-native-builder-bob library lists ${quoted} in \`dependencies\` — that ships a second copy into consumer apps, causing "Invalid hook call" (duplicate React) and duplicate-native-module crashes.`,
36030
- help: `Move ${quoted} to \`peerDependencies\` (keep ${misplaced.length === 1 ? "it" : "them"} in \`devDependencies\` for local development).`,
36031
- line: 0,
36032
- column: 0,
36033
- category: "Correctness"
36034
- }];
36092
+ help: `Move ${quoted} to \`peerDependencies\` (keep ${misplaced.length === 1 ? "it" : "them"} in \`devDependencies\` for local development).`
36093
+ })];
36035
36094
  };
36036
36095
  const BABEL_CONFIG_FILE_NAMES = [
36037
36096
  "babel.config.js",
@@ -36043,6 +36102,8 @@ const BABEL_CONFIG_FILE_NAMES = [
36043
36102
  ".babelrc.json"
36044
36103
  ];
36045
36104
  const LEGACY_PRESET_SPEC = "module:metro-react-native-babel-preset";
36105
+ const MODERN_PRESET_REFERENCE = new RegExp(`['"]module:@react-native/babel-preset['"]`);
36106
+ const ENABLE_BABEL_RUNTIME_VERSION = /enableBabelRuntime["']?\s*:\s*['"]/;
36046
36107
  const checkReactNativeMetroBabelPreset = (rootDirectory) => {
36047
36108
  for (const fileName of BABEL_CONFIG_FILE_NAMES) {
36048
36109
  const filePath = Path.join(rootDirectory, fileName);
@@ -36053,18 +36114,20 @@ const checkReactNativeMetroBabelPreset = (rootDirectory) => {
36053
36114
  } catch {
36054
36115
  continue;
36055
36116
  }
36056
- if (!contents.includes(LEGACY_PRESET_SPEC)) continue;
36057
- return [{
36117
+ if (contents.includes(LEGACY_PRESET_SPEC)) return [buildReactNativeDiagnostic({
36058
36118
  filePath: fileName,
36059
- plugin: "react-doctor",
36060
36119
  rule: "rn-no-metro-babel-preset",
36061
36120
  severity: "error",
36062
36121
  message: "`module:metro-react-native-babel-preset` was renamed to `@react-native/babel-preset` and is no longer installed by React Native 0.73+ — this preset reference fails to resolve and breaks the Metro/Babel transform.",
36063
- help: "Replace the preset with `module:@react-native/babel-preset` (or `babel-preset-expo` on Expo) and remove the old `metro-react-native-babel-preset` dependency.",
36064
- line: 0,
36065
- column: 0,
36066
- category: "Correctness"
36067
- }];
36122
+ help: "Replace the preset with `module:@react-native/babel-preset` (or `babel-preset-expo` on Expo) and remove the old `metro-react-native-babel-preset` dependency."
36123
+ })];
36124
+ if (MODERN_PRESET_REFERENCE.test(contents) && !ENABLE_BABEL_RUNTIME_VERSION.test(contents)) return [buildReactNativeDiagnostic({
36125
+ filePath: fileName,
36126
+ rule: "rn-no-metro-babel-runtime-version",
36127
+ severity: "warning",
36128
+ message: "`module:@react-native/babel-preset` has no `enableBabelRuntime` version, so Babel runtime helpers can be duplicated across files instead of imported once from @babel/runtime, increasing the JS bundle size.",
36129
+ help: "Set `enableBabelRuntime` to the @babel/runtime version from package.json, e.g. `['module:@react-native/babel-preset', { enableBabelRuntime: '^7.26.0' }]`."
36130
+ })];
36068
36131
  }
36069
36132
  return [];
36070
36133
  };
@@ -38460,9 +38523,18 @@ const shouldSuppressLocalUseHookDiagnostic = (diagnostic, rootDirectory) => {
38460
38523
  return bindingResolution !== null && !bindingResolution.isReactUseBinding;
38461
38524
  };
38462
38525
  const FILEPATH_WITH_LOCATION_PATTERN = /\S+\.\w+:\d+:\d+[\s\S]*$/;
38526
+ const LEADING_SEVERITY_LABEL_PATTERN = /^(?:Error|Warning):\s*/;
38527
+ const TRAILING_PERIOD_PATTERN = /\.$/;
38463
38528
  const REACT_COMPILER_TITLE = "React Compiler can't optimize this";
38464
38529
  const REACT_COMPILER_TODO_TITLE = "React Compiler doesn't support this syntax";
38465
- const REACT_COMPILER_MESSAGE = "This component misses React Compiler's automatic memoization & re-renders more than it should. Rewrite the flagged code so the compiler can optimize it.";
38530
+ const REACT_COMPILER_IMPACT = "This component misses React Compiler's automatic memoization & re-renders more than it should";
38531
+ const REACT_COMPILER_ACTION = "Rewrite the flagged code so the compiler can optimize it.";
38532
+ const REACT_COMPILER_GENERIC_MESSAGE = `${REACT_COMPILER_IMPACT}. ${REACT_COMPILER_ACTION}`;
38533
+ const buildReactCompilerMessage = (reasonSummary) => {
38534
+ const normalizedSummary = reasonSummary.replace(TRAILING_PERIOD_PATTERN, "");
38535
+ if (!normalizedSummary) return REACT_COMPILER_GENERIC_MESSAGE;
38536
+ return `${REACT_COMPILER_IMPACT}: ${normalizedSummary}. ${REACT_COMPILER_ACTION}`;
38537
+ };
38466
38538
  const PLUGIN_CATEGORY_MAP = {
38467
38539
  react: "Bugs",
38468
38540
  "react-hooks": "Bugs",
@@ -38501,10 +38573,19 @@ const cleanDiagnosticMessage = (message, help, plugin, rule, project) => {
38501
38573
  };
38502
38574
  };
38503
38575
  const resolveCleanedDiagnostic = (message, help, plugin, rule, project) => {
38504
- if (plugin === "react-hooks-js") return {
38505
- message: REACT_COMPILER_MESSAGE,
38506
- help: appendReanimatedSharedValueHint(message.replace(FILEPATH_WITH_LOCATION_PATTERN, "").trim() || help, rule, project)
38507
- };
38576
+ if (plugin === "react-hooks-js") {
38577
+ const bailoutReason = message.replace(FILEPATH_WITH_LOCATION_PATTERN, "").trim().replace(LEADING_SEVERITY_LABEL_PATTERN, "").trim();
38578
+ if (rule === "todo") return {
38579
+ message: REACT_COMPILER_GENERIC_MESSAGE,
38580
+ help: appendReanimatedSharedValueHint(bailoutReason || help, rule, project)
38581
+ };
38582
+ const [reasonSummary = "", ...reasonDetailLines] = bailoutReason.split("\n");
38583
+ const reasonDetail = reasonDetailLines.join("\n").trim();
38584
+ return {
38585
+ message: buildReactCompilerMessage(reasonSummary.trim()),
38586
+ help: appendReanimatedSharedValueHint(reasonDetail || help, rule, project)
38587
+ };
38588
+ }
38508
38589
  return {
38509
38590
  message: message.replace(FILEPATH_WITH_LOCATION_PATTERN, "").trim() || message,
38510
38591
  help: help || getRuleRecommendation(rule, project) || ""
@@ -39171,7 +39252,7 @@ const ScoreApiResponseSchema = Struct({
39171
39252
  })))
39172
39253
  });
39173
39254
  const parseScoreResult = (value) => getOrNull(decodeUnknownOption(ScoreApiResponseSchema)(value));
39174
- const stripFilePaths = (diagnostics) => diagnostics.map(({ filePath: _filePath, ...rest }) => rest);
39255
+ const stripLocalFileFields = (diagnostics) => diagnostics.map(({ filePath: _filePath, fileContext: _fileContext, ...rest }) => rest);
39175
39256
  const isAbortError = (error) => error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
39176
39257
  const describeFailure = (error) => {
39177
39258
  if (isAbortError(error)) return `timed out after ${FETCH_TIMEOUT_MS / 1e3}s`;
@@ -39184,7 +39265,7 @@ const calculateScore = async (diagnostics, options = {}) => {
39184
39265
  const requestUrl = options.isCi ? `${SCORE_API_URL}?ci=1` : SCORE_API_URL;
39185
39266
  try {
39186
39267
  const compressedBody = gzipSync(JSON.stringify({
39187
- diagnostics: stripFilePaths(diagnostics),
39268
+ diagnostics: stripLocalFileFields(diagnostics),
39188
39269
  ...options.metadata?.repo ? { repo: options.metadata.repo } : {},
39189
39270
  ...options.metadata?.sha ? { sha: options.metadata.sha } : {},
39190
39271
  ...options.metadata?.framework ? { framework: options.metadata.framework } : {},
@@ -39240,42 +39321,74 @@ var Score = class Score extends Service()("react-doctor/Score") {
39240
39321
  }) }));
39241
39322
  static layerOf = (result) => succeed$3(Score, Score.of({ compute: () => succeed$2(result) }));
39242
39323
  };
39243
- const decodeArtifact = decodeUnknownOption(Struct({ score: optional(Struct({
39324
+ const isControlCharacter = (codePoint) => codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
39325
+ const sanitizeTerminalText = (value) => {
39326
+ let sanitized = "";
39327
+ for (const character of value) {
39328
+ if (isControlCharacter(character.codePointAt(0) ?? 0)) continue;
39329
+ sanitized += character === "`" ? "'" : character;
39330
+ }
39331
+ return sanitized;
39332
+ };
39333
+ const SocketScoreSchema = Struct({
39244
39334
  overall: Number$1,
39245
39335
  license: Number$1,
39246
39336
  maintenance: Number$1,
39247
39337
  quality: Number$1,
39248
39338
  supplyChain: Number$1,
39249
39339
  vulnerability: Number$1
39250
- })) }));
39251
- const SCORE_AXES = [
39252
- {
39253
- key: "supplyChain",
39254
- label: "supply chain",
39255
- gates: true
39256
- },
39257
- {
39258
- key: "vulnerability",
39259
- label: "vulnerability",
39260
- gates: true
39261
- },
39340
+ });
39341
+ const SocketAlertSchema = Struct({
39342
+ type: String$1,
39343
+ severity: String$1,
39344
+ file: optional(NullOr(String$1)),
39345
+ props: optional(NullOr(Struct({ note: optional(NullOr(String$1)) })))
39346
+ });
39347
+ const SocketArtifactSchema = Struct({ score: optional(SocketScoreSchema) });
39348
+ const RawAlertsSchema = Struct({ alerts: optional(NullOr(ArraySchema(Unknown))) });
39349
+ const decodeArtifact = decodeUnknownOption(SocketArtifactSchema);
39350
+ const decodeRawAlerts = decodeUnknownOption(RawAlertsSchema);
39351
+ const decodeAlert = decodeUnknownOption(SocketAlertSchema);
39352
+ const extractAlerts = (parsed) => {
39353
+ const rawAlerts = getOrNull(decodeRawAlerts(parsed))?.alerts;
39354
+ if (!rawAlerts) return [];
39355
+ const alerts = [];
39356
+ for (const candidate of rawAlerts) {
39357
+ const alert = getOrNull(decodeAlert(candidate));
39358
+ if (alert !== null) alerts.push(alert);
39359
+ }
39360
+ return alerts;
39361
+ };
39362
+ const GATED_AXES = [{
39363
+ key: "supplyChain",
39364
+ label: "supply chain",
39365
+ guidance: {
39366
+ meaning: "risky install-time behavior — install scripts, obfuscated or native code, network/filesystem/shell access, or typosquatting",
39367
+ remediation: "Confirm this is the package you meant to install, and prefer a more established, audited alternative"
39368
+ }
39369
+ }, {
39370
+ key: "vulnerability",
39371
+ label: "vulnerability",
39372
+ guidance: {
39373
+ meaning: "known security vulnerabilities (CVEs) affecting this version",
39374
+ remediation: "Upgrade to a version with no known advisories (run `npm audit` to find one), or replace it"
39375
+ }
39376
+ }];
39377
+ const CONTEXT_AXES = [
39262
39378
  {
39263
39379
  key: "maintenance",
39264
- label: "maintenance",
39265
- gates: false
39380
+ label: "maintenance"
39266
39381
  },
39267
39382
  {
39268
39383
  key: "quality",
39269
- label: "quality",
39270
- gates: false
39384
+ label: "quality"
39271
39385
  },
39272
39386
  {
39273
39387
  key: "license",
39274
- label: "license",
39275
- gates: false
39388
+ label: "license"
39276
39389
  }
39277
39390
  ];
39278
- const GATED_AXES = SCORE_AXES.filter((axis) => axis.gates);
39391
+ const SCORE_AXES = [...GATED_AXES, ...CONTEXT_AXES];
39279
39392
  const worstGatedAxis = (score) => {
39280
39393
  let worst = GATED_AXES[0];
39281
39394
  for (const axis of GATED_AXES) if (score[axis.key] < score[worst.key]) worst = axis;
@@ -39298,8 +39411,7 @@ const resolveConcreteVersion = (spec) => {
39298
39411
  const trimmed = spec.trim();
39299
39412
  if (trimmed.length === 0) return null;
39300
39413
  if (trimmed.includes(":")) return null;
39301
- const match = trimmed.match(/\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?/);
39302
- return match ? match[0] : null;
39414
+ return import_semver.minVersion(trimmed)?.version ?? null;
39303
39415
  };
39304
39416
  const locateDependencyKey = (packageJsonText, section, name) => {
39305
39417
  const needle = `"${name}"`;
@@ -39358,7 +39470,7 @@ const readPackageJsonText = (packageJsonPath) => {
39358
39470
  }
39359
39471
  };
39360
39472
  const toPurl = (dependency) => `pkg:npm/${dependency.name}@${dependency.version}`;
39361
- const parseScoreFromBody = (body) => {
39473
+ const parseArtifactFromBody = (body) => {
39362
39474
  for (const line of body.split("\n")) {
39363
39475
  if (line.trim().length === 0) continue;
39364
39476
  let parsed;
@@ -39368,26 +39480,30 @@ const parseScoreFromBody = (body) => {
39368
39480
  continue;
39369
39481
  }
39370
39482
  const artifact = getOrNull(decodeArtifact(parsed));
39371
- if (artifact?.score) return artifact.score;
39483
+ if (artifact?.score) return {
39484
+ score: artifact.score,
39485
+ alerts: extractAlerts(parsed)
39486
+ };
39372
39487
  }
39373
39488
  return null;
39374
39489
  };
39375
- const fetchSocketScore = (dependency) => tryPromise(async (signal) => {
39490
+ const fetchSocketArtifact = (dependency) => tryPromise(async (signal) => {
39376
39491
  const requestUrl = `${SOCKET_FREE_PURL_API_BASE}/${encodeURIComponent(toPurl(dependency))}`;
39377
39492
  const response = await fetch(requestUrl, {
39378
39493
  headers: { "User-Agent": SOCKET_FREE_USER_AGENT },
39379
39494
  signal
39380
39495
  });
39381
39496
  if (!response.ok) return null;
39382
- return parseScoreFromBody(await response.text());
39383
- }).pipe(timeout(FETCH_TIMEOUT_MS), orElseSucceed(() => null), tap$1((score) => {
39497
+ return parseArtifactFromBody(await response.text());
39498
+ }).pipe(timeout(FETCH_TIMEOUT_MS), orElseSucceed(() => null), tap$1((artifact) => {
39384
39499
  const scoreAttributes = {};
39385
- if (score !== null) {
39386
- scoreAttributes["socket.score.overall"] = toHundred(score.overall);
39387
- for (const axis of SCORE_AXES) scoreAttributes[`socket.score.${axis.key}`] = toHundred(score[axis.key]);
39500
+ if (artifact !== null) {
39501
+ scoreAttributes["socket.score.overall"] = toHundred(artifact.score.overall);
39502
+ for (const axis of SCORE_AXES) scoreAttributes[`socket.score.${axis.key}`] = toHundred(artifact.score[axis.key]);
39503
+ scoreAttributes["socket.alert.count"] = artifact.alerts.length;
39388
39504
  }
39389
39505
  return annotateCurrentSpan({
39390
- "socket.scored": score !== null,
39506
+ "socket.scored": artifact !== null,
39391
39507
  ...scoreAttributes
39392
39508
  });
39393
39509
  }), withSpan("SupplyChain.fetchScore", { attributes: {
@@ -39395,16 +39511,69 @@ const fetchSocketScore = (dependency) => tryPromise(async (signal) => {
39395
39511
  "socket.version": dependency.version,
39396
39512
  "socket.purl": toPurl(dependency)
39397
39513
  } }));
39398
- const formatAxisScores = (score) => SCORE_AXES.map((axis) => `${axis.label} ${toHundred(score[axis.key])}`).join(", ");
39399
- const buildLowScoreDiagnostic = (dependency, score, failingAxis, options) => {
39514
+ const formatOtherAxisScores = (score, failingKey) => SCORE_AXES.filter((axis) => axis.key !== failingKey).map((axis) => `${axis.label} ${toHundred(score[axis.key])}`).join(", ");
39515
+ const ALERT_SEVERITY_RANK = {
39516
+ critical: 4,
39517
+ high: 3,
39518
+ middle: 2,
39519
+ medium: 2,
39520
+ low: 1
39521
+ };
39522
+ const severityRank = (severity) => ALERT_SEVERITY_RANK[severity.toLowerCase()] ?? 0;
39523
+ const displaySeverity = (severity) => {
39524
+ const normalized = sanitizeTerminalText(severity.toLowerCase());
39525
+ return normalized === "middle" ? "medium" : normalized;
39526
+ };
39527
+ const ALERT_TYPE_LABELS = {
39528
+ malware: "known malware",
39529
+ gptMalware: "AI-detected malware",
39530
+ gptSecurity: "AI-detected security risk",
39531
+ gptAnomaly: "AI-detected code anomaly",
39532
+ envVars: "environment-variable access",
39533
+ usesEval: "use of eval",
39534
+ troll: "protestware",
39535
+ didYouMean: "possible typosquat",
39536
+ typosquat: "possible typosquat"
39537
+ };
39538
+ const humanizeAlertType = (type) => type.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
39539
+ const friendlyAlertType = (type) => ALERT_TYPE_LABELS[type] ?? sanitizeTerminalText(humanizeAlertType(type));
39540
+ const summarizeAlertNote = (note) => {
39541
+ const collapsed = sanitizeTerminalText(note.replace(/\s+/g, " ").trim());
39542
+ const firstSentence = collapsed.split(/(?<=\.)\s/)[0] || collapsed;
39543
+ if (firstSentence.length <= 160) return firstSentence.replace(/\.$/, "");
39544
+ return `${firstSentence.slice(0, 160).trimEnd()}…`;
39545
+ };
39546
+ const selectTopAlerts = (alerts) => [...alerts].sort((left, right) => severityRank(right.severity) - severityRank(left.severity)).slice(0, 3);
39547
+ const formatAlertReason = (topAlerts, totalCount) => {
39548
+ if (topAlerts.length === 1) {
39549
+ const [alert] = topAlerts;
39550
+ const location = alert.file ? ` in \`${sanitizeTerminalText(alert.file)}\`` : "";
39551
+ const note = alert.props?.note ? summarizeAlertNote(alert.props.note) : null;
39552
+ const detail = note ? `: "${note}"` : "";
39553
+ return `Socket flagged a ${displaySeverity(alert.severity)} ${friendlyAlertType(alert.type)} alert${location}${detail}.`;
39554
+ }
39555
+ return `Socket flagged ${totalCount} alerts (${topAlerts.map((alert) => friendlyAlertType(alert.type)).join(", ")}${totalCount > topAlerts.length ? ` (+${totalCount - topAlerts.length} more)` : ""}); most severe: ${displaySeverity(topAlerts[0].severity)}.`;
39556
+ };
39557
+ const formatDependencyIdentity = (dependency) => import_semver.valid(dependency.spec) !== null ? `${dependency.name}@${dependency.version}` : `${dependency.name}@${dependency.version} (lowest version "${dependency.spec}" allows)`;
39558
+ const buildSupplyChainHelp = (dependency, failingAxis, topAlerts, packagePageUrl, options) => {
39559
+ const hasCriticalAlert = topAlerts.some((alert) => alert.severity.toLowerCase() === "critical");
39560
+ const entry = `\`"${dependency.name}": "${dependency.spec}"\``;
39561
+ return `${hasCriticalAlert ? `Treat ${dependency.name} as compromised — do not ship it. Remove ${entry} from package.json and your lockfile, then audit anything it ran.` : `${failingAxis.guidance.remediation}; update ${entry} in package.json.`} Full report: ${packagePageUrl}. ${hasCriticalAlert ? `Only if you've confirmed this is a false positive, set \`supplyChain.enabled: false\`.` : `If you've reviewed and accepted this package, raise \`supplyChain.minScore\` (currently ${options.minScore}) or set \`supplyChain.severity: "warning"\`.`}`;
39562
+ };
39563
+ const buildLowScoreDiagnostic = (dependency, artifact, failingAxis, options) => {
39400
39564
  const packagePageUrl = `${SOCKET_PACKAGE_PAGE_BASE}/${dependency.name}/overview/${dependency.version}`;
39565
+ const failingScore = toHundred(artifact.score[failingAxis.key]);
39566
+ const topAlerts = selectTopAlerts(artifact.alerts);
39567
+ const reason = topAlerts.length > 0 ? formatAlertReason(topAlerts, artifact.alerts.length) : `This points to ${failingAxis.guidance.meaning}.`;
39568
+ const headline = `\`${formatDependencyIdentity(dependency)}\` scored ${failingScore}/100 on Socket's ${failingAxis.label} axis (minimum ${options.minScore}).`;
39569
+ const otherAxes = `Other axes — ${formatOtherAxisScores(artifact.score, failingAxis.key)}.`;
39401
39570
  return {
39402
39571
  filePath: "package.json",
39403
39572
  plugin: SUPPLY_CHAIN_PLUGIN,
39404
39573
  rule: SUPPLY_CHAIN_RULE,
39405
39574
  severity: options.severity,
39406
- message: `\`${dependency.name}\` (declared in package.json as "${dependency.spec}", scored at ${dependency.version}) has a Socket ${failingAxis.label} score of ${toHundred(score[failingAxis.key])}/100 (below the minimum of ${options.minScore}). Axis scores — ${formatAxisScores(score)}.`,
39407
- help: `Update or replace the \`"${dependency.name}": "${dependency.spec}"\` entry in package.json. Review ${dependency.name} on Socket: ${packagePageUrl}. Or raise \`supplyChain.minScore\` if you have vetted and accepted this package.`,
39575
+ message: `${headline} ${reason} ${otherAxes}`,
39576
+ help: buildSupplyChainHelp(dependency, failingAxis, topAlerts, packagePageUrl, options),
39408
39577
  url: packagePageUrl,
39409
39578
  line: dependency.line,
39410
39579
  column: dependency.column,
@@ -39430,14 +39599,14 @@ const checkSupplyChain = (input) => gen(function* () {
39430
39599
  const packageJsonPath = Path.join(input.rootDirectory, "package.json");
39431
39600
  const dependencies = collectDependenciesToScore(readPackageJson(packageJsonPath), readPackageJsonText(packageJsonPath), options.includeDevDependencies);
39432
39601
  if (dependencies.length === 0) return [];
39433
- const scores = yield* forEach$1(dependencies, fetchSocketScore, { concurrency: 8 });
39602
+ const artifacts = yield* forEach$1(dependencies, fetchSocketArtifact, { concurrency: 8 });
39434
39603
  const diagnostics = [];
39435
39604
  for (let index = 0; index < dependencies.length; index += 1) {
39436
- const score = scores[index];
39437
- if (!score) continue;
39438
- const worstAxis = worstGatedAxis(score);
39439
- if (toHundred(score[worstAxis.key]) >= options.minScore) continue;
39440
- diagnostics.push(buildLowScoreDiagnostic(dependencies[index], score, worstAxis, options));
39605
+ const artifact = artifacts[index];
39606
+ if (!artifact) continue;
39607
+ const worstAxis = worstGatedAxis(artifact.score);
39608
+ if (toHundred(artifact.score[worstAxis.key]) >= options.minScore) continue;
39609
+ diagnostics.push(buildLowScoreDiagnostic(dependencies[index], artifact, worstAxis, options));
39441
39610
  }
39442
39611
  return diagnostics;
39443
39612
  });
@@ -40011,7 +40180,7 @@ const computeConfigFingerprint = (projectDirectory, version) => {
40011
40180
  /** Display name used in client-facing messages and progress titles. */
40012
40181
  const SERVER_DISPLAY_NAME = "React Doctor";
40013
40182
  /** Server version reported in `serverInfo`; injected at build, `dev` from source. */
40014
- const SERVER_VERSION = "0.5.1";
40183
+ const SERVER_VERSION = "0.5.2";
40015
40184
  /** `Diagnostic.source` shown next to every published diagnostic. */
40016
40185
  const DIAGNOSTIC_SOURCE = "react-doctor";
40017
40186
  /**
@@ -42058,5 +42227,5 @@ const startLanguageServer = () => {
42058
42227
  };
42059
42228
  //#endregion
42060
42229
  export { startLanguageServer };
42061
- !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]="1e6dd9cd-7bbf-509d-9302-bdf56d4cf879")}catch(e){}}();
42062
- //# debugId=1e6dd9cd-7bbf-509d-9302-bdf56d4cf879
42230
+ !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]="ed5a7ea7-27aa-5cf4-9315-356e4253f0f5")}catch(e){}}();
42231
+ //# debugId=ed5a7ea7-27aa-5cf4-9315-356e4253f0f5
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-doctor",
3
- "version": "0.5.1-dev.fee3fc4",
3
+ "version": "0.5.2-dev.022790b",
4
4
  "description": "Your agent writes bad React. This catches it",
5
5
  "keywords": [
6
6
  "accessibility",
@@ -54,7 +54,7 @@
54
54
  "agent-install": "0.0.5",
55
55
  "conf": "^15.1.0",
56
56
  "confbox": "^0.2.4",
57
- "deslop-js": "^0.0.23",
57
+ "deslop-js": "^0.0.24",
58
58
  "eslint-plugin-react-hooks": "^7.1.1",
59
59
  "jiti": "^2.7.0",
60
60
  "magicast": "^0.5.3",
@@ -64,7 +64,7 @@
64
64
  "vscode-languageserver": "^9.0.1",
65
65
  "vscode-languageserver-textdocument": "^1.0.12",
66
66
  "vscode-uri": "^3.1.0",
67
- "oxlint-plugin-react-doctor": "0.5.1-dev.fee3fc4"
67
+ "oxlint-plugin-react-doctor": "0.5.2-dev.022790b"
68
68
  },
69
69
  "devDependencies": {
70
70
  "@types/babel__code-frame": "^7.27.0",
@@ -72,9 +72,9 @@
72
72
  "@xterm/headless": "^6.0.0",
73
73
  "commander": "^14.0.3",
74
74
  "ora": "^9.4.0",
75
- "@react-doctor/api": "0.5.1",
76
- "@react-doctor/language-server": "0.5.1",
77
- "@react-doctor/core": "0.5.1"
75
+ "@react-doctor/api": "0.5.2",
76
+ "@react-doctor/core": "0.5.2",
77
+ "@react-doctor/language-server": "0.5.2"
78
78
  },
79
79
  "engines": {
80
80
  "node": "^20.19.0 || >=22.13.0"