forked from LeDDGroup/typescript-transform-paths
/
resolve-module-name.ts
executable file
·196 lines (162 loc) · 6.7 KB
/
resolve-module-name.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
import { VisitorContext } from "../types";
import { isBaseDir, isURL, maybeAddRelativeLocalPrefix } from "./general-utils";
import * as path from "path";
import { realpathSync } from "fs";
import { removeFileExtension, removeSuffix, ResolvedModuleFull, SourceFile } from "typescript";
import { getOutputDirForSourceFile } from "./ts-helpers";
/* ****************************************************************************************************************** */
// region: Types
/* ****************************************************************************************************************** */
export interface ResolvedModule {
/**
* Absolute path to resolved module
*/
resolvedPath: string | undefined;
/**
* Output path
*/
outputPath: string;
/**
* Resolved to URL
*/
isURL: boolean;
}
enum IndexType {
NonIndex,
Explicit,
Implicit,
ImplicitPackage,
}
// endregion
/* ****************************************************************************************************************** */
// region: Helpers
/* ****************************************************************************************************************** */
function getPathDetail(moduleName: string, resolvedModule: ResolvedModuleFull) {
let resolvedFileName = resolvedModule.originalPath ?? resolvedModule.resolvedFileName;
const implicitPackageIndex = resolvedModule.packageId?.subModuleName;
const resolvedDir = implicitPackageIndex
? removeSuffix(resolvedFileName, `/${implicitPackageIndex}`)
: path.dirname(resolvedFileName);
const resolvedBaseName = implicitPackageIndex ? void 0 : path.basename(resolvedFileName);
const resolvedBaseNameNoExtension = resolvedBaseName && removeFileExtension(resolvedBaseName);
const resolvedExtName = resolvedBaseName && path.extname(resolvedFileName);
let baseName = !implicitPackageIndex ? path.basename(moduleName) : void 0;
let baseNameNoExtension = baseName && removeFileExtension(baseName);
let extName = baseName && path.extname(moduleName);
// Account for possible false extensions. Example scenario:
// moduleName = './file.accounting'
// resolvedBaseName = 'file.accounting.ts'
// ('accounting' would be considered the extension)
if (resolvedBaseNameNoExtension && baseName && resolvedBaseNameNoExtension === baseName) {
baseNameNoExtension = baseName;
extName = void 0;
}
// prettier-ignore
const indexType =
implicitPackageIndex ? IndexType.ImplicitPackage :
baseNameNoExtension === 'index' && resolvedBaseNameNoExtension === 'index' ? IndexType.Explicit :
baseNameNoExtension !== 'index' && resolvedBaseNameNoExtension === 'index' ? IndexType.Implicit :
IndexType.NonIndex;
if (indexType === IndexType.Implicit) {
baseName = void 0;
baseNameNoExtension = void 0;
extName = void 0;
}
return {
baseName,
baseNameNoExtension,
extName,
resolvedBaseName,
resolvedBaseNameNoExtension,
resolvedExtName,
resolvedDir,
indexType,
implicitPackageIndex,
resolvedFileName,
};
}
function getResolvedSourceFile(context: VisitorContext, fileName: string): SourceFile {
let res: SourceFile | undefined;
const { program, tsInstance } = context;
if (program) {
/* Attempt to directly pull from Program */
res = program.getSourceFile(fileName) as SourceFile;
if (res) return res;
/* Attempt to find without extension */
res = (program.getSourceFiles() as SourceFile[]).find(
(s) => removeFileExtension(s.fileName) === removeFileExtension(fileName)
);
if (res) return res;
}
/*
* Create basic synthetic SourceFile for use with compiler API - Applies if SourceFile not found in program due to
* import being added by another transformer
*/
return tsInstance.createSourceFile(fileName, ``, tsInstance.ScriptTarget.ESNext, /* setParentNodes */ false);
}
// endregion
/* ****************************************************************************************************************** */
// region: Utils
/* ****************************************************************************************************************** */
function tryRealpathNative(value) {
try {
return realpathSync.native(value)
} catch {
return value
}
}
function nativeRelativePath(from, to) {
return path.relative(tryRealpathNative(from), tryRealpathNative(to))
}
/**
* Resolve a module name
*/
export function resolveModuleName(context: VisitorContext, moduleName: string): ResolvedModule | undefined {
const { tsInstance, compilerOptions, sourceFile, config, rootDirs } = context;
// Attempt to resolve with TS Compiler API
const { resolvedModule, failedLookupLocations } = tsInstance.resolveModuleName(
moduleName,
sourceFile.fileName,
compilerOptions,
tsInstance.sys
);
// Handle non-resolvable module
if (!resolvedModule) {
const maybeURL = failedLookupLocations[0];
if (!isURL(maybeURL)) return void 0;
return {
isURL: true,
resolvedPath: void 0,
outputPath: maybeURL,
};
}
const resolvedSourceFile = getResolvedSourceFile(context, resolvedModule.resolvedFileName);
const { indexType, resolvedBaseNameNoExtension, resolvedFileName, implicitPackageIndex, extName, resolvedDir } =
getPathDetail(moduleName, resolvedModule);
/* Determine output filename */
let outputBaseName = resolvedBaseNameNoExtension ?? "";
if (indexType === IndexType.Implicit) outputBaseName = outputBaseName.replace(/(\/index$)|(^index$)/, "");
if (outputBaseName && extName) outputBaseName = `${outputBaseName}${extName}`;
/* Determine output dir */
let srcFileOutputDir = getOutputDirForSourceFile(context, sourceFile);
let moduleFileOutputDir = implicitPackageIndex ? resolvedDir : getOutputDirForSourceFile(context, resolvedSourceFile);
// Handle rootDirs remapping
if (config.useRootDirs && rootDirs) {
let fileRootDir = "";
let moduleRootDir = "";
for (const rootDir of rootDirs) {
if (isBaseDir(rootDir, moduleFileOutputDir) && rootDir.length > moduleRootDir.length) moduleRootDir = rootDir;
if (isBaseDir(rootDir, srcFileOutputDir) && rootDir.length > fileRootDir.length) fileRootDir = rootDir;
}
/* Remove base dirs to make relative to root */
if (fileRootDir && moduleRootDir) {
srcFileOutputDir = nativeRelativePath(fileRootDir, srcFileOutputDir);
moduleFileOutputDir = nativeRelativePath(moduleRootDir, moduleFileOutputDir);
}
}
const outputDir = nativeRelativePath(srcFileOutputDir, moduleFileOutputDir);
/* Compose final output path */
const outputPath = maybeAddRelativeLocalPrefix(tsInstance.normalizePath(path.join(outputDir, outputBaseName)));
return { isURL: false, outputPath, resolvedPath: resolvedFileName };
}
// endregion