-
Notifications
You must be signed in to change notification settings - Fork 538
Expand file tree
/
Copy pathplugin-utils.ts
More file actions
459 lines (421 loc) · 12.1 KB
/
plugin-utils.ts
File metadata and controls
459 lines (421 loc) · 12.1 KB
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
import { head } from 'lodash';
import { isAbsolute, posix } from 'path';
import * as ts from 'typescript';
import { PluginOptions } from '../merge-options';
import {
getDecoratorName,
getText,
getTypeArguments,
isArray,
isBigInt,
isBoolean,
isEnum,
isInterface,
isNumber,
isString,
isStringLiteral,
isStringMapping
} from './ast-utils';
export function getDecoratorOrUndefinedByNames(
names: string[],
decorators: readonly ts.Decorator[],
factory: ts.NodeFactory
): ts.Decorator | undefined {
return (decorators || factory.createNodeArray()).find((item) => {
try {
const decoratorName = getDecoratorName(item);
return names.includes(decoratorName);
} catch {
return false;
}
});
}
export function getTypeReferenceAsString(
type: ts.Type,
typeChecker: ts.TypeChecker,
arrayDepth = 0
): {
typeName: string;
isArray?: boolean;
arrayDepth?: number;
} {
if (isArray(type)) {
const arrayType = getTypeArguments(type)[0];
const { typeName, arrayDepth: depth } = getTypeReferenceAsString(
arrayType,
typeChecker,
arrayDepth + 1
);
if (!typeName) {
return { typeName: undefined };
}
return {
typeName: `${typeName}`,
isArray: true,
arrayDepth: depth
};
}
if (isBoolean(type)) {
return { typeName: Boolean.name, arrayDepth };
}
if (isNumber(type)) {
return { typeName: Number.name, arrayDepth };
}
if (isBigInt(type)) {
return { typeName: BigInt.name, arrayDepth };
}
if (isString(type) || isStringLiteral(type) || isStringMapping(type)) {
return { typeName: String.name, arrayDepth };
}
if (isPromiseOrObservable(getText(type, typeChecker))) {
const typeArguments = getTypeArguments(type);
const elementType = getTypeReferenceAsString(
head(typeArguments),
typeChecker,
arrayDepth
);
return elementType;
}
if (type.isClass()) {
return { typeName: getText(type, typeChecker), arrayDepth };
}
try {
const text = getText(type, typeChecker);
if (text === Date.name) {
return { typeName: text, arrayDepth };
}
if (isOptionalBoolean(text)) {
return { typeName: Boolean.name, arrayDepth };
}
if (
isAutoGeneratedTypeUnion(type) ||
isAutoGeneratedEnumUnion(type, typeChecker)
) {
const types = (type as ts.UnionOrIntersectionType).types;
return getTypeReferenceAsString(
types[types.length - 1],
typeChecker,
arrayDepth
);
}
if (
text === 'any' ||
text === 'unknown' ||
text === 'object' ||
isInterface(type) ||
(type.isUnionOrIntersection() && !isEnum(type))
) {
return { typeName: 'Object', arrayDepth };
}
if (isEnum(type)) {
return { typeName: undefined, arrayDepth };
}
if (type.aliasSymbol) {
return { typeName: 'Object', arrayDepth };
}
if (
typeChecker.getApparentType(type).getSymbol().getEscapedName() ===
'String'
) {
return { typeName: String.name, arrayDepth };
}
return { typeName: undefined };
} catch {
return { typeName: undefined };
}
}
export function isPromiseOrObservable(type: string) {
return type.includes('Promise<') || type.includes('Observable<');
}
export function hasPropertyKey(
key: string,
properties: ts.NodeArray<ts.PropertyAssignment>
): boolean {
return properties
.filter((item) => !isDynamicallyAdded(item))
.some((item) => item.name.getText() === key);
}
export function getOutputExtension(fileName: string): string {
if (fileName.endsWith('.mts')) {
return '.mjs';
} else if (fileName.endsWith('.cts')) {
return '.cjs';
} else {
return '.js';
}
}
export function replaceImportPath(
typeReference: string,
fileName: string,
options: PluginOptions
) {
if (!typeReference.includes('import')) {
return { typeReference, importPath: null };
}
if (options.esmCompatible) {
typeReference = typeReference.replace(
', { with: { "resolution-mode": "import" } }',
''
);
}
let importPath = /\(\"([^)]).+(\")/.exec(typeReference)[0];
if (!importPath) {
return { typeReference: undefined, importPath: null };
}
importPath = convertPath(importPath);
importPath = importPath.slice(2, importPath.length - 1);
// Decode any URL-encoded characters (e.g. non-ASCII) that TypeScript may
// have introduced in the import path so that posix.relative can correctly
// compute a relative path against the (non-encoded) file name.
const decodedImportPath = safeDecodeURIComponent(importPath);
try {
if (isAbsolute(decodedImportPath)) {
throw {};
}
require.resolve(decodedImportPath);
if (!options.esmCompatible) {
typeReference = typeReference.replace('import', 'require');
}
return {
typeReference,
importPath: null
};
} catch {
const from = options?.readonly
? safeDecodeURIComponent(convertPath(options.pathToSource))
: posix.dirname(safeDecodeURIComponent(convertPath(fileName)));
let relativePath = posix.relative(from, decodedImportPath);
relativePath = relativePath[0] !== '.' ? './' + relativePath : relativePath;
const normalizedPath = normalizePackagePath(relativePath);
if (normalizedPath !== relativePath) {
relativePath = normalizedPath;
} else if (options.esmCompatible) {
// Add appropriate extension for non-node_modules imports
const extension = getOutputExtension(fileName);
relativePath += extension;
}
typeReference = typeReference.replace(importPath, relativePath);
if (options.readonly) {
const { typeName, typeImportStatement } =
convertToAsyncImport(typeReference);
return {
typeReference: typeImportStatement,
typeName,
importPath: relativePath
};
}
if (options.esmCompatible) {
const { typeName, typeImportStatement } =
convertToAsyncImport(typeReference);
return {
typeReference: `(${typeImportStatement}).${typeName}`,
importPath: relativePath
};
}
return {
typeReference: typeReference.replace('import', 'require'),
importPath: relativePath
};
}
}
function convertToAsyncImport(typeReference: string) {
const regexp = /import\(.+\).([^\]]+)(\])?/;
const match = regexp.exec(typeReference);
if (match?.length >= 2) {
const importPos = typeReference.indexOf(match[0]);
typeReference = typeReference.replace(`.${match[1]}`, '');
return {
typeImportStatement: insertAt(typeReference, importPos, 'await '),
typeName: match[1]
};
}
return { typeImportStatement: typeReference };
}
export function insertAt(string: string, index: number, substring: string) {
return string.slice(0, index) + substring + string.slice(index);
}
export function isDynamicallyAdded(identifier: ts.Node) {
return identifier && !identifier.parent && identifier.pos === -1;
}
/**
* When "strict" mode enabled, TypeScript transform the enum type to a union composed of
* the enum values and the undefined type. Hence, we have to lookup all the union types to get the original type
* @param type
* @param typeChecker
*/
export function isAutoGeneratedEnumUnion(
type: ts.Type,
typeChecker: ts.TypeChecker
): ts.Type {
if (type.isUnionOrIntersection() && !isEnum(type)) {
if (!type.types) {
return undefined;
}
const undefinedTypeIndex = type.types.findIndex(
(type: any) =>
type.intrinsicName === 'undefined' || type.intrinsicName === 'null'
);
if (undefinedTypeIndex < 0) {
return undefined;
}
// "strict" mode for enums
let parentType = undefined;
const isParentSymbolEqual = type.types.every((item, index) => {
if (index === undefinedTypeIndex) {
return true;
}
if (!item.symbol) {
return false;
}
if (
!(item.symbol as any).parent ||
item.symbol.flags !== ts.SymbolFlags.EnumMember
) {
return false;
}
const symbolType = typeChecker.getDeclaredTypeOfSymbol(
(item.symbol as any).parent
);
if (symbolType === parentType || !parentType) {
parentType = symbolType;
return true;
}
return false;
});
if (isParentSymbolEqual) {
return parentType;
}
}
return undefined;
}
/**
* when "strict" mode enabled, TypeScript transform the type signature of optional properties to
* the {undefined | T} where T is the original type. Hence, we have to extract the last type of type union
* @param type
*/
export function isAutoGeneratedTypeUnion(type: ts.Type): boolean {
if (type.isUnionOrIntersection() && !isEnum(type)) {
if (!type.types) {
return false;
}
const undefinedTypeIndex = type.types.findIndex(
(type: any) => type.intrinsicName === 'undefined'
);
// "strict" mode for non-enum properties
if (type.types.length === 2 && undefinedTypeIndex >= 0) {
return true;
}
}
return false;
}
export function extractTypeArgumentIfArray(type: ts.Type) {
if (isArray(type)) {
type = getTypeArguments(type)[0];
if (!type) {
return undefined;
}
return {
type,
isArray: true
};
}
return {
type,
isArray: false
};
}
/**
* when "strict" mode enabled, TypeScript transform optional boolean properties to "boolean | undefined"
* @param text
*/
function isOptionalBoolean(text: string) {
return typeof text === 'string' && text === 'boolean | undefined';
}
/**
* Converts Windows specific file paths to posix
* @param windowsPath
*/
export function convertPath(windowsPath: string) {
return windowsPath
.replace(/^\\\\\?\\/, '')
.replace(/\\/g, '/')
.replace(/\/\/+/g, '/');
}
/**
* Safely decodes URL-encoded characters in a path (e.g. non-ASCII characters
* that TypeScript may encode when generating type reference strings).
* Returns the original string if decoding fails.
* @param path
*/
export function safeDecodeURIComponent(path: string) {
try {
return decodeURIComponent(path);
} catch {
return path;
}
}
/**
* When a path goes through node_modules (e.g. a workspace package resolved to
* its physical location inside node_modules), strip the node_modules prefix so
* the generated import uses the package specifier instead of a relative path.
* This mirrors the same normalisation already done inside replaceImportPath().
*
* For example:
* ../node_modules/@amk/utils/src/dto/order.dto → @amk/utils/src/dto/order.dto
* ../../../packages/product-warehouse/dist/index (no node_modules) → unchanged
*/
export function normalizePackagePath(importPath: string): string {
const nodeModulesText = 'node_modules';
const nodeModulePos = importPath.indexOf(nodeModulesText);
if (nodeModulePos < 0) {
return importPath;
}
let packagePath = importPath.slice(
nodeModulePos + nodeModulesText.length + 1 // skip the trailing slash
);
const typesText = '@types';
const typesPos = packagePath.indexOf(typesText);
if (typesPos >= 0) {
packagePath = packagePath.slice(typesPos + typesText.length + 1);
}
const indexText = '/index';
const indexPos = packagePath.indexOf(indexText);
if (indexPos >= 0) {
packagePath = packagePath.slice(0, indexPos);
}
return packagePath;
}
/**
* Checks if a node can be directly referenced.
* In the readonly mode, only literals can be referenced directly.
* Nodes like identifiers or call expressions are not available in the auto-generated code.
*/
export function canReferenceNode(node: ts.Node, options: PluginOptions) {
if (!options.readonly) {
return true;
}
if (ts.isCallExpression(node) || ts.isIdentifier(node)) {
return false;
}
if (ts.isNewExpression(node)) {
if ((node.expression as ts.Identifier)?.escapedText === 'Date') {
return true;
}
return false;
}
if (
node.kind === ts.SyntaxKind.FalseKeyword ||
node.kind === ts.SyntaxKind.TrueKeyword ||
node.kind === ts.SyntaxKind.NullKeyword
) {
return true;
}
if (
ts.isNumericLiteral(node) ||
ts.isPrefixUnaryExpression(node) ||
ts.isStringLiteral(node)
) {
return true;
}
return false;
}