@so1ve/eslint-plugin-sort-imports 0.104.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2019-PRESENT Anthony Fu<https://github.com/antfu>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@so1ve/eslint-plugin-sort-imports",
3
+ "version": "0.104.0",
4
+ "author": "Simon Lydell",
5
+ "contributors": [
6
+ "Ray (https://github.com/so1ve) <i@mk1.io>"
7
+ ],
8
+ "description": "Easy autofixable import sorting",
9
+ "keywords": [
10
+ "eslint",
11
+ "eslint-plugin",
12
+ "eslintplugin",
13
+ "import",
14
+ "imports",
15
+ "order",
16
+ "sort",
17
+ "sorter",
18
+ "sorting"
19
+ ],
20
+ "homepage": "https://github.com/so1ve/eslint-config#readme",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/so1ve/eslint-config.git"
24
+ },
25
+ "bugs": {
26
+ "url": "https://github.com/so1ve/eslint-config/issues"
27
+ },
28
+ "license": "MIT",
29
+ "main": "src/index.js",
30
+ "files": [
31
+ "src"
32
+ ],
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "dependencies": {
37
+ "natsort": "^2.0.3"
38
+ },
39
+ "peerDependencies": {
40
+ "eslint": ">=8.40.0"
41
+ }
42
+ }
package/src/exports.js ADDED
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+
3
+ const shared = require("./shared");
4
+
5
+ // `export * from "a"` does not have `.specifiers`.
6
+ const getSpecifiers = (exportNode) => exportNode.specifiers || [];
7
+
8
+ // Full export-from statement.
9
+ // export {a, b} from "A"
10
+ // export * from "A"
11
+ // export * as A from "A"
12
+ const isExportFrom = (node) =>
13
+ (node.type === "ExportNamedDeclaration" ||
14
+ node.type === "ExportAllDeclaration") &&
15
+ node.source != null;
16
+
17
+ function isPartOfChunk(node, lastNode, sourceCode) {
18
+ if (!isExportFrom(node)) {
19
+ return "NotPartOfChunk";
20
+ }
21
+
22
+ const hasGroupingComment = sourceCode
23
+ .getCommentsBefore(node)
24
+ .some(
25
+ (comment) =>
26
+ (lastNode == null || comment.loc.start.line > lastNode.loc.end.line) &&
27
+ comment.loc.end.line < node.loc.start.line,
28
+ );
29
+
30
+ return hasGroupingComment ? "PartOfNewChunk" : "PartOfChunk";
31
+ }
32
+
33
+ function maybeReportChunkSorting(chunk, context) {
34
+ const sourceCode = context.getSourceCode();
35
+ const items = shared.getImportExportItems(
36
+ chunk,
37
+ sourceCode,
38
+ () => false, // isSideEffectImport
39
+ getSpecifiers,
40
+ );
41
+ const sortedItems = [[shared.sortImportExportItems(items)]];
42
+ const sorted = shared.printSortedItems(sortedItems, items, sourceCode);
43
+ const { start } = items[0];
44
+ const { end } = items[items.length - 1];
45
+ shared.maybeReportSorting(context, sorted, start, end);
46
+ }
47
+
48
+ function maybeReportExportSpecifierSorting(node, context) {
49
+ const sorted = shared.printWithSortedSpecifiers(
50
+ node,
51
+ context.getSourceCode(),
52
+ getSpecifiers,
53
+ );
54
+ const [start, end] = node.range;
55
+ shared.maybeReportSorting(context, sorted, start, end);
56
+ }
57
+
58
+ module.exports = {
59
+ meta: {
60
+ type: "layout",
61
+ fixable: "code",
62
+ schema: [],
63
+ docs: {
64
+ url: "https://github.com/lydell/eslint-plugin-simple-import-sort#sort-order",
65
+ },
66
+ messages: {
67
+ sort: "Run autofix to sort these exports!",
68
+ },
69
+ },
70
+ create: (context) => {
71
+ const parents = new Set();
72
+
73
+ function addParent(node) {
74
+ if (isExportFrom(node)) {
75
+ parents.add(node.parent);
76
+ }
77
+ }
78
+
79
+ return {
80
+ "ExportNamedDeclaration": (node) => {
81
+ if (node.source == null && node.declaration == null) {
82
+ maybeReportExportSpecifierSorting(node, context);
83
+ } else {
84
+ addParent(node);
85
+ }
86
+ },
87
+
88
+ "ExportAllDeclaration": addParent,
89
+
90
+ "Program:exit": () => {
91
+ const sourceCode = context.getSourceCode();
92
+ for (const parent of parents) {
93
+ for (const chunk of shared.extractChunks(parent, (node, lastNode) =>
94
+ isPartOfChunk(node, lastNode, sourceCode),
95
+ )) {
96
+ maybeReportChunkSorting(chunk, context);
97
+ }
98
+ }
99
+ parents.clear();
100
+ },
101
+ };
102
+ },
103
+ };
package/src/imports.js ADDED
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+
3
+ const shared = require("./shared");
4
+
5
+ const defaultGroups = [
6
+ // Node.js builtins prefixed with `node:`.
7
+ ["^node:"],
8
+ // Packages.
9
+ // Things that start with a letter (or digit or underscore), or `@` followed by a letter.
10
+ ["^@?\\w"],
11
+ // Absolute imports and other imports such as Vue-style `@/foo`.
12
+ // Anything not matched in another group.
13
+ ["^"],
14
+ // Relative imports.
15
+ // Anything that starts with a dot.
16
+ ["^\\."],
17
+ // Side effect imports.
18
+ ["^\\u0000"],
19
+ ];
20
+
21
+ // import def, { a, b as c, type d } from "A"
22
+ // ^ ^^^^^^ ^^^^^^
23
+ const isImportSpecifier = (node) => node.type === "ImportSpecifier";
24
+
25
+ // Exclude "ImportDefaultSpecifier" – the "def" in `import def, {a, b}`.
26
+ const getSpecifiers = (importNode) =>
27
+ importNode.specifiers.filter((node) => isImportSpecifier(node));
28
+
29
+ // Full import statement.
30
+ const isImport = (node) => node.type === "ImportDeclaration";
31
+
32
+ // import "setup"
33
+ // But not: import {} from "setup"
34
+ // And not: import type {} from "setup"
35
+ const isSideEffectImport = (importNode, sourceCode) =>
36
+ importNode.specifiers.length === 0 &&
37
+ (!importNode.importKind || importNode.importKind === "value") &&
38
+ !shared.isPunctuator(sourceCode.getFirstToken(importNode, { skip: 1 }), "{");
39
+
40
+ module.exports = {
41
+ meta: {
42
+ type: "layout",
43
+ fixable: "code",
44
+ schema: [
45
+ {
46
+ type: "object",
47
+ properties: {
48
+ groups: {
49
+ type: "array",
50
+ items: {
51
+ type: "array",
52
+ items: {
53
+ type: "string",
54
+ },
55
+ },
56
+ },
57
+ },
58
+ additionalProperties: false,
59
+ },
60
+ ],
61
+ docs: {
62
+ url: "https://github.com/lydell/eslint-plugin-simple-import-sort#sort-order",
63
+ },
64
+ messages: {
65
+ sort: "Run autofix to sort these imports!",
66
+ },
67
+ },
68
+ create: (context) => {
69
+ const { groups: rawGroups = defaultGroups } = context.options[0] || {};
70
+
71
+ const outerGroups = rawGroups.map((groups) =>
72
+ groups.map((item) => new RegExp(item, "u")),
73
+ );
74
+
75
+ const parents = new Set();
76
+
77
+ return {
78
+ "ImportDeclaration": (node) => {
79
+ parents.add(node.parent);
80
+ },
81
+
82
+ "Program:exit": () => {
83
+ for (const parent of parents) {
84
+ for (const chunk of shared.extractChunks(parent, (node) =>
85
+ isImport(node) ? "PartOfChunk" : "NotPartOfChunk",
86
+ )) {
87
+ maybeReportChunkSorting(chunk, context, outerGroups);
88
+ }
89
+ }
90
+ parents.clear();
91
+ },
92
+ };
93
+ },
94
+ };
95
+
96
+ function maybeReportChunkSorting(chunk, context, outerGroups) {
97
+ const sourceCode = context.getSourceCode();
98
+ const items = shared.getImportExportItems(
99
+ chunk,
100
+ sourceCode,
101
+ isSideEffectImport,
102
+ getSpecifiers,
103
+ );
104
+ const sortedItems = makeSortedItems(items, outerGroups);
105
+ const sorted = shared.printSortedItems(sortedItems, items, sourceCode);
106
+ const { start } = items[0];
107
+ const { end } = items[items.length - 1];
108
+ shared.maybeReportSorting(context, sorted, start, end);
109
+ }
110
+
111
+ function makeSortedItems(items, outerGroups) {
112
+ const itemGroups = outerGroups.map((groups) =>
113
+ groups.map((regex) => ({ regex, items: [] })),
114
+ );
115
+ const rest = [];
116
+
117
+ for (const item of items) {
118
+ const { originalSource } = item.source;
119
+ const source = item.isSideEffectImport
120
+ ? `\0${originalSource}`
121
+ : item.source.kind === "value"
122
+ ? originalSource
123
+ : `${originalSource}\0`;
124
+ const [matchedGroup] = shared
125
+ // eslint-disable-next-line unicorn/no-array-method-this-argument
126
+ .flatMap(itemGroups, (groups) =>
127
+ groups.map((group) => [group, group.regex.exec(source)]),
128
+ )
129
+ .reduce(
130
+ ([group, longestMatch], [nextGroup, nextMatch]) =>
131
+ nextMatch != null &&
132
+ (longestMatch == null || nextMatch[0].length > longestMatch[0].length)
133
+ ? [nextGroup, nextMatch]
134
+ : [group, longestMatch],
135
+ [undefined, undefined],
136
+ );
137
+ if (matchedGroup == null) {
138
+ rest.push(item);
139
+ } else {
140
+ matchedGroup.items.push(item);
141
+ }
142
+ }
143
+
144
+ return [...itemGroups, [{ regex: /^/, items: rest }]]
145
+ .map((groups) => groups.filter((group) => group.items.length > 0))
146
+ .filter((groups) => groups.length > 0)
147
+ .map((groups) =>
148
+ groups.map((group) => shared.sortImportExportItems(group.items)),
149
+ );
150
+ }
package/src/index.js ADDED
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+
3
+ const importsRule = require("./imports");
4
+ const exportsRule = require("./exports");
5
+
6
+ module.exports = {
7
+ rules: {
8
+ imports: importsRule,
9
+ exports: exportsRule,
10
+ },
11
+ };
package/src/shared.js ADDED
@@ -0,0 +1,870 @@
1
+ "use strict";
2
+
3
+ const natsort = require("natsort");
4
+
5
+ const NEWLINE = /(\r?\n)/;
6
+
7
+ const hasNewline = (string) => NEWLINE.test(string);
8
+
9
+ function guessNewline(sourceCode) {
10
+ const match = NEWLINE.exec(sourceCode.text);
11
+
12
+ return match == null ? "\n" : match[0];
13
+ }
14
+
15
+ function parseWhitespace(whitespace) {
16
+ const allItems = whitespace.split(NEWLINE);
17
+
18
+ // Remove blank lines. `allItems` contains alternating `spaces` (which can be
19
+ // the empty string) and `newline` (which is either "\r\n" or "\n"). So in
20
+ // practice `allItems` grows like this as there are more newlines in
21
+ // `whitespace`:
22
+ //
23
+ // [spaces]
24
+ // [spaces, newline, spaces]
25
+ // [spaces, newline, spaces, newline, spaces]
26
+ // [spaces, newline, spaces, newline, spaces, newline, spaces]
27
+ //
28
+ // If there are 5 or more items we have at least one blank line. If so, keep
29
+ // the first `spaces`, the first `newline` and the last `spaces`.
30
+ const items =
31
+ allItems.length >= 5
32
+ ? [...allItems.slice(0, 2), ...allItems.slice(-1)]
33
+ : allItems;
34
+
35
+ return (
36
+ items
37
+ .map((spacesOrNewline, index) =>
38
+ index % 2 === 0
39
+ ? { type: "Spaces", code: spacesOrNewline }
40
+ : { type: "Newline", code: spacesOrNewline },
41
+ )
42
+ // Remove empty spaces since it makes debugging easier.
43
+ .filter((token) => token.code !== "")
44
+ );
45
+ }
46
+
47
+ const compare = natsort.default();
48
+
49
+ const isIdentifier = (node) => node.type === "Identifier";
50
+
51
+ const isKeyword = (node) => node.type === "Keyword";
52
+
53
+ const isPunctuator = (node, value) =>
54
+ node.type === "Punctuator" && node.value === value;
55
+
56
+ const isBlockComment = (node) => node.type === "Block";
57
+
58
+ const isLineComment = (node) => node.type === "Line";
59
+
60
+ const isSpaces = (node) => node.type === "Spaces";
61
+
62
+ const isNewline = (node) => node.type === "Newline";
63
+
64
+ const getImportExportKind = (node) =>
65
+ node.importKind || node.exportKind || "value";
66
+
67
+ function getSource(node) {
68
+ const source = node.source.value;
69
+
70
+ return {
71
+ // Sort by directory level rather than by string length.
72
+ source: source
73
+ // Treat `.` as `./`, `..` as `../`, `../..` as `../../` etc.
74
+ .replace(/^[./]*\.$/, "$&/")
75
+ // Make `../` sort after `../../` but before `../a` etc.
76
+ // Why a comma? See the next comment.
77
+ .replace(/^[./]*\/$/, "$&,")
78
+ // Make `.` and `/` sort before any other punctation.
79
+ // The default order is: _ - , x x x . x x x / x x x
80
+ // We’re changing it to: . / , x x x _ x x x - x x x
81
+ .replace(/[./_-]/g, (char) => {
82
+ switch (char) {
83
+ case ".": {
84
+ return "_";
85
+ }
86
+ case "/": {
87
+ return "-";
88
+ }
89
+ case "_": {
90
+ return ".";
91
+ }
92
+ case "-": {
93
+ return "/";
94
+ }
95
+ // istanbul ignore next
96
+ default: {
97
+ throw new Error(`Unknown source substitution character: ${char}`);
98
+ }
99
+ }
100
+ }),
101
+ originalSource: source,
102
+ kind: getImportExportKind(node),
103
+ };
104
+ }
105
+
106
+ // Like `Array.prototype.findIndex`, but searches from the end.
107
+ function findLastIndex(array, fn) {
108
+ for (let index = array.length - 1; index >= 0; index--) {
109
+ if (fn(array[index], index, array)) {
110
+ return index;
111
+ }
112
+ }
113
+
114
+ // There are currently no usages of `findLastIndex` where nothing is found.
115
+ // istanbul ignore next
116
+ return -1;
117
+ }
118
+
119
+ // Like `Array.prototype.flatMap`, had it been available.
120
+ const flatMap = (array, fn) => array.flatMap(fn);
121
+
122
+ // Returns `sourceCode.getTokens(node)` plus whitespace and comments. All tokens
123
+ // have a `code` property with `sourceCode.getText(token)`.
124
+ function getAllTokens(node, sourceCode) {
125
+ const tokens = sourceCode.getTokens(node);
126
+ const lastTokenIndex = tokens.length - 1;
127
+
128
+ return flatMap(tokens, (token, tokenIndex) => {
129
+ const newToken = { ...token, code: sourceCode.getText(token) };
130
+
131
+ if (tokenIndex === lastTokenIndex) {
132
+ return [newToken];
133
+ }
134
+
135
+ const comments = sourceCode.getCommentsAfter(token);
136
+ const last = comments.length > 0 ? comments[comments.length - 1] : token;
137
+ const nextToken = tokens[tokenIndex + 1];
138
+
139
+ return [
140
+ newToken,
141
+ ...flatMap(comments, (comment, commentIndex) => {
142
+ const previous =
143
+ commentIndex === 0 ? token : comments[commentIndex - 1];
144
+
145
+ return [
146
+ ...parseWhitespace(
147
+ sourceCode.text.slice(previous.range[1], comment.range[0]),
148
+ ),
149
+ { ...comment, code: sourceCode.getText(comment) },
150
+ ];
151
+ }),
152
+ ...parseWhitespace(
153
+ sourceCode.text.slice(last.range[1], nextToken.range[0]),
154
+ ),
155
+ ];
156
+ });
157
+ }
158
+
159
+ // Prints tokens that are enhanced with a `code` property – like those returned
160
+ // by `getAllTokens` and `parseWhitespace`.
161
+ const printTokens = (tokens) => tokens.map((token) => token.code).join("");
162
+
163
+ const removeBlankLines = (whitespace) =>
164
+ printTokens(parseWhitespace(whitespace));
165
+
166
+ // `comments` is a list of comments that occur before `node`. Print those and
167
+ // the whitespace between themselves and between `node`.
168
+ function printCommentsBefore(node, comments, sourceCode) {
169
+ const lastIndex = comments.length - 1;
170
+
171
+ return comments
172
+ .map((comment, index) => {
173
+ const next = index === lastIndex ? node : comments[index + 1];
174
+
175
+ return (
176
+ sourceCode.getText(comment) +
177
+ removeBlankLines(sourceCode.text.slice(comment.range[1], next.range[0]))
178
+ );
179
+ })
180
+ .join("");
181
+ }
182
+
183
+ // `comments` is a list of comments that occur after `node`. Print those and
184
+ // the whitespace between themselves and between `node`.
185
+ const printCommentsAfter = (node, comments, sourceCode) =>
186
+ comments
187
+ .map((comment, index) => {
188
+ const previous = index === 0 ? node : comments[index - 1];
189
+
190
+ return (
191
+ removeBlankLines(
192
+ sourceCode.text.slice(previous.range[1], comment.range[0]),
193
+ ) + sourceCode.getText(comment)
194
+ );
195
+ })
196
+ .join("");
197
+
198
+ function getIndentation(node, sourceCode) {
199
+ const tokenBefore = sourceCode.getTokenBefore(node, {
200
+ includeComments: true,
201
+ });
202
+ if (tokenBefore == null) {
203
+ const text = sourceCode.text.slice(0, node.range[0]);
204
+ const lines = text.split(NEWLINE);
205
+
206
+ return lines[lines.length - 1];
207
+ }
208
+ const text = sourceCode.text.slice(tokenBefore.range[1], node.range[0]);
209
+ const lines = text.split(NEWLINE);
210
+
211
+ return lines.length > 1 ? lines[lines.length - 1] : "";
212
+ }
213
+
214
+ function getTrailingSpaces(node, sourceCode) {
215
+ const tokenAfter = sourceCode.getTokenAfter(node, {
216
+ includeComments: true,
217
+ });
218
+ if (tokenAfter == null) {
219
+ const text = sourceCode.text.slice(node.range[1]);
220
+ const lines = text.split(NEWLINE);
221
+
222
+ return lines[0];
223
+ }
224
+ const text = sourceCode.text.slice(node.range[1], tokenAfter.range[0]);
225
+ const lines = text.split(NEWLINE);
226
+
227
+ return lines[0];
228
+ }
229
+
230
+ const sortImportExportItems = (items) =>
231
+ [...items].sort((itemA, itemB) =>
232
+ // If both items are side effect imports, keep their original order.
233
+ itemA.isSideEffectImport && itemB.isSideEffectImport
234
+ ? itemA.index - itemB.index
235
+ : // If one of the items is a side effect import, move it first.
236
+ itemA.isSideEffectImport
237
+ ? -1
238
+ : itemB.isSideEffectImport
239
+ ? 1
240
+ : // Compare the `from` part.
241
+ compare(itemA.source.source, itemB.source.source) ||
242
+ // The `.source` has been slightly tweaked. To stay fully deterministic,
243
+ // also sort on the original value.
244
+ compare(itemA.source.originalSource, itemB.source.originalSource) ||
245
+ // Then put type imports/exports before regular ones.
246
+ compare(itemA.source.kind, itemB.source.kind) ||
247
+ // Keep the original order if the sources are the same. It’s not worth
248
+ // trying to compare anything else, and you can use `import/no-duplicates`
249
+ // to get rid of the problem anyway.
250
+ itemA.index - itemB.index,
251
+ );
252
+
253
+ const sortSpecifierItems = (items) =>
254
+ [...items].sort(
255
+ (itemA, itemB) =>
256
+ // Compare by imported or exported name (external interface name).
257
+ // import { a as b } from "a"
258
+ // ^
259
+ // export { b as a }
260
+ // ^
261
+ compare(
262
+ (itemA.node.imported || itemA.node.exported).name,
263
+ (itemB.node.imported || itemB.node.exported).name,
264
+ ) ||
265
+ // Then compare by the file-local name.
266
+ // import { a as b } from "a"
267
+ // ^
268
+ // export { b as a }
269
+ // ^
270
+ compare(itemA.node.local.name, itemB.node.local.name) ||
271
+ // Then put type specifiers before regular ones.
272
+ compare(
273
+ getImportExportKind(itemA.node),
274
+ getImportExportKind(itemB.node),
275
+ ) ||
276
+ // Keep the original order if the names are the same. It’s not worth
277
+ // trying to compare anything else, `import {a, a} from "mod"` is a syntax
278
+ // error anyway (but @babel/eslint-parser kind of supports it).
279
+ // istanbul ignore next
280
+ itemA.index - itemB.index,
281
+ );
282
+
283
+ // A “chunk” is a sequence of statements of a certain type with only comments
284
+ // and whitespace between.
285
+ function extractChunks(parentNode, isPartOfChunk) {
286
+ const chunks = [];
287
+ let chunk = [];
288
+ let lastNode;
289
+
290
+ for (const node of parentNode.body) {
291
+ const result = isPartOfChunk(node, lastNode);
292
+ switch (result) {
293
+ case "PartOfChunk": {
294
+ chunk.push(node);
295
+ break;
296
+ }
297
+
298
+ case "PartOfNewChunk": {
299
+ if (chunk.length > 0) {
300
+ chunks.push(chunk);
301
+ }
302
+ chunk = [node];
303
+ break;
304
+ }
305
+
306
+ case "NotPartOfChunk": {
307
+ if (chunk.length > 0) {
308
+ chunks.push(chunk);
309
+ chunk = [];
310
+ }
311
+ break;
312
+ }
313
+
314
+ // istanbul ignore next
315
+ default: {
316
+ throw new Error(`Unknown chunk result: ${result}`);
317
+ }
318
+ }
319
+
320
+ lastNode = node;
321
+ }
322
+
323
+ if (chunk.length > 0) {
324
+ chunks.push(chunk);
325
+ }
326
+
327
+ return chunks;
328
+ }
329
+
330
+ function maybeReportSorting(context, sorted, start, end) {
331
+ const sourceCode = context.getSourceCode();
332
+ const original = sourceCode.getText().slice(start, end);
333
+ if (original !== sorted) {
334
+ context.report({
335
+ messageId: "sort",
336
+ loc: {
337
+ start: sourceCode.getLocFromIndex(start),
338
+ end: sourceCode.getLocFromIndex(end),
339
+ },
340
+ fix: (fixer) => fixer.replaceTextRange([start, end], sorted),
341
+ });
342
+ }
343
+ }
344
+
345
+ function printSortedItems(sortedItems, originalItems, sourceCode) {
346
+ const newline = guessNewline(sourceCode);
347
+
348
+ const sorted = sortedItems
349
+ .map((groups) =>
350
+ groups
351
+ .map((groupItems) => groupItems.map((item) => item.code).join(newline))
352
+ .join(newline),
353
+ )
354
+ .join(newline + newline);
355
+
356
+ // Edge case: If the last import/export (after sorting) ends with a line
357
+ // comment and there’s code (or a multiline block comment) on the same line,
358
+ // add a newline so we don’t accidentally comment stuff out.
359
+ const flattened = flatMap(sortedItems, (groups) => groups.flat());
360
+ const lastSortedItem = flattened[flattened.length - 1];
361
+ const lastOriginalItem = originalItems[originalItems.length - 1];
362
+ const nextToken = lastSortedItem.needsNewline
363
+ ? sourceCode.getTokenAfter(lastOriginalItem.node, {
364
+ includeComments: true,
365
+ filter: (token) =>
366
+ !isLineComment(token) &&
367
+ !(
368
+ isBlockComment(token) &&
369
+ token.loc.end.line === lastOriginalItem.node.loc.end.line
370
+ ),
371
+ })
372
+ : undefined;
373
+ const maybeNewline =
374
+ nextToken != null &&
375
+ nextToken.loc.start.line === lastOriginalItem.node.loc.end.line
376
+ ? newline
377
+ : "";
378
+
379
+ return sorted + maybeNewline;
380
+ }
381
+
382
+ // Wrap the import/export nodes in `passedChunk` in objects with more data about
383
+ // the import/export. Most importantly there’s a `code` property that contains
384
+ // the node as a string, with comments (if any). Finding the corresponding
385
+ // comments is the hard part.
386
+ function getImportExportItems(
387
+ passedChunk,
388
+ sourceCode,
389
+ isSideEffectImport,
390
+ getSpecifiers,
391
+ ) {
392
+ const chunk = handleLastSemicolon(passedChunk, sourceCode);
393
+
394
+ return chunk.map((node, nodeIndex) => {
395
+ const lastLine =
396
+ nodeIndex === 0
397
+ ? node.loc.start.line - 1
398
+ : chunk[nodeIndex - 1].loc.end.line;
399
+
400
+ // Get all comments before the import/export, except:
401
+ //
402
+ // - Comments on another line for the first import/export.
403
+ // - Comments that belong to the previous import/export (if any) – that is,
404
+ // comments that are on the same line as the previous import/export. But
405
+ // multiline block comments always belong to this import/export, not the
406
+ // previous.
407
+ const commentsBefore = sourceCode
408
+ .getCommentsBefore(node)
409
+ .filter(
410
+ (comment) =>
411
+ comment.loc.start.line <= node.loc.start.line &&
412
+ comment.loc.end.line > lastLine &&
413
+ (nodeIndex > 0 || comment.loc.start.line > lastLine),
414
+ );
415
+
416
+ // Get all comments after the import/export that are on the same line.
417
+ // Multiline block comments belong to the _next_ import/export (or the
418
+ // following code in case of the last import/export).
419
+ const commentsAfter = sourceCode
420
+ .getCommentsAfter(node)
421
+ .filter((comment) => comment.loc.end.line === node.loc.end.line);
422
+
423
+ const before = printCommentsBefore(node, commentsBefore, sourceCode);
424
+ const after = printCommentsAfter(node, commentsAfter, sourceCode);
425
+
426
+ // Print the indentation before the import/export or its first comment, if
427
+ // any, to support indentation in `<script>` tags.
428
+ const indentation = getIndentation(
429
+ commentsBefore.length > 0 ? commentsBefore[0] : node,
430
+ sourceCode,
431
+ );
432
+
433
+ // Print spaces after the import/export or its last comment, if any, to
434
+ // avoid producing a sort error just because you accidentally added a few
435
+ // trailing spaces among the imports/exports.
436
+ const trailingSpaces = getTrailingSpaces(
437
+ commentsAfter.length > 0 ? commentsAfter[commentsAfter.length - 1] : node,
438
+ sourceCode,
439
+ );
440
+
441
+ const code =
442
+ indentation +
443
+ before +
444
+ printWithSortedSpecifiers(node, sourceCode, getSpecifiers) +
445
+ after +
446
+ trailingSpaces;
447
+
448
+ const all = [...commentsBefore, node, ...commentsAfter];
449
+ const [start] = all[0].range;
450
+ const [, end] = all[all.length - 1].range;
451
+
452
+ const source = getSource(node);
453
+
454
+ return {
455
+ node,
456
+ code,
457
+ start: start - indentation.length,
458
+ end: end + trailingSpaces.length,
459
+ isSideEffectImport: isSideEffectImport(node, sourceCode),
460
+ source,
461
+ index: nodeIndex,
462
+ needsNewline:
463
+ commentsAfter.length > 0 &&
464
+ isLineComment(commentsAfter[commentsAfter.length - 1]),
465
+ };
466
+ });
467
+ }
468
+
469
+ // Parsers think that a semicolon after a statement belongs to that statement.
470
+ // But in a semicolon-free code style it might belong to the next statement:
471
+ //
472
+ // import x from "x"
473
+ // ;[].forEach()
474
+ //
475
+ // If the last import/export of a chunk ends with a semicolon, and that
476
+ // semicolon isn’t located on the same line as the `from` string, adjust the
477
+ // node to end at the `from` string instead.
478
+ //
479
+ // In the above example, the import is adjusted to end after `"x"`.
480
+ function handleLastSemicolon(chunk, sourceCode) {
481
+ const lastIndex = chunk.length - 1;
482
+ const lastNode = chunk[lastIndex];
483
+ const [nextToLastToken, lastToken] = sourceCode.getLastTokens(lastNode, {
484
+ count: 2,
485
+ });
486
+ const lastIsSemicolon = isPunctuator(lastToken, ";");
487
+
488
+ if (!lastIsSemicolon) {
489
+ return chunk;
490
+ }
491
+
492
+ const semicolonBelongsToNode =
493
+ nextToLastToken.loc.end.line === lastToken.loc.start.line ||
494
+ // If there’s no more code after the last import/export the semicolon has to
495
+ // belong to the import/export, even if it is not on the same line.
496
+ sourceCode.getTokenAfter(lastToken) == null;
497
+
498
+ if (semicolonBelongsToNode) {
499
+ return chunk;
500
+ }
501
+
502
+ // Preserve the start position, but use the end position of the `from` string.
503
+ const newLastNode = {
504
+ ...lastNode,
505
+ range: [lastNode.range[0], nextToLastToken.range[1]],
506
+ loc: {
507
+ start: lastNode.loc.start,
508
+ end: nextToLastToken.loc.end,
509
+ },
510
+ };
511
+
512
+ return [...chunk.slice(0, lastIndex), newLastNode];
513
+ }
514
+
515
+ function printWithSortedSpecifiers(node, sourceCode, getSpecifiers) {
516
+ const allTokens = getAllTokens(node, sourceCode);
517
+ const openBraceIndex = allTokens.findIndex((token) =>
518
+ isPunctuator(token, "{"),
519
+ );
520
+ const closeBraceIndex = allTokens.findIndex((token) =>
521
+ isPunctuator(token, "}"),
522
+ );
523
+
524
+ const specifiers = getSpecifiers(node);
525
+
526
+ if (
527
+ openBraceIndex === -1 ||
528
+ closeBraceIndex === -1 ||
529
+ specifiers.length <= 1
530
+ ) {
531
+ return printTokens(allTokens);
532
+ }
533
+
534
+ const specifierTokens = allTokens.slice(openBraceIndex + 1, closeBraceIndex);
535
+ const itemsResult = getSpecifierItems(specifierTokens, sourceCode);
536
+
537
+ const items = itemsResult.items.map((originalItem, index) => ({
538
+ ...originalItem,
539
+ node: specifiers[index],
540
+ }));
541
+
542
+ const sortedItems = sortSpecifierItems(items);
543
+
544
+ const newline = guessNewline(sourceCode);
545
+
546
+ // `allTokens[closeBraceIndex - 1]` wouldn’t work because `allTokens` contains
547
+ // comments and whitespace.
548
+ const hasTrailingComma = isPunctuator(
549
+ sourceCode.getTokenBefore(allTokens[closeBraceIndex]),
550
+ ",",
551
+ );
552
+
553
+ const lastIndex = sortedItems.length - 1;
554
+ const sorted = flatMap(sortedItems, (item, index) => {
555
+ const previous = index === 0 ? undefined : sortedItems[index - 1];
556
+
557
+ // Add a newline if the item needs one, unless the previous item (if any)
558
+ // already ends with a newline.
559
+ const maybeNewline =
560
+ previous != null &&
561
+ needsStartingNewline(item.before) &&
562
+ !(
563
+ previous.after.length > 0 &&
564
+ isNewline(previous.after[previous.after.length - 1])
565
+ )
566
+ ? [{ type: "Newline", code: newline }]
567
+ : [];
568
+
569
+ if (index < lastIndex || hasTrailingComma) {
570
+ return [
571
+ ...maybeNewline,
572
+ ...item.before,
573
+ ...item.specifier,
574
+ { type: "Comma", code: "," },
575
+ ...item.after,
576
+ ];
577
+ }
578
+
579
+ const nonBlankIndex = item.after.findIndex(
580
+ (token) => !isNewline(token) && !isSpaces(token),
581
+ );
582
+
583
+ // Remove whitespace and newlines at the start of `.after` if the item had a
584
+ // comma before, but now hasn’t to avoid blank lines and excessive
585
+ // whitespace before `}`.
586
+ const after = item.hadComma
587
+ ? nonBlankIndex === -1
588
+ ? []
589
+ : item.after.slice(nonBlankIndex)
590
+ : item.after;
591
+
592
+ return [...maybeNewline, ...item.before, ...item.specifier, ...after];
593
+ });
594
+
595
+ const maybeNewline =
596
+ needsStartingNewline(itemsResult.after) &&
597
+ !isNewline(sorted[sorted.length - 1])
598
+ ? [{ type: "Newline", code: newline }]
599
+ : [];
600
+
601
+ return printTokens([
602
+ ...allTokens.slice(0, openBraceIndex + 1),
603
+ ...itemsResult.before,
604
+ ...sorted,
605
+ ...maybeNewline,
606
+ ...itemsResult.after,
607
+ ...allTokens.slice(closeBraceIndex),
608
+ ]);
609
+ }
610
+
611
+ const makeEmptyItem = () => ({
612
+ // "before" | "specifier" | "after"
613
+ state: "before",
614
+ before: [],
615
+ after: [],
616
+ specifier: [],
617
+ hadComma: false,
618
+ });
619
+
620
+ // Turns a list of tokens between the `{` and `}` of an import/export specifiers
621
+ // list into an object with the following properties:
622
+ //
623
+ // - before: Array of tokens – whitespace and comments after the `{` that do not
624
+ // belong to any specifier.
625
+ // - after: Array of tokens – whitespace and comments before the `}` that do not
626
+ // belong to any specifier.
627
+ // - items: Array of specifier items.
628
+ //
629
+ // Each specifier item looks like this:
630
+ //
631
+ // - before: Array of tokens – whitespace and comments before the specifier.
632
+ // - after: Array of tokens – whitespace and comments after the specifier.
633
+ // - specifier: Array of tokens – identifiers, whitespace and comments of the
634
+ // specifier.
635
+ // - hadComma: A Boolean representing if the specifier had a comma originally.
636
+ //
637
+ // We have to do carefully preserve all original whitespace this way in order to
638
+ // be compatible with other stylistic ESLint rules.
639
+ function getSpecifierItems(tokens) {
640
+ const result = {
641
+ before: [],
642
+ after: [],
643
+ items: [],
644
+ };
645
+
646
+ let current = makeEmptyItem();
647
+
648
+ for (const token of tokens) {
649
+ switch (current.state) {
650
+ case "before": {
651
+ switch (token.type) {
652
+ case "Newline": {
653
+ current.before.push(token);
654
+
655
+ // All whitespace and comments before the first newline or
656
+ // identifier belong to the `{`, not the first specifier.
657
+ if (result.before.length === 0 && result.items.length === 0) {
658
+ result.before = current.before;
659
+ current = makeEmptyItem();
660
+ }
661
+ break;
662
+ }
663
+
664
+ case "Spaces":
665
+ case "Block":
666
+ case "Line": {
667
+ current.before.push(token);
668
+ break;
669
+ }
670
+
671
+ // We’ve reached an identifier.
672
+ default: {
673
+ // All whitespace and comments before the first newline or
674
+ // identifier belong to the `{`, not the first specifier.
675
+ if (result.before.length === 0 && result.items.length === 0) {
676
+ result.before = current.before;
677
+ current = makeEmptyItem();
678
+ }
679
+
680
+ current.state = "specifier";
681
+ current.specifier.push(token);
682
+ }
683
+ }
684
+ break;
685
+ }
686
+
687
+ case "specifier": {
688
+ switch (token.type) {
689
+ case "Punctuator": {
690
+ // There can only be comma punctuators, but future-proof by checking.
691
+ // istanbul ignore else
692
+ if (isPunctuator(token, ",")) {
693
+ current.hadComma = true;
694
+ current.state = "after";
695
+ } else {
696
+ current.specifier.push(token);
697
+ }
698
+ break;
699
+ }
700
+
701
+ // When consuming the specifier part, we eat every token until a comma
702
+ // or to the end, basically.
703
+ default: {
704
+ current.specifier.push(token);
705
+ }
706
+ }
707
+ break;
708
+ }
709
+
710
+ case "after": {
711
+ switch (token.type) {
712
+ // Only whitespace and comments after a specifier that are on the same
713
+ // belong to the specifier.
714
+ case "Newline": {
715
+ current.after.push(token);
716
+ result.items.push(current);
717
+ current = makeEmptyItem();
718
+ break;
719
+ }
720
+
721
+ case "Spaces":
722
+ case "Line": {
723
+ current.after.push(token);
724
+ break;
725
+ }
726
+
727
+ case "Block": {
728
+ // Multiline block comments belong to the next specifier.
729
+ if (hasNewline(token.code)) {
730
+ result.items.push(current);
731
+ current = makeEmptyItem();
732
+ current.before.push(token);
733
+ } else {
734
+ current.after.push(token);
735
+ }
736
+ break;
737
+ }
738
+
739
+ // We’ve reached another specifier – time to process that one.
740
+ default: {
741
+ result.items.push(current);
742
+ current = makeEmptyItem();
743
+ current.state = "specifier";
744
+ current.specifier.push(token);
745
+ }
746
+ }
747
+ break;
748
+ }
749
+
750
+ // istanbul ignore next
751
+ default: {
752
+ throw new Error(`Unknown state: ${current.state}`);
753
+ }
754
+ }
755
+ }
756
+
757
+ // We’ve reached the end of the tokens. Handle what’s currently in `current`.
758
+ switch (current.state) {
759
+ // If the last specifier has a trailing comma and some of the remaining
760
+ // whitespace and comments are on the same line we end up here. If so we
761
+ // want to put that whitespace and comments in `result.after`.
762
+ case "before": {
763
+ result.after = current.before;
764
+ break;
765
+ }
766
+
767
+ // If the last specifier has no trailing comma we end up here. Move all
768
+ // trailing comments and whitespace from `.specifier` to `.after`, and
769
+ // comments and whitespace that don’t belong to the specifier to
770
+ // `result.after`. The last non-comment and non-whitespace token is usually
771
+ // an identifier, but in this case it’s a keyword:
772
+ //
773
+ // export { z, d as default } from "a"
774
+ case "specifier": {
775
+ const lastIdentifierIndex = findLastIndex(
776
+ current.specifier,
777
+ (token2) => isIdentifier(token2) || isKeyword(token2),
778
+ );
779
+
780
+ const specifier = current.specifier.slice(0, lastIdentifierIndex + 1);
781
+ const after = current.specifier.slice(lastIdentifierIndex + 1);
782
+
783
+ // If there’s a newline, put everything up to and including (hence the `+
784
+ // 1`) that newline in the specifiers’s `.after`.
785
+ const newlineIndexRaw = after.findIndex((token2) => isNewline(token2));
786
+ const newlineIndex = newlineIndexRaw === -1 ? -1 : newlineIndexRaw + 1;
787
+
788
+ // If there’s a multiline block comment, put everything _befor_ that
789
+ // comment in the specifiers’s `.after`.
790
+ const multilineBlockCommentIndex = after.findIndex(
791
+ (token2) => isBlockComment(token2) && hasNewline(token2.code),
792
+ );
793
+
794
+ const sliceIndex =
795
+ // If both a newline and a multiline block comment exists, choose the
796
+ // earlier one.
797
+ newlineIndex >= 0 && multilineBlockCommentIndex >= 0
798
+ ? Math.min(newlineIndex, multilineBlockCommentIndex)
799
+ : newlineIndex >= 0
800
+ ? newlineIndex
801
+ : multilineBlockCommentIndex >= 0
802
+ ? multilineBlockCommentIndex
803
+ : // If there are no newlines, move the last whitespace into `result.after`.
804
+ endsWithSpaces(after)
805
+ ? after.length - 1
806
+ : -1;
807
+
808
+ current.specifier = specifier;
809
+ current.after = sliceIndex === -1 ? after : after.slice(0, sliceIndex);
810
+ result.items.push(current);
811
+ result.after = sliceIndex === -1 ? [] : after.slice(sliceIndex);
812
+
813
+ break;
814
+ }
815
+
816
+ // If the last specifier has a trailing comma and all remaining whitespace
817
+ // and comments are on the same line we end up here. If so we want to move
818
+ // the final whitespace to `result.after`.
819
+ case "after": {
820
+ if (endsWithSpaces(current.after)) {
821
+ const last = current.after.pop();
822
+ result.after = [last];
823
+ }
824
+ result.items.push(current);
825
+ break;
826
+ }
827
+
828
+ // istanbul ignore next
829
+ default: {
830
+ throw new Error(`Unknown state: ${current.state}`);
831
+ }
832
+ }
833
+
834
+ return result;
835
+ }
836
+
837
+ // If a specifier item starts with a line comment or a singleline block comment
838
+ // it needs a newline before that. Otherwise that comment can end up belonging
839
+ // to the _previous_ specifier after sorting.
840
+ function needsStartingNewline(tokens) {
841
+ const before = tokens.filter((token) => !isSpaces(token));
842
+
843
+ if (before.length === 0) {
844
+ return false;
845
+ }
846
+
847
+ const firstToken = before[0];
848
+
849
+ return (
850
+ isLineComment(firstToken) ||
851
+ (isBlockComment(firstToken) && !hasNewline(firstToken.code))
852
+ );
853
+ }
854
+
855
+ function endsWithSpaces(tokens) {
856
+ const last = tokens.length > 0 ? tokens[tokens.length - 1] : undefined;
857
+
858
+ return last == null ? false : isSpaces(last);
859
+ }
860
+
861
+ module.exports = {
862
+ extractChunks,
863
+ flatMap,
864
+ getImportExportItems,
865
+ isPunctuator,
866
+ maybeReportSorting,
867
+ printSortedItems,
868
+ printWithSortedSpecifiers,
869
+ sortImportExportItems,
870
+ };