forked from polyforest/jsdoc-tsimport-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
234 lines (204 loc) · 6.3 KB
/
index.js
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
const path = require('path');
const fs = require('fs');
const env = require('jsdoc/env');
const absSrcDirs = env.opts._.map((iSrcDir) => path.join(env.pwd, iSrcDir));
/**
* @typedef {object} FileEvent
* @property {string} filename The name of the file.
* @property {string} source The contents of the file.
*/
/**
* @typedef {object} DocCommentFoundEvent
* @property {string} filename The name of the file.
* @property {string} comment The text of the JSDoc comment.
* @property {number} lineno The line number.
* @property {number} columnno The column number.
*/
/**
* A regex to capture all doc comments.
*/
const docCommentsRegex = /\/\*\*\s*(?:[^\*]|(?:\*(?!\/)))*\*\//g;
/**
* Find the module name.
*/
const moduleNameRegex = /@module\s+([\w\/]+)?/;
/**
* Finds typedefs
*/
const typedefRegex = /@typedef\s*(?:\{[^}]*\})\s*([\w-\$]*)/g;
/**
* Finds a ts import.
*/
const importRegex = /import\(['"](\@?[\.\/_a-zA-Z0-9-\$]*)(?:\.js)?['"]\)\.?([_a-zA-Z0-9-\$]*)?/g;
const typeRegex = /\{[^}]*\}/g;
const identifiers = /([\w-\$\.]+)/g;
/**
* @typedef {object} FileInfo
* @property {string} filename
* @property {?string} moduleId
* @property {string[]} typedefs
*/
/**
* A map of filenames to module ids.
*
* @type {Map<string, FileInfo>}
*/
const fileInfos = new Map();
/**
* A map of moduleId to type definition ids.
*
* @type {Map<string, Set<string>>}
*/
const moduleToTypeDefs = new Map();
/**
* Retrieves and caches file information for this plugin.
*
* @param {string} filename
* @param {?string} source
* @returns {!FileInfo}
*/
function getFileInfo(filename, source = null) {
const filenameNor = path.normalize(filename);
if (fileInfos.has(filenameNor)) return fileInfos.get(filenameNor);
const fileInfo = /** @type {FileInfo} */ ({
moduleId: null, typedefs: [], filename: filenameNor,
});
const s = source || ((fs.existsSync(filenameNor)) ?
fs.readFileSync(filenameNor).toString() : '');
s.replace(docCommentsRegex, (comment) => {
if (!fileInfo.moduleId) {
// Searches for @module doc comment
const moduleNameMatch = comment.match(moduleNameRegex);
if (moduleNameMatch) {
if (!moduleNameMatch[1]) {
// @module tag with no module name; calculate the implicit module id.
const srcDir = absSrcDirs.find((iSrcDir) =>
filenameNor.startsWith(iSrcDir));
fileInfo.moduleId = noExtension(filenameNor)
.slice(srcDir.length + 1).replace(/\\/g, '/');
} else {
fileInfo.moduleId = moduleNameMatch[1];
}
}
}
// Add all typedefs within the file.
comment.replace(typedefRegex, (_substr, defName) => {
fileInfo.typedefs.push(defName);
return '';
});
return '';
});
if (!fileInfo.moduleId) {
fileInfo.moduleId = '';
}
// Keep a list of typedefs per module.
if (!moduleToTypeDefs.has(fileInfo.moduleId)) {
moduleToTypeDefs.set(fileInfo.moduleId, new Set());
}
const typeDefsSet = moduleToTypeDefs.get(fileInfo.moduleId);
fileInfo.typedefs.forEach((item) => {
typeDefsSet.add(item);
});
fileInfos.set(filenameNor, fileInfo);
return fileInfo;
}
/**
* The beforeParse event is fired before parsing has begun.
*
* @param {FileEvent} e The event.
*/
function beforeParse(e) {
getFileInfo(e.filename, e.source);
// Find all doc comments (unfortunately needs to be done here and not
// in jsDocCommentFound or there will be errors)
e.source = e.source.replace(docCommentsRegex,
(substring) => {
return substring.replace(importRegex,
(_substring2, relImportPath, symbolName) => {
const moduleId = getModuleId(e.filename, relImportPath);
return (moduleId) ? `module:${moduleId}${symbolName?"~"+symbolName:""}` : symbolName;
});
});
};
/**
* Converts a relative path to a module identifier.
*
* @param {string} filename The normalized path of the file doing the import.
* @param {string} relImportPath The import string.
* @returns {string} The module id.
*/
function getModuleId(filename, relImportPath) {
if (!relImportPath.startsWith('.')) {
// Not a relative import.
return relImportPath;
}
const p = relPath(filename, relImportPath);
const absPath = inferExtension(p);
return getFileInfo(absPath).moduleId;
}
/**
* Returns the normalized, absolute path of `relative` to `root.
*
* @param {string} root
* @param {string} relative
* @returns {string}
*/
function relPath(root, relative) {
if (path.isAbsolute(relative)) return relative;
return path.normalize(
path.join(path.dirname(root), relative));
}
/**
* Given a filename, if there is no extension, scan the files for the
* most likely match.
*
* @param {string} filename The filename with or without an
* extension to resolve.
* @returns {string} The path to the resolved file.
*/
function inferExtension(filename) {
const filenameNor = path.normalize(filename);
const ext = path.extname(filenameNor);
if (ext && fs.existsSync(filename)) return ext;
const files = fs.readdirSync(path.dirname(filenameNor));
const name = path.basename(filenameNor);
const foundFile = files.find((iFile) => {
if (noExtension(iFile) == name) {
return true;
}
});
if (foundFile === undefined) return filename;
return path.join(path.dirname(filenameNor), foundFile);
}
/**
* Strips the extension off of a filename.
*
* @param {string} filename A filename with or without an extension.
* @returns {string} Returns the filename without extension.
*/
function noExtension(filename) {
return filename.substring(0, filename.length - path.extname(filename).length);
}
/**
* The jsdocCommentFound event is fired whenever a JSDoc comment is found.
* All file infos are now populated; replace typedef symbols with their
* module counterparts.
*
* @param {DocCommentFoundEvent} e The event.
*/
function jsdocCommentFound(e) {
const fileInfo = getFileInfo(e.filename);
const typeDefsSet = moduleToTypeDefs.get(fileInfo.moduleId);
if (!typeDefsSet) return;
e.comment = e.comment.replace(typeRegex, (typeExpr) => {
return typeExpr.replace(identifiers, (identifier) => {
return (fileInfo.moduleId && typeDefsSet.has(identifier)) ?
`module:${fileInfo.moduleId}~${identifier}` :
identifier;
});
});
}
exports.handlers = {
beforeParse: beforeParse,
jsdocCommentFound: jsdocCommentFound,
};