@umijs/preset-umi 4.0.13 → 4.0.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.
@@ -45,6 +45,7 @@ module.exports = __toCommonJS(dev_exports);
45
45
  var import_utils = require("@umijs/utils");
46
46
  var import_fs = require("fs");
47
47
  var import_path = require("path");
48
+ var import_worker_threads = require("worker_threads");
48
49
  var import_constants = require("../../constants");
49
50
  var import_AutoUpdateSourceCodeCache = require("../../libs/folderCache/AutoUpdateSourceCodeCache");
50
51
  var import_lazyImportFromCurrentPkg = require("../../utils/lazyImportFromCurrentPkg");
@@ -236,6 +237,8 @@ PORT=8888 umi dev
236
237
  };
237
238
  const debouncedPrintMemoryUsage = import_utils.lodash.debounce(import_printMemoryUsage.printMemoryUsage, 5e3);
238
239
  let srcCodeCache;
240
+ let startBuildWorker = () => {
241
+ };
239
242
  if (((_b = api.config.mfsu) == null ? void 0 : _b.strategy) === "eager") {
240
243
  srcCodeCache = new import_AutoUpdateSourceCodeCache.AutoUpdateSrcCodeCache({
241
244
  cwd: api.paths.absSrcPath,
@@ -245,17 +248,34 @@ PORT=8888 umi dev
245
248
  (0, import_watch.addUnWatch)(() => {
246
249
  srcCodeCache.unwatch();
247
250
  });
251
+ let currentWorker = null;
252
+ const initWorker = () => {
253
+ currentWorker = new import_worker_threads.Worker((0, import_path.join)(__dirname, "depBuildWorker/depBuildWorker.js"));
254
+ currentWorker.on("exit", () => {
255
+ initWorker();
256
+ });
257
+ return currentWorker;
258
+ };
259
+ currentWorker = initWorker();
260
+ startBuildWorker = () => {
261
+ return currentWorker;
262
+ };
248
263
  }
264
+ const entry = await api.applyPlugins({
265
+ key: "modifyEntry",
266
+ initialValue: {
267
+ umi: (0, import_path.join)(api.paths.absTmpPath, "umi.ts")
268
+ }
269
+ });
249
270
  const opts = __spreadProps(__spreadValues({
250
271
  config: api.config,
251
272
  pkg: api.pkg,
252
273
  cwd: api.cwd,
253
274
  rootDir: process.cwd(),
254
- entry: {
255
- umi: (0, import_path.join)(api.paths.absTmpPath, "umi.ts")
256
- },
275
+ entry,
257
276
  port: api.appData.port,
258
- host: api.appData.host
277
+ host: api.appData.host,
278
+ ip: api.appData.ip
259
279
  }, enableVite ? { modifyViteConfig } : { babelPreset, chainWebpack, modifyWebpackConfig }), {
260
280
  beforeBabelPlugins,
261
281
  beforeBabelPresets,
@@ -265,7 +285,7 @@ PORT=8888 umi dev
265
285
  ...beforeMiddlewares
266
286
  ]),
267
287
  afterMiddlewares: enableVite ? [] : middlewares.concat([
268
- (0, import_createRouteMiddleware.createRouteMiddleware)({ api }),
288
+ ...api.config.mpa ? [] : [(0, import_createRouteMiddleware.createRouteMiddleware)({ api })],
269
289
  import_faviconMiddleware.faviconMiddleware
270
290
  ]),
271
291
  onDevCompileDone(opts2) {
@@ -294,8 +314,12 @@ PORT=8888 umi dev
294
314
  mfsuInclude: import_utils.lodash.union([
295
315
  ...MFSU_EAGER_DEFAULT_INCLUDE,
296
316
  ...((_e = api.config.mfsu) == null ? void 0 : _e.include) || []
297
- ])
317
+ ]),
318
+ startBuildWorker
298
319
  });
