-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
105 lines (89 loc) · 2.64 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
import fs from 'fs';
import {glob} from 'glob';
import path from 'path';
import {build} from 'documentation';
import log from 'loglevel';
import prettier from 'prettier';
import {makeParser} from './src/parsers.js';
const sourceExtension = /\.jsx?$/i;
function isScript (filePath) {
return filePath.match(sourceExtension) != null;
}
async function parse ({path: modulePath, files, format, importMap, output}) {
const encodeModule = await makeParser();
if (!files || files.length === 0) {
log.info(`No source files found for ${modulePath}.`);
return;
}
log.info(`Parsing ${modulePath} ...`);
build(files, {shallow: true}).then(
async (root) => {
let result = (await encodeModule({root, section: root, parent: root, importMap, log})).join('\n');
const firstNamedEntry = root.find(entry => entry.name);
let moduleName = firstNamedEntry ? firstNamedEntry.name : '';
if (!result.replace(/\s/g, '').length) {
return;
}
if (format) {
result = await prettier.format(result, {parser: 'typescript'});
}
output(moduleName, result);
}
).catch((err) => {
log.error(`Unable to process ${modulePath}: ${err}`);
log.error(err.stack);
});
}
function getSourceFiles (base, ignore) {
return new Promise((resolve, reject) => {
glob('**/package.json', {cwd: base}).then(files => {
const entries = files
.filter(name => !ignore.find(i => name.includes(i)))
.map(relativePackageJsonPath => {
const packageJsonPath = path.join(base, relativePackageJsonPath);
const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
const dirPath = path.dirname(path.resolve(path.dirname(packageJsonPath), pkg.main));
return {
package: pkg,
path: path.relative(base, dirPath),
files: fs.readdirSync(dirPath)
.map(p => path.join(dirPath, p))
.filter(isScript)
};
});
resolve(entries);
}).catch(error => {
reject(error);
});
});
}
function isRequired (name) {
throw new Error(`${name} is a required argument`);
}
export default function main ({
output = isRequired('output'),
ignore = ['node_modules', 'build', 'dist', 'coverage'],
package: base = isRequired('package'),
format = true,
importMap,
logLevel = 'error',
outputPath
}) {
log.setLevel(logLevel);
getSourceFiles(path.resolve(base), ignore).then(files => {
files.forEach(moduleEntry => {
parse({
...moduleEntry,
format,
importMap,
output: (moduleName, result) => {
const file = path.basename(moduleEntry.package.main.replace(sourceExtension, '.d.ts'));
output(
path.join(path.resolve(outputPath || base), moduleEntry.path, file),
result
);
}
});
});
});
}