index.js
14.5 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
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generator = exports.BaseGenerator = exports.createTsHelperInstance = exports.getDefaultGeneratorConfig = exports.defaultConfig = void 0;
const tslib_1 = require("tslib");
const assert_1 = tslib_1.__importDefault(require("assert"));
const events_1 = require("events");
const fs_1 = tslib_1.__importDefault(require("fs"));
const crypto_1 = tslib_1.__importDefault(require("crypto"));
const chalk_1 = tslib_1.__importDefault(require("chalk"));
const path_1 = tslib_1.__importDefault(require("path"));
const generator = tslib_1.__importStar(require("./generator"));
exports.generator = generator;
const dot_prop_1 = require("dot-prop");
const config_1 = require("./config");
const watcher_1 = tslib_1.__importDefault(require("./watcher"));
const base_1 = require("./generators/base");
Object.defineProperty(exports, "BaseGenerator", { enumerable: true, get: function () { return base_1.BaseGenerator; } });
const utils = tslib_1.__importStar(require("./utils"));
const globby_1 = tslib_1.__importDefault(require("globby"));
const isInUnitTest = process.env.NODE_ENV === 'test';
exports.defaultConfig = {
cwd: utils.convertString(process.env.ETS_CWD, process.cwd()),
framework: utils.convertString(process.env.ETS_FRAMEWORK, 'egg'),
typings: utils.convertString(process.env.ETS_TYPINGS, './typings'),
caseStyle: utils.convertString(process.env.ETS_CASE_STYLE, 'lower'),
autoRemoveJs: utils.convertString(process.env.ETS_AUTO_REMOVE_JS, true),
throttle: utils.convertString(process.env.ETS_THROTTLE, 500),
watch: utils.convertString(process.env.ETS_WATCH, false),
watchOptions: undefined,
execAtInit: utils.convertString(process.env.ETS_EXEC_AT_INIT, false),
silent: utils.convertString(process.env.ETS_SILENT, isInUnitTest),
generatorConfig: {},
configFile: utils.convertString(process.env.ETS_CONFIG_FILE, '') || ['./tshelper', './tsHelper'],
};
// default watch dir
function getDefaultGeneratorConfig(opt) {
const baseConfig = {};
// extend
baseConfig.extend = {
directory: 'app/extend',
generator: 'extend',
};
// controller
baseConfig.controller = {
directory: 'app/controller',
interface: config_1.declMapping.controller,
generator: 'class',
};
// middleware
baseConfig.middleware = {
directory: 'app/middleware',
interface: config_1.declMapping.middleware,
generator: 'object',
};
// proxy
baseConfig.proxy = {
directory: 'app/proxy',
interface: 'IProxy',
generator: 'class',
enabled: false,
};
// model
baseConfig.model = {
directory: 'app/model',
generator: 'function',
interface: 'IModel',
caseStyle: 'upper',
enabled: !dot_prop_1.get(opt === null || opt === void 0 ? void 0 : opt.eggInfo, 'config.customLoader.model'),
};
// config
baseConfig.config = {
directory: 'config',
generator: 'config',
trigger: ['add', 'unlink', 'change'],
};
// plugin
baseConfig.plugin = {
directory: 'config',
generator: 'plugin',
trigger: ['add', 'unlink', 'change'],
};
// service
baseConfig.service = {
directory: 'app/service',
interface: config_1.declMapping.service,
generator: 'auto',
};
// egg
baseConfig.egg = {
directory: 'app',
generator: 'egg',
watch: false,
};
// custom loader
baseConfig.customLoader = {
generator: 'custom',
trigger: ['add', 'unlink', 'change'],
};
return baseConfig;
}
exports.getDefaultGeneratorConfig = getDefaultGeneratorConfig;
class TsHelper extends events_1.EventEmitter {
constructor(options) {
super();
this.watcherList = [];
this.cacheDist = {};
this.dtsFileList = [];
// utils
this.utils = utils;
// configure ets
this.configure(options);
// init watcher
this.initWatcher();
}
// build all watcher
build() {
// clean old files
this.cleanFiles();
this.watcherList.forEach(watcher => watcher.execute());
return this;
}
// destroy
destroy() {
this.removeAllListeners();
this.watcherList.forEach(item => item.destroy());
this.watcherList.length = 0;
}
// log
log(info, ignoreSilent) {
if (!ignoreSilent && this.config.silent) {
return;
}
utils.log(info);
}
warn(info) {
this.log(chalk_1.default.yellow(info), !isInUnitTest);
}
// create oneForAll file
createOneForAll(dist) {
const config = this.config;
const oneForAllDist = (typeof dist === 'string') ? dist : path_1.default.join(config.typings, './ets.d.ts');
const oneForAllDistDir = path_1.default.dirname(oneForAllDist);
// create d.ts includes all types.
const distContent = config_1.dtsComment + this.dtsFileList
.map(file => {
const importUrl = path_1.default
.relative(oneForAllDistDir, file.replace(/\.d\.ts$/, ''))
.replace(/\/|\\/g, '/');
return `import '${importUrl.startsWith('.') ? importUrl : `./${importUrl}`}';`;
})
.join('\n');
this.emit('update', oneForAllDist);
utils.writeFileSync(oneForAllDist, distContent);
}
// init watcher
initWatcher() {
Object.keys(this.config.generatorConfig).forEach(key => {
this.registerWatcher(key, this.config.generatorConfig[key], false);
});
}
// destroy watcher
destroyWatcher(...refs) {
this.watcherList = this.watcherList.filter(w => {
if (refs.includes(w.ref)) {
w.destroy();
return false;
}
return true;
});
}
// clean old files in startup
cleanFiles() {
const cwd = this.config.typings;
globby_1.default.sync(['**/*.d.ts', '!**/node_modules'], { cwd })
.forEach(file => {
const fileUrl = path_1.default.resolve(cwd, file);
const content = fs_1.default.readFileSync(fileUrl, 'utf-8');
const isGeneratedByEts = content.match(config_1.dtsCommentRE);
if (isGeneratedByEts)
fs_1.default.unlinkSync(fileUrl);
});
}
// register watcher
registerWatcher(name, watchConfig, removeDuplicate = true) {
if (removeDuplicate) {
this.destroyWatcher(name);
}
if (watchConfig.hasOwnProperty('enabled') && !watchConfig.enabled) {
return;
}
const directories = Array.isArray(watchConfig.directory)
? watchConfig.directory
: [watchConfig.directory];
// support array directory.
return directories.map(dir => {
const options = Object.assign({ name, ref: name, execAtInit: this.config.execAtInit }, watchConfig);
if (dir) {
options.directory = dir;
}
if (!this.config.watch) {
options.watch = false;
}
const watcher = new watcher_1.default(this);
watcher.on('update', this.generateTs.bind(this));
watcher.init(options);
this.watcherList.push(watcher);
return watcher;
});
}
loadWatcherConfig(config, options) {
const configFile = options.configFile || config.configFile;
const eggInfo = config.eggInfo;
const getConfigFromPkg = pkg => (pkg.egg || {}).tsHelper;
// read from enabled plugins
if (eggInfo.plugins) {
Object.keys(eggInfo.plugins)
.forEach(k => {
const pluginInfo = eggInfo.plugins[k];
if (pluginInfo.enable && pluginInfo.path) {
this.mergeConfig(config, getConfigFromPkg(utils.getPkgInfo(pluginInfo.path)));
}
});
}
// read from eggPaths
if (eggInfo.eggPaths) {
eggInfo.eggPaths.forEach(p => {
this.mergeConfig(config, getConfigFromPkg(utils.getPkgInfo(p)));
});
}
// read from package.json
this.mergeConfig(config, getConfigFromPkg(utils.getPkgInfo(config.cwd)));
// read from local file( default to tshelper | tsHelper )
(Array.isArray(configFile) ? configFile : [configFile]).forEach(f => {
this.mergeConfig(config, utils.requireFile(path_1.default.resolve(config.cwd, f)));
});
// merge local config and options to config
this.mergeConfig(config, options);
// create extra config
config.tsConfig = utils.loadTsConfig(path_1.default.resolve(config.cwd, './tsconfig.json'));
}
// configure
// options > configFile > package.json
configure(options) {
if (options.cwd) {
options.cwd = path_1.default.resolve(exports.defaultConfig.cwd, options.cwd);
}
// base config
const config = Object.assign({}, exports.defaultConfig);
config.id = crypto_1.default.randomBytes(16).toString('base64');
config.cwd = options.cwd || config.cwd;
config.customLoader = config.customLoader || options.customLoader;
// load egg info
config.eggInfo = utils.getEggInfo({
cwd: config.cwd,
cacheIndex: config.id,
customLoader: config.customLoader,
});
config.framework = options.framework || exports.defaultConfig.framework;
config.generatorConfig = getDefaultGeneratorConfig(config);
config.typings = path_1.default.resolve(config.cwd, config.typings);
this.config = config;
// load watcher config
this.loadWatcherConfig(this.config, options);
// deprecated framework
if (this.config.framework && this.config.framework !== exports.defaultConfig.framework) {
this.warn(`options.framework are deprecated, using default value(${exports.defaultConfig.framework}) instead`);
}
}
generateTs(result, file, startTime) {
const updateTs = (result, file) => {
const config = this.config;
const resultList = Array.isArray(result) ? result : [result];
for (const item of resultList) {
// check cache
if (this.isCached(item.dist, item.content)) {
return;
}
if (item.content) {
// create file
const dtsContent = `${config_1.dtsComment}\nimport '${config.framework}';\n${item.content}`;
utils.writeFileSync(item.dist, dtsContent);
this.emit('update', item.dist, file);
this.log(`create ${path_1.default.relative(this.config.cwd, item.dist)} (${Date.now() - startTime}ms)`);
this.updateDistFiles(item.dist);
}
else {
if (!fs_1.default.existsSync(item.dist)) {
return;
}
// remove file
fs_1.default.unlinkSync(item.dist);
delete this.cacheDist[item.dist];
this.emit('remove', item.dist, file);
this.log(`delete ${path_1.default.relative(this.config.cwd, item.dist)} (${Date.now() - startTime}ms)`);
this.updateDistFiles(item.dist, true);
}
}
};
if (typeof result.then === 'function') {
return result
.then(r => updateTs(r, file))
.catch(e => { this.log(e.message); });
}
updateTs(result, file);
}
updateDistFiles(fileUrl, isRemove) {
const index = this.dtsFileList.indexOf(fileUrl);
if (index >= 0) {
if (isRemove) {
this.dtsFileList.splice(index, 1);
}
}
else {
this.dtsFileList.push(fileUrl);
}
}
isCached(fileUrl, content) {
const cacheItem = this.cacheDist[fileUrl];
if (content && cacheItem === content) {
// no need to create file content is not changed.
return true;
}
this.cacheDist[fileUrl] = content;
return false;
}
// support dot prop config
formatConfig(config) {
const newConfig = {};
Object.keys(config).forEach(key => dot_prop_1.set(newConfig, key, config[key]));
return newConfig;
}
// merge ts helper options
mergeConfig(base, ...args) {
args.forEach(opt => {
if (!opt)
return;
const config = this.formatConfig(opt);
// compatitable for alias of generatorCofig
if (config.watchDirs)
config.generatorConfig = config.watchDirs;
Object.keys(config).forEach(key => {
if (key !== 'generatorConfig') {
base[key] = config[key] === undefined ? base[key] : config[key];
return;
}
const generatorConfig = config.generatorConfig || {};
Object.keys(generatorConfig).forEach(k => {
const item = generatorConfig[k];
if (typeof item === 'boolean') {
if (base.generatorConfig[k])
base.generatorConfig[k].enabled = item;
}
else if (item) {
// check private generator
assert_1.default(!generator.isPrivateGenerator(item.generator), `${item.generator} is a private generator, can not configure in config file`);
// compatible for deprecated fields
[
['path', 'directory'],
].forEach(([oldValue, newValue]) => {
if (item[oldValue]) {
item[newValue] = item[oldValue];
}
});
if (base.generatorConfig[k]) {
Object.assign(base.generatorConfig[k], item);
}
else {
base.generatorConfig[k] = item;
}
}
});
});
});
}
}
exports.default = TsHelper;
function createTsHelperInstance(options) {
return new TsHelper(options);
}
exports.createTsHelperInstance = createTsHelperInstance;