/
exports.js
108 lines (95 loc) · 2.7 KB
/
exports.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
"use strict";
const shared = require("./shared");
module.exports = {
meta: {
type: "layout",
fixable: "code",
schema: [],
docs: {
url: "https://github.com/lydell/eslint-plugin-simple-import-sort#sort-order",
},
messages: {
sort: "Run autofix to sort these exports!",
},
},
create: (context) => {
const parents = new Set();
const addParent = (node) => {
if (isExportFrom(node)) {
parents.add(node.parent);
}
};
return {
ExportNamedDeclaration: (node) => {
if (node.source == null && node.declaration == null) {
maybeReportExportSpecifierSorting(node, context);
} else {
addParent(node);
}
},
ExportAllDeclaration: addParent,
"Program:exit": () => {
const sourceCode = context.getSourceCode();
for (const parent of parents) {
for (const chunk of shared.extractChunks(parent, (node, lastNode) =>
isPartOfChunk(node, lastNode, sourceCode)
)) {
maybeReportChunkSorting(chunk, context);
}
}
parents.clear();
},
};
},
};
function maybeReportChunkSorting(chunk, context) {
const sourceCode = context.getSourceCode();
const items = shared.getImportExportItems(
chunk,
sourceCode,
() => false, // isSideEffectImport
getSpecifiers
);
const sortedItems = [[shared.sortImportExportItems(items)]];
const sorted = shared.printSortedItems(sortedItems, items, sourceCode);
const { start } = items[0];
const { end } = items[items.length - 1];
shared.maybeReportSorting(context, sorted, start, end);
}
function maybeReportExportSpecifierSorting(node, context) {
const sorted = shared.printWithSortedSpecifiers(
node,
context.getSourceCode(),
getSpecifiers
);
const [start, end] = node.range;
shared.maybeReportSorting(context, sorted, start, end);
}
// `export * from "a"` does not have `.specifiers`.
function getSpecifiers(exportNode) {
return exportNode.specifiers || [];
}
function isPartOfChunk(node, lastNode, sourceCode) {
if (!isExportFrom(node)) {
return "NotPartOfChunk";
}
const hasGroupingComment = sourceCode
.getCommentsBefore(node)
.some(
(comment) =>
(lastNode == null || comment.loc.start.line > lastNode.loc.end.line) &&
comment.loc.end.line < node.loc.start.line
);
return hasGroupingComment ? "PartOfNewChunk" : "PartOfChunk";
}
// Full export-from statement.
// export {a, b} from "A"
// export * from "A"
// export * as A from "A"
function isExportFrom(node) {
return (
(node.type === "ExportNamedDeclaration" ||
node.type === "ExportAllDeclaration") &&
node.source != null
);
}