@bemoje/monorepo 1.2.3 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,70 +8,115 @@ Monorepo workspace management, package discovery, and TypeScript code processing
8
8
 
9
9
  <!-- EXPORTS_START -->
10
10
 
11
- - **AbstractBase**: Abstract base class that provides common functionality for monorepo management including parenting and inspection capabilities.
12
- - **AbstractCode**: Abstract base class for representing code structures in the monorepo with inspection and preview capabilities.
13
- - **CodeBlock**: Represents a block of code within a larger code structure, defined by an index range.
14
- - **File**: Represents a file in a workspace with various utility methods to check file types and read contents.
15
- - **ImportKeywords**: Represents the imported keywords/specifiers in an import statement.
16
- - **ImportSpecifiers**: Represents and analyzes import specifiers in TypeScript/JavaScript code. This class parses and categorizes different types of import statements such as default imports, named imports, namespace imports, mixed imports, and side effect imports. It provides methods to retrieve specific parts of import statements and to manipulate them.
17
- - **ImportStatement**: Represents an import statement in TypeScript code with parsing and manipulation capabilities.
18
- - **ModuleSpecifier**: Represents a module specifier in an import statement. Module specifiers are the strings that indicate where to import from, such as './path/to/file', '
19
- - **MonoRepo**: Represents a monorepo with workspace management, TypeScript configuration, and dependency analysis capabilities.
20
11
  - **SemanticExtnamePrefix**: Constants for semantic filename prefixes used to categorize files by their purpose.
21
12
  - **SemanticExtnamePrefixDescriptions**
22
- - **TestFile**: Represents a test file in the monorepo with TypeScript code analysis capabilities.
23
- - **TsCode**: Represents TypeScript code with import parsing and manipulation capabilities.
24
- - **TsFile**: Represents a TypeScript file in the monorepo with code analysis and dependency tracking capabilities.
25
- - **Workspace**: Represents a workspace within a monorepo, providing functionality to analyze and manage workspace dependencies. A workspace is a directory containing a package.json file and typically source code files. This class provides methods and properties for analyzing: - Source and test files in the workspace - Dependencies declared in package.json - Dependencies imported in source and test files - Missing, unused, and incorrectly imported dependencies
13
+ - **createDependencyGraph** are left out, and so are test files unless `includeTests` is set. Packages in node_modules are not followed. Analyzing a whole repo takes around a second, so create the graph once and pass it to the functions that read from it.
14
+ - **findWorkspace**: Finds a workspace by its package name, its directory name or its path relative to the repo root.
26
15
  - **findWorkspacePackageName**: Finds the full package name for a workspace given a partial name.
27
- - **getAllImports**: Retrieves all import statements from TypeScript source files across all workspaces in the monorepo.
16
+ - **getAllImports**: Parses the import statements of every source file in the given workspaces.
28
17
  - **getAllWorkspacePackageJsonPaths**: Gets all workspace package.json file paths.
29
18
  - **getAllWorkspacePackageJsons**: Gets all workspace package.json contents.
30
19
  - **getAllWorkspacePackageNames**: Gets all workspace package names.
31
20
  - **getAllWorkspacePaths**: Returns an array of all workspace directory paths.
