@umijs/core 3.5.17 → 4.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +2 -0
  2. package/dist/config/config.d.ts +63 -0
  3. package/dist/config/config.js +178 -0
  4. package/dist/config/utils.d.ts +8 -0
  5. package/dist/config/utils.js +15 -0
  6. package/dist/constants.d.ts +9 -0
  7. package/dist/constants.js +12 -0
  8. package/dist/index.d.ts +5 -0
  9. package/dist/index.js +19 -0
  10. package/dist/route/defineRoutes.d.ts +1 -0
  11. package/dist/route/defineRoutes.js +28 -0
  12. package/dist/route/route.d.ts +2 -0
  13. package/dist/route/route.js +18 -0
  14. package/dist/route/routeUtils.d.ts +7 -0
  15. package/dist/route/routeUtils.js +21 -0
  16. package/dist/route/routesConfig.d.ts +0 -0
  17. package/dist/route/routesConfig.js +1 -0
  18. package/dist/route/routesConvention.d.ts +3 -0
  19. package/dist/route/routesConvention.js +73 -0
  20. package/dist/route/utils.d.ts +7 -0
  21. package/dist/route/utils.js +26 -0
  22. package/dist/service/command.d.ts +27 -0
  23. package/dist/service/command.js +14 -0
  24. package/dist/service/env.d.ts +4 -0
  25. package/dist/service/env.js +21 -0
  26. package/dist/service/hook.d.ts +16 -0
  27. package/dist/service/hook.js +18 -0
  28. package/dist/service/path.d.ts +13 -0
  29. package/dist/service/path.js +31 -0
  30. package/dist/service/plugin.d.ts +53 -0
  31. package/dist/service/plugin.js +137 -0
  32. package/dist/service/pluginAPI.d.ts +35 -0
  33. package/dist/service/pluginAPI.js +120 -0
  34. package/dist/service/service.d.ts +91 -0
  35. package/dist/service/service.js +361 -0
  36. package/dist/service/servicePlugin.d.ts +3 -0
  37. package/dist/service/servicePlugin.js +14 -0
  38. package/dist/service/utils.d.ts +2 -0
  39. package/dist/service/utils.js +12 -0
  40. package/dist/types.d.ts +108 -0
  41. package/dist/types.js +42 -0
  42. package/package.json +35 -15
  43. package/lib/Config/Config.d.ts +0 -39
  44. package/lib/Config/Config.js +0 -348
  45. package/lib/Config/types.d.ts +0 -21
  46. package/lib/Config/utils/configUtils.d.ts +0 -9
  47. package/lib/Config/utils/configUtils.js +0 -54
  48. package/lib/Config/utils/isEqual.d.ts +0 -1
  49. package/lib/Config/utils/isEqual.js +0 -45
  50. package/lib/Config/utils/mergeDefault.d.ts +0 -6
  51. package/lib/Config/utils/mergeDefault.js +0 -41
  52. package/lib/Html/Html.d.ts +0 -16
  53. package/lib/Html/Html.js +0 -292
  54. package/lib/Html/document.ejs +0 -12
  55. package/lib/Html/types.d.ts +0 -55
  56. package/lib/Logger/Common.d.ts +0 -13
  57. package/lib/Logger/Common.js +0 -53
  58. package/lib/Logger/Logger.d.ts +0 -17
  59. package/lib/Logger/Logger.js +0 -87
  60. package/lib/Route/Route.d.ts +0 -32
  61. package/lib/Route/Route.js +0 -228
  62. package/lib/Route/getConventionalRoutes.d.ts +0 -10
  63. package/lib/Route/getConventionalRoutes.js +0 -259
  64. package/lib/Route/routesToJSON.d.ts +0 -9
  65. package/lib/Route/routesToJSON.js +0 -140
  66. package/lib/Route/types.d.ts +0 -11
  67. package/lib/Service/PluginAPI.d.ts +0 -38
  68. package/lib/Service/PluginAPI.js +0 -193
  69. package/lib/Service/Service.d.ts +0 -96
  70. package/lib/Service/Service.js +0 -694
  71. package/lib/Service/enums.d.ts +0 -29
  72. package/lib/Service/enums.js +0 -67
  73. package/lib/Service/getPaths.d.ts +0 -6
  74. package/lib/Service/getPaths.js +0 -79
  75. package/lib/Service/types.d.ts +0 -52
  76. package/lib/Service/types.js +0 -17
  77. package/lib/Service/utils/isPromise.d.ts +0 -1
  78. package/lib/Service/utils/isPromise.js +0 -22
  79. package/lib/Service/utils/loadDotEnv.d.ts +0 -5
  80. package/lib/Service/utils/loadDotEnv.js +0 -54
  81. package/lib/Service/utils/pluginUtils.d.ts +0 -42
  82. package/lib/Service/utils/pluginUtils.js +0 -201
  83. package/lib/index.d.ts +0 -14
  84. package/lib/index.js +0 -81
