forked from hipstersmoothie/react-docgen-typescript-plugin
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathplugin.ts
More file actions
417 lines (363 loc) · 12.3 KB
/
plugin.ts
File metadata and controls
417 lines (363 loc) · 12.3 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
import path from "path";
import createDebug from "debug";
import ts from "typescript";
import * as docGen from "react-docgen-typescript";
import { matcher } from "micromatch";
import * as webpack from "webpack";
import findCacheDir from "find-cache-dir";
import flatCache from "flat-cache";
import crypto from "crypto";
import { LoaderOptions } from "./types";
import {
generateDocgenCodeBlock,
GeneratorOptions,
} from "./generateDocgenCodeBlock";
const debugExclude = createDebug("docgen:exclude");
const debugInclude = createDebug("docgen:include");
interface TypescriptOptions {
/**
* Specify the location of the tsconfig.json to use. Can not be used with
* compilerOptions.
**/
tsconfigPath?: string;
/** Specify TypeScript compiler options. Can not be used with tsconfigPath. */
compilerOptions?: ts.CompilerOptions;
}
export type PluginOptions = docGen.ParserOptions &
LoaderOptions &
TypescriptOptions & {
/** Glob patterns to ignore */
exclude?: string[];
/** Glob patterns to include. defaults to ts|tsx */
include?: string[];
};
/** Get the contents of the tsconfig in the system */
function getTSConfigFile(tsconfigPath: string): ts.ParsedCommandLine {
try {
const basePath = path.dirname(tsconfigPath);
const configFile = ts.readConfigFile(tsconfigPath, ts.sys.readFile);
return ts.parseJsonConfigFileContent(
configFile.config,
ts.sys,
basePath,
{},
tsconfigPath
);
} catch (error) {
return {} as ts.ParsedCommandLine;
}
}
/** Create a glob matching function. */
const matchGlob = (globs?: string[]) => {
const matchers = (globs || []).map((g) => matcher(g, { dot: true }));
return (filename: string) =>
Boolean(filename && matchers.find((match) => match(filename)));
};
// The cache is used only with webpack 4 for now as webpack 5 comes with caching of its own
const cacheId = "ts-docgen";
const cacheDir = findCacheDir({ name: cacheId });
const cache = flatCache.load(cacheId, cacheDir);
/** Run the docgen parser and inject the result into the output */
/** This is used for webpack 4 or earlier */
function processModule(
parser: docGen.FileParser,
webpackModule: webpack.Module,
tsProgram: ts.Program,
loaderOptions: Required<LoaderOptions>
) {
if (!webpackModule) {
return;
}
const hash = crypto
.createHash("sha1")
// eslint-disable-next-line
// @ts-ignore
// eslint-disable-next-line
.update(webpackModule._source._value)
.digest("hex");
const cached = cache.getKey(hash);
if (cached) {
// eslint-disable-next-line
// @ts-ignore
// eslint-disable-next-line
debugInclude(`Got cached docgen for "${webpackModule.request}"`);
// eslint-disable-next-line
// @ts-ignore
// eslint-disable-next-line
webpackModule._source._value = cached;
return;
}
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
const { userRequest } = webpackModule;
const componentDocs = parser.parseWithProgramProvider(
userRequest,
() => tsProgram
);
if (!componentDocs.length) {
return;
}
const docs = generateDocgenCodeBlock({
filename: userRequest,
source: userRequest,
componentDocs,
...loaderOptions,
}).substring(userRequest.length);
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
// eslint-disable-next-line
let sourceWithDocs = webpackModule._source._value;
sourceWithDocs += `\n${docs}\n`;
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
// eslint-disable-next-line
webpackModule._source._value = sourceWithDocs;
}
/** Inject typescript docgen information into modules at the end of a build */
export default class DocgenPlugin implements webpack.WebpackPluginInstance {
public static defaultOptions = {
setDisplayName: true,
typePropName: "type",
docgenCollectionName: "STORYBOOK_REACT_CLASSES",
};
private name = "React Docgen Typescript Plugin";
private options: PluginOptions;
constructor(options: PluginOptions = {}) {
this.options = options;
}
apply(compiler: webpack.Compiler): void {
// Property compiler.version is set only starting from webpack 5
const webpackVersion = compiler.webpack?.version || "";
const isWebpack5 = parseInt(webpackVersion.split(".")[0], 10) >= 5;
if (isWebpack5) {
this.applyWebpack5(compiler);
} else {
this.applyWebpack4(compiler);
}
}
applyWebpack5(compiler: webpack.Compiler): void {
const pluginName = "DocGenPlugin";
const {
docgenOptions,
compilerOptions,
generateOptions,
} = this.getOptions();
const docGenParser = docGen.withCompilerOptions(
compilerOptions,
docgenOptions
);
const { exclude = [], include = ["**/**.tsx"] } = this.options;
const isExcluded = matchGlob(exclude);
const isIncluded = matchGlob(include);
compiler.hooks.compilation.tap(
pluginName,
(compilation: webpack.Compilation) => {
// Since this file is needed only for webpack 5, load it only then
// to simplify the implementation of the file.
//
// eslint-disable-next-line
const { DocGenDependency } = require("./dependency");
compilation.dependencyTemplates.set(
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
DocGenDependency,
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
new DocGenDependency.Template()
);
compilation.hooks.seal.tap(pluginName, () => {
const modulesToProcess: [string, webpack.Module][] = [];
// 1. Aggregate modules to process
compilation.modules.forEach((module: webpack.Module) => {
if (!module.nameForCondition) {
return;
}
const nameForCondition = module.nameForCondition() || "";
// Ignore external modules
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
if (module.external) {
debugExclude(`Ignoring external module: ${nameForCondition}`);
return;
}
// Ignore raw requests
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
if (!module.rawRequest) {
debugExclude(
`Ignoring module without "rawRequest": ${nameForCondition}`
);
return;
}
if (isExcluded(nameForCondition)) {
debugExclude(
`Module not matched in "exclude": ${nameForCondition}`
);
return;
}
if (!isIncluded(nameForCondition)) {
debugExclude(
`Module not matched in "include": ${nameForCondition}`
);
return;
}
modulesToProcess.push([nameForCondition, module]);
});
// 2. Create a ts program with the modules
const tsProgram = ts.createProgram(
modulesToProcess.map(([name]) => name),
compilerOptions
);
// 3. Process and parse each module and add the type information
// as a dependency
modulesToProcess.forEach(([name, module]) => {
// Since this file is needed only for webpack 5, load it only then
// to simplify the implementation of the file.
//
// eslint-disable-next-line
const { DocGenDependency } = require("./dependency");
module.addDependency(
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
new DocGenDependency(
generateDocgenCodeBlock({
filename: name,
source: name,
componentDocs: docGenParser.parseWithProgramProvider(
name,
() => tsProgram
),
...generateOptions,
}).substring(name.length)
)
);
});
});
}
);
}
applyWebpack4(compiler: webpack.Compiler): void {
const { docgenOptions, compilerOptions } = this.getOptions();
const parser = docGen.withCompilerOptions(compilerOptions, docgenOptions);
const { exclude = [], include = ["**/**.tsx"] } = this.options;
const isExcluded = matchGlob(exclude);
const isIncluded = matchGlob(include);
compiler.hooks.make.tap(this.name, (compilation) => {
compilation.hooks.seal.tap(this.name, () => {
const modulesToProcess: webpack.Module[] = [];
compilation.modules.forEach((module: webpack.Module) => {
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
if (!module.built) {
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
debugExclude(`Ignoring un-built module: ${module.userRequest}`);
return;
}
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
if (module.external) {
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
debugExclude(`Ignoring external module: ${module.userRequest}`);
return;
}
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
if (!module.rawRequest) {
debugExclude(
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
`Ignoring module without "rawRequest": ${module.userRequest}`
);
return;
}
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
if (isExcluded(module.userRequest)) {
debugExclude(
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
`Module not matched in "exclude": ${module.userRequest}`
);
return;
}
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
if (!isIncluded(module.userRequest)) {
debugExclude(
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
`Module not matched in "include": ${module.userRequest}`
);
return;
}
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
debugInclude(module.userRequest);
modulesToProcess.push(module);
});
const tsProgram = ts.createProgram(
// eslint-disable-next-line
// @ts-ignore: Webpack 4 type
modulesToProcess.map((v) => v.userRequest),
compilerOptions
);
modulesToProcess.forEach((m) =>
processModule(parser, m, tsProgram, {
docgenCollectionName: "STORYBOOK_REACT_CLASSES",
setDisplayName: true,
typePropName: "type",
})
);
cache.save();
});
});
}
getOptions(): {
docgenOptions: docGen.ParserOptions;
generateOptions: {
docgenCollectionName: GeneratorOptions["docgenCollectionName"];
setDisplayName: GeneratorOptions["setDisplayName"];
typePropName: GeneratorOptions["typePropName"];
};
compilerOptions: ts.CompilerOptions;
} {
const {
tsconfigPath = "./tsconfig.json",
compilerOptions: userCompilerOptions,
docgenCollectionName,
setDisplayName,
typePropName,
...docgenOptions
} = this.options;
const { defaultOptions } = DocgenPlugin;
let compilerOptions = {
jsx: ts.JsxEmit.React,
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.Latest,
};
if (userCompilerOptions) {
compilerOptions = {
...compilerOptions,
...userCompilerOptions,
};
} else {
const { options: tsOptions } = getTSConfigFile(tsconfigPath);
compilerOptions = { ...compilerOptions, ...tsOptions };
}
return {
docgenOptions,
generateOptions: {
docgenCollectionName:
docgenCollectionName === undefined
? defaultOptions.docgenCollectionName
: docgenCollectionName,
setDisplayName: setDisplayName ?? defaultOptions.setDisplayName,
typePropName: typePropName ?? defaultOptions.typePropName,
},
compilerOptions,
};
}
}
export type DocgenPluginType = typeof DocgenPlugin;