32
- - **getImportsRecursively**: Recursively retrieves all imports for the given entry points, categorizing them into external, builtin, and internal dependencies.
33
- - **getRepoPackageJson**: Reads the repository's root package.json file.
34
- - **getRepoPackageJsonPath**: Gets the absolute path to the repository's package.json file.
21
+ - **getDependencyName**: Returns the package name part of a module specifier.
22
+ - **getExternalDependencyVersions**: Maps every package the given modules import to a caret range of its installed version, ready to be put in the 'dependencies' of a package.json. Sorted by package name. If a package ships no types of its own and its `
23
+ - **getFileImports**: Reads a TypeScript file and parses its import statements.
24
+ - **getImportsRecursively**: Follows the imports of the given entry points through the repo and lists what is depended on along the way.
25
+ - **getReachableModules**: Returns the given modules and every module they import, directly or through other modules, in the order they are discovered. Each module is returned once.
35
26
  - **getRepoRootDirpath**: Get the root directory path of the monorepo by finding the package.json with workspaces configuration.
27
+ - **getRootPackageJson**: Reads the repository's root package.json file.
28
+ - **getRootPackageJsonPath**: Gets the absolute path to the repository's package.json file.
29
+ - **getTsconfigPaths**: Reads the 'compilerOptions.paths' of the tsconfig.paths.json file in the repo root. Returns an empty object if the file does not exist.
30
+ - **getWorkspaceDependencies**: Lists what the source files of a workspace depend on: node built-ins, packages and other workspaces. Test files are not counted.
31
+ - **getWorkspaceDependencyProblems**: Compares what the files of a workspace import with what its package.json lists, and returns what does not add up. Returns undefined if there are no problems. A dependency is not reported as missing if the root package.json lists it, or if it is one of the 'paths' in the tsconfig.paths.json of the repo root.
36
32
  - **getWorkspaceDirpaths**: Get all workspace directory paths by reading the workspace patterns from the root package.json.
33
+ - **getWorkspaceFiles**: Lists the absolute paths of all TypeScript files in the 'src' directory of a workspace, sorted. This includes test files and other files with a semantic extname prefix. Filter with `isSourceFile` or `isTestFile`, or use `getWorkspaceSourceFiles` or `getWorkspaceTestFiles`.
34
+ - **getWorkspaceModules**: Returns the modules of the dependency graph that belong to the given workspace.
35
+ - **getWorkspaceSelfImports**: Finds the imports in a workspace's files that import the workspace itself by its package name. Such imports should be relative instead. The suggested replacement points at the source file named after the first imported name, if there is one. Otherwise it points at the workspace's src/index file.
36
+ - **getWorkspaceSourceFiles**: Lists the absolute paths of the source files of a workspace: the TypeScript files in its 'src' directory that have no semantic extname prefix. So no test files, example files, declaration files etc.
37
+ - **getWorkspaceTestFiles** in the 'src' directory of a workspace.
38
+ - **getWorkspaces**: Reads every workspace matched by the 'workspaces' patterns of the root package.json. The repo root itself is not included.
37
39
  - **hasExtnamePrefix**.
40
+ - **isSourceFile**: Whether the file is a source file: located in a 'src' directory and without a semantic extname prefix. So not a test file, example file, declaration file etc.
41
+ - **isTestFile**: Whether the file is a test file, e.g. 'foo.test.ts'.
42
+ - **readWorkspace**: Reads the package.json of a workspace directory and returns the workspace as plain data.
38
43
  - **resolveModuleImportPath**
39
44
  - **semverVersionBump** of a given version string or array based on the specified level. The function supports 'major', 'minor', and 'patch' levels.
45
+ - **summarizeDependencies**: Lists the names of everything the given modules import directly, grouped by kind.
40
46
 
41
47
  <!-- EXPORTS_END -->
42
48
 
43
49
  ## Usage
44
50
 
45
- ### Managing the Repository & Workspaces
51
+ Everything is a plain function that takes and returns plain data. Nothing has to be instantiated first, and each function reads only what it needs.
46
52
 
47
- The `MonoRepo` class allows structured, automated tasks against packages and workspaces in a typical monorepo environment (e.g. yarn, npm, pnpm workspaces).
53
+ ### Workspaces and their files
48
54
 
49
55
  ```ts
