-
Notifications
You must be signed in to change notification settings - Fork 124
/
typescript-import-manager.ts
292 lines (269 loc) · 8.92 KB
/
typescript-import-manager.ts
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
import {assert} from "@protobuf-ts/runtime";
import * as ts from "typescript";
import * as path from "path";
import {GeneratedFile} from "./generated-file";
import {SymbolTable} from "./symbol-table";
import {AnyTypeDescriptorProto} from "./descriptor-info";
import {TypescriptFile} from "./typescript-file";
export class TypescriptImportManager {
private readonly file: GeneratedFile;
private readonly symbols: SymbolTable;
private readonly source: TypescriptFile;
constructor(generatedFile: GeneratedFile, symbols: SymbolTable, source: TypescriptFile) {
this.file = generatedFile;
this.symbols = symbols;
this.source = source;
}
/**
* Import {importName} from "importFrom";
*
* Automatically finds a free name if the
* `importName` would collide with another
* identifier.
*
* Returns imported name.
*/
name(importName: string, importFrom: string): string {
const blackListedNames = this.symbols.list(this.file).map(e => e.name);
return ensureNamedImportPresent(
this.source.getSourceFile(),
importName,
importFrom,
blackListedNames,
statementToAdd => this.source.addStatement(statementToAdd, true)
);
}
/**
* Import * as importAs from "importFrom";
*
* Returns name for `importAs`.
*/
namespace(importAs: string, importFrom: string): string {
return ensureNamespaceImportPresent(
this.source.getSourceFile(),
importAs,
importFrom,
statementToAdd => this.source.addStatement(statementToAdd, true)
);
}
/**
* Import a previously registered identifier for a message
* or other descriptor.
*
* Uses the symbol table to look for the type, adds an
* import statement if necessary and automatically finds a
* free name if the identifier would clash in this file.
*
* If you have multiple representations for a descriptor
* in your generated code, use `kind` to discriminate.
*/
type(descriptor: AnyTypeDescriptorProto, kind = 'default'): string {
const symbolReg = this.symbols.get(descriptor, kind);
// symbol in this file?
if (symbolReg.file === this.file) {
return symbolReg.name;
}
// symbol not in file
// add an import statement
const importPath = createRelativeImportPath(
this.source.getSourceFile().fileName,
symbolReg.file.getFilename()
);
const blackListedNames = this.symbols.list(this.file).map(e => e.name);
return ensureNamedImportPresent(
this.source.getSourceFile(),
symbolReg.name,
importPath,
blackListedNames,
statementToAdd => this.source.addStatement(statementToAdd, true)
);
}
}
/**
* Import * as asName from "importFrom";
*
* If the import is already present, just return the
* identifier.
*
* If the import is not present, create the import
* statement and call `addStatementFn`.
*
* Does *not* check for collisions.
*/
function ensureNamespaceImportPresent(
currentFile: ts.SourceFile,
asName: string,
importFrom: string,
addStatementFn: (statementToAdd: ts.ImportDeclaration) => void,
): string {
const
all = findNamespaceImports(currentFile),
match = all.find(ni => ni.as === asName && ni.from === importFrom);
if (match) {
return match.as;
}
const statementToAdd = createNamespaceImport(asName, importFrom);
addStatementFn(statementToAdd);
return asName;
}
/**
* import * as <asName> from "<importFrom>";
*/
function createNamespaceImport(asName: string, importFrom: string) {
return ts.createImportDeclaration(
undefined,
undefined,
ts.createImportClause(
undefined,
ts.createNamespaceImport(ts.createIdentifier(asName))
),
ts.createStringLiteral(importFrom)
);
}
/**
* import * as <as> from "<from>";
*/
function findNamespaceImports(sourceFile: ts.SourceFile): { as: string, from: string }[] {
let r: Array<{ as: string, from: string }> = [];
for (let s of sourceFile.statements) {
if (ts.isImportDeclaration(s) && s.importClause) {
let namedBindings = s.importClause.namedBindings;
if (namedBindings && ts.isNamespaceImport(namedBindings)) {
assert(ts.isStringLiteral(s.moduleSpecifier));
r.push({
as: namedBindings.name.escapedText.toString(),
from: s.moduleSpecifier.text
});
}
}
}
return r;
}
/**
* Import {importName} from "importFrom";
*
* If the import is already present, just return the
* identifier.
*
* If the import is not present, create the import
* statement and call `addStatementFn`.
*
* If the import name is taken by another named import
* or is in the list of blacklisted names, an
* alternative name is used:
*
* Import {importName as alternativeName} from "importFrom";
*
* Returns the imported name or the alternative name.
*/
function ensureNamedImportPresent(
currentFile: ts.SourceFile,
importName: string,
importFrom: string,
blacklistedNames: string[],
addStatementFn: (statementToAdd: ts.ImportDeclaration) => void,
escapeCharacter = '$'
): string {
const
all = findNamedImports(currentFile),
taken = all.map(ni => ni.as ?? ni.name).concat(blacklistedNames),
match = all.find(ni => ni.name === importName && ni.from === importFrom);
if (match) {
return match.as ?? match.name;
}
let as: string | undefined;
if (taken.includes(importName)) {
let i = 0;
as = importName;
while (taken.includes(as)) {
as = importName + escapeCharacter;
if (i++ > 0) {
as += i;
}
}
}
const statementToAdd = createNamedImport(importName, importFrom, as);
addStatementFn(statementToAdd);
return as ?? importName;
}
/**
* import {<name>} from '<from>';
* import {<name> as <as>} from '<from>';
*/
function createNamedImport(name: string, from: string, as?: string): ts.ImportDeclaration {
if (as) {
return ts.createImportDeclaration(
undefined,
undefined,
ts.createImportClause(
undefined,
ts.createNamedImports([ts.createImportSpecifier(
ts.createIdentifier(name),
ts.createIdentifier(as)
)]),
false
),
ts.createStringLiteral(from)
);
}
return ts.createImportDeclaration(
undefined,
undefined,
ts.createImportClause(
undefined,
ts.createNamedImports([
ts.createImportSpecifier(
undefined,
ts.createIdentifier(name)
)
])
),
ts.createStringLiteral(from)
);
}
/**
* import {<name>} from '<from>';
* import {<name> as <as>} from '<from>';
*/
function findNamedImports(sourceFile: ts.SourceFile): { name: string, as: string | undefined, from: string }[] {
let r: Array<{ name: string, as: string | undefined, from: string }> = [];
for (let s of sourceFile.statements) {
if (ts.isImportDeclaration(s) && s.importClause) {
let namedBindings = s.importClause.namedBindings;
if (namedBindings && ts.isNamedImports(namedBindings)) {
for (let importSpecifier of namedBindings.elements) {
assert(ts.isStringLiteral(s.moduleSpecifier));
if (importSpecifier.propertyName) {
r.push({
name: importSpecifier.propertyName.escapedText.toString(),
as: importSpecifier.name.escapedText.toString(),
from: s.moduleSpecifier.text
})
} else {
r.push({
name: importSpecifier.name.escapedText.toString(),
as: undefined,
from: s.moduleSpecifier.text
})
}
}
}
}
}
return r;
}
/**
* Create a relative path for an import statement like
* `import {Foo} from "./foo"`
*/
function createRelativeImportPath(currentPath: string, pathToImportFrom: string): string {
// create relative path to the file to import
let fromPath = path.relative(path.dirname(currentPath), pathToImportFrom);
// and drop file extension
fromPath = fromPath.replace(/\.[a-z]+$/, '');
// and make sure to start with './' to signal relative path to module resolution
if (!fromPath.startsWith('../') && !fromPath.startsWith('./')) {
fromPath = './' + fromPath;
}
return fromPath;
}