320
+ if (api.config.mf) {
321
+ opts.mfsuServerBase = `${api.config.https ? "https" : "http"}://${api.appData.ip}:${api.appData.port}`;
322
+ }
299
323
  if (enableVite) {
300
324
  await bundlerVite.dev(opts);
301
325
  } else {
@@ -308,6 +332,7 @@ PORT=8888 umi dev
308
332
  port: parseInt(String(process.env.PORT || import_constants.DEFAULT_PORT), 10)
309
333
  });
310
334
  memo.host = process.env.HOST || import_constants.DEFAULT_HOST;
335
+ memo.ip = import_utils.address.ip();
311
336
  return memo;
312
337
  });
313
338
  api.registerMethod({
@@ -66,6 +66,7 @@ var jest_default = (api) => {
66
66
  initial: true
67
67
  });
68
68
  const hasSrc = api.paths.absSrcPath.endsWith("src");
69
+ const importSource = api.appData.umi.importSource;
69
70
  const basicDeps = {
70
71
  jest: "^27",
71
72
  "@types/jest": "^27",
@@ -79,12 +80,12 @@ var jest_default = (api) => {
79
80
  }) : basicDeps;
80
81
  h.addDevDeps(packageToInstall);
81
82
  h.addScript("test", "jest");
82
- if (res.willUseTLR) {
83
- (0, import_fs.writeFileSync)((0, import_path.join)(api.cwd, "jest-setup.ts"), `import '@testing-library/jest-dom';
84
- `.trimLeft());
85
- import_utils.logger.info("Write jest-setup.ts");
86
- }
87
- const importSource = api.appData.umi.importSource;
83
+ const setupImports = res.willUseTLR ? [
84
+ `import '@testing-library/jest-dom';`,
85
+ `import '${api.appData.umi.importSource}/test-setup'`
86
+ ] : [`import '${api.appData.umi.importSource}/test-setup'`];
87
+ (0, import_fs.writeFileSync)((0, import_path.join)(api.cwd, "jest-setup.ts"), setupImports.join("\n"));
88
+ import_utils.logger.info("Write jest-setup.ts");
88
89
  const collectCoverageFrom = hasSrc ? [
89
90
  "src/**/*.{ts,js,tsx,jsx}",
90
91
  "!src/.umi/**",
@@ -115,7 +116,9 @@ export default async () => {
115
116
  jsTransformerOpts: { jsx: 'automatic' },
116
117
  }),
117
118
  ${res.willUseTLR ? `setupFilesAfterEnv: ['<rootDir>/jest-setup.ts'],` : ""}
118
- collectCoverageFrom: [${collectCoverageFrom.map((v) => `'${v}'`).join(", ")}],
119
+ collectCoverageFrom: [
120
+ ${collectCoverageFrom.map((v) => ` '${v}'`).join(",\n")}
121
+ ],
119
122
  // if you require some es-module npm package, please uncomment below line and insert your package name
120
123
  // transformIgnorePatterns: ['node_modules/(?!.*(lodash-es|your-es-pkg-name)/)']
121
124
  })) as Config.InitialOptions;
