@umijs/core 4.0.0-rc.13 → 4.0.0-rc.16

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.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export * from './config/config';
2
2
  export * from './route/route';
3
- export { GeneratorType, IGeneratorOpts } from './service/generator';
3
+ export { Generator, GeneratorType } from './service/generator';
4
4
  export * from './service/pluginAPI';
5
5
  export * from './service/service';
6
6
  export { Env, IAdd, IEvent, IModify, IRoute } from './types';
@@ -1,5 +1,6 @@
1
1
  interface IOpts {
2
2
  routes: any[];
3
+ onResolveComponent?: (component: string) => string;
3
4
  }
4
5
  export declare function getConfigRoutes(opts: IOpts): any[];
5
6
  export {};
@@ -1,15 +1,4 @@
1
1
  "use strict";
2
- var __rest = (this && this.__rest) || function (s, e) {
3
- var t = {};
4
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
- t[p] = s[p];
6
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
- t[p[i]] = s[p[i]];
10
- }
11
- return t;
12
- };
13
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
14
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
15
4
  };
@@ -18,30 +7,68 @@ exports.getConfigRoutes = void 0;
18
7
  const assert_1 = __importDefault(require("assert"));
19
8
  function getConfigRoutes(opts) {
20
9
  const memo = { ret: {}, id: 1 };
21
- transformRoutes({ routes: opts.routes, parentId: undefined, memo });
10
+ transformRoutes({
11
+ routes: opts.routes,
12
+ parentId: undefined,
13
+ memo,
14
+ onResolveComponent: opts.onResolveComponent,
15
+ });
22
16
  return memo.ret;
23
17
  }
24
18
  exports.getConfigRoutes = getConfigRoutes;
25
19
  function transformRoutes(opts) {
26
20
  opts.routes.forEach((route) => {
27
- transformRoute({ route, parentId: opts.parentId, memo: opts.memo });
21
+ transformRoute({
22
+ route,
23
+ parentId: opts.parentId,
24
+ memo: opts.memo,
25
+ onResolveComponent: opts.onResolveComponent,
26
+ });
28
27
  });
29
28
  }
