UNPKG

next-affected

Version:

CLI tool to list Next.js pages affected by changes

177 lines (176 loc) 7.83 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getDependencyGraph = getDependencyGraph; exports.findAffectedPages = findAffectedPages; const fs = __importStar(require("fs")); const madge_1 = __importDefault(require("madge")); const path_1 = __importDefault(require("path")); const typescript_1 = __importDefault(require("typescript")); const utils_1 = require("./utils"); async function getDependencyGraph(projectDir, config) { const tsconfigPath = findTsConfig(projectDir); const tsconfigDir = path_1.default.dirname(tsconfigPath); const parsedConfig = readTsConfig(tsconfigPath); const aliases = getAliasesFromTsConfig(parsedConfig, tsconfigDir); const possibleEntryPoints = config.pagesDirectories.map((dir) => path_1.default.join(projectDir, dir)); const entryPoints = getExistingEntryPoints(possibleEntryPoints); if (entryPoints.length === 0) { throw new Error(`No valid entry points found in ${projectDir}`); } const res = await (0, madge_1.default)(entryPoints, { baseDir: projectDir, fileExtensions: ["js", "jsx", "ts", "tsx"], includeNpm: false, tsConfig: tsconfigPath, webpackConfig: fs.existsSync(path_1.default.join(projectDir, "next.config.js")) ? path_1.default.join(projectDir, "next.config.js") : undefined, alias: aliases, }); const dependencyGraph = res.obj(); // Exclude modules and their dependencies based on excludedPaths const filteredDependencyGraph = {}; for (const module in dependencyGraph) { const modulePath = (0, utils_1.normalizePath)(path_1.default.resolve(projectDir, module)); if ((0, utils_1.shouldExcludeModule)(modulePath, config, projectDir)) { continue; } const dependencies = dependencyGraph[module].filter((dep) => { const depPath = (0, utils_1.normalizePath)(path_1.default.resolve(projectDir, dep)); return !(0, utils_1.shouldExcludeModule)(depPath, config, projectDir); }); filteredDependencyGraph[module] = dependencies; } return filteredDependencyGraph; } function getExistingEntryPoints(entryPoints) { return entryPoints.filter((entryPoint) => fs.existsSync(entryPoint)); } function findTsConfig(projectDir) { const possibleConfigs = ["tsconfig.json", "tsconfig.base.json"]; let currentDir = projectDir; while (true) { for (const configName of possibleConfigs) { const tsconfigPath = path_1.default.join(currentDir, configName); if (fs.existsSync(tsconfigPath)) { return tsconfigPath; } } const parentDir = path_1.default.dirname(currentDir); if (parentDir === currentDir) { throw new Error("Could not find tsconfig.json or tsconfig.base.json"); } currentDir = parentDir; } } function readTsConfig(tsconfigPath) { const configFile = typescript_1.default.readConfigFile(tsconfigPath, typescript_1.default.sys.readFile); if (configFile.error) { throw new Error(typescript_1.default.flattenDiagnosticMessageText(configFile.error.messageText, "\n")); } const configParseResult = typescript_1.default.parseJsonConfigFileContent(configFile.config, typescript_1.default.sys, path_1.default.dirname(tsconfigPath)); if (configParseResult.errors.length > 0) { const errorMessage = configParseResult.errors .map((error) => typescript_1.default.flattenDiagnosticMessageText(error.messageText, "\n")) .join("\n"); throw new Error(errorMessage); } return configParseResult; } function getAliasesFromTsConfig(parsedConfig, tsconfigDir) { const aliases = {}; if (parsedConfig.options.paths) { const paths = parsedConfig.options.paths; for (const aliasPattern in paths) { const aliasPaths = paths[aliasPattern]; // Remove the trailing '/*' from the alias if present const aliasKey = aliasPattern.replace(/\/\*$/, ""); // Assume the first path mapping is the primary one const targetPath = aliasPaths[0]; // Remove the trailing '/*' and resolve the absolute path const targetDir = path_1.default.resolve(tsconfigDir, targetPath.replace(/\/\*$/, "")); aliases[aliasKey] = targetDir; } } return aliases; } function findAffectedPages(dependencyGraph, changedComponent, projectDir, config, maxDepth = Infinity, verbose = false, onProgress) { const visited = new Set(); const affectedPages = new Set(); let processedModules = 0; function traverse(module, depth) { if (visited.has(module) || depth > maxDepth) return; const modulePath = (0, utils_1.normalizePath)(path_1.default.resolve(projectDir, module)); if ((0, utils_1.shouldExcludeModule)(modulePath, config, projectDir)) { return; } visited.add(module); if ((0, utils_1.isPage)(modulePath, projectDir, config)) { const route = (0, utils_1.getRouteFromPage)(modulePath, projectDir, config); affectedPages.add(route); } const dependents = Object.keys(dependencyGraph).filter((key) => { const deps = dependencyGraph[key]; if (!deps) return false; const normalizedDeps = deps.map((dep) => (0, utils_1.normalizePath)(path_1.default.resolve(projectDir, dep))); return normalizedDeps.includes(modulePath); }); dependents.forEach((dependent) => { const dependentPath = (0, utils_1.normalizePath)(path_1.default.resolve(projectDir, dependent)); if ((0, utils_1.shouldExcludeModule)(dependentPath, config, projectDir)) { return; } traverse(dependent, depth + 1); }); processedModules++; if (onProgress) { onProgress(1); } if (verbose && processedModules % 100 === 0) { console.log(`Processed ${processedModules} modules...`); } } traverse(changedComponent, 0); if (verbose) { console.log(`Total modules processed: ${processedModules}`); } return Array.from(affectedPages); }