@@ -0,0 +1,5 @@
1
+ import { IApi, IRoute } from '../../types';
2
+ declare type Routes = Record<string, IRoute>;
3
+ export declare function patchRoutes(routes: Routes): Routes;
4
+ declare const _default: (api: IApi) => void;
5
+ export default _default;
@@ -0,0 +1,48 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/features/404/404.ts
20
+ var __exports = {};
21
+ __export(__exports, {
22
+ default: () => __default,
23
+ patchRoutes: () => patchRoutes
24
+ });
25
+ module.exports = __toCommonJS(__exports);
26
+ function patchRoutes(routes) {
27
+ Object.keys(routes).forEach((key) => {
28
+ if (routes[key].path === "404") {
29
+ routes[key].path = "*";
30
+ }
31
+ });
32
+ return routes;
33
+ }
34
+ var __default = (api) => {
35
+ api.describe({
36
+ key: "404"
37
+ });
38
+ api.modifyRoutes(async (routes) => {
39
+ if (api.config.routes) {
40
+ return routes;
41
+ }
42
+ return patchRoutes(routes);
43
+ });
44
+ };
45
+ // Annotate the CommonJS export names for ESM import in node:
46
+ 0 && (module.exports = {
47
+ patchRoutes
48
+ });
@@ -149,7 +149,7 @@ function parseMultipart(body, boundary) {
149
149
  function parseUrlEncoded(body) {
150
150
  return body.split("&").reduce((acc, cur) => {
151
151
  const [key, value] = cur.split("=");
152
- acc[key] = decodeURI(value);
152
+ acc[key] = decodeURIComponent(value);
153
153
  return acc;
154
154
  }, {});
155
155
  }
@@ -45,7 +45,8 @@ var appData_default = (api) => {
45
45
  memo.umi = {
46
46
  version: require("../../../package.json").version,
47
47
  name: "Umi",
48
- importSource: "umi"
48
+ importSource: "umi",
49
+ cliName: "umi"
49
50
  };
50
51
  memo.bundleStatus = {
51
52
  done: false
@@ -0,0 +1,3 @@
1
+ import type { IApi } from '../../types';
2
+ declare const _default: (api: IApi) => void;
3
+ export default _default;
@@ -0,0 +1,133 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __spreadValues = (a, b) => {
13
+ for (var prop in b || (b = {}))
14
+ if (__hasOwnProp.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ if (__getOwnPropSymbols)
17
+ for (var prop of __getOwnPropSymbols(b)) {
18
+ if (__propIsEnum.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ }
21
+ return a;
22
+ };
23
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
+ var __export = (target, all) => {
25
+ for (var name in all)
26
+ __defProp(target, name, { get: all[name], enumerable: true });
27
+ };
28
+ var __copyProps = (to, from, except, desc) => {
29
+ if (from && typeof from === "object" || typeof from === "function") {
30
+ for (let key of __getOwnPropNames(from))
31
+ if (!__hasOwnProp.call(to, key) && key !== except)
32
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
33
+ }
34
+ return to;
35
+ };
36
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
37
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
38
+
39
+ // src/features/legacy/legacy.ts
40
+ var legacy_exports = {};
41
+ __export(legacy_exports, {
42
+ default: () => legacy_default
43
+ });
44
+ module.exports = __toCommonJS(legacy_exports);
45
+ var import_types = require("@umijs/bundler-webpack/dist/types");
46
+ var import_utils = require("@umijs/utils");
47
+ var legacy_default = (api) => {
48
+ api.describe({
49
+ key: "legacy",
50
+ config: {
51
+ schema(Joi) {
52
+ return Joi.object({
53
+ buildOnly: Joi.boolean(),
54
+ nodeModulesTransform: Joi.boolean()
55
+ });
56
+ }
57
+ },
58
+ enableBy: api.EnableBy.config
59
+ });
60
+ api.modifyConfig({
61
+ stage: Number.MAX_SAFE_INTEGER,
62
+ fn: (memo) => {
63
+ const { userConfig } = api;
64
+ const { buildOnly = true, nodeModulesTransform = true } = api.config.legacy || userConfig.legacy || {};
65
+ if (api.env === import_types.Env.development) {
66
+ if (buildOnly) {
67
+ return memo;
68
+ }
69
+ memo.mfsu = false;
70
+ import_utils.logger.warn(`mfsu is not supported in ${import_utils.chalk.cyan("legacy")} mode, we automatically close mfsu`);
71
+ }
72
+ if (userConfig.srcTranspiler || userConfig.jsMinifier || userConfig.cssMinifier) {
73
+ import_utils.logger.fatal(`Manual configuration of ${[
74
+ "srcTranspiler",
75
+ "jsMinifier",
76
+ "cssMinifier"
77
+ ].map((i) => import_utils.chalk.yellow(i)).join(", ")} is not supported when ${import_utils.chalk.cyan("legacy")} build mode enabled.`);
78
+ throw new Error("Manual configuration of legacy mode is not supported.");
79
+ }
80
+ memo.srcTranspiler = import_types.Transpiler.babel;
81
+ memo.jsMinifier = import_types.JSMinifier.terser;
82
+ memo.cssMinifier = import_types.CSSMinifier.cssnano;
83
+ memo.targets = __spreadProps(__spreadValues({}, userConfig.targets), {
84
+ ie: 11
85
+ });
86
+ import_utils.logger.ready(`${import_utils.chalk.cyan("legacy")} mode is enabled, we automatically modify the ${[
87
+ "srcTranspiler",
88
+ "jsMinifier",
89
+ "cssMinifier"
90
+ ].map((i) => import_utils.chalk.yellow(i)).join(", ")} to be compatible with IE 11`);
91
+ const originChainWebpack = userConfig.chainWebpack;
92
+ memo.chainWebpack = (memo2, ...args) => {
93
+ if (originChainWebpack) {
94
+ originChainWebpack(memo2, ...args);
95
+ }
96
+ if (nodeModulesTransform) {
97
+ memo2.module.rule("extra-src").include.add(/node_modules/).end();
98
+ }
99
+ memo2.module.rule("extra-src").exclude.add(/core-js/).add(/node_modules\/(css-loader)/).end();
100
+ useBabelTransformSvgr(memo2, api);
101
+ if (!import_utils.lodash.isEmpty(userConfig.externals)) {
102
+ const externalsAsString = JSON.stringify(userConfig.externals);
103
+ const externalsType = memo2.get("externalsType");
104
+ if (externalsAsString.includes("script ") || externalsType) {
105
+ import_utils.logger.warn(`Legacy browsers do not support ${import_utils.chalk.yellow("Top level await")}, ensure you are not using both ${import_utils.chalk.bold.red(`Top level sync import`)} and ${import_utils.chalk.bold.red("Async externalsType (e.g. script)")}`);
106
+ }
107
+ }
108
+ return memo2;
109
+ };
110
+ return memo;
111
+ }
112
+ });
113
+ };
114
+ function useBabelTransformSvgr(memo, api) {
115
+ memo.module.rule("svgr").use("babel-loader").loader(require.resolve("@umijs/bundler-webpack/compiled/babel-loader")).options({
116
+ sourceType: "unambiguous",
117
+ babelrc: false,
118
+ cacheDirectory: false,
119
+ targets: api.config.targets,
120
+ presets: [
121
+ [
122
+ require.resolve("@umijs/babel-preset-umi"),
123
+ {
124
+ presetEnv: {},
125
+ presetReact: {},
126
+ presetTypeScript: {}
127
+ }
128
+ ]
129
+ ]
130
+ }).before("svgr-loader").end();
131
+ }
132
+ // Annotate the CommonJS export names for ESM import in node:
133
+ 0 && (module.exports = {});
@@ -0,0 +1,4 @@
1
+ export declare function extractExports(opts: {
2
+ entry: string;
3
+ exportName: string;
4
+ }): Promise<Record<string, any>>;
@@ -0,0 +1,112 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
20
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
21
+
22
+ // src/features/mpa/extractExports.ts
23
+ var extractExports_exports = {};
24
+ __export(extractExports_exports, {
25
+ extractExports: () => extractExports
26
+ });
27
+ module.exports = __toCommonJS(extractExports_exports);
28
+ var import_esbuild = __toESM(require("@umijs/bundler-utils/compiled/esbuild"));
29
+ async function extractExports(opts) {
30
+ const res = await import_esbuild.default.build({
31
+ format: "cjs",
32
+ platform: "browser",
33
+ target: "esnext",
34
+ loader: {
35
+ ".aac": "text",
36
+ ".css": "text",
37
+ ".less": "text",
38
+ ".sass": "text",
39
+ ".scss": "text",
40
+ ".eot": "text",
41
+ ".flac": "text",
42
+ ".gif": "text",
43
+ ".ico": "text",
44
+ ".jpeg": "text",
45
+ ".jpg": "text",
46
+ ".js": "jsx",
47
+ ".jsx": "jsx",
48
+ ".json": "json",
49
+ ".md": "jsx",
50
+ ".mdx": "jsx",
51
+ ".mp3": "text",
52
+ ".mp4": "text",
53
+ ".ogg": "text",
54
+ ".otf": "text",
55
+ ".png": "text",
56
+ ".svg": "text",
57
+ ".ts": "ts",
58
+ ".tsx": "tsx",
59
+ ".ttf": "text",
60
+ ".wav": "text",
61
+ ".webm": "text",
62
+ ".webp": "text",
63
+ ".woff": "text",
64
+ ".woff2": "text"
65
+ },
66
+ bundle: true,
67
+ write: false,
68
+ entryPoints: [`${opts.entry}?entry`],
69
+ plugins: [
70
+ {
71
+ name: "virtual-entry",
72
+ setup(build) {
73
+ build.onResolve({ filter: /\?entry$/ }, (args) => {
74
+ return {
75
+ path: args.path.split("?")[0],
76
+ namespace: "entry"
77
+ };
78
+ });
79
+ build.onResolve({ filter: /^[@a-z0-9-_~]/ }, (args) => {
80
+ return {
81
+ path: args.path,
82
+ external: true,
83
+ sideEffects: false
84
+ };
85
+ });
86
+ build.onResolve({ filter: /^\// }, (args) => {
87
+ return {
88
+ path: args.path
89
+ };
90
+ });
91
+ build.onLoad({ filter: /.*/, namespace: "entry" }, (args) => {
92
+ return {
93
+ contents: `
94
+ import * as x from "${args.path}";
95
+ ret = x.${opts.exportName} || {};
96
+ `,
97
+ loader: "ts"
98
+ };
99
+ });
100
+ }
101
+ }
102
+ ]
103
+ });
104
+ let ret = {};
105
+ let code = res.outputFiles[0].text;
106
+ eval(`(() => { ${code}; })();`);
107
+ return ret;
108
+ }
109
+ // Annotate the CommonJS export names for ESM import in node:
110
+ 0 && (module.exports = {
111
+ extractExports
112
+ });
@@ -0,0 +1,3 @@
1
+ import { IApi } from '../../types';
2
+ declare const _default: (api: IApi) => void;
3
+ export default _default;
@@ -0,0 +1,207 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __spreadValues = (a, b) => {
13
+ for (var prop in b || (b = {}))
14
+ if (__hasOwnProp.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ if (__getOwnPropSymbols)
17
+ for (var prop of __getOwnPropSymbols(b)) {
18
+ if (__propIsEnum.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ }
21
+ return a;
22
+ };
23
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
+ var __export = (target, all) => {
25
+ for (var name in all)
26
+ __defProp(target, name, { get: all[name], enumerable: true });
27
+ };
28
+ var __copyProps = (to, from, except, desc) => {
29
+ if (from && typeof from === "object" || typeof from === "function") {
30
+ for (let key of __getOwnPropNames(from))
31
+ if (!__hasOwnProp.call(to, key) && key !== except)
32
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
33
+ }
34
+ return to;
35
+ };
36
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
37
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
38
+
39
+ // src/features/mpa/mpa.ts
40
+ var mpa_exports = {};
41
+ __export(mpa_exports, {
42
+ default: () => mpa_default
43
+ });
44
+ module.exports = __toCommonJS(mpa_exports);
45
+ var import_utils = require("@umijs/utils");
46
+ var import_assert = __toESM(require("assert"));
47
+ var import_fs = require("fs");
48
+ var import_html_webpack_plugin = __toESM(require("html-webpack-plugin"));
49
+ var import_path = require("path");
50
+ var import_extractExports = require("./extractExports");
51
+ var mpa_default = (api) => {
52
+ api.describe({
53
+ key: "mpa",
54
+ config: {
55
+ schema(Joi) {
56
+ return Joi.object({
57
+ template: Joi.string(),
58
+ getConfigFromEntryFile: Joi.boolean()
59
+ });
60
+ }
61
+ },
62
+ enableBy: api.EnableBy.config
63
+ });
64
+ api.onStart(() => {
65
+ import_utils.logger.warn(import_utils.chalk.yellow("[MPA] MPA Mode Enabled"));
66
+ });
67
+ api.modifyAppData(async (memo) => {
68
+ memo.mpa = {
69
+ entry: await collectEntryWithTimeCount(api.paths.absPagesPath, api.config.mpa)
70
+ };
71
+ return memo;
72
+ });
73
+ api.onGenerateFiles(async ({ isFirstTime }) => {
74
+ if (!isFirstTime) {
75
+ api.appData.mpa.entry = await collectEntryWithTimeCount(api.paths.absPagesPath, api.config.mpa);
76
+ }
77
+ const isReact18 = api.appData.react.version.startsWith("18.");
78
+ api.appData.mpa.entry.forEach((entry) => {
79
+ const layoutImport = entry.layout ? `import Layout from '${entry.layout}';` : "";
80
+ const layoutJSX = entry.layout ? `<Layout><App /></Layout>` : `<App />`;
81
+ const rootElement = `document.getElementById('${entry.mountElementId}')`;
82
+ const renderer = isReact18 ? `ReactDOM.createRoot(${rootElement}).render(${layoutJSX});` : `ReactDOM.render(${layoutJSX}, ${rootElement});`;
83
+ const reactDOMSource = isReact18 ? "react-dom/client" : "react-dom";
84
+ api.writeTmpFile({
85
+ path: entry.tmpFilePath,
86
+ noPluginDir: true,
87
+ content: `
88
+ import React from 'react';
89
+ import ReactDOM from '${reactDOMSource}';
90
+ import App from '${entry.file}';
91
+ ${layoutImport}
92
+ ${renderer}
93
+ `.trimStart()
94
+ });
95
+ });
96
+ api.writeTmpFile({
97
+ path: "mpa/template.html",
98
+ noPluginDir: true,
99
+ content: `
100
+ <!DOCTYPE html>
101
+ <html>
102
+ <head><title><%= title %></title></head>
103
+ <body>
104
+ <div id="<%= mountElementId %>"></div>
105
+ </body>
106
+ </html>
107
+ `.trimStart()
108
+ });
109
+ });
110
+ api.modifyEntry((memo) => {
111
+ if ("umi" in memo)
112
+ delete memo["umi"];
113
+ api.appData.mpa.entry.forEach((entry) => {
114
+ memo[entry.name] = (0, import_path.join)(api.paths.absTmpPath, entry.tmpFilePath);
115
+ });
116
+ return memo;
117
+ });
118
+ api.chainWebpack((memo) => {
119
+ api.appData.mpa.entry.forEach((entry) => {
120
+ memo.plugin(`html-${entry.name}`).use(import_html_webpack_plugin.default, [
121
+ {
122
+ filename: `${entry.name}.html`,
123
+ minify: false,
124
+ template: entry.template ? (0, import_path.resolve)(api.cwd, entry.template) : api.config.mpa.template ? (0, import_path.resolve)(api.cwd, api.config.mpa.template) : (0, import_path.join)(api.paths.absTmpPath, "mpa/template.html"),
125
+ templateParameters: entry,
126
+ chunks: [entry.name]
127
+ }
128
+ ]);
129
+ });
130
+ return memo;
131
+ });
132
+ };
133
+ async function collectEntryWithTimeCount(root, opts) {
134
+ const d = new Date();
135
+ const entries = await collectEntry(root, opts);
136
+ import_utils.logger.info(`[MPA] Collect Entries in ${new Date().getTime() - d.getTime()}ms`);
137
+ return entries;
138
+ }
139
+ async function collectEntry(root, opts) {
140
+ return await (0, import_fs.readdirSync)(root).reduce(async (memoP, dir) => {
141
+ const memo = await memoP;
142
+ const absDir = (0, import_path.join)(root, dir);
143
+ if ((0, import_fs.existsSync)(absDir) && (0, import_fs.statSync)(absDir).isDirectory()) {
144
+ const indexFile = getIndexFile(absDir);
145
+ if (indexFile) {
146
+ const config = opts.getConfigFromEntryFile ? await getConfigFromEntryFile(indexFile) : await getConfig(indexFile);
147
+ memo.push(__spreadProps(__spreadValues({
148
+ name: dir,
149
+ file: indexFile,
150
+ tmpFilePath: `mpa/${dir}${(0, import_path.extname)(indexFile)}`,
151
+ mountElementId: "root"
152
+ }, config), {
153
+ title: config.title || dir
154
+ }));
155
+ }
156
+ }
157
+ return memo;
158
+ }, Promise.resolve([]));
159
+ }
160
+ function getIndexFile(dir) {
161
+ if ((0, import_fs.existsSync)((0, import_path.join)(dir, "index.tsx")))
162
+ return (0, import_path.join)(dir, "index.tsx");
163
+ if ((0, import_fs.existsSync)((0, import_path.join)(dir, "index.ts")))
164
+ return (0, import_path.join)(dir, "index.ts");
165
+ if ((0, import_fs.existsSync)((0, import_path.join)(dir, "index.jsx")))
166
+ return (0, import_path.join)(dir, "index.jsx");
167
+ if ((0, import_fs.existsSync)((0, import_path.join)(dir, "index.js")))
168
+ return (0, import_path.join)(dir, "index.js");
169
+ return null;
170
+ }
171
+ async function getConfig(indexFile) {
172
+ const dir = (0, import_path.dirname)(indexFile);
173
+ if ((0, import_fs.existsSync)((0, import_path.join)(dir, "config.json"))) {
174
+ const config = JSON.parse((0, import_fs.readFileSync)((0, import_path.join)(dir, "config.json"), "utf-8"));
175
+ checkConfig(config);
176
+ return config;
177
+ } else {
178
+ return {};
179
+ }
180
+ }
181
+ async function getConfigFromEntryFile(indexFile) {
182
+ const config = await (0, import_extractExports.extractExports)({
183
+ entry: indexFile,
184
+ exportName: "config"
185
+ });
186
+ checkConfig(config);
187
+ return config;
188
+ }
189
+ function checkConfig(config) {
190
+ if (config.layout) {
191
+ (0, import_assert.default)(typeof config.layout === "string" && (config.layout.startsWith("@/") || config.layout.startsWith("/")), `layout must be an absolute path or start with '@/'`);
192
+ }
193
+ if (config.template) {
194
+ (0, import_assert.default)(typeof config.template === "string", "template must be string");
195
+ }
196
+ if (config.title) {
197
+ (0, import_assert.default)(typeof config.title === "string", "title must be string");
198
+ }
199
+ if (config.head) {
200
+ (0, import_assert.default)(Array.isArray(config.head), "head must be string");
201
+ }
202
+ if (config.scripts) {
203
+ (0, import_assert.default)(Array.isArray(config.scripts), "scripts must be string");
204
+ }
205
+ }
206
+ // Annotate the CommonJS export names for ESM import in node:
207
+ 0 && (module.exports = {});