deslop-js 0.0.12 → 0.0.14

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/index.cjs CHANGED
@@ -33,10 +33,10 @@ let fast_glob = require("fast-glob");
33
33
  fast_glob = __toESM(fast_glob, 1);
34
34
  let node_fs_promises = require("node:fs/promises");
35
35
  let oxc_parser = require("oxc-parser");
36
- let oxc_resolver = require("oxc-resolver");
37
- let minimatch = require("minimatch");
38
36
  let typescript = require("typescript");
39
37
  typescript = __toESM(typescript, 1);
38
+ let oxc_resolver = require("oxc-resolver");
39
+ let minimatch = require("minimatch");
40
40
 
41
41
  //#region src/constants.ts
42
42
  const DEFAULT_EXTENSIONS = [
@@ -250,6 +250,7 @@ const BUILTIN_MODULES = new Set([
250
250
  ]);
251
251
  const PLATFORM_SUFFIXES = [
252
252
  ".web",
253
+ ".react-native",
253
254
  ".native",
254
255
  ".ios",
255
256
  ".android",
@@ -257,6 +258,7 @@ const PLATFORM_SUFFIXES = [
257
258
  ".windows",
258
259
  ".macos",
259
260
  ".any",
261
+ ".react-server",
260
262
  ".server",
261
263
  ".client"
262
264
  ];
@@ -952,7 +954,7 @@ const visitFunctionParameters = (parameters, captures, functionName) => {
952
954
  inspectTypeAnnotation(parameter.typeAnnotation, captures, "function-parameter", functionName ? `${functionName}(${parameterIdentifierName ?? "?"})` : parameterIdentifierName);
953
955
  }
954
956
  };
955
- const visitFunctionLike = (functionNode, captures, functionName) => {
957
+ const visitFunctionLike$1 = (functionNode, captures, functionName) => {
956
958
  const parameters = functionNode.params;
957
959
  visitFunctionParameters(parameters, captures, functionName);
958
960
  const returnTypeNode = functionNode.returnType;
@@ -967,7 +969,7 @@ const visitVariableDeclaration = (declarationNode, captures, enclosingName) => {
967
969
  const declarationName = getIdentifierName(declarator.id);
968
970
  inspectTypeAnnotation(declarator.typeAnnotation ?? (declarator.id && isOxcAstNode(declarator.id) ? declarator.id.typeAnnotation : void 0), captures, "variable-annotation", declarationName);
969
971
  const initializerNode = declarator.init;
970
- if (isOxcAstNode(initializerNode)) if (initializerNode.type === "ArrowFunctionExpression" || initializerNode.type === "FunctionExpression") visitFunctionLike(initializerNode, captures, declarationName ?? enclosingName);
972
+ if (isOxcAstNode(initializerNode)) if (initializerNode.type === "ArrowFunctionExpression" || initializerNode.type === "FunctionExpression") visitFunctionLike$1(initializerNode, captures, declarationName ?? enclosingName);
971
973
  else walkExpressionForInlineTypes(initializerNode, captures, declarationName ?? enclosingName);
972
974
  }
973
975
  };
@@ -979,7 +981,7 @@ const walkBodyForInlineTypes = (bodyNode, captures, enclosingName, recursionDept
979
981
  for (const statement of statements) {
980
982
  if (!isOxcAstNode(statement)) continue;
981
983
  if (statement.type === "VariableDeclaration") visitVariableDeclaration(statement, captures, enclosingName);
982
- else if (statement.type === "FunctionDeclaration") visitFunctionLike(statement, captures, getIdentifierName(statement.id) ?? enclosingName);
984
+ else if (statement.type === "FunctionDeclaration") visitFunctionLike$1(statement, captures, getIdentifierName(statement.id) ?? enclosingName);
983
985
  else if (statement.type === "TSTypeAliasDeclaration") {
984
986
  const typeAliasName = getIdentifierName(statement.id);
985
987
  captureIfTypeLiteral(statement.typeAnnotation, captures, "local-type-alias", typeAliasName);
@@ -992,7 +994,7 @@ const walkExpressionForInlineTypes = (expressionNode, captures, enclosingName, r
992
994
  if (recursionDepth > 200) return;
993
995
  if (!isOxcAstNode(expressionNode)) return;
994
996
  if (expressionNode.type === "ArrowFunctionExpression" || expressionNode.type === "FunctionExpression") {
995
- visitFunctionLike(expressionNode, captures, enclosingName);
997
+ visitFunctionLike$1(expressionNode, captures, enclosingName);
996
998
  return;
997
999
  }
998
1000
  for (const value of Object.values(expressionNode)) if (Array.isArray(value)) for (const element of value) walkExpressionForInlineTypes(element, captures, enclosingName, recursionDepth + 1);
@@ -1003,7 +1005,7 @@ const visitTopLevelStatement = (statementNode, captures) => {
1003
1005
  const innerNode = statementNode.type === "ExportNamedDeclaration" || statementNode.type === "ExportDefaultDeclaration" ? statementNode.declaration ?? statementNode : statementNode;
1004
1006
  const targetNode = isOxcAstNode(innerNode) ? innerNode : statementNode;
1005
1007
  if (targetNode.type === "FunctionDeclaration") {
1006
- visitFunctionLike(targetNode, captures, getIdentifierName(targetNode.id));
1008
+ visitFunctionLike$1(targetNode, captures, getIdentifierName(targetNode.id));
1007
1009
  return;
1008
1010
  }
1009
1011
  if (targetNode.type === "VariableDeclaration") {
@@ -1023,7 +1025,7 @@ const visitTopLevelStatement = (statementNode, captures) => {
1023
1025
  }
1024
1026
  if (memberCandidate.type === "MethodDefinition" || memberCandidate.type === "TSAbstractMethodDefinition") {
1025
1027
  const methodValue = memberCandidate.value;
1026
- if (isOxcAstNode(methodValue)) visitFunctionLike(methodValue, captures, qualifiedName);
1028
+ if (isOxcAstNode(methodValue)) visitFunctionLike$1(methodValue, captures, qualifiedName);
1027
1029
  }
1028
1030
  }
1029
1031
  return;
@@ -3164,6 +3166,196 @@ const discoverMobileEntryPoints = (directory) => {
3164
3166
  }
3165
3167
  };
3166
3168
 
3169
+ //#endregion
3170
+ //#region src/collect/expo-config-plugin-entries.ts
3171
+ const EXPO_CONFIG_FILE_GLOBS = ["app.config.{ts,mts,cts,js,mjs,cjs}", "app.json"];
3172
+ const NESTED_EXPO_CONFIG_FILE_GLOBS = [
3173
+ ...EXPO_CONFIG_FILE_GLOBS,
3174
+ "**/app.config.{ts,mts,cts,js,mjs,cjs}",
3175
+ "**/app.json"
3176
+ ];
3177
+ const EXPO_REACT_NATIVE_DEPENDENCIES = new Set(["expo", "react-native"]);
3178
+ const EXPO_PLUGIN_RESOLVABLE_EXTENSIONS = SOURCE_EXTENSIONS$3.map((sourceExtension) => `.${sourceExtension}`);
3179
+ const isRecord = (value) => typeof value === "object" && value !== null;
3180
+ const isExpoOrReactNativeWorkspace = (dependencies) => [...EXPO_REACT_NATIVE_DEPENDENCIES].some((dependencyName) => dependencyName in dependencies);
3181
+ const isLocalExpoPluginPath = (value) => (value.startsWith("./") || value.startsWith("../")) && !value.includes("*") && !value.includes("?");
3182
+ const isFile = (filePath) => {
3183
+ try {
3184
+ return (0, node_fs.statSync)(filePath).isFile();
3185
+ } catch {
3186
+ return false;
3187
+ }
3188
+ };
3189
+ const resolveExpoPluginPath = (configDirectory, pluginPath) => {
3190
+ const candidatePath = (0, node_path.resolve)(configDirectory, pluginPath);
3191
+ if (isFile(candidatePath)) return candidatePath;
3192
+ for (const extension of EXPO_PLUGIN_RESOLVABLE_EXTENSIONS) {
3193
+ const candidatePathWithExtension = `${candidatePath}${extension}`;
3194
+ if (isFile(candidatePathWithExtension)) return candidatePathWithExtension;
3195
+ }
3196
+ for (const extension of EXPO_PLUGIN_RESOLVABLE_EXTENSIONS) {
3197
+ const indexCandidatePath = (0, node_path.join)(candidatePath, `index${extension}`);
3198
+ if (isFile(indexCandidatePath)) return indexCandidatePath;
3199
+ }
3200
+ };
3201
+ const addExpoPluginEntry = (entries, rootDirectory, configDirectory, pluginPath) => {
3202
+ if (!isLocalExpoPluginPath(pluginPath)) return;
3203
+ const resolvedPath = resolveExpoPluginPath(configDirectory, pluginPath);
3204
+ if (!resolvedPath) return;
3205
+ const relativePath = (0, node_path.relative)(rootDirectory, resolvedPath);
3206
+ if (relativePath !== "" && (relativePath.startsWith("..") || (0, node_path.isAbsolute)(relativePath))) return;
3207
+ entries.add(resolvedPath);
3208
+ };
3209
+ const getPropertyName = (name) => {
3210
+ if (typescript.default.isIdentifier(name) || typescript.default.isStringLiteral(name) || typescript.default.isNumericLiteral(name)) return name.text;
3211
+ };
3212
+ const unwrapExpression = (expression) => {
3213
+ let currentExpression = expression;
3214
+ while (typescript.default.isParenthesizedExpression(currentExpression)) currentExpression = currentExpression.expression;
3215
+ return currentExpression;
3216
+ };
3217
+ const collectExpoPluginPathsFromArray = (array, entries, rootDirectory, configDirectory) => {
3218
+ for (const element of array.elements) {
3219
+ if (typescript.default.isStringLiteral(element) || typescript.default.isNoSubstitutionTemplateLiteral(element)) {
3220
+ addExpoPluginEntry(entries, rootDirectory, configDirectory, element.text);
3221
+ continue;
3222
+ }
3223
+ if (typescript.default.isArrayLiteralExpression(element)) {
3224
+ const [pluginName] = element.elements;
3225
+ if (pluginName && (typescript.default.isStringLiteral(pluginName) || typescript.default.isNoSubstitutionTemplateLiteral(pluginName))) addExpoPluginEntry(entries, rootDirectory, configDirectory, pluginName.text);
3226
+ }
3227
+ }
3228
+ };
3229
+ const collectExpoPluginPathsFromConfigObject = (objectLiteral, entries, rootDirectory, configDirectory) => {
3230
+ for (const property of objectLiteral.properties) if (typescript.default.isPropertyAssignment(property) && getPropertyName(property.name) === "plugins" && typescript.default.isArrayLiteralExpression(property.initializer)) collectExpoPluginPathsFromArray(property.initializer, entries, rootDirectory, configDirectory);
3231
+ };
3232
+ const collectReturnedExpoConfigPluginPaths = (body, entries, rootDirectory, configDirectory) => {
3233
+ if (!typescript.default.isBlock(body)) {
3234
+ const expression = unwrapExpression(body);
3235
+ if (typescript.default.isObjectLiteralExpression(expression)) collectExpoPluginPathsFromConfigObject(expression, entries, rootDirectory, configDirectory);
3236
+ return;
3237
+ }
3238
+ const visit = (node) => {
3239
+ if (typescript.default.isFunctionDeclaration(node) || typescript.default.isFunctionExpression(node) || typescript.default.isArrowFunction(node)) return;
3240
+ if (typescript.default.isReturnStatement(node) && node.expression) {
3241
+ const expression = unwrapExpression(node.expression);
3242
+ if (typescript.default.isObjectLiteralExpression(expression)) collectExpoPluginPathsFromConfigObject(expression, entries, rootDirectory, configDirectory);
3243
+ return;
3244
+ }
3245
+ typescript.default.forEachChild(node, visit);
3246
+ };
3247
+ visit(body);
3248
+ };
3249
+ const collectExpoPluginPathsFromConfigExpression = (expression, entries, rootDirectory, configDirectory, bindings, seenIdentifiers = /* @__PURE__ */ new Set()) => {
3250
+ const configExpression = unwrapExpression(expression);
3251
+ if (typescript.default.isObjectLiteralExpression(configExpression)) {
3252
+ collectExpoPluginPathsFromConfigObject(configExpression, entries, rootDirectory, configDirectory);
3253
+ return;
3254
+ }
3255
+ if (typescript.default.isIdentifier(configExpression)) {
3256
+ if (seenIdentifiers.has(configExpression.text)) return;
3257
+ seenIdentifiers.add(configExpression.text);
3258
+ const boundExpression = bindings.expressions.get(configExpression.text);
3259
+ if (boundExpression) {
3260
+ collectExpoPluginPathsFromConfigExpression(boundExpression, entries, rootDirectory, configDirectory, bindings, seenIdentifiers);
3261
+ return;
3262
+ }
3263
+ const boundFunction = bindings.functions.get(configExpression.text);
3264
+ if (boundFunction?.body) collectReturnedExpoConfigPluginPaths(boundFunction.body, entries, rootDirectory, configDirectory);
3265
+ return;
3266
+ }
3267
+ if (typescript.default.isArrowFunction(configExpression)) {
3268
+ collectReturnedExpoConfigPluginPaths(configExpression.body, entries, rootDirectory, configDirectory);
3269
+ return;
3270
+ }
3271
+ if (typescript.default.isFunctionExpression(configExpression) && configExpression.body) collectReturnedExpoConfigPluginPaths(configExpression.body, entries, rootDirectory, configDirectory);
3272
+ };
3273
+ const hasDefaultExportModifier = (node) => Boolean(typescript.default.canHaveModifiers(node) && typescript.default.getModifiers(node)?.some((modifier) => modifier.kind === typescript.default.SyntaxKind.DefaultKeyword));
3274
+ const isModuleExportsAssignmentTarget = (node) => typescript.default.isPropertyAccessExpression(node) && typescript.default.isIdentifier(node.expression) && node.expression.text === "module" && node.name.text === "exports";
3275
+ const collectStaticConfigBindings = (sourceFile) => {
3276
+ const expressions = /* @__PURE__ */ new Map();
3277
+ const functions = /* @__PURE__ */ new Map();
3278
+ for (const statement of sourceFile.statements) {
3279
+ if (typescript.default.isVariableStatement(statement)) {
3280
+ for (const declaration of statement.declarationList.declarations) if (typescript.default.isIdentifier(declaration.name) && declaration.initializer) expressions.set(declaration.name.text, declaration.initializer);
3281
+ continue;
3282
+ }
3283
+ if (typescript.default.isFunctionDeclaration(statement) && statement.name) functions.set(statement.name.text, statement);
3284
+ }
3285
+ return {
3286
+ expressions,
3287
+ functions
3288
+ };
3289
+ };
3290
+ const collectExpoPluginPathsFromAppConfig = (configPath, entries, rootDirectory) => {
3291
+ const extension = (0, node_path.extname)(configPath);
3292
+ const sourceFile = typescript.default.createSourceFile(configPath, (0, node_fs.readFileSync)(configPath, "utf8"), typescript.default.ScriptTarget.Latest, true, extension === ".ts" || extension === ".mts" || extension === ".cts" ? typescript.default.ScriptKind.TS : typescript.default.ScriptKind.JS);
3293
+ const configDirectory = (0, node_path.dirname)(configPath);
3294
+ const bindings = collectStaticConfigBindings(sourceFile);
3295
+ const visit = (node) => {
3296
+ if (typescript.default.isExportAssignment(node)) {
3297
+ collectExpoPluginPathsFromConfigExpression(node.expression, entries, rootDirectory, configDirectory, bindings);
3298
+ return;
3299
+ }
3300
+ if (typescript.default.isFunctionDeclaration(node) && hasDefaultExportModifier(node) && node.body) {
3301
+ collectReturnedExpoConfigPluginPaths(node.body, entries, rootDirectory, configDirectory);
3302
+ return;
3303
+ }
3304
+ if (typescript.default.isBinaryExpression(node) && node.operatorToken.kind === typescript.default.SyntaxKind.EqualsToken && isModuleExportsAssignmentTarget(node.left)) {
3305
+ collectExpoPluginPathsFromConfigExpression(node.right, entries, rootDirectory, configDirectory, bindings);
3306
+ return;
3307
+ }
3308
+ typescript.default.forEachChild(node, visit);
3309
+ };
3310
+ visit(sourceFile);
3311
+ };
3312
+ const collectPluginPathsFromJsonValue = (value) => {
3313
+ if (!Array.isArray(value)) return [];
3314
+ const pluginPaths = [];
3315
+ for (const plugin of value) {
3316
+ if (typeof plugin === "string") {
3317
+ pluginPaths.push(plugin);
3318
+ continue;
3319
+ }
3320
+ if (Array.isArray(plugin) && typeof plugin[0] === "string") pluginPaths.push(plugin[0]);
3321
+ }
3322
+ return pluginPaths;
3323
+ };
3324
+ const collectExpoPluginPathsFromAppJson = (configPath, entries, rootDirectory) => {
3325
+ const parsedJson = JSON.parse((0, node_fs.readFileSync)(configPath, "utf8"));
3326
+ const configDirectory = (0, node_path.dirname)(configPath);
3327
+ if (!isRecord(parsedJson)) return;
3328
+ const expoConfig = parsedJson.expo;
3329
+ const expoPluginPaths = isRecord(expoConfig) ? collectPluginPathsFromJsonValue(expoConfig.plugins) : [];
3330
+ for (const pluginPath of [...expoPluginPaths, ...collectPluginPathsFromJsonValue(parsedJson.plugins)]) addExpoPluginEntry(entries, rootDirectory, configDirectory, pluginPath);
3331
+ };
3332
+ const collectExpoPluginPathsFromConfig = (configPath, entries, rootDirectory) => {
3333
+ try {
3334
+ if ((0, node_path.basename)(configPath) === "app.json") {
3335
+ collectExpoPluginPathsFromAppJson(configPath, entries, rootDirectory);
3336
+ return;
3337
+ }
3338
+ collectExpoPluginPathsFromAppConfig(configPath, entries, rootDirectory);
3339
+ } catch {}
3340
+ };
3341
+ const extractExpoConfigPluginEntries = (directory, dependencies, rootDirectory = directory, includeNestedConfigs = true) => {
3342
+ if (!isExpoOrReactNativeWorkspace(dependencies)) return [];
3343
+ const entries = /* @__PURE__ */ new Set();
3344
+ const configPaths = fast_glob.default.sync(includeNestedConfigs ? NESTED_EXPO_CONFIG_FILE_GLOBS : EXPO_CONFIG_FILE_GLOBS, {
3345
+ cwd: directory,
3346
+ absolute: true,
3347
+ onlyFiles: true,
3348
+ ignore: [
3349
+ "**/node_modules/**",
3350
+ "**/dist/**",
3351
+ "**/build/**"
3352
+ ],
3353
+ deep: 6
3354
+ });
3355
+ for (const configPath of configPaths) collectExpoPluginPathsFromConfig(configPath, entries, rootDirectory);
3356
+ return [...entries];
3357
+ };
3358
+
3167
3359
  //#endregion
3168
3360
  //#region src/resolver/source-path.ts
3169
3361
  const SOURCE_EXTENSIONS$1 = [
@@ -3204,6 +3396,8 @@ const resolveSourcePath = (distPath, directory) => {
3204
3396
  const sourceCandidate = (0, node_path.resolve)(directory, withoutExtension + sourceExtension);
3205
3397
  if ((0, node_fs.existsSync)(sourceCandidate)) return sourceCandidate;
3206
3398
  }
3399
+ const indexPrefixedCandidate = resolveWithIndexPrefix(withoutExtension, directory);
3400
+ if (indexPrefixedCandidate) return indexPrefixedCandidate;
3207
3401
  }
3208
3402
  if (matchesOutputDirectory(relativeToDist)) for (const stem of SOURCE_INDEX_FALLBACK_STEMS) for (const sourceExtension of SOURCE_EXTENSIONS$1) {
3209
3403
  const fallbackCandidate = (0, node_path.resolve)(directory, stem + sourceExtension);
@@ -3217,6 +3411,15 @@ const resolveSourcePath = (distPath, directory) => {
3217
3411
  }
3218
3412
  const indexCandidate = (0, node_path.resolve)(directory, withoutExtension, "index.ts");
3219
3413
  if ((0, node_fs.existsSync)(indexCandidate)) return indexCandidate;
3414
+ const indexPrefixedCandidate = resolveWithIndexPrefix(withoutExtension, directory);
3415
+ if (indexPrefixedCandidate) return indexPrefixedCandidate;
3416
+ }
3417
+ };
3418
+ const resolveWithIndexPrefix = (stemPath, directory) => {
3419
+ const indexPrefixedStem = `${(0, node_path.dirname)(stemPath)}/index.${(0, node_path.basename)(stemPath)}`;
3420
+ for (const sourceExtension of SOURCE_EXTENSIONS$1) {
3421
+ const candidate = (0, node_path.resolve)(directory, indexPrefixedStem + sourceExtension);
3422
+ if ((0, node_fs.existsSync)(candidate)) return candidate;
3220
3423
  }
3221
3424
  };
3222
3425
 
@@ -3576,6 +3779,11 @@ const resolveEntries = async (config) => {
3576
3779
  for (const workspacePackage of entryEligiblePackages) tsConfigIncludeEntries.push(...extractTsConfigIncludeFilesEntries(workspacePackage.directory));
3577
3780
  const configStringEntries = extractConfigStringReferencedEntries(absoluteRoot);
3578
3781
  for (const workspacePackage of entryEligiblePackages) configStringEntries.push(...extractConfigStringReferencedEntries(workspacePackage.directory));
3782
+ const expoConfigPluginEntries = extractExpoConfigPluginEntries(absoluteRoot, readPackageJsonDependencies((0, node_path.join)(absoluteRoot, "package.json")), absoluteRoot, false);
3783
+ for (const workspacePackage of entryEligiblePackages) {
3784
+ const workspacePackageDependencies = readPackageJsonDependencies((0, node_path.join)(workspacePackage.directory, "package.json"));
3785
+ expoConfigPluginEntries.push(...extractExpoConfigPluginEntries(workspacePackage.directory, workspacePackageDependencies, absoluteRoot));
3786
+ }
3579
3787
  const sectionsModuleEntries = extractSectionsModuleEntries(absoluteRoot);
3580
3788
  const wranglerEntries = extractWranglerEntries(absoluteRoot);
3581
3789
  for (const workspacePackage of entryEligiblePackages) wranglerEntries.push(...extractWranglerEntries(workspacePackage.directory));
@@ -3604,6 +3812,7 @@ const resolveEntries = async (config) => {
3604
3812
  ...webWorkerEntries,
3605
3813
  ...tsConfigIncludeEntries,
3606
3814
  ...configStringEntries,
3815
+ ...expoConfigPluginEntries,
3607
3816
  ...sectionsModuleEntries,
3608
3817
  ...wranglerEntries,
3609
3818
  ...pluginFileEntries,
@@ -3823,6 +4032,7 @@ const SCRIPT_MULTIPLEXERS = new Set([
3823
4032
  "lerna",
3824
4033
  "ultra"
3825
4034
  ]);
4035
+ const TSCONFIG_PROJECT_FLAGS = new Set(["--project", "-p"]);
3826
4036
  const CONFIG_LIKE_FLAGS = new Set([
3827
4037
  "--config",
3828
4038
  "-c",
@@ -3968,7 +4178,8 @@ const extractScriptFileArguments = (scriptCommand, directory) => {
3968
4178
  const configPath = tokens[tokenIndex + 1].replace(/^['"]|['"]$/g, "");
3969
4179
  if (looksLikeFilePath(configPath)) {
3970
4180
  const absoluteConfigPath = (0, node_path.resolve)(directory, configPath);
3971
- if ((0, node_fs.existsSync)(absoluteConfigPath)) entries.push(absoluteConfigPath);
4181
+ if ((0, node_fs.existsSync)(absoluteConfigPath)) if (TSCONFIG_PROJECT_FLAGS.has(token) && TSCONFIG_PROJECT_PATTERN.test(absoluteConfigPath)) entries.push(...expandTsConfigProjectEntries(absoluteConfigPath));
4182
+ else entries.push(absoluteConfigPath);
3972
4183
  }
3973
4184
  tokenIndex++;
3974
4185
  }
@@ -3977,9 +4188,11 @@ const extractScriptFileArguments = (scriptCommand, directory) => {
3977
4188
  const equalsIndex = token.indexOf("=");
3978
4189
  if (equalsIndex > 0 && CONFIG_LIKE_FLAGS.has(token.slice(0, equalsIndex))) {
3979
4190
  const configValue = token.slice(equalsIndex + 1);
4191
+ const flagName = token.slice(0, equalsIndex);
3980
4192
  if (configValue && looksLikeFilePath(configValue)) {
3981
4193
  const absoluteConfigPath = (0, node_path.resolve)(directory, configValue);
3982
- if ((0, node_fs.existsSync)(absoluteConfigPath)) entries.push(absoluteConfigPath);
4194
+ if ((0, node_fs.existsSync)(absoluteConfigPath)) if (TSCONFIG_PROJECT_FLAGS.has(flagName) && TSCONFIG_PROJECT_PATTERN.test(absoluteConfigPath)) entries.push(...expandTsConfigProjectEntries(absoluteConfigPath));
4195
+ else entries.push(absoluteConfigPath);
3983
4196
  }
3984
4197
  continue;
3985
4198
  }
@@ -4282,6 +4495,7 @@ const extractScriptTagsFromHtmlFile = (htmlFilePath) => {
4282
4495
  return entries;
4283
4496
  };
4284
4497
  const TSCONFIG_FILENAME_GLOBS = ["tsconfig.json", "tsconfig.*.json"];
4498
+ const TSCONFIG_PROJECT_PATTERN = /(?:^|[\\/])tsconfig(?:\.[^.]+)?\.json$/;
4285
4499
  const stripJsoncCommentsLocal = (sourceText) => {
4286
4500
  let result = "";
4287
4501
  let insideString = false;
@@ -4353,6 +4567,34 @@ const extractTsConfigIncludeFilesEntries = (directory) => {
4353
4567
  } catch {}
4354
4568
  return entries;
4355
4569
  };
4570
+ const expandTsConfigProjectEntries = (tsconfigAbsolutePath) => {
4571
+ const entries = [];
4572
+ try {
4573
+ const cleaned = stripJsoncCommentsLocal((0, node_fs.readFileSync)(tsconfigAbsolutePath, "utf-8"));
4574
+ const tsconfigJson = JSON.parse(cleaned);
4575
+ const tsconfigDir = (0, node_path.dirname)(tsconfigAbsolutePath);
4576
+ if (Array.isArray(tsconfigJson.files)) for (const fileItem of tsconfigJson.files) {
4577
+ if (typeof fileItem !== "string") continue;
4578
+ const candidatePath = (0, node_path.resolve)(tsconfigDir, fileItem);
4579
+ if ((0, node_fs.existsSync)(candidatePath)) entries.push(candidatePath);
4580
+ }
4581
+ if (Array.isArray(tsconfigJson.include)) for (const includePattern of tsconfigJson.include) {
4582
+ if (typeof includePattern !== "string") continue;
4583
+ const expandedFiles = fast_glob.default.sync(includePattern, {
4584
+ cwd: tsconfigDir,
4585
+ absolute: true,
4586
+ onlyFiles: true,
4587
+ ignore: [
4588
+ "**/node_modules/**",
4589
+ "**/dist/**",
4590
+ "**/build/**"
4591
+ ]
4592
+ });
4593
+ entries.push(...expandedFiles);
4594
+ }
4595
+ } catch {}
4596
+ return entries;
4597
+ };
4356
4598
  const WRANGLER_TOML_MAIN_PATTERN = /^\s*main\s*=\s*['"]([^'"\n]+)['"]/m;
4357
4599
  const WRANGLER_JSON_MAIN_PATTERN = /"main"\s*:\s*"([^"]+)"/;
4358
4600
  const WRANGLER_SERVICE_BINDINGS_PATTERN = /entry_point\s*=\s*['"]([^'"\n]+)['"]/g;
@@ -5446,7 +5688,7 @@ const FRAMEWORK_PATTERNS = [
5446
5688
  "app/_layout.{ts,tsx,js,jsx}",
5447
5689
  "app/index.{ts,tsx,js,jsx}"
5448
5690
  ],
5449
- alwaysUsed: ["app.json", "app.config.{ts,js}"]
5691
+ alwaysUsed: ["app.json", "app.config.{ts,mts,cts,js,mjs,cjs}"]
5450
5692
  },
5451
5693
  {
5452
5694
  enablers: ["wrangler"],
@@ -5783,6 +6025,40 @@ const discoverToolingEntryPoints = (rootDir, workspacePackages) => {
5783
6025
  };
5784
6026
  };
5785
6027
 
6028
+ //#endregion
6029
+ //#region src/utils/is-platform-builtin-or-virtual.ts
6030
+ const BUILTIN_SUBPATH_NODE_MODULES = new Set([
6031
+ "fs",
6032
+ "dns",
6033
+ "stream",
6034
+ "readline",
6035
+ "timers",
6036
+ "util",
6037
+ "test",
6038
+ "assert",
6039
+ "inspector",
6040
+ "path"
6041
+ ]);
6042
+ /**
6043
+ * True for module specifiers that don't correspond to a real on-disk
6044
+ * package — Node / Bun / Cloudflare / Sass built-ins, the Deno `std`
6045
+ * bare specifier, and Vite `virtual:` modules — so they aren't mistakenly
6046
+ * surfaced as `unused-dependency` or `unresolved-import`.
6047
+ */
6048
+ const isPlatformBuiltinOrVirtualSpecifier = (specifier) => {
6049
+ if (specifier.startsWith("virtual:")) return true;
6050
+ if (specifier === "bun" || specifier.startsWith("bun:")) return true;
6051
+ if (specifier.startsWith("cloudflare:")) return true;
6052
+ if (specifier.startsWith("sass:")) return true;
6053
+ if (specifier === "std" || specifier.startsWith("std/")) return true;
6054
+ const stripped = specifier.startsWith("node:") ? specifier.slice(5) : specifier;
6055
+ const slashIndex = stripped.indexOf("/");
6056
+ if (slashIndex === -1) return BUILTIN_MODULES.has(stripped);
6057
+ const baseName = stripped.slice(0, slashIndex);
6058
+ if (!BUILTIN_MODULES.has(baseName)) return false;
6059
+ return BUILTIN_SUBPATH_NODE_MODULES.has(baseName);
6060
+ };
6061
+
5786
6062
  //#endregion
5787
6063
  //#region src/resolver/resolve.ts
5788
6064
  const fileExistsCache = /* @__PURE__ */ new Map();
@@ -6577,21 +6853,7 @@ const stripJsonComments = (content) => {
6577
6853
  }
6578
6854
  return result.replace(/,(\s*[}\]])/g, "$1");
6579
6855
  };
6580
- const BUILTIN_SUBPATH_MODULES = new Set([
6581
- "fs",
6582
- "dns",
6583
- "stream",
6584
- "readline",
6585
- "timers",
6586
- "util"
6587
- ]);
6588
- const isBuiltinModule = (specifier) => {
6589
- if (specifier.startsWith("node:")) return true;
6590
- const baseName = specifier.split("/")[0];
6591
- if (!BUILTIN_MODULES.has(baseName)) return false;
6592
- if (!specifier.includes("/")) return true;
6593
- return BUILTIN_SUBPATH_MODULES.has(baseName);
6594
- };
6856
+ const isBuiltinModule = (specifier) => isPlatformBuiltinOrVirtualSpecifier(specifier);
6595
6857
  const isBareSpecifier = (specifier) => !specifier.startsWith(".") && !specifier.startsWith("/");
6596
6858
  const extractPackageNameFromSpecifier = (specifier) => {
6597
6859
  if (specifier.startsWith("node:")) return specifier.slice(5).split("/")[0];
@@ -8476,78 +8738,2417 @@ const detectDuplicateInlineTypes = (graph) => {
8476
8738
  };
8477
8739
 
8478
8740
  //#endregion
8479
- //#region src/utils/run-safe-detector.ts
8480
- const runSafeDetector = (input) => {
8481
- try {
8482
- return input.detector();
8483
- } catch (caughtError) {
8484
- input.errorSink.push(new DetectorError({
8485
- module: input.module,
8486
- message: `${input.detectorName} threw ${input.contextDescription}`,
8487
- detail: describeUnknownError(caughtError)
8741
+ //#region src/report/cross-file-duplicate-exports.ts
8742
+ const buildReExportSourceSets = (graph) => {
8743
+ const reExportSources = /* @__PURE__ */ new Map();
8744
+ for (const edge of graph.edges) {
8745
+ if (!edge.isReExportEdge) continue;
8746
+ const existing = reExportSources.get(edge.source);
8747
+ if (existing) existing.add(edge.target);
8748
+ else reExportSources.set(edge.source, new Set([edge.target]));
8749
+ }
8750
+ return reExportSources;
8751
+ };
8752
+ /**
8753
+ * Two duplicate-export files "share a common importer" when there exists a
8754
+ * third file that imports from both, OR one duplicate file imports another.
8755
+ * This filters out coincidental duplicates among unrelated leaf modules
8756
+ * (SvelteKit/Next.js route files, scripts in different parts of a monorepo,
8757
+ * etc.) that happen to export the same name but can never be confused at any
8758
+ * import site.
8759
+ */
8760
+ const hasCommonImporter = (moduleIndices, graph) => {
8761
+ if (moduleIndices.length <= 1) return false;
8762
+ const duplicateModuleSet = new Set(moduleIndices);
8763
+ const importerOwner = /* @__PURE__ */ new Map();
8764
+ for (const moduleIndex of moduleIndices) {
8765
+ const importers = graph.reverseEdges.get(moduleIndex) ?? [];
8766
+ for (const importerIndex of importers) {
8767
+ if (duplicateModuleSet.has(importerIndex)) return true;
8768
+ const previousOwner = importerOwner.get(importerIndex);
8769
+ if (previousOwner === void 0) importerOwner.set(importerIndex, moduleIndex);
8770
+ else if (previousOwner !== moduleIndex) return true;
8771
+ }
8772
+ }
8773
+ return false;
8774
+ };
8775
+ /**
8776
+ * Cross-file duplicate exports: the same exported name lives in 2+ files.
8777
+ *
8778
+ * Filters applied (to keep the rule actionable):
8779
+ * - default exports are skipped (every module gets one and it's not actionable)
8780
+ * - re-export chains are pruned: if module A re-exports `Foo` from module B,
8781
+ * the (A, B) pair is one chain, not two real declarations
8782
+ * - TypeScript value/type namespace split: `export const X` and `export type X`
8783
+ * in the same file are distinct in TS's value/type namespaces; same name in a
8784
+ * value file and a type file is not a true duplicate either
8785
+ * - common-importer filter: only report duplicates where two of the duplicate
8786
+ * files share an importer or one imports another, so unrelated route files in
8787
+ * different parts of a repo don't get flagged
8788
+ */
8789
+ const detectCrossFileDuplicateExports = (graph) => {
8790
+ const reExportSources = buildReExportSourceSets(graph);
8791
+ const exportEntriesByName = /* @__PURE__ */ new Map();
8792
+ for (const module of graph.modules) {
8793
+ if (!module.isReachable) continue;
8794
+ if (module.isDeclarationFile) continue;
8795
+ if (module.isEntryPoint) continue;
8796
+ for (const exportInfo of module.exports) {
8797
+ if (exportInfo.isDefault) continue;
8798
+ if (exportInfo.isSynthetic) continue;
8799
+ if (exportInfo.name === "*") continue;
8800
+ if (exportInfo.isReExport) continue;
8801
+ const entry = {
8802
+ moduleIndex: module.fileId.index,
8803
+ path: module.fileId.path,
8804
+ line: exportInfo.line,
8805
+ column: exportInfo.column,
8806
+ isTypeOnly: exportInfo.isTypeOnly
8807
+ };
8808
+ const existing = exportEntriesByName.get(exportInfo.name);
8809
+ if (existing) existing.push(entry);
8810
+ else exportEntriesByName.set(exportInfo.name, [entry]);
8811
+ }
8812
+ }
8813
+ const findings = [];
8814
+ const sortedEntries = [...exportEntriesByName.entries()].sort(([nameA], [nameB]) => nameA.localeCompare(nameB));
8815
+ for (const [name, entries] of sortedEntries) {
8816
+ if (entries.length <= 1) continue;
8817
+ const hasValueExport = entries.some((entry) => !entry.isTypeOnly);
8818
+ const hasTypeExport = entries.some((entry) => entry.isTypeOnly);
8819
+ if (hasValueExport && hasTypeExport) {
8820
+ const valueModuleIndices = new Set(entries.filter((entry) => !entry.isTypeOnly).map((entry) => entry.moduleIndex));
8821
+ const typeModuleIndices = new Set(entries.filter((entry) => entry.isTypeOnly).map((entry) => entry.moduleIndex));
8822
+ if (valueModuleIndices.size <= 1 && typeModuleIndices.size <= 1) continue;
8823
+ }
8824
+ const moduleIndexSet = new Set(entries.map((entry) => entry.moduleIndex));
8825
+ const independentEntries = entries.filter((entry) => {
8826
+ const sources = reExportSources.get(entry.moduleIndex);
8827
+ if (!sources) return true;
8828
+ for (const sourceIndex of sources) if (moduleIndexSet.has(sourceIndex)) return false;
8829
+ return true;
8830
+ });
8831
+ if (independentEntries.length <= 1) continue;
8832
+ if (!hasCommonImporter(independentEntries.map((entry) => entry.moduleIndex), graph)) continue;
8833
+ const locations = independentEntries.map((entry) => ({
8834
+ path: entry.path,
8835
+ line: entry.line,
8836
+ column: entry.column,
8837
+ isTypeOnly: entry.isTypeOnly
8488
8838
  }));
8489
- return input.fallback;
8839
+ findings.push({
8840
+ name,
8841
+ locations,
8842
+ confidence: "medium",
8843
+ reason: `"${name}" is exported from ${locations.length} files that share a common importer — consumers may import the wrong one`
8844
+ });
8490
8845
  }
8846
+ return findings;
8491
8847
  };
8492
8848
 
8493
8849
  //#endregion
8494
- //#region src/semantic/program.ts
8495
- const failureFor = (reason, message, options = { rootDir: "" }) => {
8850
+ //#region src/utils/compute-line-starts.ts
8851
+ const LINE_FEED_CHAR_CODE = 10;
8852
+ const computeLineStarts = (sourceText) => {
8853
+ const lineStarts = [0];
8854
+ for (let charIndex = 0; charIndex < sourceText.length; charIndex++) if (sourceText.charCodeAt(charIndex) === LINE_FEED_CHAR_CODE) lineStarts.push(charIndex + 1);
8855
+ return lineStarts;
8856
+ };
8857
+
8858
+ //#endregion
8859
+ //#region src/utils/offset-to-line-column.ts
8860
+ const offsetToLineColumn = (byteOffset, lineStarts) => {
8861
+ let lowIndex = 0;
8862
+ let highIndex = lineStarts.length - 1;
8863
+ while (lowIndex < highIndex) {
8864
+ const middleIndex = lowIndex + highIndex + 1 >>> 1;
8865
+ if (lineStarts[middleIndex] <= byteOffset) lowIndex = middleIndex;
8866
+ else highIndex = middleIndex - 1;
8867
+ }
8496
8868
  return {
8497
- reason,
8498
- message,
8499
- error: new TypeScriptError({
8500
- code: {
8501
- "no-tsconfig": "tsconfig-not-found",
8502
- "tsconfig-parse-error": "tsconfig-parse-failed",
8503
- "program-creation-failed": "ts-program-creation-failed",
8504
- "too-many-files": "ts-program-too-large",
8505
- "typescript-load-failed": "ts-not-loadable"
8506
- }[reason],
8507
- severity: reason === "no-tsconfig" ? "info" : "warning",
8508
- message,
8509
- path: options.rootDir || void 0,
8510
- detail: options.detail
8511
- })
8869
+ line: lowIndex + 1,
8870
+ column: byteOffset - lineStarts[lowIndex]
8512
8871
  };
8513
8872
  };
8514
- const findNearestTsconfig = (rootDir, explicitPath) => {
8515
- if (explicitPath) {
8516
- const absoluteExplicit = (0, node_path.resolve)(rootDir, explicitPath);
8517
- if ((0, node_fs.existsSync)(absoluteExplicit)) return absoluteExplicit;
8518
- return;
8873
+
8874
+ //#endregion
8875
+ //#region src/duplicate-blocks/concatenate.ts
8876
+ const SENTINEL_FILE_INDEX = Number.MAX_SAFE_INTEGER;
8877
+ /**
8878
+ * Rank-reduce token hashes to dense 0..K-1 integers and concatenate every
8879
+ * file's reduced sequence with a unique negative sentinel between files. Dense
8880
+ * ranks shrink the suffix-array's bucket counters from ~4 billion to a few
8881
+ * thousand (the standard prefix-doubling speedup), and negative sentinels
8882
+ * guarantee no real-token suffix can match across a file boundary.
8883
+ */
8884
+ const rankReduceAndConcatenate = (filesHashedTokens) => {
8885
+ const uniqueHashes = /* @__PURE__ */ new Set();
8886
+ for (const fileTokens of filesHashedTokens) for (const hashedToken of fileTokens) uniqueHashes.add(hashedToken.hash);
8887
+ const sortedUniqueHashes = [...uniqueHashes].sort((leftHash, rightHash) => leftHash - rightHash);
8888
+ const hashToRank = /* @__PURE__ */ new Map();
8889
+ for (let rankIndex = 0; rankIndex < sortedUniqueHashes.length; rankIndex++) hashToRank.set(sortedUniqueHashes[rankIndex], rankIndex + 1);
8890
+ const sequenceLength = filesHashedTokens.reduce((runningSum, fileTokens) => runningSum + fileTokens.length, 0) + Math.max(0, filesHashedTokens.length - 1);
8891
+ const tokenSequence = new Array(sequenceLength);
8892
+ const fileOf = new Array(sequenceLength);
8893
+ const fileOffsets = new Array(filesHashedTokens.length);
8894
+ let writeCursor = 0;
8895
+ let nextSentinelValue = -1;
8896
+ for (let fileIndex = 0; fileIndex < filesHashedTokens.length; fileIndex++) {
8897
+ fileOffsets[fileIndex] = writeCursor;
8898
+ const fileTokens = filesHashedTokens[fileIndex];
8899
+ for (const hashedToken of fileTokens) {
8900
+ tokenSequence[writeCursor] = hashToRank.get(hashedToken.hash) ?? 0;
8901
+ fileOf[writeCursor] = fileIndex;
8902
+ writeCursor++;
8903
+ }
8904
+ if (fileIndex < filesHashedTokens.length - 1) {
8905
+ tokenSequence[writeCursor] = nextSentinelValue;
8906
+ fileOf[writeCursor] = SENTINEL_FILE_INDEX;
8907
+ writeCursor++;
8908
+ nextSentinelValue--;
8909
+ }
8519
8910
  }
8520
- for (const candidateName of DEFAULT_SEMANTIC_TSCONFIG_NAMES) {
8521
- const candidatePath = (0, node_path.resolve)(rootDir, candidateName);
8522
- if ((0, node_fs.existsSync)(candidatePath)) return candidatePath;
8911
+ return {
8912
+ tokenSequence,
8913
+ fileOf,
8914
+ fileOffsets
8915
+ };
8916
+ };
8917
+ const SENTINEL_FILE_MARKER = SENTINEL_FILE_INDEX;
8918
+
8919
+ //#endregion
8920
+ //#region src/duplicate-blocks/extract.ts
8921
+ const buildRawBlock = (suffixArray, fileOf, fileOffsets, filesTokenCounts, intervalBegin, intervalEnd, tokenLength) => {
8922
+ const candidateInstances = [];
8923
+ for (let suffixIndex = intervalBegin; suffixIndex < intervalEnd; suffixIndex++) {
8924
+ const startPosition = suffixArray[suffixIndex];
8925
+ const fileIndex = fileOf[startPosition];
8926
+ if (fileIndex === SENTINEL_FILE_MARKER) continue;
8927
+ const tokenOffsetWithinFile = startPosition - fileOffsets[fileIndex];
8928
+ if (tokenOffsetWithinFile + tokenLength > filesTokenCounts[fileIndex]) continue;
8929
+ candidateInstances.push({
8930
+ fileIndex,
8931
+ tokenOffsetWithinFile
8932
+ });
8933
+ }
8934
+ if (candidateInstances.length < 2) return void 0;
8935
+ candidateInstances.sort((leftInstance, rightInstance) => {
8936
+ if (leftInstance.fileIndex !== rightInstance.fileIndex) return leftInstance.fileIndex - rightInstance.fileIndex;
8937
+ return leftInstance.tokenOffsetWithinFile - rightInstance.tokenOffsetWithinFile;
8938
+ });
8939
+ const dedupedInstances = [];
8940
+ for (const instance of candidateInstances) {
8941
+ const lastInstance = dedupedInstances[dedupedInstances.length - 1];
8942
+ if (lastInstance !== void 0 && lastInstance.fileIndex === instance.fileIndex && instance.tokenOffsetWithinFile < lastInstance.tokenOffsetWithinFile + tokenLength) continue;
8943
+ dedupedInstances.push(instance);
8523
8944
  }
8945
+ if (dedupedInstances.length < 2) return void 0;
8946
+ return {
8947
+ instances: dedupedInstances,
8948
+ tokenLength
8949
+ };
8524
8950
  };
8525
- const createSemanticContext = (rootDir, tsconfigPath) => {
8526
- const resolvedTsconfigPath = findNearestTsconfig(rootDir, tsconfigPath);
8527
- if (!resolvedTsconfigPath) return {
8528
- ok: false,
8529
- failure: failureFor("no-tsconfig", `No tsconfig found under ${rootDir}`, { rootDir })
8951
+ /**
8952
+ * Walks `lcpArray` with a monotone stack to materialize every maximal
8953
+ * interval `[i, j]` whose minimum LCP is >= `minTokens`. Within-file
8954
+ * overlapping occurrences are dropped (keep the earliest non-overlapping
8955
+ * prefix), and any block left with fewer than two occurrences is discarded.
8956
+ */
8957
+ const extractRawDuplicateBlocks = (suffixArray, lcpArray, fileOf, fileOffsets, filesTokenCounts, minTokens) => {
8958
+ const sequenceLength = suffixArray.length;
8959
+ if (sequenceLength < 2) return [];
8960
+ const rawBlocks = [];
8961
+ const monotoneStack = [];
8962
+ for (let scanIndex = 1; scanIndex <= sequenceLength; scanIndex++) {
8963
+ const currentLcp = scanIndex < sequenceLength ? lcpArray[scanIndex] : 0;
8964
+ let intervalStart = scanIndex;
8965
+ while (monotoneStack.length > 0 && monotoneStack[monotoneStack.length - 1].lcpValue > currentLcp) {
8966
+ const popped = monotoneStack.pop();
8967
+ intervalStart = popped.startIndex;
8968
+ if (popped.lcpValue >= minTokens) {
8969
+ const candidate = buildRawBlock(suffixArray, fileOf, fileOffsets, filesTokenCounts, intervalStart - 1, scanIndex, popped.lcpValue);
8970
+ if (candidate) rawBlocks.push(candidate);
8971
+ }
8972
+ }
8973
+ if (scanIndex < sequenceLength) monotoneStack.push({
8974
+ lcpValue: currentLcp,
8975
+ startIndex: intervalStart
8976
+ });
8977
+ }
8978
+ return rawBlocks;
8979
+ };
8980
+
8981
+ //#endregion
8982
+ //#region src/duplicate-blocks/clusters.ts
8983
+ const baseName = (filePath) => {
8984
+ const trailingSlashIndex = filePath.lastIndexOf("/");
8985
+ return trailingSlashIndex === -1 ? filePath : filePath.slice(trailingSlashIndex + 1);
8986
+ };
8987
+ const buildSuggestions = (files, blocks, totalDuplicatedLines) => {
8988
+ const fileBaseNames = files.map((filePath) => baseName(filePath));
8989
+ if (files.length >= 2 && totalDuplicatedLines >= 50) {
8990
+ const estimatedSavings = blocks.reduce((runningSum, block) => runningSum + block.lineCount * Math.max(0, block.instances.length - 1), 0);
8991
+ return [{
8992
+ kind: "extract-module",
8993
+ description: `Extract ${blocks.length} shared duplicate block${blocks.length === 1 ? "" : "s"} (${totalDuplicatedLines} lines) from ${fileBaseNames.join(", ")} into a shared module`,
8994
+ estimatedSavings
8995
+ }];
8996
+ }
8997
+ return blocks.map((block) => ({
8998
+ kind: "extract-function",
8999
+ description: `Extract shared function (${block.lineCount} lines) from ${fileBaseNames.join(", ")}`,
9000
+ estimatedSavings: block.lineCount * Math.max(0, block.instances.length - 1)
9001
+ }));
9002
+ };
9003
+ const groupDuplicateBlocksIntoClusters = (duplicateBlocks) => {
9004
+ if (duplicateBlocks.length === 0) return [];
9005
+ const fileSetKeyToBucket = /* @__PURE__ */ new Map();
9006
+ for (const block of duplicateBlocks) {
9007
+ const sortedFiles = [...new Set(block.instances.map((instance) => instance.path))].sort();
9008
+ const fileSetKey = sortedFiles.join("|");
9009
+ const existing = fileSetKeyToBucket.get(fileSetKey);
9010
+ if (existing) existing.blocks.push(block);
9011
+ else fileSetKeyToBucket.set(fileSetKey, {
9012
+ files: sortedFiles,
9013
+ blocks: [block]
9014
+ });
9015
+ }
9016
+ const clusters = [];
9017
+ for (const bucket of fileSetKeyToBucket.values()) {
9018
+ const totalDuplicatedLines = bucket.blocks.reduce((runningSum, block) => runningSum + block.lineCount, 0);
9019
+ const totalDuplicatedTokens = bucket.blocks.reduce((runningSum, block) => runningSum + block.tokenCount, 0);
9020
+ clusters.push({
9021
+ files: bucket.files,
9022
+ groups: bucket.blocks,
9023
+ totalDuplicatedLines,
9024
+ totalDuplicatedTokens,
9025
+ suggestions: buildSuggestions(bucket.files, bucket.blocks, totalDuplicatedLines)
9026
+ });
9027
+ }
9028
+ clusters.sort((leftCluster, rightCluster) => {
9029
+ if (leftCluster.totalDuplicatedLines !== rightCluster.totalDuplicatedLines) return rightCluster.totalDuplicatedLines - leftCluster.totalDuplicatedLines;
9030
+ return rightCluster.groups.length - leftCluster.groups.length;
9031
+ });
9032
+ return clusters;
9033
+ };
9034
+
9035
+ //#endregion
9036
+ //#region src/duplicate-blocks/shadowed-directory-pairs.ts
9037
+ const splitDirectoryAndFile = (filePath) => {
9038
+ const trailingSlashIndex = filePath.lastIndexOf("/");
9039
+ if (trailingSlashIndex === -1) return {
9040
+ directory: "",
9041
+ baseName: filePath
8530
9042
  };
8531
- let configFileContent;
8532
- try {
8533
- configFileContent = typescript.default.readConfigFile(resolvedTsconfigPath, typescript.default.sys.readFile);
8534
- } catch (readError) {
8535
- return {
8536
- ok: false,
8537
- failure: failureFor("tsconfig-parse-error", "ts.readConfigFile threw", {
8538
- rootDir: resolvedTsconfigPath,
8539
- detail: describeUnknownError(readError)
8540
- })
9043
+ return {
9044
+ directory: filePath.slice(0, trailingSlashIndex + 1),
9045
+ baseName: filePath.slice(trailingSlashIndex + 1)
9046
+ };
9047
+ };
9048
+ const toRelative = (filePath, rootDir) => {
9049
+ if (filePath.startsWith(rootDir + "/")) return filePath.slice(rootDir.length + 1);
9050
+ if (filePath === rootDir) return "";
9051
+ return filePath;
9052
+ };
9053
+ /**
9054
+ * Collapse N two-file duplicate-block clusters that share the same
9055
+ * `(directoryA, directoryB)` and matching basenames into a single
9056
+ * `ShadowedDirectoryPair` finding — the directories themselves drifted
9057
+ * (e.g. `src/` vs `deno/lib/`, a fork, a copy-paste of a route tree).
9058
+ */
9059
+ const detectShadowedDirectoryPairs = (duplicateBlockClusters, rootDir) => {
9060
+ const directoryPairBuckets = /* @__PURE__ */ new Map();
9061
+ for (const cluster of duplicateBlockClusters) {
9062
+ if (cluster.files.length !== 2) continue;
9063
+ const [firstFile, secondFile] = cluster.files;
9064
+ const firstSplit = splitDirectoryAndFile(toRelative(firstFile, rootDir));
9065
+ const secondSplit = splitDirectoryAndFile(toRelative(secondFile, rootDir));
9066
+ if (firstSplit.baseName !== secondSplit.baseName) continue;
9067
+ const [smallerDirectory, largerDirectory] = firstSplit.directory <= secondSplit.directory ? [firstSplit.directory, secondSplit.directory] : [secondSplit.directory, firstSplit.directory];
9068
+ const pairKey = `${smallerDirectory}::${largerDirectory}`;
9069
+ const entry = {
9070
+ baseName: firstSplit.baseName,
9071
+ duplicatedLines: cluster.totalDuplicatedLines
8541
9072
  };
9073
+ const existing = directoryPairBuckets.get(pairKey);
9074
+ if (existing) existing.push(entry);
9075
+ else directoryPairBuckets.set(pairKey, [entry]);
9076
+ }
9077
+ const shadowedDirectoryPairs = [];
9078
+ for (const [pairKey, entries] of directoryPairBuckets) {
9079
+ if (entries.length < 3) continue;
9080
+ const [directoryA, directoryB] = pairKey.split("::");
9081
+ const sharedBaseNames = [...new Set(entries.map((entry) => entry.baseName))].sort();
9082
+ const totalDuplicatedLines = entries.reduce((runningSum, entry) => runningSum + entry.duplicatedLines, 0);
9083
+ shadowedDirectoryPairs.push({
9084
+ directoryA,
9085
+ directoryB,
9086
+ sharedFiles: sharedBaseNames,
9087
+ totalDuplicatedLines
9088
+ });
8542
9089
  }
8543
- if (configFileContent.error) return {
8544
- ok: false,
8545
- failure: failureFor("tsconfig-parse-error", typescript.default.flattenDiagnosticMessageText(configFileContent.error.messageText, "\n"), { rootDir: resolvedTsconfigPath })
9090
+ shadowedDirectoryPairs.sort((leftPair, rightPair) => rightPair.totalDuplicatedLines - leftPair.totalDuplicatedLines);
9091
+ return shadowedDirectoryPairs;
9092
+ };
9093
+
9094
+ //#endregion
9095
+ //#region src/duplicate-blocks/normalize.ts
9096
+ /**
9097
+ * 32-bit FNV-1a. Collisions are tolerable: ties are broken back to the
9098
+ * original (path, offset) tuples downstream, so a rare collision inflates a
9099
+ * duplicate block with one extra spurious instance at worst.
9100
+ */
9101
+ const FNV_OFFSET_BASIS = 2166136261;
9102
+ const FNV_PRIME = 16777619;
9103
+ const hashString = (input) => {
9104
+ let hash = FNV_OFFSET_BASIS;
9105
+ for (let charIndex = 0; charIndex < input.length; charIndex++) {
9106
+ hash ^= input.charCodeAt(charIndex);
9107
+ hash = Math.imul(hash, FNV_PRIME);
9108
+ }
9109
+ return hash >>> 0;
9110
+ };
9111
+ const resolveNormalization = (mode) => {
9112
+ if (mode === "strict") return {
9113
+ ignoreIdentifiers: false,
9114
+ ignoreStringValues: false,
9115
+ ignoreNumericValues: false
8546
9116
  };
8547
- let parsedCommandLine;
8548
- try {
8549
- parsedCommandLine = typescript.default.parseJsonConfigFileContent(configFileContent.config, typescript.default.sys, (0, node_path.dirname)(resolvedTsconfigPath), {
8550
- noEmit: true,
9117
+ return {
9118
+ ignoreIdentifiers: true,
9119
+ ignoreStringValues: true,
9120
+ ignoreNumericValues: true
9121
+ };
9122
+ };
9123
+ const hashSourceToken = (sourceToken, normalization) => {
9124
+ switch (sourceToken.kind) {
9125
+ case "node-enter": return hashString(`n:${sourceToken.payload}`);
9126
+ case "identifier": return normalization.ignoreIdentifiers ? hashString("id:*") : hashString(`id:${sourceToken.payload}`);
9127
+ case "string-literal": return normalization.ignoreStringValues ? hashString("s:*") : hashString(`s:${sourceToken.payload}`);
9128
+ case "numeric-literal": return normalization.ignoreNumericValues ? hashString("num:*") : hashString(`num:${sourceToken.payload}`);
9129
+ case "boolean-literal": return hashString(`b:${sourceToken.payload}`);
9130
+ case "null-literal": return hashString("null");
9131
+ case "template-literal": return hashString("tpl");
9132
+ case "regexp-literal": return hashString("re");
9133
+ default: return hashString("?");
9134
+ }
9135
+ };
9136
+ const normalizeAndHashTokens = (tokens, mode) => {
9137
+ const normalization = resolveNormalization(mode);
9138
+ const hashedTokens = new Array(tokens.length);
9139
+ for (let tokenIndex = 0; tokenIndex < tokens.length; tokenIndex++) hashedTokens[tokenIndex] = {
9140
+ hash: hashSourceToken(tokens[tokenIndex], normalization),
9141
+ originalIndex: tokenIndex
9142
+ };
9143
+ return hashedTokens;
9144
+ };
9145
+
9146
+ //#endregion
9147
+ //#region src/duplicate-blocks/suffix-array.ts
9148
+ /**
9149
+ * Prefix-doubling suffix array with two-pass radix sort, O(N log N).
9150
+ *
9151
+ * Negative values in `tokenSequence` (file-separator sentinels emitted by
9152
+ * `rankReduceAndConcatenate`) are shifted up so all ranks are >= 0. The
9153
+ * shift preserves the property that sentinels sort before all real ranks,
9154
+ * which is what stops cross-file suffix matches.
9155
+ */
9156
+ const buildSuffixArray = (tokenSequence) => {
9157
+ const sequenceLength = tokenSequence.length;
9158
+ if (sequenceLength === 0) return [];
9159
+ let minimumValue = 0;
9160
+ for (let scanIndex = 0; scanIndex < sequenceLength; scanIndex++) if (tokenSequence[scanIndex] < minimumValue) minimumValue = tokenSequence[scanIndex];
9161
+ let currentRanks = new Array(sequenceLength);
9162
+ for (let scanIndex = 0; scanIndex < sequenceLength; scanIndex++) currentRanks[scanIndex] = tokenSequence[scanIndex] - minimumValue;
9163
+ let suffixArray = new Array(sequenceLength);
9164
+ for (let positionIndex = 0; positionIndex < sequenceLength; positionIndex++) suffixArray[positionIndex] = positionIndex;
9165
+ let nextRanks = new Array(sequenceLength);
9166
+ let scratchSuffixArray = new Array(sequenceLength);
9167
+ let maximumRank = 0;
9168
+ for (let scanIndex = 0; scanIndex < sequenceLength; scanIndex++) if (currentRanks[scanIndex] > maximumRank) maximumRank = currentRanks[scanIndex];
9169
+ let stride = 1;
9170
+ while (stride < sequenceLength) {
9171
+ const bucketCount = maximumRank + 2;
9172
+ const buckets = new Array(bucketCount + 1).fill(0);
9173
+ for (let suffixIndex = 0; suffixIndex < sequenceLength; suffixIndex++) {
9174
+ const startPosition = suffixArray[suffixIndex];
9175
+ const secondaryKey = startPosition + stride < sequenceLength ? currentRanks[startPosition + stride] + 1 : 0;
9176
+ buckets[secondaryKey]++;
9177
+ }
9178
+ let prefixSum = 0;
9179
+ for (let bucketIndex = 0; bucketIndex < buckets.length; bucketIndex++) {
9180
+ const bucketCountValue = buckets[bucketIndex];
9181
+ buckets[bucketIndex] = prefixSum;
9182
+ prefixSum += bucketCountValue;
9183
+ }
9184
+ for (let suffixIndex = 0; suffixIndex < sequenceLength; suffixIndex++) {
9185
+ const startPosition = suffixArray[suffixIndex];
9186
+ const secondaryKey = startPosition + stride < sequenceLength ? currentRanks[startPosition + stride] + 1 : 0;
9187
+ scratchSuffixArray[buckets[secondaryKey]] = startPosition;
9188
+ buckets[secondaryKey]++;
9189
+ }
9190
+ for (let bucketIndex = 0; bucketIndex < buckets.length; bucketIndex++) buckets[bucketIndex] = 0;
9191
+ for (let suffixIndex = 0; suffixIndex < sequenceLength; suffixIndex++) {
9192
+ const startPosition = scratchSuffixArray[suffixIndex];
9193
+ buckets[currentRanks[startPosition]]++;
9194
+ }
9195
+ prefixSum = 0;
9196
+ for (let bucketIndex = 0; bucketIndex < buckets.length; bucketIndex++) {
9197
+ const bucketCountValue = buckets[bucketIndex];
9198
+ buckets[bucketIndex] = prefixSum;
9199
+ prefixSum += bucketCountValue;
9200
+ }
9201
+ for (let suffixIndex = 0; suffixIndex < sequenceLength; suffixIndex++) {
9202
+ const startPosition = scratchSuffixArray[suffixIndex];
9203
+ suffixArray[buckets[currentRanks[startPosition]]] = startPosition;
9204
+ buckets[currentRanks[startPosition]]++;
9205
+ }
9206
+ nextRanks[suffixArray[0]] = 0;
9207
+ for (let suffixIndex = 1; suffixIndex < sequenceLength; suffixIndex++) {
9208
+ const previousStart = suffixArray[suffixIndex - 1];
9209
+ const currentStart = suffixArray[suffixIndex];
9210
+ const previousSecondary = previousStart + stride < sequenceLength ? currentRanks[previousStart + stride] : -1;
9211
+ const currentSecondary = currentStart + stride < sequenceLength ? currentRanks[currentStart + stride] : -1;
9212
+ const isSameBucket = currentRanks[previousStart] === currentRanks[currentStart] && previousSecondary === currentSecondary;
9213
+ nextRanks[currentStart] = nextRanks[previousStart] + (isSameBucket ? 0 : 1);
9214
+ }
9215
+ const newMaximumRank = nextRanks[suffixArray[sequenceLength - 1]];
9216
+ [currentRanks, nextRanks] = [nextRanks, currentRanks];
9217
+ if (newMaximumRank === sequenceLength - 1) break;
9218
+ maximumRank = newMaximumRank;
9219
+ stride *= 2;
9220
+ }
9221
+ return suffixArray;
9222
+ };
9223
+ /**
9224
+ * Kasai's O(N) longest-common-prefix array. The `>= 0` check inside the inner
9225
+ * loop is the only non-textbook bit: it prevents a real-token LCP from
9226
+ * accidentally crossing a sentinel boundary (sentinels are negative).
9227
+ */
9228
+ const buildLcpArray = (tokenSequence, suffixArray) => {
9229
+ const sequenceLength = tokenSequence.length;
9230
+ const inverseSuffixArray = new Array(sequenceLength);
9231
+ for (let arrayIndex = 0; arrayIndex < sequenceLength; arrayIndex++) inverseSuffixArray[suffixArray[arrayIndex]] = arrayIndex;
9232
+ const lcpArray = new Array(sequenceLength).fill(0);
9233
+ let runningLcp = 0;
9234
+ for (let positionIndex = 0; positionIndex < sequenceLength; positionIndex++) {
9235
+ if (inverseSuffixArray[positionIndex] === 0) {
9236
+ runningLcp = 0;
9237
+ continue;
9238
+ }
9239
+ const previousStart = suffixArray[inverseSuffixArray[positionIndex] - 1];
9240
+ while (positionIndex + runningLcp < sequenceLength && previousStart + runningLcp < sequenceLength && tokenSequence[positionIndex + runningLcp] === tokenSequence[previousStart + runningLcp] && tokenSequence[positionIndex + runningLcp] >= 0) runningLcp++;
9241
+ lcpArray[inverseSuffixArray[positionIndex]] = runningLcp;
9242
+ if (runningLcp > 0) runningLcp--;
9243
+ }
9244
+ return lcpArray;
9245
+ };
9246
+
9247
+ //#endregion
9248
+ //#region src/utils/is-ast-node.ts
9249
+ const isAstNode = (candidate) => typeof candidate === "object" && candidate !== null && "type" in candidate;
9250
+
9251
+ //#endregion
9252
+ //#region src/duplicate-blocks/token-visitor.ts
9253
+ const NODES_DROPPED_FROM_TOKEN_STREAM = new Set([
9254
+ "ImportDeclaration",
9255
+ "ExportAllDeclaration",
9256
+ "TSTypeAnnotation",
9257
+ "TSTypeAliasDeclaration",
9258
+ "TSInterfaceDeclaration",
9259
+ "TSTypeParameterDeclaration",
9260
+ "TSTypeParameterInstantiation",
9261
+ "TSTypeReference",
9262
+ "TSAnyKeyword",
9263
+ "TSUnknownKeyword",
9264
+ "TSStringKeyword",
9265
+ "TSNumberKeyword",
9266
+ "TSBooleanKeyword",
9267
+ "TSVoidKeyword",
9268
+ "TSUndefinedKeyword",
9269
+ "TSNullKeyword",
9270
+ "TSNeverKeyword",
9271
+ "TSUnionType",
9272
+ "TSIntersectionType",
9273
+ "TSLiteralType",
9274
+ "TSArrayType",
9275
+ "TSTupleType",
9276
+ "TSTypeLiteral",
9277
+ "TSPropertySignature",
9278
+ "TSMethodSignature",
9279
+ "TSCallSignatureDeclaration",
9280
+ "TSConstructSignatureDeclaration",
9281
+ "TSIndexSignature",
9282
+ "TSConditionalType",
9283
+ "TSMappedType",
9284
+ "TSInferType",
9285
+ "TSImportType",
9286
+ "TSQualifiedName",
9287
+ "TSTypeOperator",
9288
+ "TSTypePredicate",
9289
+ "TSFunctionType",
9290
+ "TSConstructorType"
9291
+ ]);
9292
+ const visitChildrenRaw = (node, visit) => {
9293
+ if (!isAstNode(node)) return;
9294
+ for (const key of Object.keys(node)) {
9295
+ if (key === "type" || key === "start" || key === "end" || key === "loc" || key === "range") continue;
9296
+ const value = node[key];
9297
+ if (Array.isArray(value)) for (const item of value) visit(item);
9298
+ else if (value !== null && typeof value === "object") visit(value);
9299
+ }
9300
+ };
9301
+ const safeNumberOrZero = (candidate) => typeof candidate === "number" ? candidate : 0;
9302
+ /**
9303
+ * Walk an oxc AST and emit a flat token stream suitable for suffix-array-based
9304
+ * duplicate-block detection. Two structurally-identical regions of code produce the same
9305
+ * token sequence (modulo identifier/literal-value normalization, applied later
9306
+ * in `normalize.ts`).
9307
+ *
9308
+ * Implementation note: rather than a hand-written keyword/operator lexer-style
9309
+ * visitor, we walk the AST generically and emit one `node-enter` token per
9310
+ * visited node. This trades a slightly different token-density profile for
9311
+ * less code. AST-shape tokens still distinguish
9312
+ * `function add(a, b) { return a + b }` from `const add = (a, b) => a + b`.
9313
+ * Identifiers and value literals get dedicated tokens so semantic-mode
9314
+ * normalization can blind them.
9315
+ *
9316
+ * Imports and type-only constructs are dropped to keep import-block boilerplate
9317
+ * and ambient type declarations from inflating the noise floor.
9318
+ */
9319
+ const tokenizeAst = (program) => {
9320
+ const tokens = [];
9321
+ const visit = (node) => {
9322
+ if (!isAstNode(node)) return;
9323
+ const nodeType = node.type;
9324
+ if (NODES_DROPPED_FROM_TOKEN_STREAM.has(nodeType)) return;
9325
+ const start = safeNumberOrZero(node.start);
9326
+ const end = safeNumberOrZero(node.end);
9327
+ if (nodeType === "Identifier" || nodeType === "PrivateIdentifier") {
9328
+ const identifierName = node.name;
9329
+ tokens.push({
9330
+ kind: "identifier",
9331
+ payload: typeof identifierName === "string" ? identifierName : "",
9332
+ start,
9333
+ end
9334
+ });
9335
+ return;
9336
+ }
9337
+ if (nodeType === "Literal") {
9338
+ const literalValue = node.value;
9339
+ if (typeof literalValue === "string") tokens.push({
9340
+ kind: "string-literal",
9341
+ payload: literalValue,
9342
+ start,
9343
+ end
9344
+ });
9345
+ else if (typeof literalValue === "number") tokens.push({
9346
+ kind: "numeric-literal",
9347
+ payload: String(literalValue),
9348
+ start,
9349
+ end
9350
+ });
9351
+ else if (typeof literalValue === "boolean") tokens.push({
9352
+ kind: "boolean-literal",
9353
+ payload: literalValue ? "true" : "false",
9354
+ start,
9355
+ end
9356
+ });
9357
+ else if (literalValue === null) tokens.push({
9358
+ kind: "null-literal",
9359
+ payload: "null",
9360
+ start,
9361
+ end
9362
+ });
9363
+ else if (node.regex) tokens.push({
9364
+ kind: "regexp-literal",
9365
+ payload: "regex",
9366
+ start,
9367
+ end
9368
+ });
9369
+ else tokens.push({
9370
+ kind: "node-enter",
9371
+ payload: nodeType,
9372
+ start,
9373
+ end
9374
+ });
9375
+ return;
9376
+ }
9377
+ if (nodeType === "TemplateLiteral") {
9378
+ tokens.push({
9379
+ kind: "template-literal",
9380
+ payload: "tpl",
9381
+ start,
9382
+ end
9383
+ });
9384
+ visitChildrenRaw(node, visit);
9385
+ return;
9386
+ }
9387
+ tokens.push({
9388
+ kind: "node-enter",
9389
+ payload: nodeType,
9390
+ start,
9391
+ end
9392
+ });
9393
+ visitChildrenRaw(node, visit);
9394
+ };
9395
+ visit(program);
9396
+ return tokens;
9397
+ };
9398
+
9399
+ //#endregion
9400
+ //#region src/duplicate-blocks/index.ts
9401
+ const isBinaryFile = (sourceText) => {
9402
+ const sampleEnd = Math.min(sourceText.length, BINARY_DETECTION_SAMPLE_BYTES);
9403
+ let nullByteCount = 0;
9404
+ for (let charIndex = 0; charIndex < sampleEnd; charIndex++) if (sourceText.charCodeAt(charIndex) === 0) {
9405
+ nullByteCount++;
9406
+ if (nullByteCount >= 4) return true;
9407
+ }
9408
+ return false;
9409
+ };
9410
+ const isMinifiedSource = (sourceText) => {
9411
+ if (sourceText.length < 5e3) return false;
9412
+ const lineCount = (sourceText.match(/\n/g)?.length ?? 0) + 1;
9413
+ return sourceText.length / lineCount > 500;
9414
+ };
9415
+ const tokenizeFile = (filePath) => {
9416
+ let sourceStat;
9417
+ try {
9418
+ sourceStat = (0, node_fs.statSync)(filePath);
9419
+ } catch {
9420
+ return;
9421
+ }
9422
+ if (sourceStat.size > 2e6) return void 0;
9423
+ let sourceText;
9424
+ try {
9425
+ sourceText = (0, node_fs.readFileSync)(filePath, "utf-8");
9426
+ } catch {
9427
+ return;
9428
+ }
9429
+ if (sourceText.length === 0) return void 0;
9430
+ if (isBinaryFile(sourceText)) return void 0;
9431
+ if (isMinifiedSource(sourceText)) return void 0;
9432
+ let parseResult;
9433
+ try {
9434
+ parseResult = (0, oxc_parser.parseSync)(filePath, sourceText);
9435
+ } catch {
9436
+ return;
9437
+ }
9438
+ const sourceTokens = tokenizeAst(parseResult.program);
9439
+ if (sourceTokens.length === 0) return void 0;
9440
+ const lineStarts = computeLineStarts(sourceText);
9441
+ return {
9442
+ path: filePath,
9443
+ sourceTokens,
9444
+ lineStarts,
9445
+ lineCount: lineStarts.length
9446
+ };
9447
+ };
9448
+ const buildCloneInstance = (rawInstance, tokenLength, tokenizedFiles) => {
9449
+ const file = tokenizedFiles[rawInstance.fileIndex];
9450
+ const firstToken = file.sourceTokens[rawInstance.tokenOffsetWithinFile];
9451
+ const lastToken = file.sourceTokens[rawInstance.tokenOffsetWithinFile + tokenLength - 1];
9452
+ const startSpan = offsetToLineColumn(firstToken.start, file.lineStarts);
9453
+ const endSpan = offsetToLineColumn(lastToken.end, file.lineStarts);
9454
+ return {
9455
+ path: file.path,
9456
+ startLine: startSpan.line,
9457
+ endLine: endSpan.line,
9458
+ startColumn: startSpan.column,
9459
+ endColumn: endSpan.column
9460
+ };
9461
+ };
9462
+ const directoryOf = (filePath) => (0, node_path.dirname)(filePath);
9463
+ const filterRawBlocksToReportableDuplicates = (rawBlocks, tokenizedFiles, config) => {
9464
+ const duplicateBlocks = [];
9465
+ for (const rawBlock of rawBlocks) {
9466
+ const instances = rawBlock.instances.map((rawInstance) => buildCloneInstance(rawInstance, rawBlock.tokenLength, tokenizedFiles));
9467
+ let lineCount = 0;
9468
+ for (const instance of instances) {
9469
+ const instanceLineCount = instance.endLine - instance.startLine + 1;
9470
+ if (instanceLineCount > lineCount) lineCount = instanceLineCount;
9471
+ }
9472
+ if (lineCount < config.minLines) continue;
9473
+ if (instances.length < config.minOccurrences) continue;
9474
+ if (config.skipLocal) {
9475
+ if (new Set(instances.map((instance) => directoryOf(instance.path))).size < 2) continue;
9476
+ }
9477
+ const distinctFiles = new Set(instances.map((instance) => instance.path));
9478
+ const confidence = distinctFiles.size >= 2 ? "high" : "medium";
9479
+ duplicateBlocks.push({
9480
+ instances,
9481
+ tokenCount: rawBlock.tokenLength,
9482
+ lineCount,
9483
+ confidence,
9484
+ reason: distinctFiles.size >= 2 ? `${instances.length} occurrences spanning ${distinctFiles.size} files (≥${rawBlock.tokenLength} tokens, ${lineCount} lines)` : `${instances.length} occurrences within a single file (≥${rawBlock.tokenLength} tokens, ${lineCount} lines)`
9485
+ });
9486
+ }
9487
+ const maximalBlocks = dropBlocksSubsumedByLongerSibling(duplicateBlocks);
9488
+ maximalBlocks.sort((firstClone, secondClone) => {
9489
+ if (firstClone.lineCount !== secondClone.lineCount) return secondClone.lineCount - firstClone.lineCount;
9490
+ return secondClone.tokenCount - firstClone.tokenCount;
9491
+ });
9492
+ return maximalBlocks;
9493
+ };
9494
+ /**
9495
+ * The suffix-array + LCP-interval scan emits one block per LCP interval, but
9496
+ * nested intervals routinely yield the same set of source spans at multiple
9497
+ * lengths (the same maximal repeat reported at L, L-1, L-2, …). Drop any
9498
+ * block whose every instance is spatially contained inside some other block's
9499
+ * matching instance — that other block is strictly more informative.
9500
+ *
9501
+ * O(N²) worst-case, but N here is post-filter blocks (typically <1000 even on
9502
+ * large monorepos), and the early-exit on instance-count mismatch keeps it
9503
+ * tight in practice.
9504
+ */
9505
+ const dropBlocksSubsumedByLongerSibling = (blocks) => {
9506
+ const sorted = [...blocks].sort((firstBlock, secondBlock) => {
9507
+ if (firstBlock.tokenCount !== secondBlock.tokenCount) return secondBlock.tokenCount - firstBlock.tokenCount;
9508
+ return secondBlock.lineCount - firstBlock.lineCount;
9509
+ });
9510
+ const survivors = [];
9511
+ for (const candidate of sorted) {
9512
+ let subsumed = false;
9513
+ for (const survivor of survivors) {
9514
+ if (survivor.instances.length !== candidate.instances.length) continue;
9515
+ if (allInstancesContainedIn(candidate, survivor)) {
9516
+ subsumed = true;
9517
+ break;
9518
+ }
9519
+ }
9520
+ if (!subsumed) survivors.push(candidate);
9521
+ }
9522
+ return survivors;
9523
+ };
9524
+ const allInstancesContainedIn = (candidate, longer) => {
9525
+ for (const candidateInstance of candidate.instances) {
9526
+ let matched = false;
9527
+ for (const longerInstance of longer.instances) if (candidateInstance.path === longerInstance.path && isSpanContained(candidateInstance, longerInstance)) {
9528
+ matched = true;
9529
+ break;
9530
+ }
9531
+ if (!matched) return false;
9532
+ }
9533
+ return true;
9534
+ };
9535
+ const isSpanContained = (inner, outer) => {
9536
+ const innerStartsAfterOuter = inner.startLine > outer.startLine || inner.startLine === outer.startLine && inner.startColumn >= outer.startColumn;
9537
+ const innerEndsBeforeOuter = inner.endLine < outer.endLine || inner.endLine === outer.endLine && inner.endColumn <= outer.endColumn;
9538
+ return innerStartsAfterOuter && innerEndsBeforeOuter;
9539
+ };
9540
+ /**
9541
+ * Token-based duplicate block detector.
9542
+ *
9543
+ * Pipeline:
9544
+ * 1. Tokenize each file with the AST visitor in `token-visitor.ts`
9545
+ * 2. Hash + normalize tokens with the chosen detection mode
9546
+ * 3. Concatenate every file's hashed tokens with unique negative sentinels
9547
+ * 4. Build a suffix array (prefix doubling + radix sort) and LCP array
9548
+ * 5. Stack-based LCP-interval scan extracts maximal duplicate blocks
9549
+ * 6. Filter on min-tokens / min-lines / min-occurrences / skip-local
9550
+ * 7. Group clones into families; collapse N two-file families with matching
9551
+ * basenames into a `ShadowedDirectoryPair` finding
9552
+ *
9553
+ * Returns empty arrays when `config.enabled` is false.
9554
+ */
9555
+ const detectDuplicateBlocks = (graph, config, rootDir) => {
9556
+ if (!config || !config.enabled) return {
9557
+ duplicateBlocks: [],
9558
+ duplicateBlockClusters: [],
9559
+ shadowedDirectoryPairs: []
9560
+ };
9561
+ const tokenizedFiles = [];
9562
+ for (const module of graph.modules) {
9563
+ if (module.isDeclarationFile) continue;
9564
+ if (module.isConfigFile) continue;
9565
+ const tokenizedFile = tokenizeFile(module.fileId.path);
9566
+ if (!tokenizedFile) continue;
9567
+ tokenizedFiles.push(tokenizedFile);
9568
+ }
9569
+ if (tokenizedFiles.length === 0) return {
9570
+ duplicateBlocks: [],
9571
+ duplicateBlockClusters: [],
9572
+ shadowedDirectoryPairs: []
9573
+ };
9574
+ const filesHashedTokens = tokenizedFiles.map((file) => normalizeAndHashTokens(file.sourceTokens, config.mode));
9575
+ const filesTokenCounts = filesHashedTokens.map((fileTokens) => fileTokens.length);
9576
+ if (!filesTokenCounts.some((count) => count >= config.minTokens)) return {
9577
+ duplicateBlocks: [],
9578
+ duplicateBlockClusters: [],
9579
+ shadowedDirectoryPairs: []
9580
+ };
9581
+ const concatenation = rankReduceAndConcatenate(filesHashedTokens);
9582
+ if (concatenation.tokenSequence.length === 0) return {
9583
+ duplicateBlocks: [],
9584
+ duplicateBlockClusters: [],
9585
+ shadowedDirectoryPairs: []
9586
+ };
9587
+ const suffixArray = buildSuffixArray(concatenation.tokenSequence);
9588
+ const duplicateBlocks = filterRawBlocksToReportableDuplicates(extractRawDuplicateBlocks(suffixArray, buildLcpArray(concatenation.tokenSequence, suffixArray), concatenation.fileOf, concatenation.fileOffsets, filesTokenCounts, config.minTokens), tokenizedFiles, config);
9589
+ const duplicateBlockClusters = groupDuplicateBlocksIntoClusters(duplicateBlocks);
9590
+ return {
9591
+ duplicateBlocks,
9592
+ duplicateBlockClusters,
9593
+ shadowedDirectoryPairs: detectShadowedDirectoryPairs(duplicateBlockClusters, rootDir)
9594
+ };
9595
+ };
9596
+
9597
+ //#endregion
9598
+ //#region src/report/re-export-cycles.ts
9599
+ /**
9600
+ * Reports cycles in the subgraph of `isReExportEdge` edges only. These are
9601
+ * a strict subset of `circularDependencies` but worth separating: every
9602
+ * general cycle can have a legitimate bidirectional-collaboration reason,
9603
+ * but a re-export cycle has none — it always tanks tree-shaking and risks
9604
+ * the "Cannot access X before initialization" TDZ runtime error.
9605
+ */
9606
+ const detectReExportCycles = (graph) => {
9607
+ const adjacency = Array.from({ length: graph.modules.length }, () => []);
9608
+ const reExportTargetSets = Array.from({ length: graph.modules.length }, () => /* @__PURE__ */ new Set());
9609
+ for (const edge of graph.edges) {
9610
+ if (!edge.isReExportEdge) continue;
9611
+ if (edge.target >= graph.modules.length) continue;
9612
+ if (reExportTargetSets[edge.source].has(edge.target)) continue;
9613
+ reExportTargetSets[edge.source].add(edge.target);
9614
+ adjacency[edge.source].push(edge.target);
9615
+ }
9616
+ const sccComponents = computeStronglyConnectedComponents(adjacency);
9617
+ const findings = [];
9618
+ for (const component of sccComponents) {
9619
+ if (component.length === 1) {
9620
+ const onlyNode = component[0];
9621
+ if (!adjacency[onlyNode].includes(onlyNode)) continue;
9622
+ const filePath = graph.modules[onlyNode].fileId.path;
9623
+ findings.push({
9624
+ files: [filePath],
9625
+ kind: "self-loop",
9626
+ confidence: "high",
9627
+ reason: `${filePath} re-exports from itself — the barrel imports its own root, which breaks bundler tree-shaking and risks TDZ runtime errors`
9628
+ });
9629
+ continue;
9630
+ }
9631
+ const sortedFiles = component.map((moduleIndex) => graph.modules[moduleIndex].fileId.path).sort();
9632
+ findings.push({
9633
+ files: sortedFiles,
9634
+ kind: "multi-node",
9635
+ confidence: "high",
9636
+ reason: `${sortedFiles.length} modules form a re-export cycle — refactor consumers to import from the leaf module instead of the barrel`
9637
+ });
9638
+ }
9639
+ findings.sort((firstFinding, secondFinding) => firstFinding.files[0].localeCompare(secondFinding.files[0]));
9640
+ return findings;
9641
+ };
9642
+ /**
9643
+ * Iterative Tarjan's SCC. Singleton components are returned too so the
9644
+ * caller can distinguish a real self-loop from a node with no edges.
9645
+ */
9646
+ const computeStronglyConnectedComponents = (adjacency) => {
9647
+ const nodeCount = adjacency.length;
9648
+ if (nodeCount === 0) return [];
9649
+ const indices = new Array(nodeCount).fill(-1);
9650
+ const lowLinks = new Array(nodeCount).fill(0);
9651
+ const onStack = new Array(nodeCount).fill(false);
9652
+ const tarjanStack = [];
9653
+ const components = [];
9654
+ let nextIndex = 0;
9655
+ for (let startNode = 0; startNode < nodeCount; startNode++) {
9656
+ if (indices[startNode] !== -1) continue;
9657
+ const dfsStack = [{
9658
+ node: startNode,
9659
+ successorPosition: 0
9660
+ }];
9661
+ indices[startNode] = nextIndex;
9662
+ lowLinks[startNode] = nextIndex;
9663
+ nextIndex++;
9664
+ onStack[startNode] = true;
9665
+ tarjanStack.push(startNode);
9666
+ while (dfsStack.length > 0) {
9667
+ const frame = dfsStack[dfsStack.length - 1];
9668
+ const successors = adjacency[frame.node];
9669
+ if (frame.successorPosition < successors.length) {
9670
+ const successorNode = successors[frame.successorPosition];
9671
+ frame.successorPosition++;
9672
+ if (indices[successorNode] === -1) {
9673
+ indices[successorNode] = nextIndex;
9674
+ lowLinks[successorNode] = nextIndex;
9675
+ nextIndex++;
9676
+ onStack[successorNode] = true;
9677
+ tarjanStack.push(successorNode);
9678
+ dfsStack.push({
9679
+ node: successorNode,
9680
+ successorPosition: 0
9681
+ });
9682
+ } else if (onStack[successorNode]) {
9683
+ if (indices[successorNode] < lowLinks[frame.node]) lowLinks[frame.node] = indices[successorNode];
9684
+ }
9685
+ } else {
9686
+ if (lowLinks[frame.node] === indices[frame.node]) {
9687
+ const component = [];
9688
+ let popped;
9689
+ do {
9690
+ popped = tarjanStack.pop();
9691
+ onStack[popped] = false;
9692
+ component.push(popped);
9693
+ } while (popped !== frame.node);
9694
+ components.push(component);
9695
+ }
9696
+ dfsStack.pop();
9697
+ if (dfsStack.length > 0) {
9698
+ const parent = dfsStack[dfsStack.length - 1];
9699
+ if (lowLinks[frame.node] < lowLinks[parent.node]) lowLinks[parent.node] = lowLinks[frame.node];
9700
+ }
9701
+ }
9702
+ }
9703
+ }
9704
+ return components;
9705
+ };
9706
+
9707
+ //#endregion
9708
+ //#region src/report/feature-flags.ts
9709
+ const BUILTIN_SDK_PATTERNS = [
9710
+ {
9711
+ functionName: "useFlag",
9712
+ nameArgIndex: 0,
9713
+ provider: "LaunchDarkly"
9714
+ },
9715
+ {
9716
+ functionName: "useLDFlag",
9717
+ nameArgIndex: 0,
9718
+ provider: "LaunchDarkly"
9719
+ },
9720
+ {
9721
+ functionName: "useFeatureFlag",
9722
+ nameArgIndex: 0,
9723
+ provider: "LaunchDarkly"
9724
+ },
9725
+ {
9726
+ functionName: "variation",
9727
+ nameArgIndex: 0,
9728
+ provider: "LaunchDarkly"
9729
+ },
9730
+ {
9731
+ functionName: "boolVariation",
9732
+ nameArgIndex: 0,
9733
+ provider: "LaunchDarkly"
9734
+ },
9735
+ {
9736
+ functionName: "stringVariation",
9737
+ nameArgIndex: 0,
9738
+ provider: "LaunchDarkly"
9739
+ },
9740
+ {
9741
+ functionName: "numberVariation",
9742
+ nameArgIndex: 0,
9743
+ provider: "LaunchDarkly"
9744
+ },
9745
+ {
9746
+ functionName: "jsonVariation",
9747
+ nameArgIndex: 0,
9748
+ provider: "LaunchDarkly"
9749
+ },
9750
+ {
9751
+ functionName: "useGate",
9752
+ nameArgIndex: 0,
9753
+ provider: "Statsig"
9754
+ },
9755
+ {
9756
+ functionName: "checkGate",
9757
+ nameArgIndex: 0,
9758
+ provider: "Statsig"
9759
+ },
9760
+ {
9761
+ functionName: "useExperiment",
9762
+ nameArgIndex: 0,
9763
+ provider: "Statsig"
9764
+ },
9765
+ {
9766
+ functionName: "useConfig",
9767
+ nameArgIndex: 0,
9768
+ provider: "Statsig"
9769
+ },
9770
+ {
9771
+ functionName: "isEnabled",
9772
+ nameArgIndex: 0,
9773
+ provider: "Unleash"
9774
+ },
9775
+ {
9776
+ functionName: "getVariant",
9777
+ nameArgIndex: 0,
9778
+ provider: "Unleash"
9779
+ },
9780
+ {
9781
+ functionName: "isOn",
9782
+ nameArgIndex: 0,
9783
+ provider: "GrowthBook"
9784
+ },
9785
+ {
9786
+ functionName: "isOff",
9787
+ nameArgIndex: 0,
9788
+ provider: "GrowthBook"
9789
+ },
9790
+ {
9791
+ functionName: "getFeatureValue",
9792
+ nameArgIndex: 0,
9793
+ provider: "GrowthBook"
9794
+ },
9795
+ {
9796
+ functionName: "getTreatment",
9797
+ nameArgIndex: 0,
9798
+ provider: "Split"
9799
+ },
9800
+ {
9801
+ functionName: "useFeatureFlagEnabled",
9802
+ nameArgIndex: 0,
9803
+ provider: "PostHog"
9804
+ },
9805
+ {
9806
+ functionName: "useFeatureFlagPayload",
9807
+ nameArgIndex: 0,
9808
+ provider: "PostHog"
9809
+ },
9810
+ {
9811
+ functionName: "useFeatureFlagVariantKey",
9812
+ nameArgIndex: 0,
9813
+ provider: "PostHog"
9814
+ },
9815
+ {
9816
+ functionName: "getFeatureFlagPayload",
9817
+ nameArgIndex: 0,
9818
+ provider: "PostHog"
9819
+ },
9820
+ {
9821
+ functionName: "getValueAsync",
9822
+ nameArgIndex: 0,
9823
+ provider: "ConfigCat"
9824
+ },
9825
+ {
9826
+ functionName: "getValueDetailsAsync",
9827
+ nameArgIndex: 0,
9828
+ provider: "ConfigCat"
9829
+ },
9830
+ {
9831
+ functionName: "hasFeature",
9832
+ nameArgIndex: 0,
9833
+ provider: "Flagsmith"
9834
+ },
9835
+ {
9836
+ functionName: "useDecision",
9837
+ nameArgIndex: 0,
9838
+ provider: "Optimizely"
9839
+ },
9840
+ {
9841
+ functionName: "getFeatureVariable",
9842
+ nameArgIndex: 0,
9843
+ provider: "Optimizely"
9844
+ },
9845
+ {
9846
+ functionName: "getFeatureVariableBoolean",
9847
+ nameArgIndex: 0,
9848
+ provider: "Optimizely"
9849
+ },
9850
+ {
9851
+ functionName: "getFeatureVariableString",
9852
+ nameArgIndex: 0,
9853
+ provider: "Optimizely"
9854
+ },
9855
+ {
9856
+ functionName: "getFeatureVariableInteger",
9857
+ nameArgIndex: 0,
9858
+ provider: "Optimizely"
9859
+ },
9860
+ {
9861
+ functionName: "getFeatureVariableDouble",
9862
+ nameArgIndex: 0,
9863
+ provider: "Optimizely"
9864
+ },
9865
+ {
9866
+ functionName: "getFeatureVariableJson",
9867
+ nameArgIndex: 0,
9868
+ provider: "Optimizely"
9869
+ },
9870
+ {
9871
+ functionName: "getFeatureVariableJSON",
9872
+ nameArgIndex: 0,
9873
+ provider: "Optimizely"
9874
+ },
9875
+ {
9876
+ functionName: "getStringAssignment",
9877
+ nameArgIndex: 0,
9878
+ provider: "Eppo"
9879
+ },
9880
+ {
9881
+ functionName: "getBooleanAssignment",
9882
+ nameArgIndex: 0,
9883
+ provider: "Eppo"
9884
+ },
9885
+ {
9886
+ functionName: "getNumericAssignment",
9887
+ nameArgIndex: 0,
9888
+ provider: "Eppo"
9889
+ },
9890
+ {
9891
+ functionName: "getIntegerAssignment",
9892
+ nameArgIndex: 0,
9893
+ provider: "Eppo"
9894
+ },
9895
+ {
9896
+ functionName: "getJSONAssignment",
9897
+ nameArgIndex: 0,
9898
+ provider: "Eppo"
9899
+ }
9900
+ ];
9901
+ const VERCEL_FLAGS_FUNCTION_NAMES = new Set(["flag", "evaluate"]);
9902
+ const BUILTIN_ENV_PREFIXES = [
9903
+ "FEATURE_",
9904
+ "NEXT_PUBLIC_FEATURE_",
9905
+ "NEXT_PUBLIC_ENABLE_",
9906
+ "REACT_APP_FEATURE_",
9907
+ "REACT_APP_ENABLE_",
9908
+ "VITE_FEATURE_",
9909
+ "VITE_ENABLE_",
9910
+ "NUXT_PUBLIC_FEATURE_",
9911
+ "ENABLE_",
9912
+ "FF_",
9913
+ "FLAG_",
9914
+ "TOGGLE_"
9915
+ ];
9916
+ const CONFIG_OBJECT_KEYWORDS = new Set([
9917
+ "feature",
9918
+ "features",
9919
+ "featureflags",
9920
+ "featureflag",
9921
+ "flag",
9922
+ "flags",
9923
+ "toggle",
9924
+ "toggles"
9925
+ ]);
9926
+ const getStaticName = (node) => {
9927
+ if (!isAstNode(node)) return void 0;
9928
+ if (node.type === "Identifier" || node.type === "PrivateIdentifier") {
9929
+ const identifierName = node.name;
9930
+ return typeof identifierName === "string" ? identifierName : void 0;
9931
+ }
9932
+ if (node.type === "Literal") {
9933
+ const literalValue = node.value;
9934
+ return typeof literalValue === "string" ? literalValue : void 0;
9935
+ }
9936
+ };
9937
+ const extractStringArgument = (callArguments, argumentIndex) => {
9938
+ if (!Array.isArray(callArguments)) return void 0;
9939
+ const argumentNode = callArguments[argumentIndex];
9940
+ if (!isAstNode(argumentNode)) return void 0;
9941
+ if (argumentNode.type === "Literal") {
9942
+ const literalValue = argumentNode.value;
9943
+ return typeof literalValue === "string" ? literalValue : void 0;
9944
+ }
9945
+ if (argumentNode.type === "ObjectExpression") {
9946
+ const properties = argumentNode.properties;
9947
+ if (!Array.isArray(properties)) return void 0;
9948
+ for (const property of properties) {
9949
+ if (!isAstNode(property)) continue;
9950
+ if (property.type !== "Property") continue;
9951
+ const propertyKey = getStaticName(property.key);
9952
+ if (propertyKey !== "key" && propertyKey !== "name") continue;
9953
+ const propertyValueName = getStaticName(property.value);
9954
+ if (propertyValueName !== void 0) return propertyValueName;
9955
+ }
9956
+ }
9957
+ };
9958
+ const extractProcessEnvName = (memberExpression) => {
9959
+ if (!isAstNode(memberExpression)) return void 0;
9960
+ if (memberExpression.type !== "MemberExpression" && memberExpression.type !== "StaticMemberExpression") return;
9961
+ const propertyName = getStaticName(memberExpression.property);
9962
+ if (propertyName === void 0) return void 0;
9963
+ const objectNode = memberExpression.object;
9964
+ if (!isAstNode(objectNode)) return void 0;
9965
+ if (objectNode.type !== "MemberExpression" && objectNode.type !== "StaticMemberExpression") return;
9966
+ const innerObjectName = getStaticName(objectNode.object);
9967
+ const innerPropertyName = getStaticName(objectNode.property);
9968
+ if (innerObjectName === "process" && innerPropertyName === "env") return propertyName;
9969
+ };
9970
+ const isFlagEnvName = (envName, extraEnvPrefixes) => {
9971
+ for (const prefix of BUILTIN_ENV_PREFIXES) if (envName.startsWith(prefix)) return true;
9972
+ for (const prefix of extraEnvPrefixes) if (envName.startsWith(prefix)) return true;
9973
+ return false;
9974
+ };
9975
+ const collectVercelFlagsImports = (programNode) => {
9976
+ const localNames = /* @__PURE__ */ new Set();
9977
+ if (!isAstNode(programNode)) return localNames;
9978
+ const body = programNode.body;
9979
+ if (!Array.isArray(body)) return localNames;
9980
+ for (const statement of body) {
9981
+ if (!isAstNode(statement)) continue;
9982
+ if (statement.type !== "ImportDeclaration") continue;
9983
+ const sourceLiteral = statement.source;
9984
+ const sourceValue = isAstNode(sourceLiteral) ? sourceLiteral.value : void 0;
9985
+ if (typeof sourceValue !== "string") continue;
9986
+ if (!(sourceValue === "flags" || sourceValue.startsWith("flags/") || sourceValue === "@vercel/flags" || sourceValue.startsWith("@vercel/flags/"))) continue;
9987
+ const specifiers = statement.specifiers;
9988
+ if (!Array.isArray(specifiers)) continue;
9989
+ for (const specifier of specifiers) {
9990
+ if (!isAstNode(specifier)) continue;
9991
+ if (specifier.type === "ImportSpecifier") {
9992
+ const imported = specifier.imported;
9993
+ const local = specifier.local;
9994
+ const importedName = getStaticName(imported);
9995
+ const localName = getStaticName(local);
9996
+ if (importedName && VERCEL_FLAGS_FUNCTION_NAMES.has(importedName) && localName) localNames.add(localName);
9997
+ }
9998
+ }
9999
+ }
10000
+ return localNames;
10001
+ };
10002
+ const visitChildrenWithGuard = (node, visitor) => {
10003
+ if (!isAstNode(node)) return;
10004
+ for (const key of Object.keys(node)) {
10005
+ if (key === "type" || key === "start" || key === "end" || key === "loc" || key === "range") continue;
10006
+ const value = node[key];
10007
+ if (Array.isArray(value)) for (const item of value) visitor(item);
10008
+ else if (value !== null && typeof value === "object") visitor(value);
10009
+ }
10010
+ };
10011
+ const recordFlag = (context, flagName, kind, byteOffset, sdkProvider) => {
10012
+ const { line, column } = offsetToLineColumn(byteOffset, context.lineStarts);
10013
+ context.results.push({
10014
+ path: context.filePath,
10015
+ name: flagName,
10016
+ kind,
10017
+ line,
10018
+ column,
10019
+ sdkProvider,
10020
+ guardLineStart: context.guard?.startLine,
10021
+ guardLineEnd: context.guard?.endLine,
10022
+ guardsDeadCode: false
10023
+ });
10024
+ };
10025
+ const visitNode$1 = (node, context) => {
10026
+ if (!isAstNode(node)) return;
10027
+ if (node.type === "IfStatement") {
10028
+ const start = node.start;
10029
+ const end = node.end;
10030
+ const guard = typeof start === "number" && typeof end === "number" ? {
10031
+ startLine: offsetToLineColumn(start, context.lineStarts).line,
10032
+ endLine: offsetToLineColumn(end, context.lineStarts).line
10033
+ } : void 0;
10034
+ const previousGuard = context.guard;
10035
+ context.guard = guard;
10036
+ visitNode$1(node.test, context);
10037
+ context.guard = previousGuard;
10038
+ visitNode$1(node.consequent, context);
10039
+ visitNode$1(node.alternate, context);
10040
+ return;
10041
+ }
10042
+ if (node.type === "ConditionalExpression") {
10043
+ const start = node.start;
10044
+ const end = node.end;
10045
+ const guard = typeof start === "number" && typeof end === "number" ? {
10046
+ startLine: offsetToLineColumn(start, context.lineStarts).line,
10047
+ endLine: offsetToLineColumn(end, context.lineStarts).line
10048
+ } : void 0;
10049
+ const previousGuard = context.guard;
10050
+ context.guard = guard;
10051
+ visitNode$1(node.test, context);
10052
+ context.guard = previousGuard;
10053
+ visitNode$1(node.consequent, context);
10054
+ visitNode$1(node.alternate, context);
10055
+ return;
10056
+ }
10057
+ visitFlagPatternsInExpression(node, context);
10058
+ visitChildrenWithGuard(node, (child) => visitNode$1(child, context));
10059
+ };
10060
+ const visitFlagPatternsInExpression = (node, context) => {
10061
+ if (!isAstNode(node)) return;
10062
+ if (node.type === "MemberExpression" || node.type === "StaticMemberExpression") {
10063
+ const envName = extractProcessEnvName(node);
10064
+ if (envName !== void 0 && isFlagEnvName(envName, context.envPrefixes)) {
10065
+ const start = node.start;
10066
+ if (typeof start === "number") recordFlag(context, envName, "env-var", start, void 0);
10067
+ } else if (context.detectConfigObjects) {
10068
+ const objectName = getStaticName(node.object);
10069
+ const propertyName = getStaticName(node.property);
10070
+ if (objectName && propertyName) {
10071
+ if (CONFIG_OBJECT_KEYWORDS.has(objectName.toLowerCase()) || CONFIG_OBJECT_KEYWORDS.has(propertyName.toLowerCase())) {
10072
+ const start = node.start;
10073
+ if (typeof start === "number") recordFlag(context, `${objectName}.${propertyName}`, "config-object", start, void 0);
10074
+ }
10075
+ }
10076
+ }
10077
+ }
10078
+ if (node.type === "CallExpression") {
10079
+ const callee = node.callee;
10080
+ let functionName;
10081
+ if (isAstNode(callee)) {
10082
+ if (callee.type === "Identifier") functionName = getStaticName(callee);
10083
+ else if (callee.type === "MemberExpression" || callee.type === "StaticMemberExpression") functionName = getStaticName(callee.property);
10084
+ }
10085
+ if (functionName !== void 0) {
10086
+ if (context.vercelFlagsLocalNames.has(functionName) || VERCEL_FLAGS_FUNCTION_NAMES.has(functionName)) {
10087
+ const callArguments = node.arguments;
10088
+ const flagName = extractStringArgument(callArguments, 0);
10089
+ if (flagName !== void 0) {
10090
+ const start = node.start;
10091
+ if (typeof start === "number") recordFlag(context, flagName, "sdk-call", start, "Vercel Flags");
10092
+ }
10093
+ return;
10094
+ }
10095
+ for (const sdkPattern of context.sdkPatterns) {
10096
+ if (sdkPattern.functionName !== functionName) continue;
10097
+ const callArguments = node.arguments;
10098
+ const flagName = extractStringArgument(callArguments, sdkPattern.nameArgIndex);
10099
+ if (flagName === void 0) continue;
10100
+ const start = node.start;
10101
+ if (typeof start === "number") recordFlag(context, flagName, "sdk-call", start, sdkPattern.provider === "" ? void 0 : sdkPattern.provider);
10102
+ break;
10103
+ }
10104
+ }
10105
+ }
10106
+ };
10107
+ const buildSdkPatterns = (extraSdkFunctionNames) => {
10108
+ const merged = [...BUILTIN_SDK_PATTERNS];
10109
+ for (const extraName of extraSdkFunctionNames) merged.push({
10110
+ functionName: extraName,
10111
+ nameArgIndex: 0,
10112
+ provider: ""
10113
+ });
10114
+ return merged;
10115
+ };
10116
+ const detectFeatureFlags = (graph, config) => {
10117
+ if (!config?.enabled) return [];
10118
+ const sdkPatterns = buildSdkPatterns(config.extraSdkFunctionNames);
10119
+ const collectedFlags = [];
10120
+ for (const module of graph.modules) {
10121
+ if (module.isDeclarationFile) continue;
10122
+ if (module.isConfigFile) continue;
10123
+ let sourceText;
10124
+ try {
10125
+ sourceText = (0, node_fs.readFileSync)(module.fileId.path, "utf-8");
10126
+ } catch {
10127
+ continue;
10128
+ }
10129
+ let parseResult;
10130
+ try {
10131
+ parseResult = (0, oxc_parser.parseSync)(module.fileId.path, sourceText);
10132
+ } catch {
10133
+ continue;
10134
+ }
10135
+ const lineStarts = computeLineStarts(sourceText);
10136
+ const vercelFlagsLocalNames = collectVercelFlagsImports(parseResult.program);
10137
+ const visitContext = {
10138
+ filePath: module.fileId.path,
10139
+ lineStarts,
10140
+ results: [],
10141
+ envPrefixes: config.extraEnvPrefixes,
10142
+ sdkPatterns,
10143
+ detectConfigObjects: config.detectConfigObjects,
10144
+ vercelFlagsLocalNames,
10145
+ guard: void 0
10146
+ };
10147
+ visitNode$1(parseResult.program, visitContext);
10148
+ collectedFlags.push(...visitContext.results);
10149
+ }
10150
+ collectedFlags.sort((leftFlag, rightFlag) => {
10151
+ if (leftFlag.path !== rightFlag.path) return leftFlag.path.localeCompare(rightFlag.path);
10152
+ if (leftFlag.line !== rightFlag.line) return leftFlag.line - rightFlag.line;
10153
+ return leftFlag.column - rightFlag.column;
10154
+ });
10155
+ return collectedFlags;
10156
+ };
10157
+ /**
10158
+ * Mark each flag whose guard span overlaps an unused export as
10159
+ * `guardsDeadCode: true`.
10160
+ */
10161
+ const correlateFlagsWithDeadCode = (flags, scanResult) => {
10162
+ if (flags.length === 0 || scanResult.unusedExports.length === 0) return;
10163
+ const unusedByFile = /* @__PURE__ */ new Map();
10164
+ for (const unusedExport of scanResult.unusedExports) {
10165
+ const existing = unusedByFile.get(unusedExport.path);
10166
+ if (existing) existing.push(unusedExport.line);
10167
+ else unusedByFile.set(unusedExport.path, [unusedExport.line]);
10168
+ }
10169
+ for (const flag of flags) {
10170
+ if (flag.guardLineStart === void 0 || flag.guardLineEnd === void 0) continue;
10171
+ const linesInFile = unusedByFile.get(flag.path);
10172
+ if (!linesInFile) continue;
10173
+ const guardStart = flag.guardLineStart;
10174
+ const guardEnd = flag.guardLineEnd;
10175
+ for (const unusedLine of linesInFile) if (unusedLine >= guardStart && unusedLine <= guardEnd) {
10176
+ flag.guardsDeadCode = true;
10177
+ break;
10178
+ }
10179
+ }
10180
+ };
10181
+
10182
+ //#endregion
10183
+ //#region src/report/complexity.ts
10184
+ const incrementCyclomatic = (state) => {
10185
+ const topFrame = state.frameStack[state.frameStack.length - 1];
10186
+ if (topFrame) topFrame.cyclomaticComplexity++;
10187
+ };
10188
+ const incrementCognitiveWithNesting = (state) => {
10189
+ const topFrame = state.frameStack[state.frameStack.length - 1];
10190
+ if (topFrame) topFrame.cognitiveComplexity += 1 + topFrame.nestingLevel;
10191
+ };
10192
+ const incrementCognitiveFlat = (state) => {
10193
+ const topFrame = state.frameStack[state.frameStack.length - 1];
10194
+ if (topFrame) topFrame.cognitiveComplexity++;
10195
+ };
10196
+ const handleLogicalOperator = (operator, state) => {
10197
+ const topFrame = state.frameStack[state.frameStack.length - 1];
10198
+ if (!topFrame) return;
10199
+ if (topFrame.lastLogicalOperator === void 0) {
10200
+ topFrame.cognitiveComplexity++;
10201
+ topFrame.lastLogicalOperator = operator;
10202
+ return;
10203
+ }
10204
+ if (topFrame.lastLogicalOperator === operator) return;
10205
+ topFrame.cognitiveComplexity++;
10206
+ topFrame.lastLogicalOperator = operator;
10207
+ };
10208
+ const resetLogicalOperator = (state) => {
10209
+ const topFrame = state.frameStack[state.frameStack.length - 1];
10210
+ if (topFrame) topFrame.lastLogicalOperator = void 0;
10211
+ };
10212
+ const incrementNesting = (state) => {
10213
+ const topFrame = state.frameStack[state.frameStack.length - 1];
10214
+ if (topFrame) topFrame.nestingLevel++;
10215
+ };
10216
+ const decrementNesting = (state) => {
10217
+ const topFrame = state.frameStack[state.frameStack.length - 1];
10218
+ if (topFrame && topFrame.nestingLevel > 0) topFrame.nestingLevel--;
10219
+ };
10220
+ const countParameters = (parametersNode) => {
10221
+ if (!isAstNode(parametersNode)) return 0;
10222
+ const params = parametersNode;
10223
+ if (Array.isArray(params.params)) return params.params.length;
10224
+ if (Array.isArray(params.items)) return params.items.length;
10225
+ return 0;
10226
+ };
10227
+ const visitChildrenGeneric = (node, visitor) => {
10228
+ if (!isAstNode(node)) return;
10229
+ for (const key of Object.keys(node)) {
10230
+ if (key === "type" || key === "start" || key === "end" || key === "loc" || key === "range") continue;
10231
+ const value = node[key];
10232
+ if (Array.isArray(value)) for (const item of value) visitor(item);
10233
+ else if (value !== null && typeof value === "object") visitor(value);
10234
+ }
10235
+ };
10236
+ const pushFunctionFrame = (functionName, startOffset, endOffset, parameterCount, state) => {
10237
+ state.frameStack.push({
10238
+ functionName,
10239
+ startOffset,
10240
+ endOffset,
10241
+ cyclomaticComplexity: 1,
10242
+ cognitiveComplexity: 0,
10243
+ nestingLevel: 0,
10244
+ lastLogicalOperator: void 0,
10245
+ parameterCount
10246
+ });
10247
+ };
10248
+ const popFunctionFrame = (state) => {
10249
+ const completedFrame = state.frameStack.pop();
10250
+ if (!completedFrame) return;
10251
+ const { line, column } = offsetToLineColumn(completedFrame.startOffset, state.lineStarts);
10252
+ const endLine = offsetToLineColumn(completedFrame.endOffset, state.lineStarts).line;
10253
+ state.results.push({
10254
+ path: state.filePath,
10255
+ functionName: completedFrame.functionName,
10256
+ line,
10257
+ column,
10258
+ cyclomatic: completedFrame.cyclomaticComplexity,
10259
+ cognitive: completedFrame.cognitiveComplexity,
10260
+ lineCount: Math.max(1, endLine - line + 1),
10261
+ paramCount: completedFrame.parameterCount,
10262
+ confidence: "medium",
10263
+ reason: ""
10264
+ });
10265
+ };
10266
+ const visitFunctionLike = (node, kind, state) => {
10267
+ if (!isAstNode(node)) return;
10268
+ const functionName = state.pendingFunctionName ?? (() => {
10269
+ const idNode = node.id;
10270
+ const idName = isAstNode(idNode) ? idNode.name : void 0;
10271
+ return typeof idName === "string" ? idName : kind === "arrow" ? "<arrow>" : "<anonymous>";
10272
+ })();
10273
+ state.pendingFunctionName = void 0;
10274
+ const isNested = state.frameStack.length > 0;
10275
+ if (isNested) incrementNesting(state);
10276
+ const startOffset = node.start;
10277
+ const endOffset = node.end;
10278
+ const parameterCount = countParameters(node.params);
10279
+ pushFunctionFrame(functionName, typeof startOffset === "number" ? startOffset : 0, typeof endOffset === "number" ? endOffset : 0, parameterCount, state);
10280
+ visitChildrenGeneric(node, (child) => visitNode(child, state));
10281
+ popFunctionFrame(state);
10282
+ if (isNested) decrementNesting(state);
10283
+ };
10284
+ const visitNode = (node, state) => {
10285
+ if (!isAstNode(node)) return;
10286
+ switch (node.type) {
10287
+ case "FunctionDeclaration":
10288
+ case "FunctionExpression":
10289
+ case "MethodDefinition":
10290
+ if (node.type === "MethodDefinition") {
10291
+ const keyNode = node.key;
10292
+ const keyName = isAstNode(keyNode) ? keyNode.name ?? keyNode.value : void 0;
10293
+ if (typeof keyName === "string") state.pendingFunctionName = keyName;
10294
+ visitChildrenGeneric(node, (child) => visitNode(child, state));
10295
+ state.pendingFunctionName = void 0;
10296
+ return;
10297
+ }
10298
+ visitFunctionLike(node, "function", state);
10299
+ return;
10300
+ case "ArrowFunctionExpression":
10301
+ visitFunctionLike(node, "arrow", state);
10302
+ return;
10303
+ case "VariableDeclarator": {
10304
+ const declaratorId = node.id;
10305
+ const declaratorIdName = isAstNode(declaratorId) ? declaratorId.name : void 0;
10306
+ if (typeof declaratorIdName === "string") state.pendingFunctionName = declaratorIdName;
10307
+ visitChildrenGeneric(node, (child) => visitNode(child, state));
10308
+ state.pendingFunctionName = void 0;
10309
+ return;
10310
+ }
10311
+ case "PropertyDefinition": {
10312
+ const keyNode = node.key;
10313
+ const keyName = isAstNode(keyNode) ? keyNode.name : void 0;
10314
+ if (typeof keyName === "string") state.pendingFunctionName = keyName;
10315
+ visitChildrenGeneric(node, (child) => visitNode(child, state));
10316
+ state.pendingFunctionName = void 0;
10317
+ return;
10318
+ }
10319
+ case "IfStatement":
10320
+ incrementCyclomatic(state);
10321
+ incrementCognitiveWithNesting(state);
10322
+ incrementNesting(state);
10323
+ visitChildrenGeneric(node, (child) => visitNode(child, state));
10324
+ decrementNesting(state);
10325
+ resetLogicalOperator(state);
10326
+ return;
10327
+ case "ForStatement":
10328
+ case "ForInStatement":
10329
+ case "ForOfStatement":
10330
+ case "WhileStatement":
10331
+ case "DoWhileStatement":
10332
+ incrementCyclomatic(state);
10333
+ incrementCognitiveWithNesting(state);
10334
+ incrementNesting(state);
10335
+ visitChildrenGeneric(node, (child) => visitNode(child, state));
10336
+ decrementNesting(state);
10337
+ return;
10338
+ case "SwitchCase": {
10339
+ const testNode = node.test;
10340
+ if (testNode !== null && testNode !== void 0) {
10341
+ incrementCyclomatic(state);
10342
+ incrementCognitiveFlat(state);
10343
+ }
10344
+ visitChildrenGeneric(node, (child) => visitNode(child, state));
10345
+ return;
10346
+ }
10347
+ case "CatchClause":
10348
+ incrementCyclomatic(state);
10349
+ incrementCognitiveWithNesting(state);
10350
+ incrementNesting(state);
10351
+ visitChildrenGeneric(node, (child) => visitNode(child, state));
10352
+ decrementNesting(state);
10353
+ return;
10354
+ case "ConditionalExpression":
10355
+ incrementCyclomatic(state);
10356
+ incrementCognitiveWithNesting(state);
10357
+ visitChildrenGeneric(node, (child) => visitNode(child, state));
10358
+ return;
10359
+ case "LogicalExpression": {
10360
+ const operator = node.operator;
10361
+ if (operator === "&&" || operator === "||" || operator === "??") {
10362
+ incrementCyclomatic(state);
10363
+ handleLogicalOperator(operator, state);
10364
+ }
10365
+ visitChildrenGeneric(node, (child) => visitNode(child, state));
10366
+ return;
10367
+ }
10368
+ case "AssignmentExpression": {
10369
+ const operator = node.operator;
10370
+ if (operator === "&&=" || operator === "||=" || operator === "??=") incrementCyclomatic(state);
10371
+ visitChildrenGeneric(node, (child) => visitNode(child, state));
10372
+ return;
10373
+ }
10374
+ case "ChainExpression":
10375
+ incrementCyclomatic(state);
10376
+ visitChildrenGeneric(node, (child) => visitNode(child, state));
10377
+ return;
10378
+ default: visitChildrenGeneric(node, (child) => visitNode(child, state));
10379
+ }
10380
+ };
10381
+ const annotateConfidence = (finding, config) => {
10382
+ const breaches = [];
10383
+ if (finding.cyclomatic >= config.cyclomaticThreshold) breaches.push(`cyclomatic ${finding.cyclomatic} ≥ ${config.cyclomaticThreshold}`);
10384
+ if (finding.cognitive >= config.cognitiveThreshold) breaches.push(`cognitive ${finding.cognitive} ≥ ${config.cognitiveThreshold}`);
10385
+ if (finding.paramCount >= config.paramCountThreshold) breaches.push(`paramCount ${finding.paramCount} ≥ ${config.paramCountThreshold}`);
10386
+ if (finding.lineCount >= config.functionLineThreshold) breaches.push(`lineCount ${finding.lineCount} ≥ ${config.functionLineThreshold}`);
10387
+ return {
10388
+ confidence: breaches.length >= 2 ? "high" : "medium",
10389
+ reason: `${finding.functionName} breaches ${breaches.length} threshold${breaches.length === 1 ? "" : "s"}: ${breaches.join(", ")}`
10390
+ };
10391
+ };
10392
+ /**
10393
+ * Per-function cyclomatic + cognitive complexity.
10394
+ *
10395
+ * Cyclomatic (McCabe): 1 + decision points. Counts if/for/while/do/case/catch,
10396
+ * the ?: ternary, &&, ||, ??, &&=/||=/??=, and ?. (optional chaining).
10397
+ *
10398
+ * Cognitive (SonarSource): structural increments with nesting penalty.
10399
+ * Operator-sequence rule: a run of the same logical operator is +1 total;
10400
+ * each operator change adds another +1.
10401
+ *
10402
+ * Returns only functions whose metrics breach at least one threshold from
10403
+ * `config`. Threshold breach count tunes the `confidence` field.
10404
+ */
10405
+ const detectComplexHotspots = (graph, config) => {
10406
+ if (!config?.enabled) return [];
10407
+ const hotspotFindings = [];
10408
+ for (const module of graph.modules) {
10409
+ if (module.isDeclarationFile) continue;
10410
+ if (module.isConfigFile) continue;
10411
+ let sourceText;
10412
+ try {
10413
+ sourceText = (0, node_fs.readFileSync)(module.fileId.path, "utf-8");
10414
+ } catch {
10415
+ continue;
10416
+ }
10417
+ let parseResult;
10418
+ try {
10419
+ parseResult = (0, oxc_parser.parseSync)(module.fileId.path, sourceText);
10420
+ } catch {
10421
+ continue;
10422
+ }
10423
+ const visitState = {
10424
+ filePath: module.fileId.path,
10425
+ lineStarts: computeLineStarts(sourceText),
10426
+ results: [],
10427
+ frameStack: [],
10428
+ pendingFunctionName: void 0
10429
+ };
10430
+ visitNode(parseResult.program, visitState);
10431
+ for (const result of visitState.results) {
10432
+ if (!(result.cyclomatic >= config.cyclomaticThreshold || result.cognitive >= config.cognitiveThreshold || result.paramCount >= config.paramCountThreshold || result.lineCount >= config.functionLineThreshold)) continue;
10433
+ const annotated = annotateConfidence(result, config);
10434
+ hotspotFindings.push({
10435
+ ...result,
10436
+ confidence: annotated.confidence,
10437
+ reason: annotated.reason
10438
+ });
10439
+ }
10440
+ }
10441
+ hotspotFindings.sort((leftFinding, rightFinding) => {
10442
+ const leftScore = leftFinding.cyclomatic + leftFinding.cognitive;
10443
+ const rightScore = rightFinding.cyclomatic + rightFinding.cognitive;
10444
+ if (leftScore !== rightScore) return rightScore - leftScore;
10445
+ if (leftFinding.path !== rightFinding.path) return leftFinding.path.localeCompare(rightFinding.path);
10446
+ return leftFinding.line - rightFinding.line;
10447
+ });
10448
+ return hotspotFindings;
10449
+ };
10450
+
10451
+ //#endregion
10452
+ //#region src/report/private-type-leaks.ts
10453
+ const extractIdentifierName = (node) => {
10454
+ if (!isAstNode(node)) return void 0;
10455
+ if (node.type === "Identifier") {
10456
+ const identifierName = node.name;
10457
+ return typeof identifierName === "string" ? identifierName : void 0;
10458
+ }
10459
+ };
10460
+ const collectTypeReferenceNamesFromTypeNode = (typeNode, into) => {
10461
+ if (!isAstNode(typeNode)) return;
10462
+ if (typeNode.type === "TSTypeReference") {
10463
+ const referencedTypeName = typeNode.typeName;
10464
+ if (isAstNode(referencedTypeName) && referencedTypeName.type === "Identifier") {
10465
+ const name = referencedTypeName.name;
10466
+ if (typeof name === "string") into.add(name);
10467
+ }
10468
+ }
10469
+ for (const key of Object.keys(typeNode)) {
10470
+ if (key === "type" || key === "start" || key === "end") continue;
10471
+ const value = typeNode[key];
10472
+ if (Array.isArray(value)) for (const item of value) collectTypeReferenceNamesFromTypeNode(item, into);
10473
+ else if (value !== null && typeof value === "object") collectTypeReferenceNamesFromTypeNode(value, into);
10474
+ }
10475
+ };
10476
+ const isExportedDeclaration = (statement) => {
10477
+ if (!isAstNode(statement)) return false;
10478
+ return statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration";
10479
+ };
10480
+ const declarationOf = (statement) => {
10481
+ if (!isAstNode(statement)) return void 0;
10482
+ return statement.declaration;
10483
+ };
10484
+ const exportedNameOfDeclaration = (declarationNode) => {
10485
+ if (!isAstNode(declarationNode)) return void 0;
10486
+ if (declarationNode.type === "FunctionDeclaration" || declarationNode.type === "ClassDeclaration") return extractIdentifierName(declarationNode.id);
10487
+ if (declarationNode.type === "VariableDeclaration") {
10488
+ const declarators = declarationNode.declarations;
10489
+ if (Array.isArray(declarators) && declarators.length > 0) {
10490
+ const firstDeclarator = declarators[0];
10491
+ if (isAstNode(firstDeclarator)) return extractIdentifierName(firstDeclarator.id);
10492
+ }
10493
+ }
10494
+ if (declarationNode.type === "TSInterfaceDeclaration" || declarationNode.type === "TSTypeAliasDeclaration") return extractIdentifierName(declarationNode.id);
10495
+ };
10496
+ const collectFromFunctionLikeSignature = (functionLikeNode, exportName, collected) => {
10497
+ if (!isAstNode(functionLikeNode)) return;
10498
+ const params = functionLikeNode.params;
10499
+ if (Array.isArray(params)) for (const param of params) collectFromParameter(param, exportName, collected);
10500
+ const returnTypeAnnotation = functionLikeNode.returnType;
10501
+ if (isAstNode(returnTypeAnnotation)) {
10502
+ const annotation = returnTypeAnnotation.typeAnnotation;
10503
+ pushTypeReferences(annotation, exportName, collected, returnTypeAnnotation);
10504
+ }
10505
+ };
10506
+ const collectFromParameter = (parameterNode, exportName, collected) => {
10507
+ if (!isAstNode(parameterNode)) return;
10508
+ const annotation = parameterNode.typeAnnotation;
10509
+ if (isAstNode(annotation)) {
10510
+ const innerTypeNode = annotation.typeAnnotation;
10511
+ pushTypeReferences(innerTypeNode, exportName, collected, annotation);
10512
+ }
10513
+ };
10514
+ const pushTypeReferences = (typeNode, exportName, collected, spanFallbackNode) => {
10515
+ if (!isAstNode(typeNode)) return;
10516
+ const referencedTypeNames = /* @__PURE__ */ new Set();
10517
+ collectTypeReferenceNamesFromTypeNode(typeNode, referencedTypeNames);
10518
+ for (const referencedName of referencedTypeNames) {
10519
+ const offset = typeNode.start;
10520
+ const fallbackOffset = isAstNode(spanFallbackNode) && typeof spanFallbackNode.start === "number" ? spanFallbackNode.start : 0;
10521
+ collected.push({
10522
+ exportName,
10523
+ typeName: referencedName,
10524
+ byteOffset: typeof offset === "number" ? offset : fallbackOffset
10525
+ });
10526
+ }
10527
+ };
10528
+ const collectPublicSignatureReferences = (programNode) => {
10529
+ const collected = [];
10530
+ if (!isAstNode(programNode)) return collected;
10531
+ const programBody = programNode.body;
10532
+ if (!Array.isArray(programBody)) return collected;
10533
+ for (const statement of programBody) {
10534
+ if (!isExportedDeclaration(statement)) continue;
10535
+ const declarationNode = declarationOf(statement);
10536
+ if (declarationNode === void 0 || declarationNode === null) continue;
10537
+ const exportedName = exportedNameOfDeclaration(declarationNode);
10538
+ if (!exportedName) continue;
10539
+ if (isAstNode(declarationNode)) {
10540
+ if (declarationNode.type === "FunctionDeclaration" || declarationNode.type === "ArrowFunctionExpression" || declarationNode.type === "FunctionExpression") {
10541
+ collectFromFunctionLikeSignature(declarationNode, exportedName, collected);
10542
+ continue;
10543
+ }
10544
+ if (declarationNode.type === "VariableDeclaration") {
10545
+ const declarators = declarationNode.declarations;
10546
+ if (Array.isArray(declarators)) for (const declarator of declarators) {
10547
+ if (!isAstNode(declarator)) continue;
10548
+ const id = declarator.id;
10549
+ if (isAstNode(id)) {
10550
+ const annotation = id.typeAnnotation;
10551
+ if (isAstNode(annotation)) {
10552
+ const inner = annotation.typeAnnotation;
10553
+ pushTypeReferences(inner, exportedName, collected, annotation);
10554
+ }
10555
+ }
10556
+ const init = declarator.init;
10557
+ if (isAstNode(init) && (init.type === "ArrowFunctionExpression" || init.type === "FunctionExpression")) collectFromFunctionLikeSignature(init, exportedName, collected);
10558
+ }
10559
+ continue;
10560
+ }
10561
+ if (declarationNode.type === "ClassDeclaration") {
10562
+ const classBody = declarationNode.body;
10563
+ if (isAstNode(classBody)) {
10564
+ const members = classBody.body;
10565
+ if (Array.isArray(members)) for (const member of members) {
10566
+ if (!isAstNode(member)) continue;
10567
+ if (member.type === "MethodDefinition") {
10568
+ const value = member.value;
10569
+ collectFromFunctionLikeSignature(value, exportedName, collected);
10570
+ } else if (member.type === "PropertyDefinition") {
10571
+ const annotation = member.typeAnnotation;
10572
+ if (isAstNode(annotation)) {
10573
+ const inner = annotation.typeAnnotation;
10574
+ pushTypeReferences(inner, exportedName, collected, annotation);
10575
+ }
10576
+ }
10577
+ }
10578
+ }
10579
+ }
10580
+ }
10581
+ }
10582
+ return collected;
10583
+ };
10584
+ const collectLocalTypeNames = (programNode) => {
10585
+ const localTypeNames = /* @__PURE__ */ new Set();
10586
+ const exportedNames = /* @__PURE__ */ new Set();
10587
+ if (!isAstNode(programNode)) return {
10588
+ localTypeNames,
10589
+ exportedNames
10590
+ };
10591
+ const programBody = programNode.body;
10592
+ if (!Array.isArray(programBody)) return {
10593
+ localTypeNames,
10594
+ exportedNames
10595
+ };
10596
+ for (const statement of programBody) {
10597
+ if (!isAstNode(statement)) continue;
10598
+ if (statement.type === "TSInterfaceDeclaration" || statement.type === "TSTypeAliasDeclaration") {
10599
+ const name = extractIdentifierName(statement.id);
10600
+ if (name) localTypeNames.add(name);
10601
+ continue;
10602
+ }
10603
+ if (statement.type === "ExportNamedDeclaration") {
10604
+ const declarationNode = statement.declaration;
10605
+ if (isAstNode(declarationNode)) {
10606
+ if (declarationNode.type === "TSInterfaceDeclaration" || declarationNode.type === "TSTypeAliasDeclaration") {
10607
+ const name = extractIdentifierName(declarationNode.id);
10608
+ if (name) exportedNames.add(name);
10609
+ continue;
10610
+ }
10611
+ const declaredName = exportedNameOfDeclaration(declarationNode);
10612
+ if (declaredName) exportedNames.add(declaredName);
10613
+ }
10614
+ const specifiers = statement.specifiers;
10615
+ if (Array.isArray(specifiers)) for (const specifier of specifiers) {
10616
+ if (!isAstNode(specifier)) continue;
10617
+ if (specifier.type === "ExportSpecifier") {
10618
+ const exported = specifier.exported;
10619
+ const exportedNameValue = extractIdentifierName(exported);
10620
+ if (exportedNameValue) exportedNames.add(exportedNameValue);
10621
+ }
10622
+ }
10623
+ }
10624
+ }
10625
+ return {
10626
+ localTypeNames,
10627
+ exportedNames
10628
+ };
10629
+ };
10630
+ /**
10631
+ * Storybook CSF3 convention: a story file declares
10632
+ *
10633
+ * const meta = { ... } satisfies Meta<...>;
10634
+ * export default meta;
10635
+ * type Story = StoryObj<typeof meta>;
10636
+ * export const Primary: Story = { ... };
10637
+ *
10638
+ * `Story` is intentionally a local alias — consumers don't import it; the
10639
+ * Storybook runtime reads the default export. Flagging this as a leak
10640
+ * produces near-100% false positives on Storybook codebases, so skip
10641
+ * `*.stories.{ts,tsx,js,jsx,mts,mjs,cts,cjs}` files entirely.
10642
+ */
10643
+ const STORYBOOK_STORY_FILE_PATTERN = /\.stories\.(?:[cm]?ts|[cm]?js|tsx|jsx)$/;
10644
+ const isStorybookStoryFile = (filePath) => STORYBOOK_STORY_FILE_PATTERN.test(filePath);
10645
+ /**
10646
+ * Detect TypeScript "private type leak": an exported declaration's signature
10647
+ * references a type that was declared locally in the same module but is not
10648
+ * itself exported. Consumers of the export need that type to satisfy the
10649
+ * signature, but cannot import it.
10650
+ *
10651
+ * Skips declaration files (`.d.ts`) — they are pure type modules where this
10652
+ * pattern is the norm. Keeps it simple: doesn't try to chase aliased re-export
10653
+ * paths (deslop-js's broader resolver work covers that elsewhere); a leak
10654
+ * that's actually re-exported gets filtered out at the `exportedNames` set.
10655
+ */
10656
+ const detectPrivateTypeLeaks = (graph) => {
10657
+ const findings = [];
10658
+ for (const module of graph.modules) {
10659
+ if (module.isDeclarationFile) continue;
10660
+ if (module.isConfigFile) continue;
10661
+ if (!module.isReachable) continue;
10662
+ if (isStorybookStoryFile(module.fileId.path)) continue;
10663
+ let sourceText;
10664
+ try {
10665
+ sourceText = (0, node_fs.readFileSync)(module.fileId.path, "utf-8");
10666
+ } catch {
10667
+ continue;
10668
+ }
10669
+ let parseResult;
10670
+ try {
10671
+ parseResult = (0, oxc_parser.parseSync)(module.fileId.path, sourceText);
10672
+ } catch {
10673
+ continue;
10674
+ }
10675
+ const programNode = parseResult.program;
10676
+ const { localTypeNames, exportedNames } = collectLocalTypeNames(programNode);
10677
+ if (localTypeNames.size === 0) continue;
10678
+ const publicSignatureReferences = collectPublicSignatureReferences(programNode);
10679
+ if (publicSignatureReferences.length === 0) continue;
10680
+ const lineStarts = computeLineStarts(sourceText);
10681
+ const seenPairs = /* @__PURE__ */ new Set();
10682
+ for (const reference of publicSignatureReferences) {
10683
+ if (!localTypeNames.has(reference.typeName)) continue;
10684
+ if (exportedNames.has(reference.typeName)) continue;
10685
+ const pairKey = `${reference.exportName}::${reference.typeName}`;
10686
+ if (seenPairs.has(pairKey)) continue;
10687
+ seenPairs.add(pairKey);
10688
+ const { line, column } = offsetToLineColumn(reference.byteOffset, lineStarts);
10689
+ findings.push({
10690
+ path: module.fileId.path,
10691
+ exportName: reference.exportName,
10692
+ typeName: reference.typeName,
10693
+ line,
10694
+ column,
10695
+ confidence: "high",
10696
+ reason: `${reference.exportName}'s signature references ${reference.typeName}, declared locally but not exported — consumers can't satisfy the type without importing it`
10697
+ });
10698
+ }
10699
+ }
10700
+ findings.sort((leftLeak, rightLeak) => {
10701
+ if (leftLeak.path !== rightLeak.path) return leftLeak.path.localeCompare(rightLeak.path);
10702
+ return leftLeak.line - rightLeak.line;
10703
+ });
10704
+ return findings;
10705
+ };
10706
+
10707
+ //#endregion
10708
+ //#region src/report/typescript-smells.ts
10709
+ const parseSource = (filePath) => {
10710
+ let sourceText;
10711
+ try {
10712
+ sourceText = (0, node_fs.readFileSync)(filePath, "utf-8");
10713
+ } catch {
10714
+ return;
10715
+ }
10716
+ let parseResult;
10717
+ try {
10718
+ parseResult = (0, oxc_parser.parseSync)(filePath, sourceText);
10719
+ } catch {
10720
+ return;
10721
+ }
10722
+ const rawComments = parseResult.comments;
10723
+ const comments = Array.isArray(rawComments) ? rawComments.filter(isParsedSourceComment) : [];
10724
+ return {
10725
+ programNode: parseResult.program,
10726
+ sourceText,
10727
+ lineStarts: computeLineStarts(sourceText),
10728
+ comments
10729
+ };
10730
+ };
10731
+ const isParsedSourceComment = (candidate) => {
10732
+ if (typeof candidate !== "object" || candidate === null) return false;
10733
+ const fields = candidate;
10734
+ return (fields.type === "Line" || fields.type === "Block") && typeof fields.value === "string" && typeof fields.start === "number" && typeof fields.end === "number";
10735
+ };
10736
+ const sliceSnippet = (sourceText, start, end) => {
10737
+ const SNIPPET_BUDGET_CHARS = 80;
10738
+ const raw = sourceText.slice(start, Math.min(end, start + SNIPPET_BUDGET_CHARS)).replace(/\s+/g, " ").trim();
10739
+ return end - start > SNIPPET_BUDGET_CHARS ? `${raw}…` : raw;
10740
+ };
10741
+ const isAnyOrUnknownTypeAnnotation = (typeAnnotation) => {
10742
+ if (!isAstNode(typeAnnotation)) return void 0;
10743
+ if (typeAnnotation.type === "TSAnyKeyword") return "any";
10744
+ if (typeAnnotation.type === "TSUnknownKeyword") return "unknown";
10745
+ };
10746
+ const isLiteralLikeNonNull = (expression) => {
10747
+ if (!isAstNode(expression)) return false;
10748
+ if (expression.type === "Literal") return expression.value !== null;
10749
+ if (expression.type === "TemplateLiteral" || expression.type === "ArrayExpression" || expression.type === "ObjectExpression" || expression.type === "FunctionExpression" || expression.type === "ArrowFunctionExpression" || expression.type === "ClassExpression") return true;
10750
+ return false;
10751
+ };
10752
+ const collectUnnecessaryAssertionsInNode = (node, filePath, sourceText, lineStarts, results) => {
10753
+ if (!isAstNode(node)) return;
10754
+ if (node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression") {
10755
+ const innerExpression = node.expression;
10756
+ const typeAnnotation = node.typeAnnotation;
10757
+ if (node.type === "TSAsExpression") {
10758
+ const outerKind = isAnyOrUnknownTypeAnnotation(typeAnnotation);
10759
+ if (outerKind === void 0 && isAstNode(innerExpression) && innerExpression.type === "TSAsExpression") {
10760
+ const innerTypeAnnotation = innerExpression.typeAnnotation;
10761
+ const innerKind = isAnyOrUnknownTypeAnnotation(innerTypeAnnotation);
10762
+ if (innerKind !== void 0) pushAssertion(node, "redundant-double-assertion", `\`x as ${innerKind} as T\` first widens to ${innerKind} just to assert to T — drop the intermediate ${innerKind} and assert directly`, "if you must assert, write `x as T` directly", filePath, sourceText, lineStarts, results);
10763
+ }
10764
+ if (outerKind === "any") pushAssertion(node, "assertion-to-any", "`as any` opts out of TypeScript's type system — narrow to a specific type or use `unknown`", "replace `as any` with the actual type, or use `as unknown as T` only when you genuinely need to discard the inferred type", filePath, sourceText, lineStarts, results);
10765
+ }
10766
+ }
10767
+ if (node.type === "TSTypeAssertion") pushAssertion(node, "angle-bracket-assertion", "`<T>x` style assertion is parsed as a JSX tag in `.tsx` and is deprecated in mixed-extension projects — prefer `x as T`", "rewrite `<T>x` as `x as T`", filePath, sourceText, lineStarts, results);
10768
+ if (node.type === "TSNonNullExpression") {
10769
+ const innerExpression = node.expression;
10770
+ if (isAstNode(innerExpression) && innerExpression.type === "TSNonNullExpression") pushAssertion(node, "double-non-null", "`x!!` is the non-null assertion applied twice — the second `!` is always a no-op", "drop one of the `!` operators", filePath, sourceText, lineStarts, results);
10771
+ else if (isLiteralLikeNonNull(innerExpression)) pushAssertion(node, "redundant-non-null-on-literal", "`!` after a literal / array / object / function expression is redundant — those values are never null", "remove the trailing `!`", filePath, sourceText, lineStarts, results);
10772
+ }
10773
+ };
10774
+ const pushAssertion = (node, kind, reason, suggestion, filePath, sourceText, lineStarts, results) => {
10775
+ if (!isAstNode(node)) return;
10776
+ const startOffset = node.start;
10777
+ const endOffset = node.end;
10778
+ if (typeof startOffset !== "number" || typeof endOffset !== "number") return;
10779
+ const { line, column } = offsetToLineColumn(startOffset, lineStarts);
10780
+ const isHighConfidenceKind = kind === "double-non-null" || kind === "redundant-non-null-on-literal" || kind === "redundant-double-assertion";
10781
+ results.push({
10782
+ path: filePath,
10783
+ kind,
10784
+ snippet: sliceSnippet(sourceText, startOffset, endOffset),
10785
+ line,
10786
+ column,
10787
+ confidence: isHighConfidenceKind ? "high" : "medium",
10788
+ reason,
10789
+ suggestion
10790
+ });
10791
+ };
10792
+ const visitForUnnecessaryAssertions = (node, filePath, sourceText, lineStarts, results) => {
10793
+ if (!isAstNode(node)) return;
10794
+ collectUnnecessaryAssertionsInNode(node, filePath, sourceText, lineStarts, results);
10795
+ for (const propertyKey of Object.keys(node)) {
10796
+ if (propertyKey === "type" || propertyKey === "start" || propertyKey === "end" || propertyKey === "loc" || propertyKey === "range") continue;
10797
+ const value = node[propertyKey];
10798
+ if (Array.isArray(value)) for (const item of value) visitForUnnecessaryAssertions(item, filePath, sourceText, lineStarts, results);
10799
+ else if (value !== null && typeof value === "object") visitForUnnecessaryAssertions(value, filePath, sourceText, lineStarts, results);
10800
+ }
10801
+ };
10802
+ const importExpressionSpecifier = (importExpression) => {
10803
+ if (!isAstNode(importExpression)) return void 0;
10804
+ if (importExpression.type !== "ImportExpression") return void 0;
10805
+ const sourceNode = importExpression.source;
10806
+ if (!isAstNode(sourceNode)) return void 0;
10807
+ if (sourceNode.type !== "Literal") return void 0;
10808
+ const literalValue = sourceNode.value;
10809
+ return typeof literalValue === "string" ? literalValue : void 0;
10810
+ };
10811
+ const findThenImportInExpressionStatement = (expressionNode) => {
10812
+ if (!isAstNode(expressionNode)) return void 0;
10813
+ if (expressionNode.type !== "CallExpression") return void 0;
10814
+ const callee = expressionNode.callee;
10815
+ if (!isAstNode(callee)) return void 0;
10816
+ if (callee.type !== "MemberExpression" && callee.type !== "StaticMemberExpression") return void 0;
10817
+ const propertyNode = callee.property;
10818
+ const propertyName = isAstNode(propertyNode) ? propertyNode.name : void 0;
10819
+ if (propertyName !== "then" && propertyName !== "catch" && propertyName !== "finally") return void 0;
10820
+ const objectNode = callee.object;
10821
+ const specifier = importExpressionSpecifier(objectNode);
10822
+ if (specifier === void 0) return void 0;
10823
+ return {
10824
+ importExpression: objectNode,
10825
+ specifier
10826
+ };
10827
+ };
10828
+ const findAwaitImportInExpression = (expressionNode) => {
10829
+ if (!isAstNode(expressionNode)) return void 0;
10830
+ if (expressionNode.type !== "AwaitExpression") return void 0;
10831
+ const argumentNode = expressionNode.argument;
10832
+ const specifier = importExpressionSpecifier(argumentNode);
10833
+ if (specifier === void 0) return void 0;
10834
+ return {
10835
+ importExpression: argumentNode,
10836
+ specifier
10837
+ };
10838
+ };
10839
+ const collectLazyImportsAtTopLevel = (programNode, filePath, lineStarts, results) => {
10840
+ if (!isAstNode(programNode)) return;
10841
+ const programBody = programNode.body;
10842
+ if (!Array.isArray(programBody)) return;
10843
+ for (const topLevelStatement of programBody) {
10844
+ if (!isAstNode(topLevelStatement)) continue;
10845
+ if (topLevelStatement.type === "VariableDeclaration") {
10846
+ const declarators = topLevelStatement.declarations;
10847
+ if (!Array.isArray(declarators)) continue;
10848
+ for (const declarator of declarators) {
10849
+ if (!isAstNode(declarator)) continue;
10850
+ const initializer = declarator.init;
10851
+ const awaitImport = findAwaitImportInExpression(initializer);
10852
+ if (awaitImport) recordLazyImport(awaitImport, "top-level-await-import", filePath, lineStarts, results);
10853
+ }
10854
+ continue;
10855
+ }
10856
+ if (topLevelStatement.type === "ExpressionStatement") {
10857
+ const innerExpression = topLevelStatement.expression;
10858
+ const awaitImport = findAwaitImportInExpression(innerExpression);
10859
+ if (awaitImport) {
10860
+ recordLazyImport(awaitImport, "top-level-await-import", filePath, lineStarts, results);
10861
+ continue;
10862
+ }
10863
+ const thenImport = findThenImportInExpressionStatement(innerExpression);
10864
+ if (thenImport) recordLazyImport(thenImport, "top-level-then-import", filePath, lineStarts, results);
10865
+ }
10866
+ }
10867
+ };
10868
+ const recordLazyImport = (match, kind, filePath, lineStarts, results) => {
10869
+ if (!isAstNode(match.importExpression)) return;
10870
+ const startOffset = match.importExpression.start;
10871
+ if (typeof startOffset !== "number") return;
10872
+ const { line, column } = offsetToLineColumn(startOffset, lineStarts);
10873
+ results.push({
10874
+ path: filePath,
10875
+ specifier: match.specifier,
10876
+ kind,
10877
+ line,
10878
+ column,
10879
+ confidence: kind === "top-level-await-import" ? "high" : "medium",
10880
+ reason: kind === "top-level-await-import" ? `top-level \`await import("${match.specifier}")\` runs synchronously before the module finishes loading anyway — there is no laziness benefit, prefer a static \`import\`` : `top-level \`import("${match.specifier}").then(...)\` runs at module evaluation — prefer a static \`import\` and a regular function call unless the dynamic-import contract is intentional`
10881
+ });
10882
+ };
10883
+ const buildPackageJsonTypeCache = () => {
10884
+ const directoryToType = /* @__PURE__ */ new Map();
10885
+ const resolveModuleType = (filePath) => {
10886
+ let currentDirectory = (0, node_path.dirname)((0, node_path.resolve)(filePath));
10887
+ const visitedDirectories = [];
10888
+ while (true) {
10889
+ visitedDirectories.push(currentDirectory);
10890
+ const cached = directoryToType.get(currentDirectory);
10891
+ if (cached !== void 0) {
10892
+ for (const visitedDirectory of visitedDirectories) directoryToType.set(visitedDirectory, cached);
10893
+ return cached;
10894
+ }
10895
+ const packageJsonPath = (0, node_path.join)(currentDirectory, "package.json");
10896
+ if ((0, node_fs.existsSync)(packageJsonPath)) try {
10897
+ const packageJson = JSON.parse((0, node_fs.readFileSync)(packageJsonPath, "utf-8"));
10898
+ const moduleType = packageJson.type === "module" ? "module" : packageJson.type === "commonjs" ? "commonjs" : void 0;
10899
+ for (const visitedDirectory of visitedDirectories) directoryToType.set(visitedDirectory, moduleType);
10900
+ return moduleType;
10901
+ } catch {
10902
+ for (const visitedDirectory of visitedDirectories) directoryToType.set(visitedDirectory, void 0);
10903
+ return;
10904
+ }
10905
+ const parentDirectory = (0, node_path.dirname)(currentDirectory);
10906
+ if (parentDirectory === currentDirectory) {
10907
+ for (const visitedDirectory of visitedDirectories) directoryToType.set(visitedDirectory, void 0);
10908
+ return;
10909
+ }
10910
+ currentDirectory = parentDirectory;
10911
+ }
10912
+ };
10913
+ return { resolveModuleType };
10914
+ };
10915
+ const isEsmFilePath = (filePath, typeCache) => {
10916
+ if (filePath.endsWith(".mts") || filePath.endsWith(".mjs")) return true;
10917
+ if (filePath.endsWith(".cts") || filePath.endsWith(".cjs")) return false;
10918
+ return typeCache.resolveModuleType(filePath) === "module";
10919
+ };
10920
+ const collectCommonjsInEsm = (programNode, filePath, sourceText, lineStarts, results) => {
10921
+ if (!isAstNode(programNode)) return;
10922
+ visitForCommonjs(programNode, filePath, sourceText, lineStarts, results);
10923
+ };
10924
+ const visitForCommonjs = (node, filePath, sourceText, lineStarts, results) => {
10925
+ if (!isAstNode(node)) return;
10926
+ if (node.type === "CallExpression") {
10927
+ const callee = node.callee;
10928
+ if (isAstNode(callee) && callee.type === "Identifier") {
10929
+ if (callee.name === "require") {
10930
+ const callArguments = node.arguments;
10931
+ if (Array.isArray(callArguments) && callArguments.length > 0) {
10932
+ const firstArgument = callArguments[0];
10933
+ if (isAstNode(firstArgument) && firstArgument.type === "Literal" && typeof firstArgument.value === "string") {
10934
+ const startOffset = node.start;
10935
+ const endOffset = node.end;
10936
+ if (typeof startOffset === "number" && typeof endOffset === "number") {
10937
+ const { line, column } = offsetToLineColumn(startOffset, lineStarts);
10938
+ results.push({
10939
+ path: filePath,
10940
+ kind: "require",
10941
+ line,
10942
+ column,
10943
+ confidence: "high",
10944
+ reason: "synchronous `require()` is unavailable in native ESM — use a static `import` or top-level `await import()`",
10945
+ snippet: sliceSnippet(sourceText, startOffset, endOffset)
10946
+ });
10947
+ }
10948
+ }
10949
+ }
10950
+ }
10951
+ }
10952
+ }
10953
+ if (node.type === "AssignmentExpression") {
10954
+ const leftSide = node.left;
10955
+ if (isAstNode(leftSide)) {
10956
+ if (leftSide.type === "MemberExpression" || leftSide.type === "StaticMemberExpression") {
10957
+ const objectNode = leftSide.object;
10958
+ const propertyNode = leftSide.property;
10959
+ const objectName = isAstNode(objectNode) ? objectNode.name : void 0;
10960
+ const propertyName = isAstNode(propertyNode) ? propertyNode.name : void 0;
10961
+ if (objectName === "module" && propertyName === "exports") {
10962
+ const startOffset = node.start;
10963
+ const endOffset = node.end;
10964
+ if (typeof startOffset === "number" && typeof endOffset === "number") {
10965
+ const { line, column } = offsetToLineColumn(startOffset, lineStarts);
10966
+ results.push({
10967
+ path: filePath,
10968
+ kind: "module-exports",
10969
+ line,
10970
+ column,
10971
+ confidence: "high",
10972
+ reason: "`module.exports = ...` is CommonJS — replace with `export default` or named `export` for ESM",
10973
+ snippet: sliceSnippet(sourceText, startOffset, endOffset)
10974
+ });
10975
+ }
10976
+ } else if (objectName === "exports") {
10977
+ const startOffset = node.start;
10978
+ const endOffset = node.end;
10979
+ if (typeof startOffset === "number" && typeof endOffset === "number") {
10980
+ const { line, column } = offsetToLineColumn(startOffset, lineStarts);
10981
+ results.push({
10982
+ path: filePath,
10983
+ kind: "exports-assignment",
10984
+ line,
10985
+ column,
10986
+ confidence: "high",
10987
+ reason: "`exports.x = ...` is CommonJS — replace with a named `export` for ESM",
10988
+ snippet: sliceSnippet(sourceText, startOffset, endOffset)
10989
+ });
10990
+ }
10991
+ }
10992
+ }
10993
+ }
10994
+ }
10995
+ for (const propertyKey of Object.keys(node)) {
10996
+ if (propertyKey === "type" || propertyKey === "start" || propertyKey === "end" || propertyKey === "loc" || propertyKey === "range") continue;
10997
+ const value = node[propertyKey];
10998
+ if (Array.isArray(value)) for (const item of value) visitForCommonjs(item, filePath, sourceText, lineStarts, results);
10999
+ else if (value !== null && typeof value === "object") visitForCommonjs(value, filePath, sourceText, lineStarts, results);
11000
+ }
11001
+ };
11002
+ const TS_IGNORE_LEADING = /^\s*@ts-ignore\b/;
11003
+ const TS_NOCHECK_LEADING = /^\s*@ts-nocheck\b/;
11004
+ const TS_EXPECT_ERROR_LEADING = /^\s*@ts-expect-error\b(.*)$/;
11005
+ const collectTypeScriptEscapeHatches = (comments, filePath, lineStarts, results) => {
11006
+ for (const comment of comments) {
11007
+ const commentBody = comment.type === "Block" ? comment.value.split("\n")[0] : comment.value;
11008
+ if (TS_IGNORE_LEADING.test(commentBody)) {
11009
+ pushEscapeHatch(comment.start, "ts-ignore", "`@ts-ignore` silently swallows the next line's type errors forever — use `@ts-expect-error` so the suppression breaks if the underlying error gets fixed", "rewrite as `@ts-expect-error <why this is okay>`", "high", filePath, lineStarts, results);
11010
+ continue;
11011
+ }
11012
+ if (TS_NOCHECK_LEADING.test(commentBody)) {
11013
+ pushEscapeHatch(comment.start, "ts-nocheck", "`@ts-nocheck` disables type checking for the entire file — fix the underlying types or scope the suppression to a specific line", "remove `@ts-nocheck` and address the underlying type errors, or use per-line `@ts-expect-error` with a justification", "medium", filePath, lineStarts, results);
11014
+ continue;
11015
+ }
11016
+ const expectErrorMatch = commentBody.match(TS_EXPECT_ERROR_LEADING);
11017
+ if (expectErrorMatch) {
11018
+ if ((expectErrorMatch[1] ?? "").trim().length === 0) pushEscapeHatch(comment.start, "ts-expect-error-without-explanation", "`@ts-expect-error` should be followed by a comment explaining why the next line legitimately produces a type error", "add a short justification: `// @ts-expect-error: <why this is okay>`", "low", filePath, lineStarts, results);
11019
+ }
11020
+ }
11021
+ };
11022
+ const pushEscapeHatch = (commentStartOffset, kind, reason, suggestion, confidence, filePath, lineStarts, results) => {
11023
+ const { line, column } = offsetToLineColumn(commentStartOffset, lineStarts);
11024
+ results.push({
11025
+ path: filePath,
11026
+ kind,
11027
+ line,
11028
+ column,
11029
+ confidence,
11030
+ reason,
11031
+ suggestion
11032
+ });
11033
+ };
11034
+ const isTypeScriptOrJsFile = (filePath) => filePath.endsWith(".ts") || filePath.endsWith(".tsx") || filePath.endsWith(".mts") || filePath.endsWith(".cts") || filePath.endsWith(".js") || filePath.endsWith(".jsx") || filePath.endsWith(".mjs") || filePath.endsWith(".cjs");
11035
+ const isTypeScriptFileExtension = (filePath) => filePath.endsWith(".ts") || filePath.endsWith(".tsx") || filePath.endsWith(".mts") || filePath.endsWith(".cts");
11036
+ const detectTypeScriptSmells = (graph) => {
11037
+ const unnecessaryAssertions = [];
11038
+ const lazyImportsAtTopLevel = [];
11039
+ const commonjsInEsm = [];
11040
+ const typeScriptEscapeHatches = [];
11041
+ const packageJsonTypeCache = buildPackageJsonTypeCache();
11042
+ for (const module of graph.modules) {
11043
+ if (module.isDeclarationFile) continue;
11044
+ const filePath = module.fileId.path;
11045
+ if (!isTypeScriptOrJsFile(filePath)) continue;
11046
+ const parsedSource = parseSource(filePath);
11047
+ if (!parsedSource) continue;
11048
+ if (isTypeScriptFileExtension(filePath)) {
11049
+ visitForUnnecessaryAssertions(parsedSource.programNode, filePath, parsedSource.sourceText, parsedSource.lineStarts, unnecessaryAssertions);
11050
+ collectTypeScriptEscapeHatches(parsedSource.comments, filePath, parsedSource.lineStarts, typeScriptEscapeHatches);
11051
+ }
11052
+ collectLazyImportsAtTopLevel(parsedSource.programNode, filePath, parsedSource.lineStarts, lazyImportsAtTopLevel);
11053
+ if (isEsmFilePath(filePath, packageJsonTypeCache)) collectCommonjsInEsm(parsedSource.programNode, filePath, parsedSource.sourceText, parsedSource.lineStarts, commonjsInEsm);
11054
+ }
11055
+ unnecessaryAssertions.sort((leftFinding, rightFinding) => {
11056
+ if (leftFinding.path !== rightFinding.path) return leftFinding.path.localeCompare(rightFinding.path);
11057
+ return leftFinding.line - rightFinding.line;
11058
+ });
11059
+ lazyImportsAtTopLevel.sort((leftFinding, rightFinding) => {
11060
+ if (leftFinding.path !== rightFinding.path) return leftFinding.path.localeCompare(rightFinding.path);
11061
+ return leftFinding.line - rightFinding.line;
11062
+ });
11063
+ commonjsInEsm.sort((leftFinding, rightFinding) => {
11064
+ if (leftFinding.path !== rightFinding.path) return leftFinding.path.localeCompare(rightFinding.path);
11065
+ return leftFinding.line - rightFinding.line;
11066
+ });
11067
+ typeScriptEscapeHatches.sort((leftFinding, rightFinding) => {
11068
+ if (leftFinding.path !== rightFinding.path) return leftFinding.path.localeCompare(rightFinding.path);
11069
+ return leftFinding.line - rightFinding.line;
11070
+ });
11071
+ return {
11072
+ unnecessaryAssertions,
11073
+ lazyImportsAtTopLevel,
11074
+ commonjsInEsm,
11075
+ typeScriptEscapeHatches
11076
+ };
11077
+ };
11078
+
11079
+ //#endregion
11080
+ //#region src/utils/run-safe-detector.ts
11081
+ const runSafeDetector = (input) => {
11082
+ try {
11083
+ return input.detector();
11084
+ } catch (caughtError) {
11085
+ input.errorSink.push(new DetectorError({
11086
+ module: input.module,
11087
+ message: `${input.detectorName} threw ${input.contextDescription}`,
11088
+ detail: describeUnknownError(caughtError)
11089
+ }));
11090
+ return input.fallback;
11091
+ }
11092
+ };
11093
+
11094
+ //#endregion
11095
+ //#region src/semantic/program.ts
11096
+ const failureFor = (reason, message, options = { rootDir: "" }) => {
11097
+ return {
11098
+ reason,
11099
+ message,
11100
+ error: new TypeScriptError({
11101
+ code: {
11102
+ "no-tsconfig": "tsconfig-not-found",
11103
+ "tsconfig-parse-error": "tsconfig-parse-failed",
11104
+ "program-creation-failed": "ts-program-creation-failed",
11105
+ "too-many-files": "ts-program-too-large",
11106
+ "typescript-load-failed": "ts-not-loadable"
11107
+ }[reason],
11108
+ severity: reason === "no-tsconfig" ? "info" : "warning",
11109
+ message,
11110
+ path: options.rootDir || void 0,
11111
+ detail: options.detail
11112
+ })
11113
+ };
11114
+ };
11115
+ const findNearestTsconfig = (rootDir, explicitPath) => {
11116
+ if (explicitPath) {
11117
+ const absoluteExplicit = (0, node_path.resolve)(rootDir, explicitPath);
11118
+ if ((0, node_fs.existsSync)(absoluteExplicit)) return absoluteExplicit;
11119
+ return;
11120
+ }
11121
+ for (const candidateName of DEFAULT_SEMANTIC_TSCONFIG_NAMES) {
11122
+ const candidatePath = (0, node_path.resolve)(rootDir, candidateName);
11123
+ if ((0, node_fs.existsSync)(candidatePath)) return candidatePath;
11124
+ }
11125
+ };
11126
+ const createSemanticContext = (rootDir, tsconfigPath) => {
11127
+ const resolvedTsconfigPath = findNearestTsconfig(rootDir, tsconfigPath);
11128
+ if (!resolvedTsconfigPath) return {
11129
+ ok: false,
11130
+ failure: failureFor("no-tsconfig", `No tsconfig found under ${rootDir}`, { rootDir })
11131
+ };
11132
+ let configFileContent;
11133
+ try {
11134
+ configFileContent = typescript.default.readConfigFile(resolvedTsconfigPath, typescript.default.sys.readFile);
11135
+ } catch (readError) {
11136
+ return {
11137
+ ok: false,
11138
+ failure: failureFor("tsconfig-parse-error", "ts.readConfigFile threw", {
11139
+ rootDir: resolvedTsconfigPath,
11140
+ detail: describeUnknownError(readError)
11141
+ })
11142
+ };
11143
+ }
11144
+ if (configFileContent.error) return {
11145
+ ok: false,
11146
+ failure: failureFor("tsconfig-parse-error", typescript.default.flattenDiagnosticMessageText(configFileContent.error.messageText, "\n"), { rootDir: resolvedTsconfigPath })
11147
+ };
11148
+ let parsedCommandLine;
11149
+ try {
11150
+ parsedCommandLine = typescript.default.parseJsonConfigFileContent(configFileContent.config, typescript.default.sys, (0, node_path.dirname)(resolvedTsconfigPath), {
11151
+ noEmit: true,
8551
11152
  skipLibCheck: true,
8552
11153
  allowJs: true,
8553
11154
  isolatedModules: false
@@ -8915,6 +11516,55 @@ const detectUnusedEnumMembers = (graph, config, context, referenceIndex) => {
8915
11516
  return findings;
8916
11517
  };
8917
11518
 
11519
+ //#endregion
11520
+ //#region src/utils/is-framework-lifecycle-method.ts
11521
+ /**
11522
+ * Methods invoked by-name by React / Angular runtimes. Static "no caller"
11523
+ * analysis can't see those call sites, so without this allowlist
11524
+ * `unusedClassMembers` would fire on every component.
11525
+ */
11526
+ const FRAMEWORK_LIFECYCLE_METHODS = new Set([
11527
+ "render",
11528
+ "componentDidMount",
11529
+ "componentDidUpdate",
11530
+ "componentWillUnmount",
11531
+ "shouldComponentUpdate",
11532
+ "getSnapshotBeforeUpdate",
11533
+ "getDerivedStateFromProps",
11534
+ "getDerivedStateFromError",
11535
+ "componentDidCatch",
11536
+ "componentWillMount",
11537
+ "componentWillReceiveProps",
11538
+ "componentWillUpdate",
11539
+ "UNSAFE_componentWillMount",
11540
+ "UNSAFE_componentWillReceiveProps",
11541
+ "UNSAFE_componentWillUpdate",
11542
+ "getChildContext",
11543
+ "contextType",
11544
+ "ngOnInit",
11545
+ "ngOnDestroy",
11546
+ "ngOnChanges",
11547
+ "ngDoCheck",
11548
+ "ngAfterContentInit",
11549
+ "ngAfterContentChecked",
11550
+ "ngAfterViewInit",
11551
+ "ngAfterViewChecked",
11552
+ "ngAcceptInputType",
11553
+ "canActivate",
11554
+ "canDeactivate",
11555
+ "canActivateChild",
11556
+ "canMatch",
11557
+ "resolve",
11558
+ "intercept",
11559
+ "transform",
11560
+ "validate",
11561
+ "registerOnChange",
11562
+ "registerOnTouched",
11563
+ "writeValue",
11564
+ "setDisabledState"
11565
+ ]);
11566
+ const isFrameworkLifecycleMethod = (name) => FRAMEWORK_LIFECYCLE_METHODS.has(name);
11567
+
8918
11568
  //#endregion
8919
11569
  //#region src/semantic/unused-class-members.ts
8920
11570
  const isClassExported = (declaration) => {
@@ -9046,6 +11696,7 @@ const detectUnusedClassMembers = (graph, config, context, referenceIndex, decora
9046
11696
  if (memberHasExternalReference(memberSymbol, referenceIndex)) continue;
9047
11697
  const memberName = typescript.default.isIdentifier(member.name) ? member.name.text : member.name.getText(sourceFile);
9048
11698
  if (overriddenMemberNames.has(memberName)) continue;
11699
+ if (isFrameworkLifecycleMethod(memberName)) continue;
9049
11700
  const { line: zeroIndexedLine, character: zeroIndexedColumn } = sourceFile.getLineAndCharacterOfPosition(member.getStart(sourceFile));
9050
11701
  const line = zeroIndexedLine + 1;
9051
11702
  const column = zeroIndexedColumn + 1;
@@ -9446,6 +12097,22 @@ const generateReport = (graph, config) => {
9446
12097
  const simplifiableFunctions = config.reportRedundancy ? safeReportDetector("detectSimplifiableFunctions", () => detectSimplifiableFunctions(graph), [], errorSink) : [];
9447
12098
  const simplifiableExpressions = config.reportRedundancy ? safeReportDetector("detectSimplifiableExpressions", () => detectSimplifiableExpressions(graph), [], errorSink) : [];
9448
12099
  const duplicateConstants = config.reportRedundancy ? safeReportDetector("detectDuplicateConstants", () => detectDuplicateConstants(graph), [], errorSink) : [];
12100
+ const crossFileDuplicateExports = config.reportRedundancy ? safeReportDetector("detectCrossFileDuplicateExports", () => detectCrossFileDuplicateExports(graph), [], errorSink) : [];
12101
+ const duplicateBlockResult = safeReportDetector("detectDuplicateBlocks", () => detectDuplicateBlocks(graph, config.duplicateBlocks, config.rootDir), {
12102
+ duplicateBlocks: [],
12103
+ duplicateBlockClusters: [],
12104
+ shadowedDirectoryPairs: []
12105
+ }, errorSink);
12106
+ const reExportCycles = safeReportDetector("detectReExportCycles", () => detectReExportCycles(graph), [], errorSink);
12107
+ const featureFlags = safeReportDetector("detectFeatureFlags", () => detectFeatureFlags(graph, config.featureFlags), [], errorSink);
12108
+ const complexFunctions = safeReportDetector("detectComplexHotspots", () => detectComplexHotspots(graph, config.complexity), [], errorSink);
12109
+ const privateTypeLeaks = safeReportDetector("detectPrivateTypeLeaks", () => detectPrivateTypeLeaks(graph), [], errorSink);
12110
+ const typeScriptSmellsResult = safeReportDetector("detectTypeScriptSmells", () => detectTypeScriptSmells(graph), {
12111
+ unnecessaryAssertions: [],
12112
+ lazyImportsAtTopLevel: [],
12113
+ commonjsInEsm: [],
12114
+ typeScriptEscapeHatches: []
12115
+ }, errorSink);
9449
12116
  let semanticResult;
9450
12117
  try {
9451
12118
  semanticResult = runSemanticAnalysis(graph, config);
@@ -9470,6 +12137,7 @@ const generateReport = (graph, config) => {
9470
12137
  errorSink.push(semanticError);
9471
12138
  }
9472
12139
  const redundantAliases = config.reportRedundancy ? [...syntacticRedundantAliases, ...semanticResult.redundantAliases] : [];
12140
+ if (featureFlags.length > 0) correlateFlagsWithDeadCode(featureFlags, { unusedExports });
9473
12141
  const totalExports = graph.modules.reduce((exportCount, module) => exportCount + module.exports.filter((exportInfo) => !(exportInfo.name === "*" && exportInfo.isNamespaceReExport)).length, 0);
9474
12142
  return {
9475
12143
  unusedFiles,
@@ -9490,6 +12158,18 @@ const generateReport = (graph, config) => {
9490
12158
  simplifiableFunctions,
9491
12159
  simplifiableExpressions,
9492
12160
  duplicateConstants,
12161
+ crossFileDuplicateExports,
12162
+ duplicateBlocks: duplicateBlockResult.duplicateBlocks,
12163
+ duplicateBlockClusters: duplicateBlockResult.duplicateBlockClusters,
12164
+ shadowedDirectoryPairs: duplicateBlockResult.shadowedDirectoryPairs,
12165
+ reExportCycles,
12166
+ featureFlags,
12167
+ complexFunctions,
12168
+ privateTypeLeaks,
12169
+ unnecessaryAssertions: typeScriptSmellsResult.unnecessaryAssertions,
12170
+ lazyImportsAtTopLevel: typeScriptSmellsResult.lazyImportsAtTopLevel,
12171
+ commonjsInEsm: typeScriptSmellsResult.commonjsInEsm,
12172
+ typeScriptEscapeHatches: typeScriptSmellsResult.typeScriptEscapeHatches,
9493
12173
  analysisErrors: errorSink,
9494
12174
  totalFiles: graph.modules.length,
9495
12175
  totalExports,
@@ -9577,18 +12257,53 @@ const detectReactNative = (rootDir, workspacePackages) => {
9577
12257
  *
9578
12258
  * - `reportRedundancy: true` — on because redundancy findings are mostly
9579
12259
  * high-signal and the detectors carry their own confidence tiers.
12260
+ *
12261
+ * - `duplicateBlocks: undefined` — token-based copy-paste detection (suffix
12262
+ * array + LCP) is opt-in. It re-parses every source
12263
+ * file to emit a token stream and adds significant runtime to the scan.
12264
+ * Pass `duplicateBlocks: { enabled: true }` to turn it on.
9580
12265
  */
9581
12266
  const fillSemanticConfig = (semanticOverrides) => {
9582
- if (semanticOverrides === void 0) return void 0;
12267
+ const overrides = semanticOverrides ?? {};
12268
+ return {
12269
+ enabled: overrides.enabled ?? true,
12270
+ reportUnusedTypes: overrides.reportUnusedTypes ?? true,
12271
+ reportUnusedEnumMembers: overrides.reportUnusedEnumMembers ?? true,
12272
+ reportUnusedClassMembers: overrides.reportUnusedClassMembers ?? false,
12273
+ reportRedundantVariableAliases: overrides.reportRedundantVariableAliases ?? true,
12274
+ reportMisclassifiedDependencies: overrides.reportMisclassifiedDependencies ?? true,
12275
+ reportRoundTripAliases: overrides.reportRoundTripAliases ?? true,
12276
+ decoratorAllowlist: overrides.decoratorAllowlist ?? DEFAULT_SEMANTIC_DECORATOR_ALLOWLIST
12277
+ };
12278
+ };
12279
+ const fillDuplicateBlocksConfig = (duplicateBlocksOverrides) => {
12280
+ const overrides = duplicateBlocksOverrides ?? {};
12281
+ return {
12282
+ enabled: overrides.enabled ?? true,
12283
+ mode: overrides.mode ?? "semantic",
12284
+ minTokens: overrides.minTokens ?? 50,
12285
+ minLines: overrides.minLines ?? 5,
12286
+ minOccurrences: overrides.minOccurrences ?? 2,
12287
+ skipLocal: overrides.skipLocal ?? false
12288
+ };
12289
+ };
12290
+ const fillFeatureFlagsConfig = (flagsOverrides) => {
12291
+ const overrides = flagsOverrides ?? {};
12292
+ return {
12293
+ enabled: overrides.enabled ?? true,
12294
+ extraEnvPrefixes: overrides.extraEnvPrefixes ?? [],
12295
+ extraSdkFunctionNames: overrides.extraSdkFunctionNames ?? [],
12296
+ detectConfigObjects: overrides.detectConfigObjects ?? false
12297
+ };
12298
+ };
12299
+ const fillComplexityConfig = (complexityOverrides) => {
12300
+ const overrides = complexityOverrides ?? {};
9583
12301
  return {
9584
- enabled: semanticOverrides.enabled ?? false,
9585
- reportUnusedTypes: semanticOverrides.reportUnusedTypes ?? true,
9586
- reportUnusedEnumMembers: semanticOverrides.reportUnusedEnumMembers ?? true,
9587
- reportUnusedClassMembers: semanticOverrides.reportUnusedClassMembers ?? false,
9588
- reportRedundantVariableAliases: semanticOverrides.reportRedundantVariableAliases ?? true,
9589
- reportMisclassifiedDependencies: semanticOverrides.reportMisclassifiedDependencies ?? true,
9590
- reportRoundTripAliases: semanticOverrides.reportRoundTripAliases ?? true,
9591
- decoratorAllowlist: semanticOverrides.decoratorAllowlist ?? DEFAULT_SEMANTIC_DECORATOR_ALLOWLIST
12302
+ enabled: overrides.enabled ?? true,
12303
+ cyclomaticThreshold: overrides.cyclomaticThreshold ?? 10,
12304
+ cognitiveThreshold: overrides.cognitiveThreshold ?? 15,
12305
+ paramCountThreshold: overrides.paramCountThreshold ?? 5,
12306
+ functionLineThreshold: overrides.functionLineThreshold ?? 80
9592
12307
  };
9593
12308
  };
9594
12309
  const defineConfig = (options) => ({
@@ -9600,7 +12315,10 @@ const defineConfig = (options) => ({
9600
12315
  reportTypes: options.reportTypes ?? false,
9601
12316
  includeEntryExports: options.includeEntryExports ?? false,
9602
12317
  reportRedundancy: options.reportRedundancy ?? true,
9603
- semantic: fillSemanticConfig(options.semantic)
12318
+ semantic: fillSemanticConfig(options.semantic),
12319
+ duplicateBlocks: fillDuplicateBlocksConfig(options.duplicateBlocks),
12320
+ featureFlags: fillFeatureFlagsConfig(options.featureFlags),
12321
+ complexity: fillComplexityConfig(options.complexity)
9604
12322
  });
9605
12323
  const buildEmptyScanResult = (errors, elapsedMs) => ({
9606
12324
  unusedFiles: [],
@@ -9621,6 +12339,18 @@ const buildEmptyScanResult = (errors, elapsedMs) => ({
9621
12339
  simplifiableFunctions: [],
9622
12340
  simplifiableExpressions: [],
9623
12341
  duplicateConstants: [],
12342
+ crossFileDuplicateExports: [],
12343
+ duplicateBlocks: [],
12344
+ duplicateBlockClusters: [],
12345
+ shadowedDirectoryPairs: [],
12346
+ reExportCycles: [],
12347
+ featureFlags: [],
12348
+ complexFunctions: [],
12349
+ privateTypeLeaks: [],
12350
+ unnecessaryAssertions: [],
12351
+ lazyImportsAtTopLevel: [],
12352
+ commonjsInEsm: [],
12353
+ typeScriptEscapeHatches: [],
9624
12354
  analysisErrors: errors,
9625
12355
  totalFiles: 0,
9626
12356
  totalExports: 0,