@@ -1,694 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
-
8
- function _react() {
9
- const data = _interopRequireDefault(require("react"));
10
-
11
- _react = function _react() {
12
- return data;
13
- };
14
-
15
- return data;
16
- }
17
-
18
- function _tapable() {
19
- const data = require("@umijs/deps/compiled/tapable");
20
-
21
- _tapable = function _tapable() {
22
- return data;
23
- };
24
-
25
- return data;
26
- }
27
-
28
- function _utils() {
29
- const data = require("@umijs/utils");
30
-
31
- _utils = function _utils() {
32
- return data;
33
- };
34
-
35
- return data;
36
- }
37
-
38
- function _assert() {
39
- const data = _interopRequireDefault(require("assert"));
40
-
41
- _assert = function _assert() {
42
- return data;
43
- };
44
-
45
- return data;
46
- }
47
-
48
- function _events() {
49
- const data = require("events");
50
-
51
- _events = function _events() {
52
- return data;
53
- };
54
-
55
- return data;
56
- }
57
-
58
- function _fs() {
59
- const data = require("fs");
60
-
61
- _fs = function _fs() {
62
- return data;
63
- };
64
-
65
- return data;
66
- }
67
-
68
- function _path() {
69
- const data = require("path");
70
-
71
- _path = function _path() {
72
- return data;
73
- };
74
-
75
- return data;
76
- }
77
-
78
- var _Config = _interopRequireDefault(require("../Config/Config"));
79
-
80
- var _configUtils = require("../Config/utils/configUtils");
81
-
82
- var _Logger = _interopRequireDefault(require("../Logger/Logger"));
83
-
84
- var _enums = require("./enums");
85
-
86
- var _getPaths = _interopRequireDefault(require("./getPaths"));
87
-
88
- var _PluginAPI = _interopRequireDefault(require("./PluginAPI"));
89
-
90
- var _isPromise = _interopRequireDefault(require("./utils/isPromise"));
91
-
92
- var _loadDotEnv = _interopRequireDefault(require("./utils/loadDotEnv"));
93
-
94
- var _pluginUtils = require("./utils/pluginUtils");
95
-
96
- const _excluded = ["presets", "plugins"];
97
-
98
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
99
-
100
- function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
101
-
102
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
103
-
104
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
105
-
106
- function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
107
-
108
- function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
109
-
110
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
111
-
112
- function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
113
-
114
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
115
-
116
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
117
-
118
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
119
-
120
- const logger = new _Logger.default('umi:core:Service'); // TODO
121
- // 1. duplicated key
122
-
123
- class Service extends _events().EventEmitter {
124
- // lifecycle stage
125
- // registered commands
126
- // including presets and plugins
127
- // plugin methods
128
- // initial presets and plugins from arguments, config, process.env, and package.json
129
- // presets and plugins for registering
130
- // user config
131
- // babel register
132
- // hooks
133
- // paths
134
- constructor(opts) {
135
- super();
136
- this.cwd = void 0;
137
- this.pkg = void 0;
138
- this.skipPluginIds = new Set();
139
- this.stage = _enums.ServiceStage.uninitialized;
140
- this.commands = {};
141
- this.plugins = {};
142
- this.pluginMethods = {};
143
- this.initialPresets = void 0;
144
- this.initialPlugins = void 0;
145
- this._extraPresets = [];
146
- this._extraPlugins = [];
147
- this.userConfig = void 0;
148
- this.configInstance = void 0;
149
- this.config = null;
150
- this.babelRegister = void 0;
151
- this.hooksByPluginId = {};
152
- this.hooks = {};
153
- this.paths = {};
154
- this.env = void 0;
155
- this.ApplyPluginsType = _enums.ApplyPluginsType;
156
- this.EnableBy = _enums.EnableBy;
157
- this.ConfigChangeType = _enums.ConfigChangeType;
158
- this.ServiceStage = _enums.ServiceStage;
159
- this.args = void 0;
160
- logger.debug('opts:');
161
- logger.debug(opts);
162
- this.cwd = opts.cwd || process.cwd(); // repoDir should be the root dir of repo
163
-
164
- this.pkg = opts.pkg || this.resolvePackage();
165
- this.env = opts.env || process.env.NODE_ENV;
166
- (0, _assert().default)((0, _fs().existsSync)(this.cwd), `cwd ${this.cwd} does not exist.`); // register babel before config parsing
167
-
168
- this.babelRegister = new (_utils().BabelRegister)(); // load .env or .local.env
169
-
170
- logger.debug('load env');
171
- this.loadEnv(); // get user config without validation
172
-
173
- logger.debug('get user config');
174
- const configFiles = opts.configFiles;
175
- this.configInstance = new _Config.default({
176
- cwd: this.cwd,
177
- service: this,
178
- localConfig: this.env === 'development',
179
- configFiles: Array.isArray(configFiles) && !!configFiles[0] ? configFiles : undefined
180
- });
181
- this.userConfig = this.configInstance.getUserConfig();
182
- logger.debug('userConfig:');
183
- logger.debug(this.userConfig); // get paths
184
-
185
- this.paths = (0, _getPaths.default)({
186
- cwd: this.cwd,
187
- config: this.userConfig,
188
- env: this.env
189
- });
190
- logger.debug('paths:');
191
- logger.debug(this.paths); // setup initial presets and plugins
192
-
193
- const baseOpts = {
194
- pkg: this.pkg,
195
- cwd: this.cwd
196
- };
197
- this.initialPresets = (0, _pluginUtils.resolvePresets)(_objectSpread(_objectSpread({}, baseOpts), {}, {
198
- presets: opts.presets || [],
199
- userConfigPresets: this.userConfig.presets || []
200
- }));
201
- this.initialPlugins = (0, _pluginUtils.resolvePlugins)(_objectSpread(_objectSpread({}, baseOpts), {}, {
202
- plugins: opts.plugins || [],
203
- userConfigPlugins: this.userConfig.plugins || []
204
- }));
205
- this.babelRegister.setOnlyMap({
206
- key: 'initialPlugins',
207
- value: _utils().lodash.uniq([...this.initialPresets.map(({
208
- path
209
- }) => path), ...this.initialPlugins.map(({
210
- path
211
- }) => path)])
212
- });
213
- logger.debug('initial presets:');
214
- logger.debug(this.initialPresets);
215
- logger.debug('initial plugins:');
216
- logger.debug(this.initialPlugins);
217
- }
218
-
219
- setStage(stage) {
220
- this.stage = stage;
221
- }
222
-
223
- resolvePackage() {
224
- try {
225
- return require((0, _path().join)(this.cwd, 'package.json'));
226
- } catch (e) {
227
- return {};
228
- }
229
- }
230
-
231
- loadEnv() {
232
- const basePath = (0, _path().join)(this.cwd, '.env');
233
- const localPath = `${basePath}.local`;
234
- (0, _loadDotEnv.default)(localPath);
235
- (0, _loadDotEnv.default)(basePath);
236
- }
237
-
238
- init() {
239
- var _this = this;
240
-
241
- return _asyncToGenerator(function* () {
242
- _this.setStage(_enums.ServiceStage.init); // we should have the final hooksByPluginId which is added with api.register()
243
-
244
-
245
- yield _this.initPresetsAndPlugins(); // collect false configs, then add to this.skipPluginIds
246
- // skipPluginIds include two parts:
247
- // 1. api.skipPlugins()
248
- // 2. user config with the `false` value
249
- // Object.keys(this.hooksByPluginId).forEach(pluginId => {
250
- // const { key } = this.plugins[pluginId];
251
- // if (this.getPluginOptsWithKey(key) === false) {
252
- // this.skipPluginIds.add(pluginId);
253
- // }
254
- // });
255
- // delete hooks from this.hooksByPluginId with this.skipPluginIds
256
- // for (const pluginId of this.skipPluginIds) {
257
- // if (this.hooksByPluginId[pluginId]) delete this.hooksByPluginId[pluginId];
258
- // delete this.plugins[pluginId];
259
- // }
260
- // hooksByPluginId -> hooks
261
- // hooks is mapped with hook key, prepared for applyPlugins()
262
-
263
- _this.setStage(_enums.ServiceStage.initHooks);
264
-
265
- Object.keys(_this.hooksByPluginId).forEach(id => {
266
- const hooks = _this.hooksByPluginId[id];
267
- hooks.forEach(hook => {
268
- const key = hook.key;
269
- hook.pluginId = id;
270
- _this.hooks[key] = (_this.hooks[key] || []).concat(hook);
271
- });
272
- }); // plugin is totally ready
273
-
274
- _this.setStage(_enums.ServiceStage.pluginReady);
275
-
276
- yield _this.applyPlugins({
277
- key: 'onPluginReady',
278
- type: _enums.ApplyPluginsType.event
279
- }); // get config, including:
280
- // 1. merge default config
281
- // 2. validate
282
-
283
- _this.setStage(_enums.ServiceStage.getConfig);
284
-
285
- const defaultConfig = yield _this.applyPlugins({
286
- key: 'modifyDefaultConfig',
287
- type: _this.ApplyPluginsType.modify,
288
- initialValue: yield _this.configInstance.getDefaultConfig()
289
- });
290
- _this.config = yield _this.applyPlugins({
291
- key: 'modifyConfig',
292
- type: _this.ApplyPluginsType.modify,
293
- initialValue: _this.configInstance.getConfig({
294
- defaultConfig
295
- })
296
- }); // merge paths to keep the this.paths ref
297
-
298
- _this.setStage(_enums.ServiceStage.getPaths); // config.outputPath may be modified by plugins
299
-
300
-
301
- if (_this.config.outputPath) {
302
- _this.paths.absOutputPath = (0, _path().join)(_this.cwd, _this.config.outputPath);
303
- }
304
-
305
- const paths = yield _this.applyPlugins({
306
- key: 'modifyPaths',
307
- type: _enums.ApplyPluginsType.modify,
308
- initialValue: _this.paths
309
- });
310
- Object.keys(paths).forEach(key => {
311
- _this.paths[key] = paths[key];
312
- });
313
- })();
314
- }
315
-
316
- initPresetsAndPlugins() {
317
- var _this2 = this;
318
-
319
- return _asyncToGenerator(function* () {
320
- _this2.setStage(_enums.ServiceStage.initPresets);
321
-
322
- _this2._extraPlugins = [];
323
-
324
- while (_this2.initialPresets.length) {
325
- yield _this2.initPreset(_this2.initialPresets.shift());
326
- }
327
-
328
- _this2.setStage(_enums.ServiceStage.initPlugins);
329
-
330
- _this2._extraPlugins.push(..._this2.initialPlugins);
331
-
332
- while (_this2._extraPlugins.length) {
333
- yield _this2.initPlugin(_this2._extraPlugins.shift());
334
- }
335
- })();
336
- }
337
-
338
- getPluginAPI(opts) {
339
- const pluginAPI = new _PluginAPI.default(opts); // register built-in methods
340
-
341
- ['onPluginReady', 'modifyPaths', 'onStart', 'modifyDefaultConfig', 'modifyConfig'].forEach(name => {
342
- pluginAPI.registerMethod({
343
- name,
344
- exitsError: false
345
- });
346
- });
347
- return new Proxy(pluginAPI, {
348
- get: (target, prop) => {
349
- // 由于 pluginMethods 需要在 register 阶段可用
350
- // 必须通过 proxy 的方式动态获取最新,以实现边注册边使用的效果
351
- if (this.pluginMethods[prop]) return this.pluginMethods[prop];
352
-
353
- if (['applyPlugins', 'ApplyPluginsType', 'EnableBy', 'ConfigChangeType', 'babelRegister', 'stage', 'ServiceStage', 'paths', 'cwd', 'pkg', 'userConfig', 'config', 'env', 'args', 'hasPlugins', 'hasPresets'].includes(prop)) {
354
- return typeof this[prop] === 'function' ? this[prop].bind(this) : this[prop];
355
- }
356
-
357
- return target[prop];
358
- }
359
- });
360
- }
361
-
362
- applyAPI(opts) {
363
- return _asyncToGenerator(function* () {
364
- let ret = opts.apply()(opts.api);
365
-
366
- if ((0, _isPromise.default)(ret)) {
367
- ret = yield ret;
368
- }
369
-
370
- return ret || {};
371
- })();
372
- }
373
-
374
- initPreset(preset) {
375
- var _this3 = this;
376
-
377
- return _asyncToGenerator(function* () {
378
- const id = preset.id,
379
- key = preset.key,
380
- apply = preset.apply;
381
- preset.isPreset = true;
382
-
383
- const api = _this3.getPluginAPI({
384
- id,
385
- key,
386
- service: _this3
387
- }); // register before apply
388
-
389
-
390
- _this3.registerPlugin(preset); // TODO: ...defaultConfigs 考虑要不要支持,可能这个需求可以通过其他渠道实现
391
-
392
-
393
- const _yield$_this3$applyAP = yield _this3.applyAPI({
394
- api,
395
- apply
396
- }),
397
- presets = _yield$_this3$applyAP.presets,
398
- plugins = _yield$_this3$applyAP.plugins,
399
- defaultConfigs = _objectWithoutProperties(_yield$_this3$applyAP, _excluded); // register extra presets and plugins
400
-
401
-
402
- if (presets) {
403
- (0, _assert().default)(Array.isArray(presets), `presets returned from preset ${id} must be Array.`); // 插到最前面,下个 while 循环优先执行
404
-
405
- _this3._extraPresets.splice(0, 0, ...presets.map(path => {
406
- return (0, _pluginUtils.pathToObj)({
407
- type: _enums.PluginType.preset,
408
- path,
409
- cwd: _this3.cwd
410
- });
411
- }));
412
- } // 深度优先
413
-
414
-
415
- const extraPresets = _utils().lodash.clone(_this3._extraPresets);
416
-
417
- _this3._extraPresets = [];
418
-
419
- while (extraPresets.length) {
420
- yield _this3.initPreset(extraPresets.shift());
421
- }
422
-
423
- if (plugins) {
424
- (0, _assert().default)(Array.isArray(plugins), `plugins returned from preset ${id} must be Array.`);
425
-
426
- _this3._extraPlugins.push(...plugins.map(path => {
427
- return (0, _pluginUtils.pathToObj)({
428
- type: _enums.PluginType.plugin,
429
- path,
430
- cwd: _this3.cwd
431
- });
432
- }));
433
- }
434
- })();
435
- }
436
-
437
- initPlugin(plugin) {
438
- var _this4 = this;
439
-
440
- return _asyncToGenerator(function* () {
441
- const id = plugin.id,
442
- key = plugin.key,
443
- apply = plugin.apply;
444
-
445
- const api = _this4.getPluginAPI({
446
- id,
447
- key,
448
- service: _this4
449
- }); // register before apply
450
-
451
-
452
- _this4.registerPlugin(plugin);
453
-
454
- yield _this4.applyAPI({
455
- api,
456
- apply
457
- });
458
- })();
459
- }
460
-
461
- getPluginOptsWithKey(key) {
462
- return (0, _configUtils.getUserConfigWithKey)({
463
- key,
464
- userConfig: this.userConfig
465
- });
466
- }
467
-
468
- registerPlugin(plugin) {
469
- // 考虑要不要去掉这里的校验逻辑
470
- // 理论上不会走到这里,因为在 describe 的时候已经做了冲突校验
471
- if (this.plugins[plugin.id]) {
472
- const name = plugin.isPreset ? 'preset' : 'plugin';
473
- throw new Error(`\
474
- ${name} ${plugin.id} is already registered by ${this.plugins[plugin.id].path}, \
475
- ${name} from ${plugin.path} register failed.`);
476
- }
477
-
478
- this.plugins[plugin.id] = plugin;
479
- }
480
-
481
- isPluginEnable(pluginId) {
482
- // api.skipPlugins() 的插件
483
- if (this.skipPluginIds.has(pluginId)) return false;
484
- const _this$plugins$pluginI = this.plugins[pluginId],
485
- key = _this$plugins$pluginI.key,
486
- enableBy = _this$plugins$pluginI.enableBy; // 手动设置为 false
487
-
488
- if (this.userConfig[key] === false) return false; // 配置开启
489
-
490
- if (enableBy === this.EnableBy.config && !(key in this.userConfig)) {
491
- return false;
492
- } // 函数自定义开启
493
-
494
-
495
- if (typeof enableBy === 'function') {
496
- return enableBy();
497
- } // 注册开启
498
-
499
-
500
- return true;
501
- }
502
-
503
- hasPlugins(pluginIds) {
504
- return pluginIds.every(pluginId => {
505
- const plugin = this.plugins[pluginId];
506
- return plugin && !plugin.isPreset && this.isPluginEnable(pluginId);
507
- });
508
- }
509
-
510
- hasPresets(presetIds) {
511
- return presetIds.every(presetId => {
512
- const preset = this.plugins[presetId];
513
- return preset && preset.isPreset && this.isPluginEnable(presetId);
514
- });
515
- }
516
-
517
- applyPlugins(opts) {
518
- var _this5 = this;
519
-
520
- return _asyncToGenerator(function* () {
521
- const hooks = _this5.hooks[opts.key] || [];
522
-
523
- switch (opts.type) {
524
- case _enums.ApplyPluginsType.add:
525
- if ('initialValue' in opts) {
526
- (0, _assert().default)(Array.isArray(opts.initialValue), `applyPlugins failed, opts.initialValue must be Array if opts.type is add.`);
527
- }
528
-
529
- const tAdd = new (_tapable().AsyncSeriesWaterfallHook)(['memo']);
530
-
531
- var _iterator = _createForOfIteratorHelper(hooks),
532
- _step;
533
-
534
- try {
535
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
536
- const hook = _step.value;
537
-
538
- if (!_this5.isPluginEnable(hook.pluginId)) {
539
- continue;
540
- }
541
-
542
- tAdd.tapPromise({
543
- name: hook.pluginId,
544
- stage: hook.stage || 0,
545
- // @ts-ignore
546
- before: hook.before
547
- }, /*#__PURE__*/function () {
548
- var _ref = _asyncToGenerator(function* (memo) {
549
- const items = yield hook.fn(opts.args);
550
- return memo.concat(items);
551
- });
552
-
553
- return function (_x) {
554
- return _ref.apply(this, arguments);
555
- };
556
- }());
557
- }
558
- } catch (err) {
559
- _iterator.e(err);
560
- } finally {
561
- _iterator.f();
562
- }
563
-
564
- return yield tAdd.promise(opts.initialValue || []);
565
-
566
- case _enums.ApplyPluginsType.modify:
567
- const tModify = new (_tapable().AsyncSeriesWaterfallHook)(['memo']);
568
-
569
- var _iterator2 = _createForOfIteratorHelper(hooks),
570
- _step2;
571
-
572
- try {
573
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
574
- const hook = _step2.value;
575
-
576
- if (!_this5.isPluginEnable(hook.pluginId)) {
577
- continue;
578
- }
579
-
580
- tModify.tapPromise({
581
- name: hook.pluginId,
582
- stage: hook.stage || 0,
583
- // @ts-ignore
584
- before: hook.before
585
- }, /*#__PURE__*/function () {
586
- var _ref2 = _asyncToGenerator(function* (memo) {
587
- return yield hook.fn(memo, opts.args);
588
- });
589
-
590
- return function (_x2) {
591
- return _ref2.apply(this, arguments);
592
- };
593
- }());
594
- }
595
- } catch (err) {
596
- _iterator2.e(err);
597
- } finally {
598
- _iterator2.f();
599
- }
600
-
601
- return yield tModify.promise(opts.initialValue);
602
-
603
- case _enums.ApplyPluginsType.event:
604
- const tEvent = new (_tapable().AsyncSeriesWaterfallHook)(['_']);
605
-
606
- var _iterator3 = _createForOfIteratorHelper(hooks),
607
- _step3;
608
-
609
- try {
610
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
611
- const hook = _step3.value;
612
-
613
- if (!_this5.isPluginEnable(hook.pluginId)) {
614
- continue;
615
- }
616
-
617
- tEvent.tapPromise({
618
- name: hook.pluginId,
619
- stage: hook.stage || 0,
620
- // @ts-ignore
621
- before: hook.before
622
- }, /*#__PURE__*/_asyncToGenerator(function* () {
623
- yield hook.fn(opts.args);
624
- }));
625
- }
626
- } catch (err) {
627
- _iterator3.e(err);
628
- } finally {
629
- _iterator3.f();
630
- }
631
-
632
- return yield tEvent.promise();
633
-
634
- default:
635
- throw new Error(`applyPlugin failed, type is not defined or is not matched, got ${opts.type}.`);
636
- }
637
- })();
638
- }
639
-
640
- run({
641
- name,
642
- args = {}
643
- }) {
644
- var _this6 = this;
645
-
646
- return _asyncToGenerator(function* () {
647
- args._ = args._ || []; // shift the command itself
648
-
649
- if (args._[0] === name) args._.shift();
650
- _this6.args = args;
651
- yield _this6.init();
652
- logger.debug('plugins:');
653
- logger.debug(_this6.plugins);
654
-
655
- _this6.setStage(_enums.ServiceStage.run);
656
-
657
- yield _this6.applyPlugins({
658
- key: 'onStart',
659
- type: _enums.ApplyPluginsType.event,
660
- args: {
661
- name,
662
- args
663
- }
664
- });
665
- return _this6.runCommand({
666
- name,
667
- args
668
- });
669
- })();
670
- }
671
-
672
- runCommand({
673
- name,
674
- args = {}
675
- }) {
676
- var _this7 = this;
677
-
678
- return _asyncToGenerator(function* () {
679
- (0, _assert().default)(_this7.stage >= _enums.ServiceStage.init, `service is not initialized.`);
680
- args._ = args._ || []; // shift the command itself
681
-
682
- if (args._[0] === name) args._.shift();
683
- const command = typeof _this7.commands[name] === 'string' ? _this7.commands[_this7.commands[name]] : _this7.commands[name];
684
- (0, _assert().default)(command, `run command failed, command ${name} does not exists.`);
685
- const fn = command.fn;
686
- return fn({
687
- args
688
- });
689
- })();
690
- }
691
-
692
- }
693
-
694
- exports.default = Service;