@tai-kun/vp-lint-plugins 0.0.3 → 0.0.4

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.
@@ -10,6 +10,7 @@ export { default as jsdocParamOrder } from "./rules/jsdoc-param-order.js";
10
10
  export { default as jsdocTagLines } from "./rules/jsdoc-tag-lines.js";
11
11
  export { default as jsdocTagOrder } from "./rules/jsdoc-tag-order.js";
12
12
  export { default as memberOrdering } from "./rules/member-ordering.js";
13
+ export { default as mergeImports } from "./rules/merge-imports.js";
13
14
  export { default as objectPropertiesNewline } from "./rules/object-properties-newline.js";
14
15
  export { default as overloadSignaturesAdjacent } from "./rules/overload-signatures-adjacent.js";
15
16
  export { default as sortImportExportSpecifiers } from "./rules/sort-import-export-specifiers.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAClG,OAAO,EAAE,OAAO,IAAI,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AAC/F,OAAO,EAAE,OAAO,IAAI,iCAAiC,EAAE,MAAM,kDAAkD,CAAC;AAChH,OAAO,EAAE,OAAO,IAAI,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AACvF,OAAO,EAAE,OAAO,IAAI,4BAA4B,EAAE,MAAM,6CAA6C,CAAC;AACtG,OAAO,EAAE,OAAO,IAAI,2BAA2B,EAAE,MAAM,4CAA4C,CAAC;AACpG,OAAO,EAAE,OAAO,IAAI,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AACxF,OAAO,EAAE,OAAO,IAAI,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AAChG,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,OAAO,IAAI,uBAAuB,EAAE,MAAM,sCAAsC,CAAC;AAC1F,OAAO,EAAE,OAAO,IAAI,0BAA0B,EAAE,MAAM,yCAAyC,CAAC;AAChG,OAAO,EAAE,OAAO,IAAI,0BAA0B,EAAE,MAAM,0CAA0C,CAAC;AACjG,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EAAE,OAAO,IAAI,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AACpF,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,OAAO,IAAI,4BAA4B,EAAE,MAAM,4CAA4C,CAAC;AAErG,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAClG,OAAO,EAAE,OAAO,IAAI,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AAC/F,OAAO,EAAE,OAAO,IAAI,iCAAiC,EAAE,MAAM,kDAAkD,CAAC;AAChH,OAAO,EAAE,OAAO,IAAI,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AACvF,OAAO,EAAE,OAAO,IAAI,4BAA4B,EAAE,MAAM,6CAA6C,CAAC;AACtG,OAAO,EAAE,OAAO,IAAI,2BAA2B,EAAE,MAAM,4CAA4C,CAAC;AACpG,OAAO,EAAE,OAAO,IAAI,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AACxF,OAAO,EAAE,OAAO,IAAI,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AAChG,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,EAAE,OAAO,IAAI,uBAAuB,EAAE,MAAM,sCAAsC,CAAC;AAC1F,OAAO,EAAE,OAAO,IAAI,0BAA0B,EAAE,MAAM,yCAAyC,CAAC;AAChG,OAAO,EAAE,OAAO,IAAI,0BAA0B,EAAE,MAAM,0CAA0C,CAAC;AACjG,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EAAE,OAAO,IAAI,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AACpF,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,OAAO,IAAI,4BAA4B,EAAE,MAAM,4CAA4C,CAAC;AAErG,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC"}
package/dist/src/index.js CHANGED
@@ -10,6 +10,7 @@ export { default as jsdocParamOrder } from "./rules/jsdoc-param-order.js";
10
10
  export { default as jsdocTagLines } from "./rules/jsdoc-tag-lines.js";
11
11
  export { default as jsdocTagOrder } from "./rules/jsdoc-tag-order.js";
12
12
  export { default as memberOrdering } from "./rules/member-ordering.js";
13
+ export { default as mergeImports } from "./rules/merge-imports.js";
13
14
  export { default as objectPropertiesNewline } from "./rules/object-properties-newline.js";
14
15
  export { default as overloadSignaturesAdjacent } from "./rules/overload-signatures-adjacent.js";
15
16
  export { default as sortImportExportSpecifiers } from "./rules/sort-import-export-specifiers.js";
