@umijs/core 3.5.18 → 4.0.0-beta.2

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 (88) hide show
  1. package/README.md +2 -0
  2. package/dist/config/config.d.ts +63 -0
  3. package/dist/config/config.js +182 -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 +6 -0
  9. package/dist/index.js +21 -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/generatePlugin.d.ts +4 -0
  27. package/dist/service/generatePlugin.js +91 -0
  28. package/dist/service/generator.d.ts +60 -0
  29. package/dist/service/generator.js +20 -0
  30. package/dist/service/hook.d.ts +16 -0
  31. package/dist/service/hook.js +18 -0
  32. package/dist/service/path.d.ts +13 -0
  33. package/dist/service/path.js +31 -0
  34. package/dist/service/plugin.d.ts +53 -0
  35. package/dist/service/plugin.js +137 -0
  36. package/dist/service/pluginAPI.d.ts +37 -0
  37. package/dist/service/pluginAPI.js +127 -0
  38. package/dist/service/service.d.ts +94 -0
  39. package/dist/service/service.js +342 -0
  40. package/dist/service/servicePlugin.d.ts +3 -0
  41. package/dist/service/servicePlugin.js +14 -0
  42. package/dist/service/utils.d.ts +2 -0
  43. package/dist/service/utils.js +12 -0
  44. package/dist/types.d.ts +108 -0
  45. package/dist/types.js +42 -0
  46. package/package.json +35 -15
  47. package/lib/Config/Config.d.ts +0 -39
  48. package/lib/Config/Config.js +0 -348
  49. package/lib/Config/types.d.ts +0 -21
  50. package/lib/Config/utils/configUtils.d.ts +0 -9
  51. package/lib/Config/utils/configUtils.js +0 -54
  52. package/lib/Config/utils/isEqual.d.ts +0 -1
  53. package/lib/Config/utils/isEqual.js +0 -45
  54. package/lib/Config/utils/mergeDefault.d.ts +0 -6
  55. package/lib/Config/utils/mergeDefault.js +0 -41
  56. package/lib/Html/Html.d.ts +0 -16
  57. package/lib/Html/Html.js +0 -292
  58. package/lib/Html/document.ejs +0 -12
  59. package/lib/Html/types.d.ts +0 -55
  60. package/lib/Logger/Common.d.ts +0 -13
  61. package/lib/Logger/Common.js +0 -53
  62. package/lib/Logger/Logger.d.ts +0 -17
  63. package/lib/Logger/Logger.js +0 -87
  64. package/lib/Route/Route.d.ts +0 -32
  65. package/lib/Route/Route.js +0 -228
  66. package/lib/Route/getConventionalRoutes.d.ts +0 -10
  67. package/lib/Route/getConventionalRoutes.js +0 -259
  68. package/lib/Route/routesToJSON.d.ts +0 -9
  69. package/lib/Route/routesToJSON.js +0 -140
  70. package/lib/Route/types.d.ts +0 -11
  71. package/lib/Service/PluginAPI.d.ts +0 -38
  72. package/lib/Service/PluginAPI.js +0 -193
  73. package/lib/Service/Service.d.ts +0 -96
  74. package/lib/Service/Service.js +0 -694
  75. package/lib/Service/enums.d.ts +0 -29
  76. package/lib/Service/enums.js +0 -67
  77. package/lib/Service/getPaths.d.ts +0 -6
  78. package/lib/Service/getPaths.js +0 -79
  79. package/lib/Service/types.d.ts +0 -52
  80. package/lib/Service/types.js +0 -17
  81. package/lib/Service/utils/isPromise.d.ts +0 -1
  82. package/lib/Service/utils/isPromise.js +0 -22
  83. package/lib/Service/utils/loadDotEnv.d.ts +0 -5
  84. package/lib/Service/utils/loadDotEnv.js +0 -54
  85. package/lib/Service/utils/pluginUtils.d.ts +0 -42
  86. package/lib/Service/utils/pluginUtils.js +0 -201
  87. package/lib/index.d.ts +0 -14
  88. package/lib/index.js +0 -81
