-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
no-unused-modules.js
1088 lines (962 loc) · 33.8 KB
/
no-unused-modules.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @fileOverview Ensures that modules contain exports and/or all
* modules are consumed within other modules.
* @author René Fermann
*/
import { getPhysicalFilename } from 'eslint-module-utils/contextCompat';
import { getFileExtensions } from 'eslint-module-utils/ignore';
import resolve from 'eslint-module-utils/resolve';
import visit from 'eslint-module-utils/visit';
import { dirname, join, resolve as resolvePath } from 'path';
import readPkgUp from 'eslint-module-utils/readPkgUp';
import values from 'object.values';
import includes from 'array-includes';
import flatMap from 'array.prototype.flatmap';
import { walkSync } from '../core/fsWalk';
import ExportMapBuilder from '../exportMap/builder';
import recursivePatternCapture from '../exportMap/patternCapture';
import docsUrl from '../docsUrl';
/**
* Attempt to load the internal `FileEnumerator` class, which has existed in a couple
* of different places, depending on the version of `eslint`. Try requiring it from both
* locations.
* @returns Returns the `FileEnumerator` class if its requirable, otherwise `undefined`.
*/
function requireFileEnumerator() {
let FileEnumerator;
// Try getting it from the eslint private / deprecated api
try {
({ FileEnumerator } = require('eslint/use-at-your-own-risk'));
} catch (e) {
// Absorb this if it's MODULE_NOT_FOUND
if (e.code !== 'MODULE_NOT_FOUND') {
throw e;
}
// If not there, then try getting it from eslint/lib/cli-engine/file-enumerator (moved there in v6)
try {
({ FileEnumerator } = require('eslint/lib/cli-engine/file-enumerator'));
} catch (e) {
// Absorb this if it's MODULE_NOT_FOUND
if (e.code !== 'MODULE_NOT_FOUND') {
throw e;
}
}
}
return FileEnumerator;
}
/**
*
* @param FileEnumerator the `FileEnumerator` class from `eslint`'s internal api
* @param {string} src path to the src root
* @param {string[]} extensions list of supported extensions
* @returns {{ filename: string, ignored: boolean }[]} list of files to operate on
*/
function listFilesUsingFileEnumerator(FileEnumerator, src, extensions) {
const e = new FileEnumerator({
extensions,
});
return Array.from(
e.iterateFiles(src),
({ filePath, ignored }) => ({ filename: filePath, ignored }),
);
}
/**
* Attempt to require old versions of the file enumeration capability from v6 `eslint` and earlier, and use
* those functions to provide the list of files to operate on
* @param {string} src path to the src root
* @param {string[]} extensions list of supported extensions
* @returns {string[]} list of files to operate on
*/
function listFilesWithLegacyFunctions(src, extensions) {
try {
// eslint/lib/util/glob-util has been moved to eslint/lib/util/glob-utils with version 5.3
const { listFilesToProcess: originalListFilesToProcess } = require('eslint/lib/util/glob-utils');
// Prevent passing invalid options (extensions array) to old versions of the function.
// https://github.com/eslint/eslint/blob/v5.16.0/lib/util/glob-utils.js#L178-L280
// https://github.com/eslint/eslint/blob/v5.2.0/lib/util/glob-util.js#L174-L269
return originalListFilesToProcess(src, {
extensions,
});
} catch (e) {
// Absorb this if it's MODULE_NOT_FOUND
if (e.code !== 'MODULE_NOT_FOUND') {
throw e;
}
// Last place to try (pre v5.3)
const {
listFilesToProcess: originalListFilesToProcess,
} = require('eslint/lib/util/glob-util');
const patterns = src.concat(
flatMap(
src,
(pattern) => extensions.map((extension) => (/\*\*|\*\./).test(pattern) ? pattern : `${pattern}/**/*${extension}`),
),
);
return originalListFilesToProcess(patterns);
}
}
/**
* Given a source root and list of supported extensions, use fsWalk and the
* new `eslint` `context.session` api to build the list of files we want to operate on
* @param {string[]} srcPaths array of source paths (for flat config this should just be a singular root (e.g. cwd))
* @param {string[]} extensions list of supported extensions
* @param {{ isDirectoryIgnored: (path: string) => boolean, isFileIgnored: (path: string) => boolean }} session eslint context session object
* @returns {string[]} list of files to operate on
*/
function listFilesWithModernApi(srcPaths, extensions, session) {
/** @type {string[]} */
const files = [];
for (let i = 0; i < srcPaths.length; i++) {
const src = srcPaths[i];
// Use walkSync along with the new session api to gather the list of files
const entries = walkSync(src, {
deepFilter(entry) {
const fullEntryPath = resolvePath(src, entry.path);
// Include the directory if it's not marked as ignore by eslint
return !session.isDirectoryIgnored(fullEntryPath);
},
entryFilter(entry) {
const fullEntryPath = resolvePath(src, entry.path);
// Include the file if it's not marked as ignore by eslint and its extension is included in our list
return (
!session.isFileIgnored(fullEntryPath)
&& extensions.find((extension) => entry.path.endsWith(extension))
);
},
});
// Filter out directories and map entries to their paths
files.push(
...entries
.filter((entry) => !entry.dirent.isDirectory())
.map((entry) => entry.path),
);
}
return files;
}
/**
* Given a src pattern and list of supported extensions, return a list of files to process
* with this rule.
* @param {string} src - file, directory, or glob pattern of files to act on
* @param {string[]} extensions - list of supported file extensions
* @param {import('eslint').Rule.RuleContext} context - the eslint context object
* @returns {string[] | { filename: string, ignored: boolean }[]} the list of files that this rule will evaluate.
*/
function listFilesToProcess(src, extensions, context) {
// If the context object has the new session functions, then prefer those
// Otherwise, fallback to using the deprecated `FileEnumerator` for legacy support.
// https://github.com/eslint/eslint/issues/18087
if (
context.session
&& context.session.isFileIgnored
&& context.session.isDirectoryIgnored
) {
return listFilesWithModernApi(src, extensions, context.session);
}
// Fallback to og FileEnumerator
const FileEnumerator = requireFileEnumerator();
// If we got the FileEnumerator, then let's go with that
if (FileEnumerator) {
return listFilesUsingFileEnumerator(FileEnumerator, src, extensions);
}
// If not, then we can try even older versions of this capability (listFilesToProcess)
return listFilesWithLegacyFunctions(src, extensions);
}
const EXPORT_DEFAULT_DECLARATION = 'ExportDefaultDeclaration';
const EXPORT_NAMED_DECLARATION = 'ExportNamedDeclaration';
const EXPORT_ALL_DECLARATION = 'ExportAllDeclaration';
const IMPORT_DECLARATION = 'ImportDeclaration';
const IMPORT_NAMESPACE_SPECIFIER = 'ImportNamespaceSpecifier';
const IMPORT_DEFAULT_SPECIFIER = 'ImportDefaultSpecifier';
const VARIABLE_DECLARATION = 'VariableDeclaration';
const FUNCTION_DECLARATION = 'FunctionDeclaration';
const CLASS_DECLARATION = 'ClassDeclaration';
const IDENTIFIER = 'Identifier';
const OBJECT_PATTERN = 'ObjectPattern';
const ARRAY_PATTERN = 'ArrayPattern';
const TS_INTERFACE_DECLARATION = 'TSInterfaceDeclaration';
const TS_TYPE_ALIAS_DECLARATION = 'TSTypeAliasDeclaration';
const TS_ENUM_DECLARATION = 'TSEnumDeclaration';
const DEFAULT = 'default';
function forEachDeclarationIdentifier(declaration, cb) {
if (declaration) {
const isTypeDeclaration = declaration.type === TS_INTERFACE_DECLARATION
|| declaration.type === TS_TYPE_ALIAS_DECLARATION
|| declaration.type === TS_ENUM_DECLARATION;
if (
declaration.type === FUNCTION_DECLARATION
|| declaration.type === CLASS_DECLARATION
|| isTypeDeclaration
) {
cb(declaration.id.name, isTypeDeclaration);
} else if (declaration.type === VARIABLE_DECLARATION) {
declaration.declarations.forEach(({ id }) => {
if (id.type === OBJECT_PATTERN) {
recursivePatternCapture(id, (pattern) => {
if (pattern.type === IDENTIFIER) {
cb(pattern.name, false);
}
});
} else if (id.type === ARRAY_PATTERN) {
id.elements.forEach(({ name }) => {
cb(name, false);
});
} else {
cb(id.name, false);
}
});
}
}
}
/**
* List of imports per file.
*
* Represented by a two-level Map to a Set of identifiers. The upper-level Map
* keys are the paths to the modules containing the imports, while the
* lower-level Map keys are the paths to the files which are being imported
* from. Lastly, the Set of identifiers contains either names being imported
* or a special AST node name listed above (e.g ImportDefaultSpecifier).
*
* For example, if we have a file named foo.js containing:
*
* import { o2 } from './bar.js';
*
* Then we will have a structure that looks like:
*
* Map { 'foo.js' => Map { 'bar.js' => Set { 'o2' } } }
*
* @type {Map<string, Map<string, Set<string>>>}
*/
const importList = new Map();
/**
* List of exports per file.
*
* Represented by a two-level Map to an object of metadata. The upper-level Map
* keys are the paths to the modules containing the exports, while the
* lower-level Map keys are the specific identifiers or special AST node names
* being exported. The leaf-level metadata object at the moment only contains a
* `whereUsed` property, which contains a Set of paths to modules that import
* the name.
*
* For example, if we have a file named bar.js containing the following exports:
*
* const o2 = 'bar';
* export { o2 };
*
* And a file named foo.js containing the following import:
*
* import { o2 } from './bar.js';
*
* Then we will have a structure that looks like:
*
* Map { 'bar.js' => Map { 'o2' => { whereUsed: Set { 'foo.js' } } } }
*
* @type {Map<string, Map<string, object>>}
*/
const exportList = new Map();
const visitorKeyMap = new Map();
/** @type {Set<string>} */
const ignoredFiles = new Set();
const filesOutsideSrc = new Set();
const isNodeModule = (path) => (/\/(node_modules)\//).test(path);
/**
* read all files matching the patterns in src and ignoreExports
*
* return all files matching src pattern, which are not matching the ignoreExports pattern
* @type {(src: string, ignoreExports: string, context: import('eslint').Rule.RuleContext) => Set<string>}
*/
function resolveFiles(src, ignoreExports, context) {
const extensions = Array.from(getFileExtensions(context.settings));
const srcFileList = listFilesToProcess(src, extensions, context);
// prepare list of ignored files
const ignoredFilesList = listFilesToProcess(ignoreExports, extensions, context);
// The modern api will return a list of file paths, rather than an object
if (ignoredFilesList.length && typeof ignoredFilesList[0] === 'string') {
ignoredFilesList.forEach((filename) => ignoredFiles.add(filename));
} else {
ignoredFilesList.forEach(({ filename }) => ignoredFiles.add(filename));
}
// prepare list of source files, don't consider files from node_modules
const resolvedFiles = srcFileList.length && typeof srcFileList[0] === 'string'
? srcFileList.filter((filePath) => !isNodeModule(filePath))
: flatMap(srcFileList, ({ filename }) => isNodeModule(filename) ? [] : filename);
return new Set(resolvedFiles);
}
/**
* parse all source files and build up 2 maps containing the existing imports and exports
*/
const prepareImportsAndExports = (srcFiles, context) => {
const exportAll = new Map();
srcFiles.forEach((file) => {
const exports = new Map();
const imports = new Map();
const currentExports = ExportMapBuilder.get(file, context);
if (currentExports) {
const {
dependencies,
reexports,
imports: localImportList,
namespace,
visitorKeys,
} = currentExports;
visitorKeyMap.set(file, visitorKeys);
// dependencies === export * from
const currentExportAll = new Set();
dependencies.forEach((getDependency) => {
const dependency = getDependency();
if (dependency === null) {
return;
}
currentExportAll.add(dependency.path);
});
exportAll.set(file, currentExportAll);
reexports.forEach((value, key) => {
if (key === DEFAULT) {
exports.set(IMPORT_DEFAULT_SPECIFIER, { whereUsed: new Set() });
} else {
exports.set(key, { whereUsed: new Set() });
}
const reexport = value.getImport();
if (!reexport) {
return;
}
let localImport = imports.get(reexport.path);
let currentValue;
if (value.local === DEFAULT) {
currentValue = IMPORT_DEFAULT_SPECIFIER;
} else {
currentValue = value.local;
}
if (typeof localImport !== 'undefined') {
localImport = new Set([...localImport, currentValue]);
} else {
localImport = new Set([currentValue]);
}
imports.set(reexport.path, localImport);
});
localImportList.forEach((value, key) => {
if (isNodeModule(key)) {
return;
}
const localImport = imports.get(key) || new Set();
value.declarations.forEach(({ importedSpecifiers }) => {
importedSpecifiers.forEach((specifier) => {
localImport.add(specifier);
});
});
imports.set(key, localImport);
});
importList.set(file, imports);
// build up export list only, if file is not ignored
if (ignoredFiles.has(file)) {
return;
}
namespace.forEach((value, key) => {
if (key === DEFAULT) {
exports.set(IMPORT_DEFAULT_SPECIFIER, { whereUsed: new Set() });
} else {
exports.set(key, { whereUsed: new Set() });
}
});
}
exports.set(EXPORT_ALL_DECLARATION, { whereUsed: new Set() });
exports.set(IMPORT_NAMESPACE_SPECIFIER, { whereUsed: new Set() });
exportList.set(file, exports);
});
exportAll.forEach((value, key) => {
value.forEach((val) => {
const currentExports = exportList.get(val);
if (currentExports) {
const currentExport = currentExports.get(EXPORT_ALL_DECLARATION);
currentExport.whereUsed.add(key);
}
});
});
};
/**
* traverse through all imports and add the respective path to the whereUsed-list
* of the corresponding export
*/
const determineUsage = () => {
importList.forEach((listValue, listKey) => {
listValue.forEach((value, key) => {
const exports = exportList.get(key);
if (typeof exports !== 'undefined') {
value.forEach((currentImport) => {
let specifier;
if (currentImport === IMPORT_NAMESPACE_SPECIFIER) {
specifier = IMPORT_NAMESPACE_SPECIFIER;
} else if (currentImport === IMPORT_DEFAULT_SPECIFIER) {
specifier = IMPORT_DEFAULT_SPECIFIER;
} else {
specifier = currentImport;
}
if (typeof specifier !== 'undefined') {
const exportStatement = exports.get(specifier);
if (typeof exportStatement !== 'undefined') {
const { whereUsed } = exportStatement;
whereUsed.add(listKey);
exports.set(specifier, { whereUsed });
}
}
});
}
});
});
};
const getSrc = (src) => {
if (src) {
return src;
}
return [process.cwd()];
};
/**
* prepare the lists of existing imports and exports - should only be executed once at
* the start of a new eslint run
*/
/** @type {Set<string>} */
let srcFiles;
let lastPrepareKey;
const doPreparation = (src, ignoreExports, context) => {
const prepareKey = JSON.stringify({
src: (src || []).sort(),
ignoreExports: (ignoreExports || []).sort(),
extensions: Array.from(getFileExtensions(context.settings)).sort(),
});
if (prepareKey === lastPrepareKey) {
return;
}
importList.clear();
exportList.clear();
ignoredFiles.clear();
filesOutsideSrc.clear();
srcFiles = resolveFiles(getSrc(src), ignoreExports, context);
prepareImportsAndExports(srcFiles, context);
determineUsage();
lastPrepareKey = prepareKey;
};
const newNamespaceImportExists = (specifiers) => specifiers.some(({ type }) => type === IMPORT_NAMESPACE_SPECIFIER);
const newDefaultImportExists = (specifiers) => specifiers.some(({ type }) => type === IMPORT_DEFAULT_SPECIFIER);
const fileIsInPkg = (file) => {
const { path, pkg } = readPkgUp({ cwd: file });
const basePath = dirname(path);
const checkPkgFieldString = (pkgField) => {
if (join(basePath, pkgField) === file) {
return true;
}
};
const checkPkgFieldObject = (pkgField) => {
const pkgFieldFiles = flatMap(values(pkgField), (value) => typeof value === 'boolean' ? [] : join(basePath, value));
if (includes(pkgFieldFiles, file)) {
return true;
}
};
const checkPkgField = (pkgField) => {
if (typeof pkgField === 'string') {
return checkPkgFieldString(pkgField);
}
if (typeof pkgField === 'object') {
return checkPkgFieldObject(pkgField);
}
};
if (pkg.private === true) {
return false;
}
if (pkg.bin) {
if (checkPkgField(pkg.bin)) {
return true;
}
}
if (pkg.browser) {
if (checkPkgField(pkg.browser)) {
return true;
}
}
if (pkg.main) {
if (checkPkgFieldString(pkg.main)) {
return true;
}
}
return false;
};
module.exports = {
meta: {
type: 'suggestion',
docs: {
category: 'Helpful warnings',
description: 'Forbid modules without exports, or exports without matching import in another module.',
url: docsUrl('no-unused-modules'),
},
schema: [{
properties: {
src: {
description: 'files/paths to be analyzed (only for unused exports)',
type: 'array',
uniqueItems: true,
items: {
type: 'string',
minLength: 1,
},
},
ignoreExports: {
description: 'files/paths for which unused exports will not be reported (e.g module entry points)',
type: 'array',
uniqueItems: true,
items: {
type: 'string',
minLength: 1,
},
},
missingExports: {
description: 'report modules without any exports',
type: 'boolean',
},
unusedExports: {
description: 'report exports without any usage',
type: 'boolean',
},
ignoreUnusedTypeExports: {
description: 'ignore type exports without any usage',
type: 'boolean',
},
},
anyOf: [
{
properties: {
unusedExports: { enum: [true] },
src: {
minItems: 1,
},
},
required: ['unusedExports'],
},
{
properties: {
missingExports: { enum: [true] },
},
required: ['missingExports'],
},
],
}],
},
create(context) {
const {
src,
ignoreExports = [],
missingExports,
unusedExports,
ignoreUnusedTypeExports,
} = context.options[0] || {};
if (unusedExports) {
doPreparation(src, ignoreExports, context);
}
const file = getPhysicalFilename(context);
const checkExportPresence = (node) => {
if (!missingExports) {
return;
}
if (ignoredFiles.has(file)) {
return;
}
const exportCount = exportList.get(file);
const exportAll = exportCount.get(EXPORT_ALL_DECLARATION);
const namespaceImports = exportCount.get(IMPORT_NAMESPACE_SPECIFIER);
exportCount.delete(EXPORT_ALL_DECLARATION);
exportCount.delete(IMPORT_NAMESPACE_SPECIFIER);
if (exportCount.size < 1) {
// node.body[0] === 'undefined' only happens, if everything is commented out in the file
// being linted
context.report(node.body[0] ? node.body[0] : node, 'No exports found');
}
exportCount.set(EXPORT_ALL_DECLARATION, exportAll);
exportCount.set(IMPORT_NAMESPACE_SPECIFIER, namespaceImports);
};
const checkUsage = (node, exportedValue, isTypeExport) => {
if (!unusedExports) {
return;
}
if (isTypeExport && ignoreUnusedTypeExports) {
return;
}
if (ignoredFiles.has(file)) {
return;
}
if (fileIsInPkg(file)) {
return;
}
if (filesOutsideSrc.has(file)) {
return;
}
// make sure file to be linted is included in source files
if (!srcFiles.has(file)) {
srcFiles = resolveFiles(getSrc(src), ignoreExports, context);
if (!srcFiles.has(file)) {
filesOutsideSrc.add(file);
return;
}
}
exports = exportList.get(file);
if (!exports) {
console.error(`file \`${file}\` has no exports. Please update to the latest, and if it still happens, report this on https://github.com/import-js/eslint-plugin-import/issues/2866!`);
}
// special case: export * from
const exportAll = exports.get(EXPORT_ALL_DECLARATION);
if (typeof exportAll !== 'undefined' && exportedValue !== IMPORT_DEFAULT_SPECIFIER) {
if (exportAll.whereUsed.size > 0) {
return;
}
}
// special case: namespace import
const namespaceImports = exports.get(IMPORT_NAMESPACE_SPECIFIER);
if (typeof namespaceImports !== 'undefined') {
if (namespaceImports.whereUsed.size > 0) {
return;
}
}
// exportsList will always map any imported value of 'default' to 'ImportDefaultSpecifier'
const exportsKey = exportedValue === DEFAULT ? IMPORT_DEFAULT_SPECIFIER : exportedValue;
const exportStatement = exports.get(exportsKey);
const value = exportsKey === IMPORT_DEFAULT_SPECIFIER ? DEFAULT : exportsKey;
if (typeof exportStatement !== 'undefined') {
if (exportStatement.whereUsed.size < 1) {
context.report(
node,
`exported declaration '${value}' not used within other modules`,
);
}
} else {
context.report(
node,
`exported declaration '${value}' not used within other modules`,
);
}
};
/**
* only useful for tools like vscode-eslint
*
* update lists of existing exports during runtime
*/
const updateExportUsage = (node) => {
if (ignoredFiles.has(file)) {
return;
}
let exports = exportList.get(file);
// new module has been created during runtime
// include it in further processing
if (typeof exports === 'undefined') {
exports = new Map();
}
const newExports = new Map();
const newExportIdentifiers = new Set();
node.body.forEach(({ type, declaration, specifiers }) => {
if (type === EXPORT_DEFAULT_DECLARATION) {
newExportIdentifiers.add(IMPORT_DEFAULT_SPECIFIER);
}
if (type === EXPORT_NAMED_DECLARATION) {
if (specifiers.length > 0) {
specifiers.forEach((specifier) => {
if (specifier.exported) {
newExportIdentifiers.add(specifier.exported.name || specifier.exported.value);
}
});
}
forEachDeclarationIdentifier(declaration, (name) => {
newExportIdentifiers.add(name);
});
}
});
// old exports exist within list of new exports identifiers: add to map of new exports
exports.forEach((value, key) => {
if (newExportIdentifiers.has(key)) {
newExports.set(key, value);
}
});
// new export identifiers added: add to map of new exports
newExportIdentifiers.forEach((key) => {
if (!exports.has(key)) {
newExports.set(key, { whereUsed: new Set() });
}
});
// preserve information about namespace imports
const exportAll = exports.get(EXPORT_ALL_DECLARATION);
let namespaceImports = exports.get(IMPORT_NAMESPACE_SPECIFIER);
if (typeof namespaceImports === 'undefined') {
namespaceImports = { whereUsed: new Set() };
}
newExports.set(EXPORT_ALL_DECLARATION, exportAll);
newExports.set(IMPORT_NAMESPACE_SPECIFIER, namespaceImports);
exportList.set(file, newExports);
};
/**
* only useful for tools like vscode-eslint
*
* update lists of existing imports during runtime
*/
const updateImportUsage = (node) => {
if (!unusedExports) {
return;
}
let oldImportPaths = importList.get(file);
if (typeof oldImportPaths === 'undefined') {
oldImportPaths = new Map();
}
const oldNamespaceImports = new Set();
const newNamespaceImports = new Set();
const oldExportAll = new Set();
const newExportAll = new Set();
const oldDefaultImports = new Set();
const newDefaultImports = new Set();
const oldImports = new Map();
const newImports = new Map();
oldImportPaths.forEach((value, key) => {
if (value.has(EXPORT_ALL_DECLARATION)) {
oldExportAll.add(key);
}
if (value.has(IMPORT_NAMESPACE_SPECIFIER)) {
oldNamespaceImports.add(key);
}
if (value.has(IMPORT_DEFAULT_SPECIFIER)) {
oldDefaultImports.add(key);
}
value.forEach((val) => {
if (
val !== IMPORT_NAMESPACE_SPECIFIER
&& val !== IMPORT_DEFAULT_SPECIFIER
) {
oldImports.set(val, key);
}
});
});
function processDynamicImport(source) {
if (source.type !== 'Literal') {
return null;
}
const p = resolve(source.value, context);
if (p == null) {
return null;
}
newNamespaceImports.add(p);
}
visit(node, visitorKeyMap.get(file), {
ImportExpression(child) {
processDynamicImport(child.source);
},
CallExpression(child) {
if (child.callee.type === 'Import') {
processDynamicImport(child.arguments[0]);
}
},
});
node.body.forEach((astNode) => {
let resolvedPath;
// support for export { value } from 'module'
if (astNode.type === EXPORT_NAMED_DECLARATION) {
if (astNode.source) {
resolvedPath = resolve(astNode.source.raw.replace(/('|")/g, ''), context);
astNode.specifiers.forEach((specifier) => {
const name = specifier.local.name || specifier.local.value;
if (name === DEFAULT) {
newDefaultImports.add(resolvedPath);
} else {
newImports.set(name, resolvedPath);
}
});
}
}
if (astNode.type === EXPORT_ALL_DECLARATION) {
resolvedPath = resolve(astNode.source.raw.replace(/('|")/g, ''), context);
newExportAll.add(resolvedPath);
}
if (astNode.type === IMPORT_DECLARATION) {
resolvedPath = resolve(astNode.source.raw.replace(/('|")/g, ''), context);
if (!resolvedPath) {
return;
}
if (isNodeModule(resolvedPath)) {
return;
}
if (newNamespaceImportExists(astNode.specifiers)) {
newNamespaceImports.add(resolvedPath);
}
if (newDefaultImportExists(astNode.specifiers)) {
newDefaultImports.add(resolvedPath);
}
astNode.specifiers
.filter((specifier) => specifier.type !== IMPORT_DEFAULT_SPECIFIER && specifier.type !== IMPORT_NAMESPACE_SPECIFIER)
.forEach((specifier) => {
newImports.set(specifier.imported.name || specifier.imported.value, resolvedPath);
});
}
});
newExportAll.forEach((value) => {
if (!oldExportAll.has(value)) {
let imports = oldImportPaths.get(value);
if (typeof imports === 'undefined') {
imports = new Set();
}
imports.add(EXPORT_ALL_DECLARATION);
oldImportPaths.set(value, imports);
let exports = exportList.get(value);
let currentExport;
if (typeof exports !== 'undefined') {
currentExport = exports.get(EXPORT_ALL_DECLARATION);
} else {
exports = new Map();
exportList.set(value, exports);
}
if (typeof currentExport !== 'undefined') {
currentExport.whereUsed.add(file);
} else {
const whereUsed = new Set();
whereUsed.add(file);
exports.set(EXPORT_ALL_DECLARATION, { whereUsed });
}
}
});
oldExportAll.forEach((value) => {
if (!newExportAll.has(value)) {
const imports = oldImportPaths.get(value);
imports.delete(EXPORT_ALL_DECLARATION);
const exports = exportList.get(value);
if (typeof exports !== 'undefined') {
const currentExport = exports.get(EXPORT_ALL_DECLARATION);
if (typeof currentExport !== 'undefined') {
currentExport.whereUsed.delete(file);
}
}
}
});
newDefaultImports.forEach((value) => {
if (!oldDefaultImports.has(value)) {
let imports = oldImportPaths.get(value);
if (typeof imports === 'undefined') {
imports = new Set();
}
imports.add(IMPORT_DEFAULT_SPECIFIER);
oldImportPaths.set(value, imports);
let exports = exportList.get(value);
let currentExport;
if (typeof exports !== 'undefined') {
currentExport = exports.get(IMPORT_DEFAULT_SPECIFIER);
} else {
exports = new Map();
exportList.set(value, exports);
}
if (typeof currentExport !== 'undefined') {
currentExport.whereUsed.add(file);
} else {
const whereUsed = new Set();
whereUsed.add(file);
exports.set(IMPORT_DEFAULT_SPECIFIER, { whereUsed });
}
}
});
oldDefaultImports.forEach((value) => {
if (!newDefaultImports.has(value)) {
const imports = oldImportPaths.get(value);
imports.delete(IMPORT_DEFAULT_SPECIFIER);
const exports = exportList.get(value);
if (typeof exports !== 'undefined') {
const currentExport = exports.get(IMPORT_DEFAULT_SPECIFIER);
if (typeof currentExport !== 'undefined') {
currentExport.whereUsed.delete(file);
}
}
}
});
newNamespaceImports.forEach((value) => {
if (!oldNamespaceImports.has(value)) {
let imports = oldImportPaths.get(value);
if (typeof imports === 'undefined') {
imports = new Set();
}
imports.add(IMPORT_NAMESPACE_SPECIFIER);
oldImportPaths.set(value, imports);
let exports = exportList.get(value);
let currentExport;
if (typeof exports !== 'undefined') {
currentExport = exports.get(IMPORT_NAMESPACE_SPECIFIER);
} else {
exports = new Map();
exportList.set(value, exports);
}
if (typeof currentExport !== 'undefined') {