30
29
  function transformRoute(opts) {
31
30
  (0, assert_1.default)(!opts.route.children, 'children is not allowed in route props, use routes instead.');
32
31
  const id = String(opts.memo.id++);
33
- const _a = opts.route, { routes, component } = _a, routeProps = __rest(_a, ["routes", "component"]);
32
+ const { routes, component, wrappers, ...routeProps } = opts.route;
34
33
  let absPath = opts.route.path;
35
34
  if ((absPath === null || absPath === void 0 ? void 0 : absPath.charAt(0)) !== '/') {
36
35
  const parentAbsPath = opts.parentId
37
- ? opts.memo.ret[opts.parentId].absPath.replace(/\/*$/, '/') // to remove '/'s on the tail
36
+ ? opts.memo.ret[opts.parentId].absPath.replace(/\/+$/, '/') // to remove '/'s on the tail
38
37
  : '/';
39
38
  absPath = parentAbsPath + absPath;
40
39
  }
41
- opts.memo.ret[id] = Object.assign(Object.assign(Object.assign(Object.assign({}, routeProps), { path: opts.route.path }), (component ? { file: component } : {})), { parentId: opts.parentId, id });
40
+ opts.memo.ret[id] = {
41
+ ...routeProps,
42
+ path: opts.route.path,
43
+ ...(component
44
+ ? {
45
+ file: opts.onResolveComponent
46
+ ? opts.onResolveComponent(component)
47
+ : component,
48
+ }
49
+ : {}),
50
+ parentId: opts.parentId,
51
+ id,
52
+ };
42
53
  if (absPath) {
43
54
  opts.memo.ret[id].absPath = absPath;
44
55
  }
56
+ if (wrappers === null || wrappers === void 0 ? void 0 : wrappers.length) {
57
+ let parentId = opts.parentId;
58
+ let path = opts.route.path;
59
+ wrappers.forEach((wrapper) => {
60
+ const { id } = transformRoute({
61
+ route: { path, component: wrapper },
62
+ parentId,
63
+ memo: opts.memo,
64
+ onResolveComponent: opts.onResolveComponent,
65
+ });
66
+ parentId = id;
67
+ path = '';
68
+ });
69
+ opts.memo.ret[id].parentId = parentId;
70
+ opts.memo.ret[id].path = path;
71
+ }
45
72
  if (opts.route.routes) {
46
73
  transformRoutes({
47
74
  routes: opts.route.routes,
@@ -49,4 +76,5 @@ function transformRoute(opts) {
49
76
  memo: opts.memo,
50
77
  });
51
78
  }
79
+ return { id };
52
80
  }
@@ -44,7 +44,7 @@ function visitFiles(opts) {
44
44
  let file = (0, path_1.resolve)(opts.dir, filename);
45
45
  let stat = (0, fs_1.lstatSync)(file);
46
46
  if (stat.isDirectory()) {
47
- visitFiles(Object.assign(Object.assign({}, opts), { dir: file }));
47
+ visitFiles({ ...opts, dir: file });
48
48
  }
49
49
  else if (stat.isFile() &&
50
50
  ['.tsx', '.ts', '.js', '.jsx', '.md', '.mdx', '.vue'].includes((0, path_1.extname)(file))) {
@@ -1,5 +1,6 @@
1
1
  import { yParser } from '@umijs/utils';
2
2
  import { Plugin } from './plugin';
3
+ import { ResolveConfigMode } from './pluginAPI';
3
4
  export interface IOpts {
4
5
  name: string;
5
6
  description?: string;
@@ -11,12 +12,14 @@ export interface IOpts {
11
12
  }): void;
12
13
  };
13
14
  plugin: Plugin;
15
+ configResolveMode?: ResolveConfigMode;
14
16
  }
15
17
  export declare class Command {
16
18
  name: string;
17
19
  description?: string;
18
20
  options?: string;
19
21
  details?: string;
22
+ configResolveMode: ResolveConfigMode;
20
23
  fn: {
21
24
  ({ args }: {
22
25
  args: yParser.Arguments;
@@ -9,6 +9,7 @@ class Command {
9
9
  this.details = opts.details;
10
10
  this.fn = opts.fn;
11
11
  this.plugin = opts.plugin;
12
+ this.configResolveMode = opts.configResolveMode || 'strict';
12
13
  }
13
14
  }
14
15
  exports.Command = Command;
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  const utils_1 = require("@umijs/utils");
13
4
  const generator_1 = require("./generator");
@@ -19,70 +10,74 @@ exports.default = (api) => {
19
10
  umi generate
20
11
  `,
21
12
  description: 'generate code snippets quickly',
22
- fn({ args }) {
13
+ configResolveMode: 'loose',
14
+ async fn({ args }) {
23
15
  var _a;
24
- return __awaiter(this, void 0, void 0, function* () {
25
- const [type] = args._;
26
- const runGenerator = (generator) => __awaiter(this, void 0, void 0, function* () {
27
- yield (generator === null || generator === void 0 ? void 0 : generator.fn({
16
+ const [type] = args._;
17
+ const runGenerator = async (generator) => {
18
+ await (generator === null || generator === void 0 ? void 0 : generator.fn({
19
+ args,
20
+ generateFile: utils_1.generateFile,
21
+ installDeps: utils_1.installDeps,
22
+ updatePackageJSON: utils_1.updatePackageJSON,
23
+ }));
24
+ };
25
+ if (type) {
26
+ const generator = api.service.generators[type];
27
+ if (!generator) {
28
+ throw new Error(`Generator ${type} not found.`);
29
+ }
30
+ if (generator.type === generator_1.GeneratorType.enable) {
31
+ const enable = await ((_a = generator.checkEnable) === null || _a === void 0 ? void 0 : _a.call(generator, {
28
32
  args,
29
- generateFile: utils_1.generateFile,
30
- installDeps: utils_1.installDeps,
31
- updatePackageJSON: utils_1.updatePackageJSON,
32
33
  }));
33
- });
34
- if (type) {
35
- const generator = api.service.generators[type];
36
- if (!generator) {
37
- throw new Error(`Generator ${type} not found.`);
38
- }
39
- if (generator.type === generator_1.GeneratorType.enable) {
40
- const enable = yield ((_a = generator.checkEnable) === null || _a === void 0 ? void 0 : _a.call(generator, {
41
- args,
42
- }));
43
- if (!enable) {
44
- throw new Error(`Generator ${type} is unable.The corresponding function has been turned on or is not available.`);
34
+ if (!enable) {
35
+ if (typeof generator.disabledDescription === 'function') {
36
+ utils_1.logger.warn(generator.disabledDescription());
37
+ }
38
+ else {
39
+ utils_1.logger.warn(generator.disabledDescription);
45
40
  }
41
+ return;
46
42
  }
47
- yield runGenerator(generator);
48
43
  }
49
- else {
50
- const getEnableGenerators = (generators) => __awaiter(this, void 0, void 0, function* () {
51
- var _b, _c;
52
- const questions = [];
53
- for (const key of Object.keys(generators)) {
54
- if (generators[key].type === generator_1.GeneratorType.generate) {
44
+ await runGenerator(generator);
45
+ }
46
+ else {
47
+ const getEnableGenerators = async (generators) => {
48
+ var _a;
49
+ const questions = [];
50
+ for (const key of Object.keys(generators)) {
51
+ const g = generators[key];
52
+ if (g.type === generator_1.GeneratorType.generate) {
53
+ questions.push({
54
+ title: `${g.name} -- ${g.description}` || '',
55
+ value: g.key,
56
+ });
57
+ }
58
+ else {
59
+ const enable = await ((_a = g === null || g === void 0 ? void 0 : g.checkEnable) === null || _a === void 0 ? void 0 : _a.call(g, {
60
+ args,
61
+ }));
62
+ if (enable) {
55
63
  questions.push({
56
- title: `${generators[key].name} -- ${generators[key].description}` ||
57
- '',
58
- value: generators[key].key,
64
+ title: `${g.name} -- ${g.description}` || '',
65
+ value: g.key,
59
66
  });
60
67
  }
61
- else {
62
- const enable = yield ((_c = (_b = generators[key]) === null || _b === void 0 ? void 0 : _b.checkEnable) === null || _c === void 0 ? void 0 : _c.call(_b, {
63
- args,
64
- }));
65
- if (enable) {
66
- questions.push({
67
- title: `${generators[key].name} -- ${generators[key].description}` ||
68
- '',
69
- value: generators[key].key,
70
- });
71
- }
72
- }
73
68
  }
74
- return questions;
75
- });
76
- const questions = yield getEnableGenerators(api.service.generators);
77
- const { gType } = yield (0, utils_1.prompts)({
78
- type: 'select',
79
- name: 'gType',
80
- message: 'Pick generator type',
81
- choices: questions,
82
- });
83
- yield runGenerator(api.service.generators[gType]);
84
- }
85
- });
69
+ }
70
+ return questions;
71
+ };
72
+ const questions = await getEnableGenerators(api.service.generators);
73
+ const { gType } = await (0, utils_1.prompts)({
74
+ type: 'select',
75
+ name: 'gType',
76
+ message: 'Pick generator type',
77
+ choices: questions,
78
+ });
79
+ await runGenerator(api.service.generators[gType]);
80
+ }
86
81
  },
87
82
  });
88
83
  };
@@ -4,16 +4,45 @@ export declare enum GeneratorType {
4
4
  generate = "generate",
5
5
  enable = "enable"
6
6
  }
7
- export interface IGeneratorOpts {
7
+ declare type IGeneratorOptsWithoutEnableCheck = {
8
8
  key: string;
9
9
  name: string;
10
10
  description: string;
11
- type?: GeneratorType;
12
- checkEnable?: {
11
+ type: GeneratorType.generate;
12
+ fn: {
13
+ (opts: {
14
+ args: any;
15
+ generateFile: typeof generateFile;
16
+ updatePackageJSON: {
17
+ (opts: {
18
+ opts: object;
19
+ cwd?: string;
20
+ }): void;
21
+ };
22
+ installDeps: {
23
+ (opts: {
24
+ opts: {
25
+ devDependencies?: string[];
26
+ dependencies?: string[];
27
+ };
28
+ cwd?: string;
29
+ }): void;
30
+ };
31
+ }): void;
32
+ };
33
+ plugin: Plugin;
34
+ };
35
+ declare type IGeneratorOptsWithEnableCheck = {
36
+ key: string;
37
+ name: string;
38
+ description: string;
39
+ type: GeneratorType.enable;
40
+ checkEnable: {
13
41
  (opts: {
14
42
  args: any;
15
43
  }): boolean;
16
44
  };
45
+ disabledDescription: string | (() => string);
17
46
  fn: {
18
47
  (opts: {
19
48
  args: any;
@@ -36,14 +65,7 @@ export interface IGeneratorOpts {
36
65
  }): void;
37
66
  };
38
67
  plugin: Plugin;
39
- }
40
- export declare class Generator {
41
- key: IGeneratorOpts['key'];
42
- name: IGeneratorOpts['name'];
43
- description: IGeneratorOpts['description'];
44
- type?: IGeneratorOpts['type'];
45
- checkEnable?: IGeneratorOpts['checkEnable'];
46
- fn: IGeneratorOpts['fn'];
47
- plugin: IGeneratorOpts['plugin'];
48
- constructor(opts: IGeneratorOpts);
49
- }
68
+ };
69
+ export declare type Generator = IGeneratorOptsWithEnableCheck | IGeneratorOptsWithoutEnableCheck;
70
+ export declare function makeGenerator<T>(opts: T): T;
71
+ export {};
@@ -1,20 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Generator = exports.GeneratorType = void 0;
3
+ exports.makeGenerator = exports.GeneratorType = void 0;
4
4
  var GeneratorType;
5
5
  (function (GeneratorType) {
6
6
  GeneratorType["generate"] = "generate";
7
7
  GeneratorType["enable"] = "enable";
8
8
  })(GeneratorType = exports.GeneratorType || (exports.GeneratorType = {}));
9
- class Generator {
10
- constructor(opts) {
11
- this.key = opts.key;
12
- this.name = opts.name;
13
- this.type = opts.type;
14
- this.description = opts.description;
15
- this.checkEnable = opts.checkEnable;
16
- this.fn = opts.fn;
17
- this.plugin = opts.plugin;
18
- }
9
+ function makeGenerator(opts) {
10
+ return {
11
+ ...opts,
12
+ };
19
13
  }
20
- exports.Generator = Generator;
14
+ exports.makeGenerator = makeGenerator;
@@ -12,3 +12,4 @@ export declare function getPaths(opts: {
12
12
  absNodeModulesPath: string;
13
13
  absOutputPath: string;
14
14
  };
15
+ export declare type Paths = ReturnType<typeof getPaths>;
@@ -1,11 +1,14 @@
1
1
  import { logger } from '@umijs/utils';
2
2
  import { EnableBy, Env, IPluginConfig } from '../types';
3
3
  import { IOpts as ICommandOpts } from './command';
4
- import { IGeneratorOpts } from './generator';
4
+ import { Generator } from './generator';
5
5
  import { IOpts as IHookOpts } from './hook';
6
6
  import { Plugin } from './plugin';
7
7
  import { Service } from './service';
8
8
  declare type Logger = typeof logger;
9
+ declare const resolveConfigModes: readonly ["strict", "loose"];
10
+ export declare type ResolveConfigMode = typeof resolveConfigModes[number];
11
+ declare type DistributiveOmit<T, K extends keyof any> = T extends any ? Omit<T, K> : never;
9
12
  export declare class PluginAPI {
10
13
  service: Service;
11
14
  plugin: Plugin;
@@ -25,7 +28,7 @@ export declare class PluginAPI {
25
28
  registerCommand(opts: Omit<ICommandOpts, 'plugin'> & {
26
29
  alias?: string | string[];
27
30
  }): void;
28
- registerGenerator(opts: Omit<IGeneratorOpts, 'plugin'>): void;
31
+ registerGenerator(opts: DistributiveOmit<Generator, 'plugin'>): void;
29
32
  register(opts: Omit<IHookOpts, 'plugin'>): void;
30
33
  registerMethod(opts: {
31
34
  name: string;
@@ -12,6 +12,7 @@ const generator_1 = require("./generator");
12
12
  const hook_1 = require("./hook");
13
13
  const plugin_1 = require("./plugin");
14
14
  const utils_2 = require("./utils");
15
+ const resolveConfigModes = ['strict', 'loose'];
15
16
  class PluginAPI {
16
17
  constructor(opts) {
17
18
  this.service = opts.service;
@@ -48,15 +49,20 @@ class PluginAPI {
48
49
  delete opts.alias;
49
50
  const registerCommand = (commandOpts) => {
50
51
  var _a;
51
- const { name } = commandOpts;
52
+ const { name, configResolveMode } = commandOpts;
53
+ (0, assert_1.default)(!configResolveMode ||
54
+ resolveConfigModes.indexOf(configResolveMode) >= 0, `configResolveMode must be one of ${resolveConfigModes.join(',')}, but got ${configResolveMode}`);
52
55
  (0, assert_1.default)(!this.service.commands[name], `api.registerCommand() failed, the command ${name} is exists from ${(_a = this.service.commands[name]) === null || _a === void 0 ? void 0 : _a.plugin.id}.`);
53
- this.service.commands[name] = new command_1.Command(Object.assign(Object.assign({}, commandOpts), { plugin: this.plugin }));
56
+ this.service.commands[name] = new command_1.Command({
57
+ ...commandOpts,
58
+ plugin: this.plugin,
59
+ });
54
60
  };
55
61
  registerCommand(opts);
56
62
  if (alias) {
57
63
  const aliases = (0, utils_2.makeArray)(alias);
58
64
  aliases.forEach((alias) => {
59
- registerCommand(Object.assign(Object.assign({}, opts), { name: alias }));
65
+ registerCommand({ ...opts, name: alias });
60
66
  });
61
67
  }
62
68
  }
@@ -64,13 +70,16 @@ class PluginAPI {
64
70
  var _a;
65
71
  const { key } = opts;
66
72
  (0, assert_1.default)(!this.service.generators[key], `api.registerGenerator() failed, the generator ${key} is exists from ${(_a = this.service.generators[key]) === null || _a === void 0 ? void 0 : _a.plugin.id}.`);
67
- this.service.generators[key] = new generator_1.Generator(Object.assign(Object.assign({}, opts), { plugin: this.plugin }));
73
+ this.service.generators[key] = (0, generator_1.makeGenerator)({
74
+ ...opts,
75
+ plugin: this.plugin,
76
+ });
68
77
  }
69
78
  register(opts) {
70
79
  var _a, _b;
71
80
  (0, assert_1.default)(this.service.stage <= types_1.ServiceStage.initPlugins, 'api.register() should not be called after plugin register stage.');
72
81
  (_a = this.service.hooks)[_b = opts.key] || (_a[_b] = []);
73
- this.service.hooks[opts.key].push(new hook_1.Hook(Object.assign(Object.assign({}, opts), { plugin: this.plugin })));
82
+ this.service.hooks[opts.key].push(new hook_1.Hook({ ...opts, plugin: this.plugin }));
74
83
  }
75
84
  registerMethod(opts) {
76
85
  (0, assert_1.default)(!this.service.pluginMethods[opts.name], `api.registerMethod() failed, method ${opts.name} is already exist.`);
@@ -81,7 +90,10 @@ class PluginAPI {
81
90
  // 否则 pluginId 会不会,导致不能正确 skip plugin
82
91
  function (fn) {
83
92
  // @ts-ignore
84
- this.register(Object.assign({ key: opts.name }, (utils_1.lodash.isPlainObject(fn) ? fn : { fn })));
93
+ this.register({
94
+ key: opts.name,
95
+ ...(utils_1.lodash.isPlainObject(fn) ? fn : { fn }),
96
+ });
85
97
  },
86
98
  };
87
99
  }
@@ -1,6 +1,6 @@
1
1
  import { yParser } from '@umijs/utils';
2
2
  import { Config } from '../config/config';
3
- import { ApplyPluginsType, ConfigChangeType, EnableBy, Env, IEvent, IModify, ServiceStage } from '../types';
3
+ import { ApplyPluginsType, ConfigChangeType, EnableBy, Env, IEvent, IFrameworkType, IModify, ServiceStage } from '../types';
4
4
  import { Command } from './command';
5
5
  import { Generator } from './generator';
6
6
  import { Hook } from './hook';
@@ -22,6 +22,7 @@ export declare class Service {
22
22
  subpaths: string[];
23
23
  external?: boolean;
24
24
  }>;
25
+ framework?: IFrameworkType;
25
26
  [key: string]: any;
26
27
  };
27
28
  args: yParser.Arguments;
@@ -80,6 +81,10 @@ export declare class Service {
80
81
  name: string;
81
82
  args?: any;
82
83
  }): Promise<void>;
84
+ resolveConfig(): Promise<{
85
+ config: any;
86
+ defaultConfig: any;
87
+ }>;
83
88
  _baconPlugins(): void;
84
89
  initPreset(opts: {
85
90
  preset: Plugin;
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -80,16 +71,16 @@ class Service {
80
71
  continue;
81
72
  tAdd.tapPromise({
82
73
  name: hook.plugin.key,
83
- stage: hook.stage,
74
+ stage: hook.stage || 0,
84
75
  before: hook.before,
85
- }, (memo) => __awaiter(this, void 0, void 0, function* () {
76
+ }, async (memo) => {
86
77
  var _a, _b;
87
78
  const dateStart = new Date();
88
- const items = yield hook.fn(opts.args);
79
+ const items = await hook.fn(opts.args);
89
80
  (_a = hook.plugin.time.hooks)[_b = opts.key] || (_a[_b] = []);
90
81
  hook.plugin.time.hooks[opts.key].push(new Date().getTime() - dateStart.getTime());
91
82
  return memo.concat(items);
92
- }));
83
+ });
93
84
  }
94
85
  return tAdd.promise(opts.initialValue || []);
95
86
  case types_1.ApplyPluginsType.modify:
@@ -99,16 +90,16 @@ class Service {
99
90
  continue;
100
91
  tModify.tapPromise({
101
92
  name: hook.plugin.key,
102
- stage: hook.stage,
93
+ stage: hook.stage || 0,
103
94
  before: hook.before,
104
- }, (memo) => __awaiter(this, void 0, void 0, function* () {
105
- var _c, _d;
95
+ }, async (memo) => {
96
+ var _a, _b;
106
97
  const dateStart = new Date();
107
- const ret = yield hook.fn(memo, opts.args);
108
- (_c = hook.plugin.time.hooks)[_d = opts.key] || (_c[_d] = []);
98
+ const ret = await hook.fn(memo, opts.args);
99
+ (_a = hook.plugin.time.hooks)[_b = opts.key] || (_a[_b] = []);
109
100
  hook.plugin.time.hooks[opts.key].push(new Date().getTime() - dateStart.getTime());
110
101
  return ret;
111
- }));
102
+ });
112
103
  }
113
104
  return tModify.promise(opts.initialValue);
114
105
  case types_1.ApplyPluginsType.event:
@@ -139,176 +130,186 @@ class Service {
139
130
  name: hook.plugin.key,
140
131
  stage: hook.stage || 0,
141
132
  before: hook.before,
142
- }, () => __awaiter(this, void 0, void 0, function* () {
143
- var _f, _g;
133
+ }, async () => {
134
+ var _a, _b;
144
135
  const dateStart = new Date();
145
- yield hook.fn(opts.args);
146
- (_f = hook.plugin.time.hooks)[_g = opts.key] || (_f[_g] = []);
136
+ await hook.fn(opts.args);
137
+ (_a = hook.plugin.time.hooks)[_b = opts.key] || (_a[_b] = []);
147
138
  hook.plugin.time.hooks[opts.key].push(new Date().getTime() - dateStart.getTime());
148
- }));
139
+ });
149
140
  }
150
141
  return tEvent.promise(1);
151
142
  default:
152
143
  throw new Error(`applyPlugins failed, type is not defined or is not matched, got ${opts.type}.`);
153
144
  }
154
145
  }
155
- run(opts) {
156
- return __awaiter(this, void 0, void 0, function* () {
157
- const { name, args = {} } = opts;
158
- args._ = args._ || [];
159
- // shift the command itself
160
- if (args._[0] === name)
161
- args._.shift();
162
- this.args = args;
163
- this.name = name;
164
- // loadEnv
165
- this.stage = types_1.ServiceStage.init;
166
- (0, env_1.loadEnv)({ cwd: this.cwd, envFile: '.env' });
167
- // get pkg from package.json
168
- let pkg = {};
169
- let pkgPath = '';
170
- try {
171
- pkg = require((0, path_1.join)(this.cwd, 'package.json'));
172
- pkgPath = (0, path_1.join)(this.cwd, 'package.json');
173
- }
174
- catch (_e) {
175
- // APP_ROOT
176
- if (this.cwd !== process.cwd()) {
177
- try {
178
- pkg = require((0, path_1.join)(process.cwd(), 'package.json'));
179
- pkgPath = (0, path_1.join)(process.cwd(), 'package.json');
180
- }
181
- catch (_e) { }
146
+ async run(opts) {
147
+ const { name, args = {} } = opts;
148
+ args._ = args._ || [];
149
+ // shift the command itself
150
+ if (args._[0] === name)
151
+ args._.shift();
152
+ this.args = args;
153
+ this.name = name;
154
+ // loadEnv
155
+ this.stage = types_1.ServiceStage.init;
156
+ (0, env_1.loadEnv)({ cwd: this.cwd, envFile: '.env' });
157
+ // get pkg from package.json
158
+ let pkg = {};
159
+ let pkgPath = '';
160
+ try {
161
+ pkg = require((0, path_1.join)(this.cwd, 'package.json'));
162
+ pkgPath = (0, path_1.join)(this.cwd, 'package.json');
163
+ }
164
+ catch (_e) {
165
+ // APP_ROOT
166
+ if (this.cwd !== process.cwd()) {
167
+ try {
168
+ pkg = require((0, path_1.join)(process.cwd(), 'package.json'));
169
+ pkgPath = (0, path_1.join)(process.cwd(), 'package.json');
182
170
  }
171
+ catch (_e) { }
183
172
  }
184
- this.pkg = pkg;
185
- this.pkgPath = pkgPath || (0, path_1.join)(this.cwd, 'package.json');
186
- const prefix = this.opts.frameworkName || constants_1.DEFAULT_FRAMEWORK_NAME;
187
- // get user config
188
- const configManager = new config_1.Config({
189
- cwd: this.cwd,
190
- env: this.env,
191
- defaultConfigFiles: this.opts.defaultConfigFiles,
192
- specifiedEnv: process.env[`${prefix}_ENV`.toUpperCase()],
173
+ }
174
+ this.pkg = pkg;
175
+ this.pkgPath = pkgPath || (0, path_1.join)(this.cwd, 'package.json');
176
+ const prefix = this.opts.frameworkName || constants_1.DEFAULT_FRAMEWORK_NAME;
177
+ // get user config
178
+ const configManager = new config_1.Config({
179
+ cwd: this.cwd,
180
+ env: this.env,
181
+ defaultConfigFiles: this.opts.defaultConfigFiles,
182
+ specifiedEnv: process.env[`${prefix}_ENV`.toUpperCase()],
183
+ });
184
+ this.configManager = configManager;
185
+ this.userConfig = configManager.getUserConfig().config;
186
+ // get paths
187
+ const paths = (0, path_2.getPaths)({
188
+ cwd: this.cwd,
189
+ env: this.env,
190
+ prefix: this.opts.frameworkName || constants_1.DEFAULT_FRAMEWORK_NAME,
191
+ });
192
+ // temporary paths for use by function generateFinalConfig.
193
+ // the value of paths may be updated by plugins later
194
+ this.paths = paths;
195
+ // resolve initial presets and plugins
196
+ const { plugins, presets } = plugin_1.Plugin.getPluginsAndPresets({
197
+ cwd: this.cwd,
198
+ pkg,
199
+ plugins: [require.resolve('./generatePlugin')].concat(this.opts.plugins || []),
200
+ presets: [require.resolve('./servicePlugin')].concat(this.opts.presets || []),
201
+ userConfig: this.userConfig,
202
+ prefix,
203
+ });
204
+ // register presets and plugins
205
+ this.stage = types_1.ServiceStage.initPresets;
206
+ const presetPlugins = [];
207
+ while (presets.length) {
208
+ await this.initPreset({
209
+ preset: presets.shift(),
210
+ presets,
211
+ plugins: presetPlugins,
193
212
  });
194
- this.configManager = configManager;
195
- this.userConfig = configManager.getUserConfig().config;
196
- // get paths (move after?)
197
- // resolve initial presets and plugins
198
- const { plugins, presets } = plugin_1.Plugin.getPluginsAndPresets({
213
+ }
214
+ plugins.unshift(...presetPlugins);
215
+ this.stage = types_1.ServiceStage.initPlugins;
216
+ while (plugins.length) {
217
+ await this.initPlugin({ plugin: plugins.shift(), plugins });
218
+ }
219
+ const command = this.commands[name];
220
+ (0, assert_1.default)(command, `Invalid command ${name}, it's not registered.`);
221
+ // collect configSchemas and configDefaults
222
+ for (const id of Object.keys(this.plugins)) {
223
+ const { config, key } = this.plugins[id];
224
+ if (config.schema)
225
+ this.configSchemas[key] = config.schema;
226
+ if (config.default !== undefined) {
227
+ this.configDefaults[key] = config.default;
228
+ }
229
+ this.configOnChanges[key] = config.onChange || types_1.ConfigChangeType.reload;
230
+ }
231
+ // setup api.config from modifyConfig and modifyDefaultConfig
232
+ this.stage = types_1.ServiceStage.resolveConfig;
233
+ const { config, defaultConfig } = await this.resolveConfig();
234
+ if (this.config.outputPath) {
235
+ paths.absOutputPath = (0, path_1.isAbsolute)(this.config.outputPath)
236
+ ? this.config.outputPath
237
+ : (0, path_1.join)(this.cwd, this.config.outputPath);
238
+ }
239
+ this.paths = await this.applyPlugins({
240
+ key: 'modifyPaths',
241
+ initialValue: paths,
242
+ });
243
+ // applyPlugin collect app data
244
+ // TODO: some data is mutable
245
+ this.stage = types_1.ServiceStage.collectAppData;
246
+ this.appData = await this.applyPlugins({
247
+ key: 'modifyAppData',
248
+ initialValue: {
249
+ // base
199
250
  cwd: this.cwd,
200
251
  pkg,
201
- plugins: [require.resolve('./generatePlugin')].concat(this.opts.plugins || []),
202
- presets: [require.resolve('./servicePlugin')].concat(this.opts.presets || []),
252
+ pkgPath,
253
+ plugins,
254
+ presets,
255
+ name,
256
+ args,
257
+ // config
203
258
  userConfig: this.userConfig,
204
- prefix,
205
- });
206
- // register presets and plugins
207
- this.stage = types_1.ServiceStage.initPresets;
208
- const presetPlugins = [];
209
- while (presets.length) {
210
- yield this.initPreset({
211
- preset: presets.shift(),
212
- presets,
213
- plugins: presetPlugins,
214
- });
215
- }
216
- plugins.unshift(...presetPlugins);
217
- this.stage = types_1.ServiceStage.initPlugins;
218
- while (plugins.length) {
219
- yield this.initPlugin({ plugin: plugins.shift(), plugins });
220
- }
221
- // collect configSchemas and configDefaults
222
- for (const id of Object.keys(this.plugins)) {
223
- const { config, key } = this.plugins[id];
224
- if (config.schema)
225
- this.configSchemas[key] = config.schema;
226
- if (config.default !== undefined) {
227
- this.configDefaults[key] = config.default;
228
- }
229
- this.configOnChanges[key] = config.onChange || types_1.ConfigChangeType.reload;
230
- }
231
- // setup api.config from modifyConfig and modifyDefaultConfig
232
- const paths = (0, path_2.getPaths)({
233
- cwd: this.cwd,
234
- env: this.env,
235
- prefix: this.opts.frameworkName || constants_1.DEFAULT_FRAMEWORK_NAME,
236
- });
237
- this.stage = types_1.ServiceStage.resolveConfig;
238
- const config = yield this.applyPlugins({
239
- key: 'modifyConfig',
240
- // why clone deep?
241
- // user may change the config in modifyConfig
242
- // e.g. memo.alias = xxx
243
- initialValue: utils_1.lodash.cloneDeep(configManager.getConfig({
259
+ mainConfigFile: configManager.mainConfigFile,
260
+ config,
261
+ defaultConfig: defaultConfig,
262
+ // TODO
263
+ // moduleGraph,
264
+ // routes,
265
+ // npmClient,
266
+ // nodeVersion,
267
+ // gitInfo,
268
+ // gitBranch,
269
+ // debugger info,
270
+ // devPort,
271
+ // devHost,
272
+ // env
273
+ },
274
+ });
275
+ // applyPlugin onCheck
276
+ this.stage = types_1.ServiceStage.onCheck;
277
+ await this.applyPlugins({
278
+ key: 'onCheck',
279
+ });
280
+ // applyPlugin onStart
281
+ this.stage = types_1.ServiceStage.onStart;
282
+ await this.applyPlugins({
283
+ key: 'onStart',
284
+ });
285
+ // run command
286
+ this.stage = types_1.ServiceStage.runCommand;
287
+ let ret = await command.fn({ args });
288
+ this._baconPlugins();
289
+ return ret;
290
+ }
291
+ async resolveConfig() {
292
+ // configManager and paths are not available until the init stage
293
+ (0, assert_1.default)(this.stage > types_1.ServiceStage.init, `Can't generate final config before init stage`);
294
+ const resolveMode = this.commands[this.name].configResolveMode;
295
+ const config = await this.applyPlugins({
296
+ key: 'modifyConfig',
297
+ // why clone deep?
298
+ // user may change the config in modifyConfig
299
+ // e.g. memo.alias = xxx
300
+ initialValue: utils_1.lodash.cloneDeep(resolveMode === 'strict'
301
+ ? this.configManager.getConfig({
244
302
  schemas: this.configSchemas,
245
- }).config),
246
- args: { paths },
247
- });
248
- const defaultConfig = yield this.applyPlugins({
249
- key: 'modifyDefaultConfig',
250
- initialValue: this.configDefaults,
251
- });
252
- this.config = utils_1.lodash.merge(defaultConfig, config);
253
- if (this.config.outputPath) {
254
- paths.absOutputPath = (0, path_1.isAbsolute)(this.config.outputPath)
255
- ? this.config.outputPath
256
- : (0, path_1.join)(this.cwd, this.config.outputPath);
257
- }
258
- this.paths = yield this.applyPlugins({
259
- key: 'modifyPaths',
260
- initialValue: paths,
261
- });
262
- // applyPlugin collect app data
263
- // TODO: some data is mutable
264
- this.stage = types_1.ServiceStage.collectAppData;
265
- this.appData = yield this.applyPlugins({
266
- key: 'modifyAppData',
267
- initialValue: {
268
- // base
269
- cwd: this.cwd,
270
- pkg,
271
- pkgPath,
272
- plugins,
273
- presets,
274
- name,
275
- args,
276
- // config
277
- userConfig: this.userConfig,
278
- mainConfigFile: configManager.mainConfigFile,
279
- config,
280
- defaultConfig: defaultConfig,
281
- // TODO
282
- // moduleGraph,
283
- // routes,
284
- // npmClient,
285
- // nodeVersion,
286
- // gitInfo,
287
- // gitBranch,
288
- // debugger info,
289
- // devPort,
290
- // devHost,
291
- // env
292
- },
293
- });
294
- // applyPlugin onCheck
295
- this.stage = types_1.ServiceStage.onCheck;
296
- yield this.applyPlugins({
297
- key: 'onCheck',
298
- });
299
- // applyPlugin onStart
300
- this.stage = types_1.ServiceStage.onStart;
301
- yield this.applyPlugins({
302
- key: 'onStart',
303
- });
304
- // run command
305
- this.stage = types_1.ServiceStage.runCommand;
306
- const command = this.commands[name];
307
- (0, assert_1.default)(command, `Invalid command ${name}, it's not registered.`);
308
- let ret = yield command.fn({ args });
309
- this._baconPlugins();
310
- return ret;
303
+ }).config
304
+ : this.configManager.getUserConfig().config),
305
+ args: { paths: this.paths },
311
306
  });
307
+ const defaultConfig = await this.applyPlugins({
308
+ key: 'modifyDefaultConfig',
309
+ initialValue: this.configDefaults,
310
+ });
311
+ this.config = utils_1.lodash.merge(defaultConfig, config);
312
+ return { config, defaultConfig };
312
313
  }
313
314
  _baconPlugins() {
314
315
  // TODO: prettier
@@ -320,80 +321,76 @@ class Service {
320
321
  }
321
322
  }
322
323
  }
323
- initPreset(opts) {
324
- return __awaiter(this, void 0, void 0, function* () {
325
- const { presets, plugins } = yield this.initPlugin({
326
- plugin: opts.preset,
327
- presets: opts.presets,
328
- plugins: opts.plugins,
329
- });
330
- opts.presets.unshift(...(presets || []));
331
- opts.plugins.push(...(plugins || []));
324
+ async initPreset(opts) {
325
+ const { presets, plugins } = await this.initPlugin({
326
+ plugin: opts.preset,
327
+ presets: opts.presets,
328
+ plugins: opts.plugins,
332
329
  });
330
+ opts.presets.unshift(...(presets || []));
331
+ opts.plugins.push(...(plugins || []));
333
332
  }
334
- initPlugin(opts) {
333
+ async initPlugin(opts) {
335
334
  var _a, _b;
336
- return __awaiter(this, void 0, void 0, function* () {
337
- // register to this.plugins
338
- (0, assert_1.default)(!this.plugins[opts.plugin.id], `${opts.plugin.type} ${opts.plugin.id} is already registered by ${(_a = this.plugins[opts.plugin.id]) === null || _a === void 0 ? void 0 : _a.path}, ${opts.plugin.type} from ${opts.plugin.path} register failed.`);
339
- this.plugins[opts.plugin.id] = opts.plugin;
340
- // apply with PluginAPI
341
- const pluginAPI = new pluginAPI_1.PluginAPI({
342
- plugin: opts.plugin,
343
- service: this,
344
- });
345
- pluginAPI.registerPresets = pluginAPI.registerPresets.bind(pluginAPI, opts.presets || []);
346
- pluginAPI.registerPlugins = pluginAPI.registerPlugins.bind(pluginAPI, opts.plugins);
347
- const proxyPluginAPI = pluginAPI_1.PluginAPI.proxyPluginAPI({
335
+ // register to this.plugins
336
+ (0, assert_1.default)(!this.plugins[opts.plugin.id], `${opts.plugin.type} ${opts.plugin.id} is already registered by ${(_a = this.plugins[opts.plugin.id]) === null || _a === void 0 ? void 0 : _a.path}, ${opts.plugin.type} from ${opts.plugin.path} register failed.`);
337
+ this.plugins[opts.plugin.id] = opts.plugin;
338
+ // apply with PluginAPI
339
+ const pluginAPI = new pluginAPI_1.PluginAPI({
340
+ plugin: opts.plugin,
341
+ service: this,
342
+ });
343
+ pluginAPI.registerPresets = pluginAPI.registerPresets.bind(pluginAPI, opts.presets || []);
344
+ pluginAPI.registerPlugins = pluginAPI.registerPlugins.bind(pluginAPI, opts.plugins);
345
+ const proxyPluginAPI = pluginAPI_1.PluginAPI.proxyPluginAPI({
346
+ service: this,
347
+ pluginAPI,
348
+ serviceProps: [
349
+ 'appData',
350
+ 'applyPlugins',
351
+ 'args',
352
+ 'config',
353
+ 'cwd',
354
+ 'pkg',
355
+ 'pkgPath',
356
+ 'name',
357
+ 'paths',
358
+ 'userConfig',
359
+ 'env',
360
+ 'isPluginEnable',
361
+ ],
362
+ staticProps: {
363
+ ApplyPluginsType: types_1.ApplyPluginsType,
364
+ ConfigChangeType: types_1.ConfigChangeType,
365
+ EnableBy: types_1.EnableBy,
366
+ ServiceStage: types_1.ServiceStage,
348
367
  service: this,
349
- pluginAPI,
350
- serviceProps: [
351
- 'appData',
352
- 'applyPlugins',
353
- 'args',
354
- 'config',
355
- 'cwd',
356
- 'pkg',
357
- 'pkgPath',
358
- 'name',
359
- 'paths',
360
- 'userConfig',
361
- 'env',
362
- 'isPluginEnable',
363
- ],
364
- staticProps: {
365
- ApplyPluginsType: types_1.ApplyPluginsType,
366
- ConfigChangeType: types_1.ConfigChangeType,
367
- EnableBy: types_1.EnableBy,
368
- ServiceStage: types_1.ServiceStage,
369
- service: this,
370
- },
371
- });
372
- let dateStart = new Date();
373
- let ret = yield opts.plugin.apply()(proxyPluginAPI);
374
- opts.plugin.time.register = new Date().getTime() - dateStart.getTime();
375
- if (opts.plugin.type === 'plugin') {
376
- (0, assert_1.default)(!ret, `plugin should return nothing`);
377
- }
378
- // key should be unique
379
- (0, assert_1.default)(!this.keyToPluginMap[opts.plugin.key], `key ${opts.plugin.key} is already registered by ${(_b = this.keyToPluginMap[opts.plugin.key]) === null || _b === void 0 ? void 0 : _b.path}, ${opts.plugin.type} from ${opts.plugin.path} register failed.`);
380
- this.keyToPluginMap[opts.plugin.key] = opts.plugin;
381
- if (ret === null || ret === void 0 ? void 0 : ret.presets) {
382
- ret.presets = ret.presets.map((preset) => new plugin_1.Plugin({
383
- path: preset,
384
- type: types_1.PluginType.preset,
385
- cwd: this.cwd,
386
- }));
387
- }
388
- if (ret === null || ret === void 0 ? void 0 : ret.plugins) {
389
- ret.plugins = ret.plugins.map((plugin) => new plugin_1.Plugin({
390
- path: plugin,
391
- type: types_1.PluginType.plugin,
392
- cwd: this.cwd,
393
- }));
394
- }
395
- return ret || {};
368
+ },
396
369
  });
370
+ let dateStart = new Date();
371
+ let ret = await opts.plugin.apply()(proxyPluginAPI);
372
+ opts.plugin.time.register = new Date().getTime() - dateStart.getTime();
373
+ if (opts.plugin.type === 'plugin') {
374
+ (0, assert_1.default)(!ret, `plugin should return nothing`);
375
+ }
376
+ // key should be unique
377
+ (0, assert_1.default)(!this.keyToPluginMap[opts.plugin.key], `key ${opts.plugin.key} is already registered by ${(_b = this.keyToPluginMap[opts.plugin.key]) === null || _b === void 0 ? void 0 : _b.path}, ${opts.plugin.type} from ${opts.plugin.path} register failed.`);
378
+ this.keyToPluginMap[opts.plugin.key] = opts.plugin;
379
+ if (ret === null || ret === void 0 ? void 0 : ret.presets) {
380
+ ret.presets = ret.presets.map((preset) => new plugin_1.Plugin({
381
+ path: preset,
382
+ type: types_1.PluginType.preset,
383
+ cwd: this.cwd,
384
+ }));
385
+ }
386
+ if (ret === null || ret === void 0 ? void 0 : ret.plugins) {
387
+ ret.plugins = ret.plugins.map((plugin) => new plugin_1.Plugin({
388
+ path: plugin,
389
+ type: types_1.PluginType.plugin,
390
+ cwd: this.cwd,
391
+ }));
392
+ }
393
+ return ret || {};
397
394
  }
398
395
  isPluginEnable(hook) {
399
396
  let plugin;
package/dist/types.d.ts CHANGED
@@ -108,3 +108,4 @@ export interface IAdd<T, U> {
108
108
  };
109
109
  }): void;
110
110
  }
111
+ export declare type IFrameworkType = 'vue' | 'react';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umijs/core",
3
- "version": "4.0.0-rc.13",
3
+ "version": "4.0.0-rc.16",
4
4
  "homepage": "https://github.com/umijs/umi-next/tree/master/packages/core#readme",
5
5
  "bugs": "https://github.com/umijs/umi-next/issues",
6
6
  "repository": {
@@ -16,13 +16,13 @@
16
16
  ],
17
17
  "scripts": {
18
18
  "build": "pnpm tsc",
19
- "build:deps": "pnpm esno ../../scripts/bundleDeps.ts",
19
+ "build:deps": "umi-scripts bundleDeps",
20
20
  "dev": "pnpm build -- --watch",
21
- "test": "jest -c ../../jest.turbo.config.ts"
21
+ "test": "umi-scripts jest-turbo"
22
22
  },
23
23
  "dependencies": {
24
- "@umijs/bundler-utils": "4.0.0-rc.13",
25
- "@umijs/utils": "4.0.0-rc.13"
24
+ "@umijs/bundler-utils": "4.0.0-rc.16",
25
+ "@umijs/utils": "4.0.0-rc.16"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@hapi/joi": "17.1.1",