@@ -11,6 +11,7 @@ import jsdocParamOrder from "./rules/jsdoc-param-order.js";
11
11
  import jsdocTagLines from "./rules/jsdoc-tag-lines.js";
12
12
  import jsdocTagOrder from "./rules/jsdoc-tag-order.js";
13
13
  import memberOrdering from "./rules/member-ordering.js";
14
+ import mergeImports from "./rules/merge-imports.js";
14
15
  import objectPropertiesNewline from "./rules/object-properties-newline.js";
15
16
  import overloadSignaturesAdjacent from "./rules/overload-signatures-adjacent.js";
16
17
  import sortImportExportSpecifiers from "./rules/sort-import-export-specifiers.js";
@@ -22,6 +23,7 @@ import typeLiteralPropertiesNewline from "./rules/type-literal-properties-newlin
22
23
  export default definePlugin({
23
24
  meta: { name: "tai-kun" },
24
25
  rules: {
26
+ "merge-imports": mergeImports,
25
27
  "sort-jsx-props": sortJsxProps,
26
28
  "spaced-comment": spacedComment,
27
29
  "jsdoc-tag-lines": jsdocTagLines,
@@ -0,0 +1,8 @@
1
+ /**
2
+ * 同じモジュールを指す連続した import 宣言を 1 つにまとめます。
3
+ *
4
+ * 別名の default import、namespace import、副作用だけの import、属性が異なる import は安全にまとめられないため対象外にします。コメントが specifier の外側にある場合も、コメントを失わないように対象外にします。
5
+ */
6
+ declare const mergeImports: import("vite-plus/lint/plugins").Rule;
7
+ export default mergeImports;
8
+ //# sourceMappingURL=merge-imports.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"merge-imports.d.ts","sourceRoot":"","sources":["../../../src/rules/merge-imports.ts"],"names":[],"mappings":"AAgOA;;;;GAIG;AACH,QAAA,MAAM,YAAY,uCAqEhB,CAAC;eAEY,YAAY"}
@@ -0,0 +1,199 @@
1
+ import { defineRule } from "vite-plus/lint/plugins";
2
+ function getModuleName(node) {
3
+ return node.source.value;
4
+ }
5
+ function getAttributeKey(attribute) {
6
+ const key = attribute.key.type === "Identifier" ? attribute.key.name : attribute.key.value;
7
+ return `${key}:${attribute.value.value}`;
8
+ }
9
+ function getAttributesKey(node) {
10
+ return node.attributes.map(getAttributeKey).join(",");
11
+ }
12
+ function getLineIndent(source, offset) {
13
+ const lineStart = source.lastIndexOf("\n", offset) + 1;
14
+ const match = /^[ \t]*/u.exec(source.slice(lineStart, offset));
15
+ return match?.[0] ?? "";
16
+ }
17
+ function isMergeableDeclaration(node) {
18
+ return (node.type === "ImportDeclaration" &&
19
+ node.phase === null &&
20
+ node.specifiers.length > 0 &&
21
+ node.specifiers.every((specifier) => specifier.type !== "ImportNamespaceSpecifier"));
22
+ }
23
+ function hasUnsafeComment(declarations, comments) {
24
+ const first = declarations[0];
25
+ const last = declarations.at(-1);
26
+ if (first === undefined || last === undefined) {
27
+ return true;
28
+ }
29
+ const specifierRanges = declarations.flatMap((declaration) => declaration.specifiers.map((specifier) => specifier.range));
30
+ return comments.some((comment) => comment.range[0] >= first.range[0] &&
31
+ comment.range[1] <= last.range[1] &&
32
+ !specifierRanges.some((range) => comment.range[0] >= range[0] && comment.range[1] <= range[1]));
33
+ }
34
+ function buildNamedClause(declarations, specifiers, sourceCode) {
35
+ const texts = specifiers.map((specifier) => specifier.text);
36
+ const multiline = declarations.find((declaration) => {
37
+ const firstSpecifier = declaration.specifiers.find((specifier) => specifier.type === "ImportSpecifier");
38
+ return (firstSpecifier !== undefined && firstSpecifier.loc.start.line > declaration.loc.start.line);
39
+ });
40
+ if (multiline === undefined) {
41
+ return `{ ${texts.join(", ")} }`;
42
+ }
43
+ const firstNamed = multiline.specifiers.find((specifier) => specifier.type === "ImportSpecifier");
44
+ const lastNamed = multiline.specifiers.findLast((specifier) => specifier.type === "ImportSpecifier");
45
+ const firstDeclaration = declarations[0];
46
+ if (firstNamed === undefined || lastNamed === undefined || firstDeclaration === undefined) {
47
+ return `{ ${texts.join(", ")} }`;
48
+ }
49
+ const indent = getLineIndent(sourceCode.text, firstNamed.range[0]);
50
+ const closingIndent = getLineIndent(sourceCode.text, firstDeclaration.range[0]);
51
+ const beforeSource = sourceCode.text.slice(lastNamed.range[1], multiline.source.range[0]);
52
+ const trailingComma = /,\s*\}/u.test(beforeSource);
53
+ return `{\n${indent}${texts.join(`,\n${indent}`)}${trailingComma ? "," : ""}\n${closingIndent}}`;
54
+ }
55
+ function buildReplacement(declarations, sourceCode) {
56
+ const first = declarations[0];
57
+ if (first === undefined) {
58
+ return null;
59
+ }
60
+ const defaultSpecifiers = declarations.flatMap((declaration) => declaration.specifiers
61
+ .filter((specifier) => specifier.type === "ImportDefaultSpecifier")
62
+ .map((specifier) => ({
63
+ local: specifier.local.name,
64
+ typeOnly: declaration.importKind === "type",
65
+ })));
66
+ const hasNamed = declarations.some((declaration) => declaration.specifiers.some((specifier) => specifier.type === "ImportSpecifier"));
67
+ let defaultSpecifier = null;
68
+ for (const specifier of defaultSpecifiers) {
69
+ if (defaultSpecifier === null) {
70
+ defaultSpecifier = specifier;
71
+ continue;
72
+ }
73
+ // default import は 1 つしか置けないため、別名の default import はまとめられません。
74
+ if (defaultSpecifier.local !== specifier.local ||
75
+ defaultSpecifier.typeOnly !== specifier.typeOnly) {
76
+ return null;
77
+ }
78
+ }
79
+ const allTypeOnly = declarations.every((declaration) => declaration.importKind === "type");
80
+ // `import type Foo, { Bar }` は書けないため、default と名前付きを併存させる場合は `type default as Foo` を使う通常の import に変換します。
81
+ const useTypeOnlyDeclaration = allTypeOnly && !(defaultSpecifier !== null && hasNamed);
82
+ const namedByLocal = new Map();
83
+ const named = [];
84
+ function addNamed(local, text) {
85
+ const existing = namedByLocal.get(local);
86
+ if (existing !== undefined) {
87
+ return existing === text;
88
+ }
89
+ namedByLocal.set(local, text);
90
+ named.push({
91
+ text,
92
+ local,
93
+ });
94
+ return true;
95
+ }
96
+ let defaultClause = null;
97
+ if (defaultSpecifier !== null) {
98
+ if (useTypeOnlyDeclaration || !defaultSpecifier.typeOnly) {
99
+ defaultClause = defaultSpecifier.local;
100
+ }
101
+ else if (!addNamed(defaultSpecifier.local, `type default as ${defaultSpecifier.local}`)) {
102
+ return null;
103
+ }
104
+ }
105
+ for (const declaration of declarations) {
106
+ const forceType = !useTypeOnlyDeclaration && declaration.importKind === "type";
107
+ for (const specifier of declaration.specifiers) {
108
+ if (specifier.type !== "ImportSpecifier") {
109
+ continue;
110
+ }
111
+ const original = sourceCode.getText(specifier);
112
+ const text = forceType && specifier.importKind !== "type" ? `type ${original}` : original;
113
+ if (!addNamed(specifier.local.name, text)) {
114
+ return null;
115
+ }
116
+ }
117
+ }
118
+ if (defaultClause !== null && namedByLocal.has(defaultClause)) {
119
+ return null;
120
+ }
121
+ const bindings = [];
122
+ if (defaultClause !== null) {
123
+ bindings.push(defaultClause);
124
+ }
125
+ if (named.length > 0) {
126
+ bindings.push(buildNamedClause(declarations, named, sourceCode));
127
+ }
128
+ if (bindings.length === 0) {
129
+ return null;
130
+ }
131
+ const sourceText = sourceCode.getText(first.source);
132
+ // `with { ... }` や `assert { ... }`、セミコロンの有無を元の宣言から引き継ぎます。
133
+ const suffix = sourceCode.text.slice(first.source.range[1], first.range[1]);
134
+ return `import ${useTypeOnlyDeclaration ? "type " : ""}${bindings.join(", ")} from ${sourceText}${suffix}`;
135
+ }
136
+ /**
137
+ * 同じモジュールを指す連続した import 宣言を 1 つにまとめます。
138
+ *
139
+ * 別名の default import、namespace import、副作用だけの import、属性が異なる import は安全にまとめられないため対象外にします。コメントが specifier の外側にある場合も、コメントを失わないように対象外にします。
140
+ */
141
+ const mergeImports = defineRule({
142
+ meta: {
143
+ docs: {
144
+ description: "Merge consecutive import declarations that import from the same module.",
145
+ },
146
+ type: "layout",
147
+ fixable: "whitespace",
148
+ messages: {
149
+ merge: "Import declarations from the same module must be merged.",
150
+ },
151
+ },
152
+ create(context) {
153
+ const sourceCode = context.sourceCode;
154
+ return {
155
+ Program(node) {
156
+ const comments = sourceCode.getAllComments();
157
+ let index = 0;
158
+ while (index < node.body.length) {
159
+ const first = node.body[index];
160
+ if (first === undefined || !isMergeableDeclaration(first)) {
161
+ index += 1;
162
+ continue;
163
+ }
164
+ const declarations = [first];
165
+ let next = index + 1;
166
+ while (next < node.body.length) {
167
+ const candidate = node.body[next];
168
+ if (candidate === undefined ||
169
+ !isMergeableDeclaration(candidate) ||
170
+ getModuleName(candidate) !== getModuleName(first) ||
171
+ getAttributesKey(candidate) !== getAttributesKey(first)) {
172
+ break;
173
+ }
174
+ declarations.push(candidate);
175
+ next += 1;
176
+ }
177
+ if (declarations.length > 1 && !hasUnsafeComment(declarations, comments)) {
178
+ const replacement = buildReplacement(declarations, sourceCode);
179
+ const last = declarations.at(-1);
180
+ if (replacement !== null && last !== undefined) {
181
+ context.report({
182
+ fix(fixer) {
183
+ return [
184
+ fixer.replaceText(first, replacement),
185
+ fixer.removeRange([first.range[1], last.range[1]]),
186
+ ];
187
+ },
188
+ node: first,
189
+ messageId: "merge",
190
+ });
191
+ }
192
+ }
193
+ index = next;
194
+ }
195
+ },
196
+ };
197
+ },
198
+ });
199
+ export default mergeImports;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tai-kun/vp-lint-plugins",
3
- "version": "0.0.3",
3
+ "version": "0.0.4",
4
4
  "description": "",
5
5
  "homepage": "https://tai-kun.github.io/vp-lint-plugins/",
6
6
  "license": "MIT",
package/src/index.ts CHANGED
@@ -10,6 +10,7 @@ export { default as jsdocParamOrder } from "./rules/jsdoc-param-order.js";
10
10
  export { default as jsdocTagLines } from "./rules/jsdoc-tag-lines.js";
11
11
  export { default as jsdocTagOrder } from "./rules/jsdoc-tag-order.js";
12
12
  export { default as memberOrdering } from "./rules/member-ordering.js";
13
+ export { default as mergeImports } from "./rules/merge-imports.js";
13
14
  export { default as objectPropertiesNewline } from "./rules/object-properties-newline.js";
14
15
  export { default as overloadSignaturesAdjacent } from "./rules/overload-signatures-adjacent.js";
15
16
  export { default as sortImportExportSpecifiers } from "./rules/sort-import-export-specifiers.js";
package/src/plugin.ts CHANGED
@@ -12,6 +12,7 @@ import jsdocParamOrder from "./rules/jsdoc-param-order.js";
12
12
  import jsdocTagLines from "./rules/jsdoc-tag-lines.js";
13
13
  import jsdocTagOrder from "./rules/jsdoc-tag-order.js";
14
14
  import memberOrdering from "./rules/member-ordering.js";
15
+ import mergeImports from "./rules/merge-imports.js";
15
16
  import objectPropertiesNewline from "./rules/object-properties-newline.js";
16
17
  import overloadSignaturesAdjacent from "./rules/overload-signatures-adjacent.js";
17
18
  import sortImportExportSpecifiers from "./rules/sort-import-export-specifiers.js";
@@ -24,6 +25,7 @@ import typeLiteralPropertiesNewline from "./rules/type-literal-properties-newlin
24
25
  export default definePlugin({
25
26
  meta: { name: "tai-kun" },
26
27
  rules: {
28
+ "merge-imports": mergeImports,
27
29
  "sort-jsx-props": sortJsxProps,
28
30
  "spaced-comment": spacedComment,
29
31
  "jsdoc-tag-lines": jsdocTagLines,
@@ -0,0 +1,301 @@
1
+ import { defineRule } from "vite-plus/lint/plugins";
2
+ import type { ESTree, Comment, SourceCode } from "vite-plus/lint/plugins";
3
+
4
+ interface NamedSpecifier {
5
+ local: string;
6
+ text: string;
7
+ }
8
+
9
+ function getModuleName(node: ESTree.ImportDeclaration): string {
10
+ return node.source.value;
11
+ }
12
+
13
+ function getAttributeKey(attribute: ESTree.ImportAttribute): string {
14
+ const key = attribute.key.type === "Identifier" ? attribute.key.name : attribute.key.value;
15
+
16
+ return `${key}:${attribute.value.value}`;
17
+ }
18
+
19
+ function getAttributesKey(node: ESTree.ImportDeclaration): string {
20
+ return node.attributes.map(getAttributeKey).join(",");
21
+ }
22
+
23
+ function getLineIndent(source: string, offset: number): string {
24
+ const lineStart = source.lastIndexOf("\n", offset) + 1;
25
+ const match = /^[ \t]*/u.exec(source.slice(lineStart, offset));
26
+
27
+ return match?.[0] ?? "";
28
+ }
29
+
30
+ function isMergeableDeclaration(node: ESTree.Node): node is ESTree.ImportDeclaration {
31
+ return (
32
+ node.type === "ImportDeclaration" &&
33
+ node.phase === null &&
34
+ node.specifiers.length > 0 &&
35
+ node.specifiers.every((specifier) => specifier.type !== "ImportNamespaceSpecifier")
36
+ );
37
+ }
38
+
39
+ function hasUnsafeComment(
40
+ declarations: readonly ESTree.ImportDeclaration[],
41
+ comments: readonly Comment[],
42
+ ): boolean {
43
+ const first = declarations[0];
44
+ const last = declarations.at(-1);
45
+
46
+ if (first === undefined || last === undefined) {
47
+ return true;
48
+ }
49
+
50
+ const specifierRanges = declarations.flatMap((declaration) =>
51
+ declaration.specifiers.map((specifier) => specifier.range),
52
+ );
53
+
54
+ return comments.some(
55
+ (comment) =>
56
+ comment.range[0] >= first.range[0] &&
57
+ comment.range[1] <= last.range[1] &&
58
+ !specifierRanges.some(
59
+ (range) => comment.range[0] >= range[0] && comment.range[1] <= range[1],
60
+ ),
61
+ );
62
+ }
63
+
64
+ function buildNamedClause(
65
+ declarations: readonly ESTree.ImportDeclaration[],
66
+ specifiers: readonly NamedSpecifier[],
67
+ sourceCode: SourceCode,
68
+ ): string {
69
+ const texts = specifiers.map((specifier) => specifier.text);
70
+ const multiline = declarations.find((declaration) => {
71
+ const firstSpecifier = declaration.specifiers.find(
72
+ (specifier): specifier is ESTree.ImportSpecifier => specifier.type === "ImportSpecifier",
73
+ );
74
+
75
+ return (
76
+ firstSpecifier !== undefined && firstSpecifier.loc.start.line > declaration.loc.start.line
77
+ );
78
+ });
79
+
80
+ if (multiline === undefined) {
81
+ return `{ ${texts.join(", ")} }`;
82
+ }
83
+
84
+ const firstNamed = multiline.specifiers.find(
85
+ (specifier): specifier is ESTree.ImportSpecifier => specifier.type === "ImportSpecifier",
86
+ );
87
+ const lastNamed = multiline.specifiers.findLast(
88
+ (specifier): specifier is ESTree.ImportSpecifier => specifier.type === "ImportSpecifier",
89
+ );
90
+ const firstDeclaration = declarations[0];
91
+
92
+ if (firstNamed === undefined || lastNamed === undefined || firstDeclaration === undefined) {
93
+ return `{ ${texts.join(", ")} }`;
94
+ }
95
+
96
+ const indent = getLineIndent(sourceCode.text, firstNamed.range[0]);
97
+ const closingIndent = getLineIndent(sourceCode.text, firstDeclaration.range[0]);
98
+ const beforeSource = sourceCode.text.slice(lastNamed.range[1], multiline.source.range[0]);
99
+ const trailingComma = /,\s*\}/u.test(beforeSource);
100
+
101
+ return `{\n${indent}${texts.join(`,\n${indent}`)}${trailingComma ? "," : ""}\n${closingIndent}}`;
102
+ }
103
+
104
+ function buildReplacement(
105
+ declarations: readonly ESTree.ImportDeclaration[],
106
+ sourceCode: SourceCode,
107
+ ): string | null {
108
+ const first = declarations[0];
109
+
110
+ if (first === undefined) {
111
+ return null;
112
+ }
113
+
114
+ const defaultSpecifiers = declarations.flatMap((declaration) =>
115
+ declaration.specifiers
116
+ .filter(
117
+ (specifier): specifier is ESTree.ImportDefaultSpecifier =>
118
+ specifier.type === "ImportDefaultSpecifier",
119
+ )
120
+ .map((specifier) => ({
121
+ local: specifier.local.name,
122
+ typeOnly: declaration.importKind === "type",
123
+ })),
124
+ );
125
+ const hasNamed = declarations.some((declaration) =>
126
+ declaration.specifiers.some((specifier) => specifier.type === "ImportSpecifier"),
127
+ );
128
+
129
+ let defaultSpecifier: {
130
+ local: string;
131
+ typeOnly: boolean;
132
+ } | null = null;
133
+
134
+ for (const specifier of defaultSpecifiers) {
135
+ if (defaultSpecifier === null) {
136
+ defaultSpecifier = specifier;
137
+ continue;
138
+ }
139
+
140
+ // default import は 1 つしか置けないため、別名の default import はまとめられません。
141
+ if (
142
+ defaultSpecifier.local !== specifier.local ||
143
+ defaultSpecifier.typeOnly !== specifier.typeOnly
144
+ ) {
145
+ return null;
146
+ }
147
+ }
148
+
149
+ const allTypeOnly = declarations.every((declaration) => declaration.importKind === "type");
150
+ // `import type Foo, { Bar }` は書けないため、default と名前付きを併存させる場合は `type default as Foo` を使う通常の import に変換します。
151
+ const useTypeOnlyDeclaration = allTypeOnly && !(defaultSpecifier !== null && hasNamed);
152
+ const namedByLocal = new Map<string, string>();
153
+ const named: NamedSpecifier[] = [];
154
+
155
+ function addNamed(local: string, text: string): boolean {
156
+ const existing = namedByLocal.get(local);
157
+
158
+ if (existing !== undefined) {
159
+ return existing === text;
160
+ }
161
+
162
+ namedByLocal.set(local, text);
163
+ named.push({
164
+ text,
165
+ local,
166
+ });
167
+
168
+ return true;
169
+ }
170
+
171
+ let defaultClause: string | null = null;
172
+
173
+ if (defaultSpecifier !== null) {
174
+ if (useTypeOnlyDeclaration || !defaultSpecifier.typeOnly) {
175
+ defaultClause = defaultSpecifier.local;
176
+ } else if (!addNamed(defaultSpecifier.local, `type default as ${defaultSpecifier.local}`)) {
177
+ return null;
178
+ }
179
+ }
180
+
181
+ for (const declaration of declarations) {
182
+ const forceType = !useTypeOnlyDeclaration && declaration.importKind === "type";
183
+
184
+ for (const specifier of declaration.specifiers) {
185
+ if (specifier.type !== "ImportSpecifier") {
186
+ continue;
187
+ }
188
+
189
+ const original = sourceCode.getText(specifier);
190
+ const text = forceType && specifier.importKind !== "type" ? `type ${original}` : original;
191
+
192
+ if (!addNamed(specifier.local.name, text)) {
193
+ return null;
194
+ }
195
+ }
196
+ }
197
+
198
+ if (defaultClause !== null && namedByLocal.has(defaultClause)) {
199
+ return null;
200
+ }
201
+
202
+ const bindings: string[] = [];
203
+
204
+ if (defaultClause !== null) {
205
+ bindings.push(defaultClause);
206
+ }
207
+
208
+ if (named.length > 0) {
209
+ bindings.push(buildNamedClause(declarations, named, sourceCode));
210
+ }
211
+
212
+ if (bindings.length === 0) {
213
+ return null;
214
+ }
215
+
216
+ const sourceText = sourceCode.getText(first.source);
217
+ // `with { ... }` や `assert { ... }`、セミコロンの有無を元の宣言から引き継ぎます。
218
+ const suffix = sourceCode.text.slice(first.source.range[1], first.range[1]);
219
+
220
+ return `import ${useTypeOnlyDeclaration ? "type " : ""}${bindings.join(
221
+ ", ",
222
+ )} from ${sourceText}${suffix}`;
223
+ }
224
+
225
+ /**
226
+ * 同じモジュールを指す連続した import 宣言を 1 つにまとめます。
227
+ *
228
+ * 別名の default import、namespace import、副作用だけの import、属性が異なる import は安全にまとめられないため対象外にします。コメントが specifier の外側にある場合も、コメントを失わないように対象外にします。
229
+ */
230
+ const mergeImports = defineRule({
231
+ meta: {
232
+ docs: {
233
+ description: "Merge consecutive import declarations that import from the same module.",
234
+ },
235
+ type: "layout",
236
+ fixable: "whitespace",
237
+ messages: {
238
+ merge: "Import declarations from the same module must be merged.",
239
+ },
240
+ },
241
+ create(context) {
242
+ const sourceCode = context.sourceCode;
243
+
244
+ return {
245
+ Program(node): void {
246
+ const comments = sourceCode.getAllComments();
247
+ let index = 0;
248
+
249
+ while (index < node.body.length) {
250
+ const first = node.body[index];
251
+
252
+ if (first === undefined || !isMergeableDeclaration(first)) {
253
+ index += 1;
254
+ continue;
255
+ }
256
+
257
+ const declarations = [first];
258
+ let next = index + 1;
259
+
260
+ while (next < node.body.length) {
261
+ const candidate = node.body[next];
262
+
263
+ if (
264
+ candidate === undefined ||
265
+ !isMergeableDeclaration(candidate) ||
266
+ getModuleName(candidate) !== getModuleName(first) ||
267
+ getAttributesKey(candidate) !== getAttributesKey(first)
268
+ ) {
269
+ break;
270
+ }
271
+
272
+ declarations.push(candidate);
273
+ next += 1;
274
+ }
275
+
276
+ if (declarations.length > 1 && !hasUnsafeComment(declarations, comments)) {
277
+ const replacement = buildReplacement(declarations, sourceCode);
278
+ const last = declarations.at(-1);
279
+
280
+ if (replacement !== null && last !== undefined) {
281
+ context.report({
282
+ fix(fixer) {
283
+ return [
284
+ fixer.replaceText(first, replacement),
285
+ fixer.removeRange([first.range[1], last.range[1]]),
286
+ ];
287
+ },
288
+ node: first,
289
+ messageId: "merge",
290
+ });
291
+ }
292
+ }
293
+
294
+ index = next;
295
+ }
296
+ },
297
+ };
298
+ },
299
+ });
300
+
301
+ export default mergeImports;