@kongyo2/ts-comment-scanner 1.11.1 → 1.17.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/src/imports.ts ADDED
@@ -0,0 +1,145 @@
1
+ import ts from "typescript";
2
+ import { firstIndexAtOrAfter, type Range } from "./ranges.js";
3
+
4
+ /**
5
+ * The gap in front of an import or export declaration that an import sorter
6
+ * reads to tell whether the declaration starts a new group, which it sorts
7
+ * and merges apart from the group before it: the declaration's leading
8
+ * trivia, from the end of the token before it to its first token.
9
+ */
10
+ export interface ImportGroupGap extends Range {
11
+ /** The sorters that start a new group at the declaration after the gap. */
12
+ splits: Array<"typescript" | "dprint">;
13
+ }
14
+
15
+ /**
16
+ * The gaps the import sorters read, in document order — one for every
17
+ * declaration past the first of a run a sorter sorts, so that the same
18
+ * declarations have gaps however the comments around them change:
19
+ *
20
+ * - TypeScript's organizeImports (`groupByNewlineContiguous` in tsc 6 and in
21
+ * tsc 7's port; tsserver and VS Code, prettier-plugin-organize-imports)
22
+ * sorts the import declarations of the file, and those of each ambient
23
+ * module, across whatever stands between them, and the file's export
24
+ * declarations in the runs of exportRuns. A declaration starts a group
25
+ * when its leading trivia holds two line breaks outside comments: `\n`,
26
+ * `\r` or `\r\n`, its scanner's NewLineTrivia — U+2028 and U+2029 are
27
+ * skipped as whitespace.
28
+ * - dprint's TypeScript plugin (`module.sortImportDeclarations` and
29
+ * `sortExportDeclarations`, on by default; `get_stmt_groups`) sorts runs of
30
+ * adjacent top-level declarations of one kind, imports with specifiers or
31
+ * `export … from`s, and starts a group where a declaration starts two or
32
+ * more lines below the end of the one before it, counting line feeds alone.
33
+ * A declaration a `dprint-ignore` comment exempts ends dprint's run, and
34
+ * stays in it here, which only reads more gaps. `deno fmt`, which runs the
35
+ * plugin, keeps the order.
36
+ */
37
+ export function importGroupGaps(
38
+ source: string,
39
+ sourceFile: ts.SourceFile,
40
+ comments: readonly Range[],
41
+ ): ImportGroupGap[] {
42
+ const readers = new Map<ts.Statement, Set<"typescript" | "dprint">>();
43
+ const read = (declaration: ts.Statement, sorter: "typescript" | "dprint"): void => {
44
+ const sorters = readers.get(declaration) ?? new Set();
45
+ sorters.add(sorter);
46
+ readers.set(declaration, sorters);
47
+ };
48
+ for (const statements of [sourceFile.statements, ...ambientModuleBodies(sourceFile)]) {
49
+ for (const declaration of statements.filter(ts.isImportDeclaration).slice(1)) read(declaration, "typescript");
50
+ }
51
+ for (const run of exportRuns(sourceFile.statements)) {
52
+ for (const declaration of run.slice(1)) read(declaration, "typescript");
53
+ }
54
+ for (const [index, statement] of sourceFile.statements.entries()) {
55
+ const kind = dprintKind(statement);
56
+ if (index > 0 && kind !== undefined && dprintKind(sourceFile.statements[index - 1] as ts.Statement) === kind) {
57
+ read(statement, "dprint");
58
+ }
59
+ }
60
+ return [...readers]
61
+ .sort(([a], [b]) => a.pos - b.pos)
62
+ .map(([declaration, sorters]) => {
63
+ const gap = { start: declaration.pos, end: declaration.getStart(sourceFile) };
64
+ const splits = [...sorters].filter((sorter) =>
65
+ sorter === "typescript"
66
+ ? newLineTrivia(source, gap, comments) >= 2
67
+ : source.slice(gap.start, gap.end).split("\n").length > 2,
68
+ );
69
+ return { ...gap, splits };
70
+ });
71
+ }
72
+
73
+ /**
74
+ * The statements of the ambient modules (`declare module "m" { … }`,
75
+ * `declare global { … }`) at the top of the file, whose imports
76
+ * organizeImports sorts too; it leaves their exports in one run.
77
+ */
78
+ function ambientModuleBodies(sourceFile: ts.SourceFile): Array<ts.NodeArray<ts.Statement>> {
79
+ return sourceFile.statements.flatMap((statement) =>
80
+ ts.isModuleDeclaration(statement) &&
81
+ statement.body !== undefined &&
82
+ (ts.isStringLiteral(statement.name) || (statement.flags & ts.NodeFlags.GlobalAugmentation) !== 0)
83
+ ? [(statement.body as ts.ModuleBlock).statements]
84
+ : [],
85
+ );
86
+ }
87
+
88
+ /**
89
+ * The runs of top-level export declarations that tsc 6's organizeImports
90
+ * sorts (`getTopLevelExportGroups`): `export … from`s join the run across
91
+ * the statements between them, and a local `export { … }` takes the export
92
+ * declarations right after it into the run and ends it. tsc 7 also ends a run
93
+ * at any other statement, so its runs divide these and it reads no gap tsc 6
94
+ * does not.
95
+ */
96
+ function exportRuns(statements: readonly ts.Statement[]): ts.ExportDeclaration[][] {
97
+ const runs: ts.ExportDeclaration[][] = [];
98
+ let run: ts.ExportDeclaration[] = [];
99
+ let ending = false;
100
+ for (const statement of statements) {
101
+ if (ts.isExportDeclaration(statement)) {
102
+ run.push(statement);
103
+ ending ||= statement.moduleSpecifier === undefined;
104
+ } else if (ending) {
105
+ runs.push(run);
106
+ run = [];
107
+ ending = false;
108
+ }
109
+ }
110
+ runs.push(run);
111
+ return runs;
112
+ }
113
+
114
+ /** What dprint sorts the statement among: imports with specifiers, `export … from`s, or neither. */
115
+ function dprintKind(statement: ts.Statement): "imports" | "exports" | undefined {
116
+ if (ts.isImportDeclaration(statement)) {
117
+ const clause = statement.importClause;
118
+ const bindings = clause?.namedBindings;
119
+ const specified =
120
+ clause?.name !== undefined ||
121
+ (bindings !== undefined && (ts.isNamespaceImport(bindings) || bindings.elements.length > 0));
122
+ return specified ? "imports" : undefined;
123
+ }
124
+ return ts.isExportDeclaration(statement) && statement.moduleSpecifier !== undefined ? "exports" : undefined;
125
+ }
126
+
127
+ /** The line breaks TypeScript's scanner reads as NewLineTrivia in the gap, past its (sorted) comments. */
128
+ function newLineTrivia(source: string, gap: Range, comments: readonly Range[]): number {
129
+ let count = 0;
130
+ let from = gap.start;
131
+ for (
132
+ let index = firstIndexAtOrAfter(comments, gap.start, (comment) => comment.start);
133
+ (comments[index]?.start ?? gap.end) < gap.end;
134
+ index += 1
135
+ ) {
136
+ const comment = comments[index] as Range;
137
+ count += lineBreaks(source.slice(from, comment.start));
138
+ from = comment.end;
139
+ }
140
+ return count + lineBreaks(source.slice(from, gap.end));
141
+ }
142
+
143
+ function lineBreaks(text: string): number {
144
+ return text.match(/\r\n?|\n/g)?.length ?? 0;
145
+ }