50
- import { MonoRepo } from '@mono/monorepo'
56
+ import { findWorkspace, getWorkspaceSourceFiles, getWorkspaces } from '@mono/monorepo'
57
+
58
+ // Every workspace matched by the 'workspaces' patterns of the root package.json
59
+ const workspaces = getWorkspaces()
60
+ console.log(workspaces.map((ws) => ws.name))
61
+
62
+ // A single workspace, by package name, directory name or path
63
+ const ws = findWorkspace('string', workspaces)
64
+ if (ws) {
65
+ console.log(ws.name) // '@mono/string'
66
+ console.log(ws.relativePath) // 'libs/string'
67
+ console.log(ws.packageJson.dependencies)
68
+ console.log(getWorkspaceSourceFiles(ws)) // absolute paths, without tests and examples
69
+ }
70
+ ```
71
+
72
+ ### Import statements
51
73
 
52
- const repo = new MonoRepo()
74
+ Import statements are parsed with `@mono/tscode`.
53
75
 
54
- // Access all registered packages/workspaces
55
- const workspaces = repo.workspaces
56
- console.log(`Found ${workspaces.length} workspaces`)
76
+ ```ts
77
+ import { getAllImports, getFileImports } from '@mono/monorepo'
57
78
 
58
- // Get specific workspaces by name or type
59
- const packageJson = repo.getWorkspace('my-package')?.packageJson
79
+ for (const { statement } of getFileImports('libs/string/src/lib/strRepeat.ts')) {
80
+ console.log(statement.modulePath.path, statement.getNames())
81
+ }
60
82
 
61
- // Bump version for all packages (semver)
62
- repo.bumpVersions('patch')
83
+ // The import statements of every source file in the repo
84
+ const imports = getAllImports()
63
85
  ```
64
86
 
65
- ### Script & File Operations
87
+ ### Dependencies
88
+
89
+ Which files import what is analyzed by [dependency-cruiser](https://github.com/sverweij/dependency-cruiser). `createDependencyGraph` runs it with the repo's tsconfig paths and returns the result as plain data. Analyzing a whole repo takes around a second, so create the graph once and pass it to the functions that read from it.
66
90
 
67
91
  ```ts
68
- import { TsFile, findWorkspacePackageName } from '@mono/monorepo'
92
+ import {
93
+ createDependencyGraph,
94
+ getImportsRecursively,
95
+ getWorkspaceDependencies,
96
+ getWorkspaceDependencyProblems,
97
+ } from '@mono/monorepo'
98
+
99
+ const graph = await createDependencyGraph({ includeTests: true })
69
100
 
70
- const tsFile = new TsFile('path/to/my-file.ts')
101
+ for (const ws of graph.workspaces) {
102
+ // { builtin: ['fs'], external: ['upath'], internal: ['@mono/path'] }
103
+ console.log(ws.name, getWorkspaceDependencies(ws, graph))
71
104
 
72
- // Read structural code representations (imports, blocks, components)
73
- const imports = tsFile.imports
105
+ // The same, but following the imports into other workspaces
106
+ console.log(getWorkspaceDependencies(ws, graph, { recursive: true }))
74
107
 
75
- // Use utility functions independently of classes
76
- const packageName = findWorkspacePackageName('libs/my-feature')
108
+ // { unused: [...], missing: [...], missingDev: [...] } or undefined
109
+ console.log(getWorkspaceDependencyProblems(ws, graph))
110
+ }
111
+
112
+ // Everything that is reached from an entry point, and what it depends on
113
+ const { filepaths, local, recursive } = await getImportsRecursively(['libs/string/src/index.ts'], { graph })
114
+ console.log(local.external) // { 'es-toolkit': '^1.45.1' }
115
+ ```
116
+
117
+ The graph itself is a `Map` of modules by their path relative to the repo root. Each module lists its dependencies with a `kind`: `local`, `workspace`, `external`, `builtin` or `unresolved`.
118
+
119
+ ```ts
120
+ const module = graph.modules.get('libs/string/src/lib/strRepeat.ts')
121
+ console.log(module?.dependencies.filter((dep) => dep.kind === 'external').map((dep) => dep.name))
77
122
  ```