@@ -0,0 +1,91 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const utils_1 = require("@umijs/utils");
13
+ const generator_1 = require("./generator");
14
+ exports.default = (api) => {
15
+ api.registerCommand({
16
+ name: 'generate',
17
+ alias: 'g',
18
+ details: `
19
+ umi generate
20
+ `,
21
+ description: 'generate code snippets quickly',
22
+ fn({ args }) {
23
+ var _a;
24
+ return __awaiter(this, void 0, void 0, function* () {
25
+ const [type] = args._;
26
+ const runGenerator = (generator) => {
27
+ generator === null || generator === void 0 ? void 0 : generator.fn({
28
+ api,
29
+ args,
30
+ generateFile: utils_1.generateFile,
31
+ installDeps: utils_1.installDeps,
32
+ updatePackageJSON: utils_1.updatePackageJSON,
33
+ });
34
+ };
35
+ if (type) {
36
+ const generator = api.service.generators[type];
37
+ if (!generator) {
38
+ throw new Error(`Generator ${type} not found.`);
39
+ }
40
+ if (generator.type === generator_1.GeneratorType.enable) {
41
+ const enable = yield ((_a = generator.checkEnable) === null || _a === void 0 ? void 0 : _a.call(generator, {
42
+ api,
43
+ args,
44
+ }));
45
+ if (!enable) {
46
+ throw new Error(`Generator ${type} is unable.The corresponding function has been turned on or is not available.`);
47
+ }
48
+ }
49
+ runGenerator(generator);
50
+ }
51
+ else {
52
+ const getEnableGenerators = (generators) => __awaiter(this, void 0, void 0, function* () {
53
+ const questions = [];
54
+ Object.keys(generators).forEach((key) => __awaiter(this, void 0, void 0, function* () {
55
+ var _b, _c;
56
+ if (generators[key].type === generator_1.GeneratorType.generate) {
57
+ questions.push({
58
+ title: `${generators[key].name} -- ${generators[key].description}` ||
59
+ '',
60
+ value: generators[key].key,
61
+ });
62
+ }
63
+ else {
64
+ const enable = yield ((_c = (_b = generators[key]) === null || _b === void 0 ? void 0 : _b.checkEnable) === null || _c === void 0 ? void 0 : _c.call(_b, {
65
+ api,
66
+ args,
67
+ }));
68
+ if (enable) {
69
+ questions.push({
70
+ title: `${generators[key].name} -- ${generators[key].description}` ||
71
+ '',
72
+ value: generators[key].key,
73
+ });
74
+ }
75
+ }
76
+ }));
77
+ return questions;
78
+ });
79
+ const questions = yield getEnableGenerators(api.service.generators);
80
+ const { gType } = yield (0, utils_1.prompts)({
81
+ type: 'select',
82
+ name: 'gType',
83
+ message: 'Pick generator type',
84
+ choices: questions,
85
+ });
86
+ runGenerator(api.service.generators[gType]);
87
+ }
88
+ });
89
+ },
90
+ });
91
+ };
@@ -0,0 +1,60 @@
1
+ import { prompts } from '@umijs/utils';
2
+ import { Plugin } from './plugin';
3
+ import { PluginAPI } from './pluginAPI';
4
+ import { IServicePluginAPI } from './service';
5
+ export declare enum GeneratorType {
6
+ generate = "generate",
7
+ enable = "enable"
8
+ }
9
+ export interface IGeneratorOpts {
10
+ key: string;
11
+ name?: string;
12
+ description?: string;
13
+ type?: GeneratorType;
14
+ checkEnable?: {
15
+ (opts: {
16
+ args: any;
17
+ api: PluginAPI & IServicePluginAPI;
18
+ }): boolean;
19
+ };
20
+ fn: {
21
+ (opts: {
22
+ args: any;
23
+ api: PluginAPI & IServicePluginAPI;
24
+ generateFile: {
25
+ (opts: {
26
+ path: string;
27
+ target: string;
28
+ data?: any;
29
+ questions?: prompts.PromptObject[];
30
+ }): void;
31
+ };
32
+ updatePackageJSON: {
33
+ (opts: {
34
+ opts: object;
35
+ cwd?: string;
36
+ }): void;
37
+ };
38
+ installDeps: {
39
+ (opts: {
40
+ opts: {
41
+ devDependencies?: string[];
42
+ dependencies?: string[];
43
+ };
44
+ cwd?: string;
45
+ }): void;
46
+ };
47
+ }): void;
48
+ };
49
+ plugin: Plugin;
50
+ }
51
+ export declare class Generator {
52
+ key: IGeneratorOpts['key'];
53
+ name?: IGeneratorOpts['name'];
54
+ description?: IGeneratorOpts['description'];
55
+ type?: IGeneratorOpts['type'];
56
+ checkEnable?: IGeneratorOpts['checkEnable'];
57
+ fn: IGeneratorOpts['fn'];
58
+ plugin: IGeneratorOpts['plugin'];
59
+ constructor(opts: IGeneratorOpts);
60
+ }
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Generator = exports.GeneratorType = void 0;
4
+ var GeneratorType;
5
+ (function (GeneratorType) {
6
+ GeneratorType["generate"] = "generate";
7
+ GeneratorType["enable"] = "enable";
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
+ }
19
+ }
20
+ exports.Generator = Generator;
@@ -0,0 +1,16 @@
1
+ import { Plugin } from './plugin';
2
+ export interface IOpts {
3
+ plugin: Plugin;
4
+ key: string;
5
+ fn: Function;
6
+ before?: string;
7
+ stage?: number;
8
+ }
9
+ export declare class Hook {
10
+ plugin: Plugin;
11
+ key: string;
12
+ fn: Function;
13
+ before?: string;
14
+ stage?: number;
15
+ constructor(opts: IOpts);
16
+ }
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Hook = void 0;
7
+ const assert_1 = __importDefault(require("assert"));
8
+ class Hook {
9
+ constructor(opts) {
10
+ (0, assert_1.default)(opts.key && opts.fn, `Invalid hook ${opts}, key and fn must supplied.`);
11
+ this.plugin = opts.plugin;
12
+ this.key = opts.key;
13
+ this.fn = opts.fn;
14
+ this.before = opts.before;
15
+ this.stage = opts.stage || 0;
16
+ }
17
+ }
18
+ exports.Hook = Hook;
@@ -0,0 +1,13 @@
1
+ import { Env } from '../types';
2
+ export declare function getPaths(opts: {
3
+ cwd: string;
4
+ prefix: string;
5
+ env: Env;
6
+ }): {
7
+ cwd: string;
8
+ absSrcPath: string;
9
+ absPagesPath: string;
10
+ absTmpPath: string;
11
+ absNodeModulesPath: string;
12
+ absOutputPath: string;
13
+ };
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getPaths = void 0;
4
+ const utils_1 = require("@umijs/utils");
5
+ const fs_1 = require("fs");
6
+ const path_1 = require("path");
7
+ const types_1 = require("../types");
8
+ function winJoin(...args) {
9
+ return (0, utils_1.winPath)((0, path_1.join)(...args));
10
+ }
11
+ function getPaths(opts) {
12
+ const cwd = opts.cwd;
13
+ const src = winJoin(cwd, 'src');
14
+ const absSrcPath = (0, fs_1.existsSync)(src) && (0, fs_1.statSync)(src).isDirectory() ? src : cwd;
15
+ const absPagesPath = winJoin(absSrcPath, 'pages');
16
+ const tmp = opts.env === types_1.Env.development
17
+ ? `.${opts.prefix}`
18
+ : `.${opts.prefix}-${opts.env}`;
19
+ const absTmpPath = winJoin(absSrcPath, tmp);
20
+ const absNodeModulesPath = winJoin(cwd, 'node_modules');
21
+ const absOutputPath = winJoin(cwd, 'dist');
22
+ return {
23
+ cwd,
24
+ absSrcPath,
25
+ absPagesPath,
26
+ absTmpPath,
27
+ absNodeModulesPath,
28
+ absOutputPath,
29
+ };
30
+ }
31
+ exports.getPaths = getPaths;
@@ -0,0 +1,53 @@
1
+ import { EnableBy, IPluginConfig } from '../types';
2
+ declare type PluginType = 'plugin' | 'preset';
3
+ interface IOpts {
4
+ path: string;
5
+ cwd: string;
6
+ type: PluginType;
7
+ }
8
+ export interface IPluginObject {
9
+ id: string;
10
+ key: string;
11
+ apply?: Function;
12
+ config?: IPluginConfig;
13
+ enableBy?: EnableBy | (() => boolean);
14
+ }
15
+ export declare class Plugin {
16
+ private cwd;
17
+ type: PluginType;
18
+ path: string;
19
+ id: string;
20
+ key: string;
21
+ apply: Function;
22
+ config: IPluginConfig;
23
+ enableBy: EnableBy | (() => boolean);
24
+ constructor(opts: IOpts);
25
+ merge(opts: {
26
+ key?: string;
27
+ config?: IPluginConfig;
28
+ enableBy?: EnableBy | (() => boolean);
29
+ }): void;
30
+ getId(opts: {
31
+ pkg: any;
32
+ isPkgEntry: boolean;
33
+ pkgJSONPath: string | null;
34
+ }): any;
35
+ getKey(opts: {
36
+ pkg: any;
37
+ isPkgEntry: boolean;
38
+ }): string;
39
+ static isPluginOrPreset(type: 'plugin' | 'preset', name: string): boolean;
40
+ static stripNoneUmiScope(name: string): string;
41
+ static getPluginsAndPresets(opts: {
42
+ cwd: string;
43
+ pkg: any;
44
+ userConfig: any;
45
+ plugins?: string[];
46
+ presets?: string[];
47
+ prefix: string;
48
+ }): {
49
+ presets: Plugin[];
50
+ plugins: Plugin[];
51
+ };
52
+ }
53
+ export {};
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Plugin = void 0;
7
+ const utils_1 = require("@umijs/utils");
8
+ const assert_1 = __importDefault(require("assert"));
9
+ const fs_1 = require("fs");
10
+ const path_1 = require("path");
11
+ const types_1 = require("../types");
12
+ const RE = {
13
+ plugin: /^(@umijs\/|umi-)plugin-/,
14
+ preset: /^(@umijs\/|umi-)preset-/,
15
+ };
16
+ class Plugin {
17
+ constructor(opts) {
18
+ this.config = {};
19
+ this.enableBy = types_1.EnableBy.register;
20
+ this.type = opts.type;
21
+ this.path = (0, utils_1.winPath)(opts.path);
22
+ this.cwd = opts.cwd;
23
+ (0, assert_1.default)((0, fs_1.existsSync)(this.path), `Invalid ${this.type} ${this.path}, it's not exists.`);
24
+ let pkg = null;
25
+ // path is the package entry
26
+ let isPkgEntry = false;
27
+ const pkgJSONPath = utils_1.pkgUp.sync({ cwd: this.path });
28
+ if (pkgJSONPath) {
29
+ pkg = require(pkgJSONPath);
30
+ isPkgEntry =
31
+ (0, utils_1.winPath)((0, path_1.join)((0, path_1.dirname)(pkgJSONPath), pkg.main || 'index.js')) ===
32
+ (0, utils_1.winPath)(this.path);
33
+ }
34
+ this.id = this.getId({ pkg, isPkgEntry, pkgJSONPath });
35
+ this.key = this.getKey({ pkg, isPkgEntry });
36
+ this.apply = () => {
37
+ try {
38
+ const ret = require(this.path);
39
+ // use the default member for es modules
40
+ return ret.__esModule ? ret.default : ret;
41
+ }
42
+ catch (e) {
43
+ throw new Error(`Register ${this.type} ${this.path} failed, since ${e.message}`);
44
+ }
45
+ };
46
+ }
47
+ merge(opts) {
48
+ if (opts.key)
49
+ this.key = opts.key;
50
+ if (opts.config)
51
+ this.config = opts.config;
52
+ if (opts.enableBy)
53
+ this.enableBy = opts.enableBy;
54
+ }
55
+ getId(opts) {
56
+ let id;
57
+ if (opts.isPkgEntry) {
58
+ id = opts.pkg.name;
59
+ }
60
+ else if ((0, utils_1.winPath)(this.path).startsWith((0, utils_1.winPath)(this.cwd))) {
61
+ id = `./${(0, utils_1.winPath)((0, path_1.relative)(this.cwd, this.path))}`;
62
+ }
63
+ else if (opts.pkgJSONPath) {
64
+ id = (0, utils_1.winPath)((0, path_1.join)(opts.pkg.name, (0, path_1.relative)((0, path_1.dirname)(opts.pkgJSONPath), this.path)));
65
+ }
66
+ else {
67
+ id = (0, utils_1.winPath)(this.path);
68
+ }
69
+ id = id.replace('@umijs/preset-built-in/lib/plugins', '@@');
70
+ id = id.replace(/\.js$/, '');
71
+ return id;
72
+ }
73
+ getKey(opts) {
74
+ // e.g.
75
+ // initial-state -> initialState
76
+ // webpack.css-loader -> webpack.cssLoader
77
+ function nameToKey(name) {
78
+ return name
79
+ .split('.')
80
+ .map((part) => utils_1.lodash.camelCase(part))
81
+ .join('.');
82
+ }
83
+ return nameToKey(opts.isPkgEntry
84
+ ? Plugin.stripNoneUmiScope(opts.pkg.name).replace(RE[this.type], '')
85
+ : (0, path_1.basename)(this.path, (0, path_1.extname)(this.path)));
86
+ }
87
+ static isPluginOrPreset(type, name) {
88
+ return RE[type].test(Plugin.stripNoneUmiScope(name));
89
+ }
90
+ static stripNoneUmiScope(name) {
91
+ if (name.charAt(0) === '@' && !name.startsWith('@umijs/')) {
92
+ name = name.split('/')[1];
93
+ }
94
+ return name;
95
+ }
96
+ static getPluginsAndPresets(opts) {
97
+ function get(type) {
98
+ const types = `${type}s`;
99
+ return [
100
+ // opts
101
+ ...(opts[types] || []),
102
+ // env
103
+ ...(process.env[`${opts.prefix}_${types}`.toUpperCase()] || '')
104
+ .split(',')
105
+ .filter(Boolean),
106
+ // dependencies
107
+ ...Object.keys(opts.pkg.devDependencies || {})
108
+ .concat(Object.keys(opts.pkg.dependencies || {}))
109
+ .filter(Plugin.isPluginOrPreset.bind(null, type)),
110
+ // user config
111
+ ...(opts.userConfig[types] || []),
112
+ ].map((path) => {
113
+ (0, assert_1.default)(typeof path === 'string', `Invalid plugin ${path}, it must be string.`);
114
+ let resolved;
115
+ try {
116
+ resolved = utils_1.resolve.sync(path, {
117
+ basedir: opts.cwd,
118
+ extensions: ['.tsx', '.ts', '.mjs', '.jsx', '.js'],
119
+ });
120
+ }
121
+ catch (_e) {
122
+ throw new Error(`Invalid plugin ${path}, can not be resolved.`);
123
+ }
124
+ return new Plugin({
125
+ path: resolved,
126
+ type,
127
+ cwd: opts.cwd,
128
+ });
129
+ });
130
+ }
131
+ return {
132
+ presets: get('preset'),
133
+ plugins: get('plugin'),
134
+ };
135
+ }
136
+ }
137
+ exports.Plugin = Plugin;
@@ -0,0 +1,37 @@
1
+ import { EnableBy, IPluginConfig } from '../types';
2
+ import { IOpts as ICommandOpts } from './command';
3
+ import { IGeneratorOpts } from './generator';
4
+ import { IOpts as IHookOpts } from './hook';
5
+ import { Plugin } from './plugin';
6
+ import { Service } from './service';
7
+ export declare class PluginAPI {
8
+ service: Service;
9
+ plugin: Plugin;
10
+ constructor(opts: {
11
+ service: Service;
12
+ plugin: Plugin;
13
+ });
14
+ describe(opts: {
15
+ key?: string;
16
+ config?: IPluginConfig;
17
+ enableBy?: EnableBy | (() => boolean);
18
+ }): void;
19
+ registerCommand(opts: Omit<ICommandOpts, 'plugin'> & {
20
+ alias?: string | string[];
21
+ }): void;
22
+ registerGenerator(opts: Omit<IGeneratorOpts, 'plugin'>): void;
23
+ register(opts: Omit<IHookOpts, 'plugin'>): void;
24
+ registerMethod(opts: {
25
+ name: string;
26
+ fn?: Function;
27
+ }): void;
28
+ registerPresets(source: Plugin[], presets: any[]): void;
29
+ registerPlugins(source: Plugin[], plugins: any[]): void;
30
+ skipPlugins(ids: string[]): void;
31
+ static proxyPluginAPI(opts: {
32
+ pluginAPI: PluginAPI;
33
+ service: Service;
34
+ serviceProps: string[];
35
+ staticProps: Record<string, any>;
36
+ }): PluginAPI;
37
+ }
@@ -0,0 +1,127 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.PluginAPI = void 0;
7
+ const utils_1 = require("@umijs/utils");
8
+ const assert_1 = __importDefault(require("assert"));
9
+ const types_1 = require("../types");
10
+ const command_1 = require("./command");
11
+ const generator_1 = require("./generator");
12
+ const hook_1 = require("./hook");
13
+ const plugin_1 = require("./plugin");
14
+ const utils_2 = require("./utils");
15
+ class PluginAPI {
16
+ constructor(opts) {
17
+ this.service = opts.service;
18
+ this.plugin = opts.plugin;
19
+ // TODO
20
+ // logger
21
+ }
22
+ describe(opts) {
23
+ this.plugin.merge(opts);
24
+ }
25
+ registerCommand(opts) {
26
+ const { alias } = opts;
27
+ delete opts.alias;
28
+ const registerCommand = (commandOpts) => {
29
+ var _a;
30
+ const { name } = commandOpts;
31
+ (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}.`);
32
+ this.service.commands[name] = new command_1.Command(Object.assign(Object.assign({}, commandOpts), { plugin: this.plugin }));
33
+ };
34
+ registerCommand(opts);
35
+ if (alias) {
36
+ const aliases = (0, utils_2.makeArray)(alias);
37
+ aliases.forEach((alias) => {
38
+ registerCommand(Object.assign(Object.assign({}, opts), { name: alias }));
39
+ });
40
+ }
41
+ }
42
+ registerGenerator(opts) {
43
+ var _a;
44
+ const { key } = opts;
45
+ (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}.`);
46
+ this.service.generators[key] = new generator_1.Generator(Object.assign(Object.assign({}, opts), { plugin: this.plugin }));
47
+ }
48
+ register(opts) {
49
+ var _a, _b;
50
+ (_a = this.service.hooks)[_b = opts.key] || (_a[_b] = []);
51
+ this.service.hooks[opts.key].push(new hook_1.Hook(Object.assign(Object.assign({}, opts), { plugin: this.plugin })));
52
+ }
53
+ registerMethod(opts) {
54
+ (0, assert_1.default)(!this.service.pluginMethods[opts.name], `api.registerMethod() failed, method ${opts.name} is already exist.`);
55
+ this.service.pluginMethods[opts.name] = {
56
+ plugin: this.plugin,
57
+ fn: opts.fn ||
58
+ ((fn) => {
59
+ this.register(Object.assign({ key: opts.name }, (utils_1.lodash.isPlainObject(fn) ? fn : { fn })));
60
+ }),
61
+ };
62
+ }
63
+ registerPresets(source, presets) {
64
+ (0, assert_1.default)(this.service.stage === types_1.ServiceStage.initPresets, `api.registerPresets() failed, it should only used in presets.`);
65
+ source.splice(0, 0, ...presets.map((preset) => {
66
+ return new plugin_1.Plugin({
67
+ path: preset,
68
+ cwd: this.service.cwd,
69
+ type: types_1.PluginType.plugin,
70
+ });
71
+ }));
72
+ }
73
+ registerPlugins(source, plugins) {
74
+ (0, assert_1.default)(this.service.stage === types_1.ServiceStage.initPresets ||
75
+ this.service.stage === types_1.ServiceStage.initPlugins, `api.registerPlugins() failed, it should only be used in registering stage.`);
76
+ const mappedPlugins = plugins.map((plugin) => {
77
+ if (utils_1.lodash.isPlainObject(plugin)) {
78
+ (0, assert_1.default)(plugin.id && plugin.key, `Invalid plugin object, id and key must supplied.`);
79
+ plugin.type = types_1.PluginType.plugin;
80
+ plugin.enableBy = plugin.enableBy || types_1.EnableBy.register;
81
+ plugin.apply = plugin.apply || (() => () => { });
82
+ plugin.config = plugin.config || {};
83
+ return plugin;
84
+ }
85
+ else {
86
+ return new plugin_1.Plugin({
87
+ path: plugin,
88
+ cwd: this.service.cwd,
89
+ type: types_1.PluginType.plugin,
90
+ });
91
+ }
92
+ });
93
+ if (this.service.stage === types_1.ServiceStage.initPresets) {
94
+ source.push(...mappedPlugins);
95
+ }
96
+ else {
97
+ source.splice(0, 0, ...mappedPlugins);
98
+ }
99
+ }
100
+ skipPlugins(ids) {
101
+ ids.forEach((id) => {
102
+ this.service.skipPluginIds.add(id);
103
+ });
104
+ }
105
+ static proxyPluginAPI(opts) {
106
+ return new Proxy(opts.pluginAPI, {
107
+ get: (target, prop) => {
108
+ if (opts.service.pluginMethods[prop]) {
109
+ return opts.service.pluginMethods[prop].fn;
110
+ }
111
+ if (opts.serviceProps.includes(prop)) {
112
+ // @ts-ignore
113
+ const serviceProp = opts.service[prop];
114
+ return typeof serviceProp === 'function'
115
+ ? serviceProp.bind(opts.service)
116
+ : serviceProp;
117
+ }
118
+ if (prop in opts.staticProps) {
119
+ return opts.staticProps[prop];
120
+ }
121
+ // @ts-ignore
122
+ return target[prop];
123
+ },
124
+ });
125
+ }
126
+ }
127
+ exports.PluginAPI = PluginAPI;