0
# Core Analysis
1
2
Core programmatic interface for analyzing projects and detecting unused code, dependencies, and files. The analysis engine processes workspaces and builds dependency graphs to identify issues.
3
4
## Capabilities
5
6
### Main Analysis Function
7
8
The primary entry point for programmatic analysis of projects.
9
10
```typescript { .api }
11
/**
12
* Main analysis function that processes workspace and returns issues
13
* @param options - Configuration options for analysis
14
* @returns Promise resolving to analysis results
15
*/
16
function main(options: MainOptions): Promise<MainResult>;
17
18
interface MainOptions {
19
/** Current working directory for analysis */
20
cwd: string;
21
/** Cache location for analysis results */
22
cacheLocation: string;
23
/** Configuration CLI argument */
24
config?: string;
25
/** Configuration file path */
26
configFilePath?: string;
27
/** Dependencies flag from CLI */
28
dependencies: boolean;
29
/** Exports flag from CLI */
30
exports: boolean;
31
/** Files flag from CLI */
32
files: boolean;
33
/** Experimental tags for filtering analysis */
34
experimentalTags: string[];
35
/** Types to include in fixes */
36
fixTypes: string[];
37
/** Whether to respect .gitignore files */
38
gitignore: boolean;
39
/** Specific issue types to include in analysis */
40
includedIssueTypes: Partial<Report>;
41
/** Enable caching */
42
isCache: boolean;
43
/** Debug mode */
44
isDebug: boolean;
45
/** Disable configuration hints */
46
isDisableConfigHints: boolean;
47
/** Fix issues automatically */
48
isFix: boolean;
49
/** Fix dependencies */
50
isFixDependencies: boolean;
51
/** Fix unused files */
52
isFixFiles: boolean;
53
/** Fix unused exports */
54
isFixUnusedExports: boolean;
55
/** Fix unused types */
56
isFixUnusedTypes: boolean;
57
/** Format files after fixing */
58
isFormat: boolean;
59
/** Include entry exports in unused exports report */
60
isIncludeEntryExports: boolean;
61
/** Isolate workspaces into separate programs */
62
isIsolateWorkspaces: boolean;
63
/** Analyze only production source files (no test files, devDependencies) */
64
isProduction: boolean;
65
/** Report class members */
66
isReportClassMembers: boolean;
67
/** Report dependencies issues */
68
isReportDependencies: boolean;
69
/** Report type issues */
70
isReportTypes: boolean;
71
/** Report value issues */
72
isReportValues: boolean;
73
/** Show dynamic progress updates */
74
isShowProgress: boolean;
75
/** Skip library files */
76
isSkipLibs: boolean;
77
/** Consider only direct dependencies of workspace */
78
isStrict: boolean;
79
/** Trace mode for debugging */
80
isTrace: boolean;
81
/** Treat configuration hints as errors */
82
isTreatConfigHintsAsErrors: boolean;
83
/** Watch mode for continuous analysis */
84
isWatch: boolean;
85
/** Parsed configuration object */
86
parsedConfig: KnipConfig;
87
/** Issue severity rules */
88
rules: Record<string, 'error' | 'warn' | 'off'>;
89
/** Tags for filtering exports */
90
tags: string[];
91
/** Export to trace */
92
traceExport?: string;
93
/** File to trace */
94
traceFile?: string;
95
/** TypeScript configuration file path */
96
tsConfigFile?: string;
97
/** Single workspace to analyze */
98
workspace?: string;
99
/** Available workspaces */
100
workspaces: string[];
101
}
102
103
interface MainResult {
104
/** Collected issues organized by type */
105
issues: Issues;
106
/** Counters for each issue type */
107
counters: Counters;
108
/** Hints about tagged exports */
109
tagHints: Set<TagHint>;
110
/** Configuration improvement suggestions */
111
configurationHints: Set<ConfigurationHint>;
112
/** List of included workspace directories */
113
includedWorkspaceDirs: string[];
114
}
115
```
116
117
**Usage Examples:**
118
119
```typescript
120
import { main } from "knip";
121
122
// Basic project analysis
123
const results = await main({
124
cwd: process.cwd(),
125
isShowProgress: true,
126
});
127
128
// Production-only analysis
129
const prodResults = await main({
130
cwd: process.cwd(),
131
isProduction: true,
132
isStrict: true,
133
});
134
135
// Custom configuration
136
const customResults = await main({
137
cwd: "/path/to/project",
138
configFilePath: "./knip.config.js",
139
includedIssueTypes: {
140
dependencies: true,
141
exports: true,
142
files: false,
143
},
144
});
145
146
// Process results
147
console.log(`Total issues: ${results.counters.total}`);
148
console.log(`Unused dependencies: ${results.counters.dependencies}`);
149
console.log(`Unused exports: ${results.counters.exports}`);
150
151
// Access specific issues
152
for (const [filePath, fileIssues] of Object.entries(results.issues.exports)) {
153
for (const [symbol, issue] of Object.entries(fileIssues)) {
154
console.log(`Unused export "${symbol}" in ${filePath}`);
155
}
156
}
157
```
158
159
### Analysis Results
160
161
The analysis results provide comprehensive information about detected issues.
162
163
```typescript { .api }
164
interface Issues {
165
/** Unused files */
166
files: Set<string>;
167
/** Internal representation of unused files */
168
_files: Record<string, Record<string, Issue>>;
169
/** Unused dependencies */
170
dependencies: Record<string, Record<string, Issue>>;
171
/** Unused devDependencies */
172
devDependencies: Record<string, Record<string, Issue>>;
173
/** Referenced optional peerDependencies */
174
optionalPeerDependencies: Record<string, Record<string, Issue>>;
175
/** Unlisted dependencies */
176
unlisted: Record<string, Record<string, Issue>>;
177
/** Unlisted binaries */
178
binaries: Record<string, Record<string, Issue>>;
179
/** Unresolved imports */
180
unresolved: Record<string, Record<string, Issue>>;
181
/** Unused exports */
182
exports: Record<string, Record<string, Issue>>;
183
/** Unused exported types */
184
types: Record<string, Record<string, Issue>>;
185
/** Exports in used namespace */
186
nsExports: Record<string, Record<string, Issue>>;
187
/** Exported types in used namespace */
188
nsTypes: Record<string, Record<string, Issue>>;
189
/** Duplicate exports */
190
duplicates: Record<string, Record<string, Issue>>;
191
/** Unused exported enum members */
192
enumMembers: Record<string, Record<string, Issue>>;
193
/** Unused exported class members */
194
classMembers: Record<string, Record<string, Issue>>;
195
}
196
197
interface Issue {
198
/** Type of issue */
199
type: IssueType;
200
/** File path where issue occurs */
201
filePath: string;
202
/** Workspace containing the issue */
203
workspace: string;
204
/** Symbol name with the issue */
205
symbol: string;
206
/** Additional symbols involved */
207
symbols?: IssueSymbol[];
208
/** Type of symbol (variable, function, class, etc.) */
209
symbolType?: SymbolType;
210
/** Parent symbol if applicable */
211
parentSymbol?: string;
212
/** Import specifier if applicable */
213
specifier?: string;
214
/** Issue severity level */
215
severity?: IssueSeverity;
216
/** Position in file */
217
pos?: number;
218
/** Line number */
219
line?: number;
220
/** Column number */
221
col?: number;
222
/** Whether issue was automatically fixed */
223
isFixed?: boolean;
224
}
225
226
interface Counters {
227
files: number;
228
dependencies: number;
229
devDependencies: number;
230
optionalPeerDependencies: number;
231
unlisted: number;
232
binaries: number;
233
unresolved: number;
234
exports: number;
235
types: number;
236
nsExports: number;
237
nsTypes: number;
238
duplicates: number;
239
enumMembers: number;
240
classMembers: number;
241
processed: number;
242
total: number;
243
}
244
245
type IssueType = 'files' | 'dependencies' | 'devDependencies' | 'optionalPeerDependencies'
246
| 'unlisted' | 'binaries' | 'unresolved' | 'exports' | 'types' | 'nsExports'
247
| 'nsTypes' | 'duplicates' | 'enumMembers' | 'classMembers';
248
249
type IssueSeverity = 'error' | 'warn' | 'off';
250
```
251
252
### Analysis Options
253
254
Configuration options for customizing the analysis behavior.
255
256
```typescript { .api }
257
interface Report {
258
files: boolean;
259
dependencies: boolean;
260
devDependencies: boolean;
261
optionalPeerDependencies: boolean;
262
unlisted: boolean;
263
binaries: boolean;
264
unresolved: boolean;
265
exports: boolean;
266
types: boolean;
267
nsExports: boolean;
268
nsTypes: boolean;
269
duplicates: boolean;
270
enumMembers: boolean;
271
classMembers: boolean;
272
}
273
274
interface TagHint {
275
type: 'tag';
276
filePath: string;
277
identifier: string;
278
tagName: string;
279
}
280
281
interface ConfigurationHint {
282
type: ConfigurationHintType;
283
identifier: string | RegExp;
284
filePath?: string;
285
workspaceName?: string;
286
size?: number;
287
}
288
289
type ConfigurationHintType = 'ignoreBinaries' | 'ignoreDependencies' | 'ignoreUnresolved'
290
| 'ignoreWorkspaces' | 'entry-redundant' | 'project-redundant' | 'entry-top-level'
291
| 'project-top-level' | 'entry-empty' | 'project-empty' | 'package-entry'
292
| 'workspace-unconfigured';
293
```
294
295
### Error Handling
296
297
The main function handles various error conditions and provides detailed error information.
298
299
**Common Error Scenarios:**
300
301
- **Configuration Error**: Invalid or missing configuration files
302
- **File System Error**: Inaccessible files or directories
303
- **TypeScript Error**: Invalid TypeScript configuration
304
- **Plugin Error**: Plugin-specific configuration or execution errors
305
306
```typescript
307
try {
308
const results = await main(options);
309
// Process successful results
310
} catch (error) {
311
if (error.code === 'CONFIGURATION_ERROR') {
312
console.error('Configuration error:', error.message);
313
} else if (error.code === 'FILE_SYSTEM_ERROR') {
314
console.error('File system error:', error.message);
315
} else {
316
console.error('Analysis error:', error.message);
317
}
318
}
319
```