@dd-code/uni-tools 1.0.9 → 1.0.11

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.js CHANGED
@@ -3,14 +3,15 @@
3
3
  var path = require('path');
4
4
  var fs = require('fs');
5
5
  var crypto = require('crypto');
6
+ var chokidar = require('chokidar');
6
7
  var cliProgress = require('cli-progress');
7
8
  var chalk = require('chalk');
8
9
  var fsExtra = require('fs-extra');
9
- var chokidar = require('chokidar');
10
10
  var WebSocket = require('ws');
11
11
  var express = require('express');
12
12
  var http = require('http');
13
13
  var cors = require('cors');
14
+ require('child_process');
14
15
 
15
16
  /******************************************************************************
16
17
  Copyright (c) Microsoft Corporation.
@@ -153,6 +154,23 @@ function uniReadFile(filaPath) {
153
154
  }
154
155
  return "";
155
156
  }
157
+ /**
158
+ * 读取文件内容
159
+ * 支持JSON文件的自动解析
160
+ * @param {string} filaPath - 文件路径
161
+ * @returns {string|Object} 返回文件内容,JSON文件返回对象,其他返回字符串
162
+ */
163
+ function uniFsReadJSONFile(filaPath) {
164
+ try {
165
+ var res = fs.readFileSync(filaPath, "utf-8");
166
+ return JSON.parse(res);
167
+ }
168
+ catch (e) {
169
+ // console.error(`${filaPath} notfound`);
170
+ // console.log(e);
171
+ }
172
+ return {};
173
+ }
156
174
  /**
157
175
  * 写入文件内容
158
176
  * 自动创建目录结构,支持对象和字符串内容
@@ -184,6 +202,7 @@ var loadViteConfig = function (mode) {
184
202
  return loadEnv(mode, ROOT, "MFE_");
185
203
  };
186
204
  var walkDir = function (outDir, emitted) {
205
+ if (emitted === void 0) { emitted = new Set(); }
187
206
  var root = path.isAbsolute(outDir)
188
207
  ? outDir
189
208
  : path.resolve(process.cwd(), outDir);
@@ -197,6 +216,7 @@ var walkDir = function (outDir, emitted) {
197
216
  walk(p);
198
217
  else
199
218
  all.push(path.relative(root, p));
219
+ // path.relative(root, p)
200
220
  });
201
221
  };
202
222
  walk(root);
@@ -228,6 +248,22 @@ function generateHash(content, algorithm, encoding) {
228
248
  function generateSHA256(content) {
229
249
  return generateHash(content, "sha256");
230
250
  }
251
+ var genreFileInfoRow = function (row) {
252
+ var fileName = row.fileName, source = row.source;
253
+ var name = path.basename(fileName);
254
+ var dir = path.dirname(fileName);
255
+ var suffix = dir === "." ? "" : "".concat(dir, "/");
256
+ return {
257
+ fileName: fileName,
258
+ fileUrl: "".concat(suffix).concat(generateSHA256((source === null || source === void 0 ? void 0 : source.toString()) || "").slice(0, 8), "_").concat(name),
259
+ };
260
+ };
261
+ var createFileWatcher = function (filePath, opt) {
262
+ var watcher = chokidar.watch(filePath, __assign({ persistent: true, ignoreInitial: true, usePolling: true, interval: 100, awaitWriteFinish: { stabilityThreshold: 200, pollInterval: 100 }, followSymlinks: true, depth: 99 }, opt));
263
+ return watcher;
264
+ };
265
+ var checkIsBuildInChild = function () { return process.env.MFE_TARGET_DIR === "root"; };
266
+ var checkIsInnerBuild = function () { return process.env.MFE_INNER_BUILD === "true"; };
231
267
 
232
268
  var UniCdnManager = /** @class */ (function () {
233
269
  function UniCdnManager() {
@@ -260,10 +296,19 @@ var cdn = new UniCdnManager();
260
296
 
261
297
  // CDN 文件保存路径
262
298
  var SAVE_CDN_FILE_PATH = path.join(process.cwd(), "node_modules/@dd-code/uni-files");
299
+ path.join(process.cwd(), "node_modules/@dd-code/__main-pwd.txt");
300
+ path.join(process.cwd(), "node_modules/@dd-code/manifest-list.json");
263
301
  path.join(process.cwd(), "node_modules/@dd-code/current-files");
302
+ // 发布目录路径
303
+ var PUBLISH_PATH = path.join(process.cwd(), "dist/publish");
264
304
  // Manifest 文件名
265
305
  var MANIFEST_NAME = "mfe-uni-manifest.json";
266
- var ROOT_APP_CODE = "main"; //"__MFE_APP_ROOT__";
306
+ var ROOT_APP_CODE = "__MFE_APP_ROOT__";
307
+ var EBuildMode;
308
+ (function (EBuildMode) {
309
+ EBuildMode["BUILD"] = "build";
310
+ EBuildMode["SERVE"] = "serve";
311
+ })(EBuildMode || (EBuildMode = {}));
267
312
  // Manifest CDN 目录 URL 模板
268
313
  var MANIFEST_CND_DIR_URL = "{mode}/static-repository/mfe-uni/{code}/{appCode}";
269
314
  var getManifestCdnDirUrl = function (_a) {
@@ -354,6 +399,7 @@ var formatCliCommandConfig = function (mode) {
354
399
  code: viteEnv.MFE_UNI_CODE,
355
400
  mode: mode,
356
401
  cdn: viteEnv.MFE_CDN_HOST,
402
+ serve: viteEnv.MFE_UNI_SERVE, // 是否开启 serve 功能
357
403
  };
358
404
  };
359
405
  var checkIsRootManifest = function (manifest) {
@@ -361,12 +407,13 @@ var checkIsRootManifest = function (manifest) {
361
407
  };
362
408
  var WS_PORT = 3560;
363
409
  var WS_PATH = "/__mfe__ws__";
410
+ var HTTP_PATH = "/__mfe__http__";
364
411
  var E_WS_TYPE;
365
412
  (function (E_WS_TYPE) {
366
413
  E_WS_TYPE["INIT"] = "init_files";
367
414
  E_WS_TYPE["CHANGE"] = "change_files";
368
415
  })(E_WS_TYPE || (E_WS_TYPE = {}));
369
- var getMainAppJSon = function (mode, appCode) {
416
+ var getNodeModuleMainAppJSon = function (mode, appCode) {
370
417
  return path.join(SAVE_CDN_FILE_PATH, mode || "dev", appCode, "app.json");
371
418
  };
372
419
  var getMainAppJsonPath = function () {
@@ -422,10 +469,17 @@ var CliProgressManager = /** @class */ (function () {
422
469
  var CliProgressManager$1 = new CliProgressManager();
423
470
 
424
471
  var getDownloadedFilePath = function (conf) {
425
- return path.resolve(SAVE_CDN_FILE_PATH, conf.env, conf.appCode);
472
+ if (!conf.mode && !conf.env) {
473
+ throw new Error("appCode: ".concat(conf.appCode, " mode or env is required"));
474
+ }
475
+ if (!conf.appCode) {
476
+ throw new Error("appCode is required");
477
+ }
478
+ return path.resolve(SAVE_CDN_FILE_PATH, conf.mode || conf.env, conf.appCode);
426
479
  };
427
480
  var getNodeModulesEnvAppCodeFilePath = function (conf, fileName) {
428
- return path.resolve(getDownloadedFilePath(conf), fileName);
481
+ var savePath = getDownloadedFilePath(conf);
482
+ return path.resolve(savePath, fileName);
429
483
  };
430
484
  /**
431
485
  * 获取清单文件 URL 列表
@@ -594,19 +648,20 @@ var downloadProjectFiles = function (manifestList) { return __awaiter(void 0, vo
594
648
  }); };
595
649
 
596
650
  var checkDownloadFilesIsExpired = function (manifestList) {
597
- return manifestList.filter(function (conf) {
651
+ var filterList = manifestList.filter(function (conf) {
598
652
  var targetPath = getNodeModulesEnvAppCodeFilePath(conf, MANIFEST_NAME);
599
653
  var oldJson = uniReadFile(targetPath);
600
654
  var flag = !oldJson || (oldJson === null || oldJson === void 0 ? void 0 : oldJson.hash) !== conf.hash;
601
655
  return flag;
602
656
  });
657
+ return filterList;
603
658
  };
604
659
  var createManifestManager = function () {
605
660
  var envObj = process.env;
606
661
  var row = {
607
662
  code: "",
608
663
  mode: "",
609
- cdn: '',
664
+ cdn: "",
610
665
  hash: "",
611
666
  publicPath: "",
612
667
  appCode: "",
@@ -618,26 +673,29 @@ var createManifestManager = function () {
618
673
  get value() {
619
674
  return row;
620
675
  },
621
- setFiles: function (outDir, all) {
622
- var files = all.map(function (i) {
623
- var filePath = path.resolve(outDir, i);
624
- var content = fs.readFileSync(filePath, "utf-8");
625
- var contentHash = generateSHA256(content);
626
- return {
627
- fileName: i,
628
- fileUrl: "".concat(contentHash.slice(0, 8), "_").concat(path.basename(i)),
629
- };
630
- });
676
+ setFiles: function (files) {
677
+ // const files = all.map((i) => {
678
+ // const filePath = path.resolve(outDir, i);
679
+ // const content = fs.readFileSync(filePath, "utf-8");
680
+ // const contentHash = generateSHA256(content).slice(0, 8);
681
+ // const dirName = path.dirname(i);
682
+ // const fileName = path.basename(i)
683
+ // const suffixName = dirName === "." ? "" : `${dirName}/`;
684
+ // return {
685
+ // fileName: i,
686
+ // fileUrl: `${suffixName}${contentHash}_${fileName}`,
687
+ // };
688
+ // });
631
689
  row.files = files;
632
690
  },
633
691
  setPagesJson: function (pagesJson) {
634
692
  row.pagesJson = pagesJson;
635
693
  },
636
- saveFile: function (outDir) {
637
- var files = row.files.filter(function (i) { return i.fileName !== MANIFEST_NAME; });
638
- row.hash = generateSHA256(JSON.stringify(__assign(__assign({}, row), { files: files })));
639
- var filePath = path.resolve(outDir, MANIFEST_NAME);
640
- writeFiles(filePath, JSON.stringify(row, null, 2));
694
+ saveFile: function (filePath) {
695
+ // const files = row.files.filter((i) => i.fileName !== MANIFEST_NAME);
696
+ var newManifest = __assign(__assign({}, row), { isServe: undefined });
697
+ newManifest.hash = generateSHA256(JSON.stringify(__assign({}, newManifest)));
698
+ writeFiles(filePath, JSON.stringify(newManifest, null, 2));
641
699
  },
642
700
  setEnv: function (mode) {
643
701
  // const env = loadViteConfig(mode);
@@ -652,6 +710,7 @@ var createManifestManager = function () {
652
710
  row.isRoot = true;
653
711
  row.apps = mfeJson.apps;
654
712
  }
713
+ row.isServe = env.serve;
655
714
  row.publicPath = getManifestCdnDirUrl(row);
656
715
  },
657
716
  dependencies: [],
@@ -666,15 +725,103 @@ var createManifestManager = function () {
666
725
  };
667
726
  };
668
727
 
669
- var resetOutDir = function (currentManifestJson, config) {
728
+ var num = 5;
729
+ var getMainProcess = function () { return __awaiter(void 0, void 0, void 0, function () {
730
+ var URL, mainProcess, result;
731
+ return __generator(this, function (_a) {
732
+ switch (_a.label) {
733
+ case 0:
734
+ URL = "http://localhost:".concat(WS_PORT).concat(HTTP_PATH, "/root-path");
735
+ return [4 /*yield*/, fetch(URL)];
736
+ case 1:
737
+ mainProcess = _a.sent();
738
+ return [4 /*yield*/, mainProcess.json()];
739
+ case 2:
740
+ result = _a.sent();
741
+ console.log(result, "mainProcess");
742
+ return [2 /*return*/, result];
743
+ }
744
+ });
745
+ }); };
746
+ var getMainProcessLoop = function () { return __awaiter(void 0, void 0, void 0, function () {
747
+ var mainProcess;
748
+ return __generator(this, function (_a) {
749
+ switch (_a.label) {
750
+ case 0:
751
+ _a.trys.push([0, 2, , 3]);
752
+ return [4 /*yield*/, getMainProcess()];
753
+ case 1:
754
+ mainProcess = _a.sent();
755
+ return [2 /*return*/, mainProcess];
756
+ case 2:
757
+ _a.sent();
758
+ return [3 /*break*/, 3];
759
+ case 3: return [2 /*return*/, new Promise(function (resolve) {
760
+ setTimeout(function () {
761
+ num--;
762
+ if (num <= 0) {
763
+ resolve(null);
764
+ num = 5;
765
+ }
766
+ resolve(getMainProcessLoop());
767
+ }, 100);
768
+ })];
769
+ }
770
+ });
771
+ }); };
772
+ var resetOutDir = function (currentManifestJson, config) { return __awaiter(void 0, void 0, void 0, function () {
773
+ var currentManifest, mainProcess, exp;
670
774
  var _a;
671
- var exp = new RegExp("/(".concat(currentManifestJson.value.appCode, ")/?"));
672
- process.env.MFE_SOURCE_OUTPUT_DIR = config.build.outDir;
673
- process.env.MFE_ROOT_OUTPUT_DIR = (_a = process.env.MFE_SOURCE_OUTPUT_DIR) === null || _a === void 0 ? void 0 : _a.replace(exp, "/").replace(/\/$/, "");
674
- // if (!currentManifestJson.value.isRoot)
675
- process.env.UNI_OUTPUT_DIR = process.env.MFE_ROOT_OUTPUT_DIR;
676
- };
775
+ return __generator(this, function (_b) {
776
+ switch (_b.label) {
777
+ case 0:
778
+ currentManifest = currentManifestJson.value;
779
+ if (!(!currentManifest.isRoot &&
780
+ checkIsBuildInChild() &&
781
+ !currentManifest.isServe)) return [3 /*break*/, 2];
782
+ return [4 /*yield*/, getMainProcessLoop()];
783
+ case 1:
784
+ mainProcess = _b.sent();
785
+ if (mainProcess) {
786
+ config.build.outDir = "".concat(mainProcess.UNI_OUTPUT_DIR, "/").concat(currentManifest.appCode);
787
+ process.env.MFE_INNER_BUILD = "true";
788
+ }
789
+ else {
790
+ process.env.MFE_TARGET_DIR = "";
791
+ }
792
+ _b.label = 2;
793
+ case 2:
794
+ exp = new RegExp("/(".concat(currentManifest.appCode, ")/?"));
795
+ // http://localhost:3560/__mfe__http__/root-path
796
+ // if()
797
+ process.env.MFE_SOURCE_OUTPUT_DIR = config.build.outDir;
798
+ process.env.MFE_ROOT_OUTPUT_DIR = (_a = process.env.MFE_SOURCE_OUTPUT_DIR) === null || _a === void 0 ? void 0 : _a.replace(exp, "/").replace(/\/$/, "");
799
+ // if (!currentManifestJson.value.isRoot)
800
+ // console.log(config);
801
+ if (!checkIsInnerBuild()) {
802
+ // setTimeout(() => {
803
+ process.env.UNI_OUTPUT_DIR = process.env.MFE_ROOT_OUTPUT_DIR;
804
+ // }, 500);
805
+ }
806
+ return [2 /*return*/];
807
+ }
808
+ });
809
+ }); };
677
810
 
811
+ var addUniCopyPluginHook = function (_a) {
812
+ var before = _a.before, after = _a.after;
813
+ var FileWatcher = require("@dcloudio/uni-cli-shared/dist/watcher").FileWatcher;
814
+ var originalCopy = FileWatcher.prototype.copy;
815
+ // Hook copy方法
816
+ FileWatcher.prototype.copy = function (from) {
817
+ var to = this.to(from);
818
+ var fromPath = this.from(from);
819
+ before === null || before === void 0 ? void 0 : before(fromPath, to);
820
+ var result = originalCopy.call(this, from);
821
+ after === null || after === void 0 ? void 0 : after(fromPath, to);
822
+ return result;
823
+ };
824
+ };
678
825
  var copyFilesByTargetPath = function (sourcePath, targetPath) {
679
826
  if (!fs.existsSync(sourcePath))
680
827
  return;
@@ -743,6 +890,8 @@ var createAppsAssetsPlugin = function (manifestJson) {
743
890
  buildStart: function () {
744
891
  if (isMoved)
745
892
  return;
893
+ if (checkIsBuildInChild() && !manifestJson.value.isRoot)
894
+ return;
746
895
  var basePath = path.resolve(SAVE_CDN_FILE_PATH, manifestJson.value.mode || "dev");
747
896
  moveOtherApps({
748
897
  base: basePath,
@@ -851,42 +1000,140 @@ var transformToWeixinFormat = function (uniPagesConfig) {
851
1000
  return weixinConfig;
852
1001
  };
853
1002
 
1003
+ // import { addRunningAppToSave } from "../running-core";
1004
+ var CollectFiles = /** @class */ (function () {
1005
+ function CollectFiles() {
1006
+ this.callbackFiles = [];
1007
+ this.callbackFiles = [];
1008
+ this.emitted = new Map();
1009
+ this.outDir = "";
1010
+ }
1011
+ Object.defineProperty(CollectFiles.prototype, "collectedBuildFiles", {
1012
+ get: function () {
1013
+ return Array.from(this.emitted.values());
1014
+ },
1015
+ enumerable: false,
1016
+ configurable: true
1017
+ });
1018
+ CollectFiles.prototype.collectBoundleFile = function (bundles) {
1019
+ var _this = this;
1020
+ Object.keys(bundles).forEach(function (key) {
1021
+ var boundle = bundles[key];
1022
+ var fileName = boundle.fileName, source = boundle.source, code = boundle.code;
1023
+ var fileInfo = genreFileInfoRow({ fileName: fileName, source: code || source });
1024
+ _this.emitted.set(fileName, fileInfo);
1025
+ });
1026
+ };
1027
+ CollectFiles.prototype.addManifestFile = function () {
1028
+ this.emitted.set(MANIFEST_NAME, {
1029
+ fileName: MANIFEST_NAME,
1030
+ fileUrl: MANIFEST_NAME,
1031
+ });
1032
+ };
1033
+ CollectFiles.prototype.collectCopyFiles = function () {
1034
+ var _this = this;
1035
+ this.callbackFiles.forEach(function (_a) {
1036
+ var abs = _a.abs, filePath = _a.filePath;
1037
+ try {
1038
+ var stat = fs.statSync(abs);
1039
+ if (stat.isFile()) {
1040
+ var fileInfo = genreFileInfoRow({
1041
+ fileName: filePath,
1042
+ source: fs.readFileSync(abs, "utf8"),
1043
+ });
1044
+ _this.emitted.set(filePath, fileInfo);
1045
+ }
1046
+ else if (stat.isDirectory()) {
1047
+ var files = walkDir(abs);
1048
+ files.forEach(function (file) {
1049
+ var absFilePath = path.resolve(abs, file);
1050
+ var fullFileName = path.join(filePath, file);
1051
+ _this.emitted.set(fullFileName, genreFileInfoRow({
1052
+ fileName: fullFileName,
1053
+ source: fs.readFileSync(absFilePath, "utf8"),
1054
+ }));
1055
+ });
1056
+ }
1057
+ }
1058
+ catch (e) {
1059
+ console.log(e);
1060
+ }
1061
+ });
1062
+ this.addManifestFile();
1063
+ };
1064
+ CollectFiles.prototype.copyFilesToPublishDir = function () {
1065
+ var _this = this;
1066
+ this.collectedBuildFiles.forEach(function (_a) {
1067
+ var fileName = _a.fileName, fileUrl = _a.fileUrl;
1068
+ var sourcePath = path.resolve(_this.outDir, fileName);
1069
+ var targetPath = path.resolve(PUBLISH_PATH, fileUrl);
1070
+ copyFilesByTargetPath(sourcePath, targetPath);
1071
+ });
1072
+ };
1073
+ return CollectFiles;
1074
+ }());
854
1075
  var createManifestPlugin = function (manifestJson) {
855
- var emitted = new Set();
1076
+ var collectFiles = new CollectFiles();
856
1077
  return {
857
1078
  name: "@dd-code:genre-mainfest-file-list",
858
1079
  enforce: "post",
1080
+ config: function (config) {
1081
+ var _a;
1082
+ var outDir = ((_a = config.build) === null || _a === void 0 ? void 0 : _a.outDir) || "dist";
1083
+ collectFiles.outDir = outDir;
1084
+ addUniCopyPluginHook({
1085
+ after: function (fromPath, to) {
1086
+ collectFiles.callbackFiles.push({
1087
+ abs: fromPath,
1088
+ filePath: path.relative(outDir, to),
1089
+ });
1090
+ },
1091
+ });
1092
+ },
859
1093
  renderStart: function () {
860
1094
  var content = initPrePagesJson();
861
1095
  var json = getPagesJson(content);
862
1096
  manifestJson.setPagesJson(json);
863
1097
  },
864
1098
  writeBundle: function (_outputOptions, bundle) {
865
- Object.values(bundle).forEach(function (item) {
866
- if (item && item.fileName)
867
- emitted.add(item.fileName);
868
- });
1099
+ collectFiles.collectBoundleFile(bundle);
869
1100
  },
870
1101
  closeBundle: function () {
871
- var outDir = process.env.MFE_SOURCE_OUTPUT_DIR || "dist";
872
- var all = walkDir(outDir, emitted);
873
- manifestJson.setFiles(outDir, all);
874
1102
  var sourcePath = manifestJson.value.isRoot
875
1103
  ? process.env.MFE_ROOT_OUTPUT_DIR
876
1104
  : path.resolve(process.env.MFE_ROOT_OUTPUT_DIR, manifestJson.value.appCode);
877
- // debugger;
878
- manifestJson.saveFile(sourcePath);
879
- // const targetPath = path.resolve(TEMP_FILE_PATH, manifestJson.value.appCode);
880
- // copyFilesByTargetPath(sourcePath, targetPath);
1105
+ var filePath = path.resolve(sourcePath, MANIFEST_NAME);
1106
+ collectFiles.collectCopyFiles();
1107
+ manifestJson.setFiles(collectFiles.collectedBuildFiles);
1108
+ manifestJson.saveFile(filePath);
1109
+ // console.log({ filePath }, "sourcePath");
1110
+ // addRunningAppToSave(manifestJson.value.appCode, filePath);
1111
+ setTimeout(function () {
1112
+ collectFiles.copyFilesToPublishDir();
1113
+ }, 0);
881
1114
  },
882
1115
  };
883
1116
  };
884
1117
 
1118
+ var app = null;
885
1119
  var createHttpServer = function () {
886
- var app = express();
1120
+ if (app)
1121
+ return app;
1122
+ app = express();
887
1123
  var server = http.createServer(app);
1124
+ app.get("".concat(HTTP_PATH, "/root-path"), function (req, res) {
1125
+ res.send(process.env);
1126
+ });
888
1127
  app.use(cors({ origin: "*" }));
889
- return server;
1128
+ return {
1129
+ server: server,
1130
+ start: function (type) {
1131
+ var originKey = type || "http";
1132
+ server.listen(WS_PORT, function () {
1133
+ console.log("[uni-".concat(originKey, "] ").concat(originKey, "://localhost:").concat(WS_PORT).concat(HTTP_PATH));
1134
+ });
1135
+ },
1136
+ };
890
1137
  };
891
1138
 
892
1139
  var WsServer = /** @class */ (function () {
@@ -908,17 +1155,12 @@ var WsServer = /** @class */ (function () {
908
1155
  if (this.wss)
909
1156
  return; // 避免重复创建
910
1157
  this.wss = new WebSocket.WebSocketServer({
911
- server: this.httpServer, // 绑定到 Vite 的 HTTP 服务器
1158
+ server: this.httpServer.server, // 绑定到 Vite 的 HTTP 服务器
912
1159
  path: WS_PATH, // WS 连接路径,前端连接时用 ws://localhost:5173/__mfe__ws__
913
1160
  });
914
1161
  this.onMessage(this.handleMessage);
915
1162
  this.onConnection();
916
- this.start();
917
- };
918
- WsServer.prototype.start = function () {
919
- this.httpServer.listen(WS_PORT, function () {
920
- console.log("[uni-WS] \u72EC\u7ACB\u670D\u52A1\u5DF2\u542F\u52A8\uFF1Aws://localhost:".concat(WS_PORT).concat(WS_PATH));
921
- });
1163
+ this.httpServer.start('ws');
922
1164
  };
923
1165
  WsServer.prototype.onMessage = function (callback) {
924
1166
  // WebSocketServer 不支持直接监听 message,必须在 connection 后的 socket 上监听
@@ -1048,9 +1290,37 @@ var WsClientServer = /** @class */ (function () {
1048
1290
  // export const mfeServer = new WsServer();
1049
1291
  // export const mfeClientServer = new WsClientServer();
1050
1292
 
1051
- /**
1052
- * 过滤 Manifest 列表并获取主应用 app.json 路径
1053
- */
1293
+ // export const addRunningAppToSave = (appCode, filePath: string) => {
1294
+ // const content = uniReadFile(SERVE_MPWEIXIN_MANIFEST);
1295
+ // if (content) {
1296
+ // content[appCode] = filePath;
1297
+ // }
1298
+ // writeFiles(SERVE_MPWEIXIN_MANIFEST, JSON.stringify(content, null, 2));
1299
+ // };
1300
+ var getAppsManifestList = function (mode) {
1301
+ var _a;
1302
+ var manifest = formatCliCommandConfig(mode);
1303
+ if (!manifest.isRoot) {
1304
+ return [];
1305
+ }
1306
+ if (manifest.serve) {
1307
+ return [];
1308
+ }
1309
+ var mfeJson = getMfeJson();
1310
+ if (!((_a = mfeJson === null || mfeJson === void 0 ? void 0 : mfeJson.apps) === null || _a === void 0 ? void 0 : _a.length)) {
1311
+ throw new Error("mfeJson.apps is empty");
1312
+ }
1313
+ var apps = ((mfeJson === null || mfeJson === void 0 ? void 0 : mfeJson.apps) || []).map(function (_a) {
1314
+ var appCode = _a.appCode;
1315
+ return {
1316
+ appCode: appCode,
1317
+ filePath: "".concat(process.env.UNI_OUTPUT_DIR, "/").concat(appCode, "/").concat(MANIFEST_NAME),
1318
+ };
1319
+ });
1320
+ // console.log(apps);
1321
+ return apps;
1322
+ };
1323
+
1054
1324
  var filterManifestJsonListAndMainPageJson = function (manifestJsonList) {
1055
1325
  var outputPageJsonPath = getMainAppJsonPath();
1056
1326
  return {
@@ -1058,9 +1328,6 @@ var filterManifestJsonListAndMainPageJson = function (manifestJsonList) {
1058
1328
  manifestList: manifestJsonList.filter(function (item) { return !checkIsRootManifest(item); }),
1059
1329
  };
1060
1330
  };
1061
- /**
1062
- * 根据 Manifest 列表渲染 app.json 的 subPackages
1063
- */
1064
1331
  var renderPagesJsonByArray = function (appPages, pageJson) {
1065
1332
  var _loop_1 = function (app) {
1066
1333
  var _a = getPagesJson(JSON.stringify((app === null || app === void 0 ? void 0 : app.pagesJson) || {}), true).pages, pages = _a === void 0 ? [] : _a;
@@ -1068,7 +1335,6 @@ var renderPagesJsonByArray = function (appPages, pageJson) {
1068
1335
  root: app.appCode,
1069
1336
  pages: __spreadArray([], pages, true),
1070
1337
  };
1071
- // 移除旧的 subPackage 配置并添加新的
1072
1338
  pageJson.subPackages = pageJson.subPackages.filter(function (i) { return i.root !== currentTemp.root; });
1073
1339
  pageJson.subPackages.push(currentTemp);
1074
1340
  pageJson.subPackages = pageJson.subPackages.filter(function (i) { return i.pages.length; });
@@ -1082,62 +1348,43 @@ var renderPagesJsonByArray = function (appPages, pageJson) {
1082
1348
  }
1083
1349
  return pageJson;
1084
1350
  };
1085
- /**
1086
- * 生成完整的主应用 app.json
1087
- */
1088
1351
  var genreFullMainAppJsonByManifestList = function (appJson, manifestList) {
1089
1352
  return renderPagesJsonByArray(manifestList, appJson);
1090
1353
  };
1091
- /**
1092
- * 监听 dist 目录变化并同步文件
1093
- */
1094
- var watchDistChangeAndSyncFile = function (mainPwd, onReady, onChange) {
1095
- var root = process.env.MFE_SOURCE_OUTPUT_DIR;
1096
- if (!root) {
1097
- console.error("[Watcher] MFE_SOURCE_OUTPUT_DIR not set");
1098
- return;
1354
+ var DistWatcher = /** @class */ (function () {
1355
+ function DistWatcher() {
1099
1356
  }
1100
- var filePath = path.resolve(root);
1101
- // 确保目录存在,避免监听失效
1102
- checkAndgenreDir(filePath);
1103
- // 监听父级目录,过滤出目标目录下的变化,解决目录重建导致监听失效的问题
1104
- var parentDir = path.dirname(filePath);
1105
- var watcher = chokidar.watch(parentDir, {
1106
- persistent: true,
1107
- ignoreInitial: true,
1108
- usePolling: true,
1109
- interval: 100,
1110
- awaitWriteFinish: { stabilityThreshold: 200, pollInterval: 100 },
1111
- followSymlinks: true,
1112
- depth: 99
1113
- });
1114
- var isTargetFile = function (p) {
1115
- return p.startsWith(filePath + path.sep) || p === filePath;
1116
- };
1117
- watcher.on("ready", onReady);
1118
- ["add", "change", "unlink"].forEach(function (evt) {
1119
- // @ts-ignore
1120
- watcher.on(evt, function (p) {
1121
- if (!isTargetFile(p))
1122
- return;
1123
- var rel = path.relative(filePath, p);
1124
- var sourcePath = p;
1125
- var targetPath = path.join(mainPwd, rel);
1126
- // 仅文件内容变化才执行复制操作,目录变化由构建工具处理
1127
- if (["add", "change"].includes(evt)) {
1128
- copyFilesByTargetPath(sourcePath, targetPath);
1129
- }
1130
- onChange === null || onChange === void 0 ? void 0 : onChange({ type: evt, p: p, sourcePath: sourcePath, targetPath: targetPath });
1357
+ DistWatcher.prototype.start = function (mainPwd, onReady, onChange) {
1358
+ var root = process.env.MFE_SOURCE_OUTPUT_DIR;
1359
+ if (!root)
1360
+ return;
1361
+ var filePath = path.resolve(root);
1362
+ checkAndgenreDir(filePath);
1363
+ var parentDir = path.dirname(filePath);
1364
+ var watcher = createFileWatcher(parentDir);
1365
+ var isTargetFile = function (p) {
1366
+ return p.startsWith(filePath + path.sep) || p === filePath;
1367
+ };
1368
+ watcher.on("ready", onReady);
1369
+ ["add", "change", "unlink"].forEach(function (evt) {
1370
+ // @ts-ignore
1371
+ watcher.on(evt, function (p) {
1372
+ if (!isTargetFile(p))
1373
+ return;
1374
+ var rel = path.relative(filePath, p);
1375
+ var sourcePath = p;
1376
+ var targetPath = path.join(mainPwd, rel);
1377
+ if (["add", "change"].includes(evt)) {
1378
+ copyFilesByTargetPath(sourcePath, targetPath);
1379
+ }
1380
+ onChange === null || onChange === void 0 ? void 0 : onChange({ type: evt, p: p, sourcePath: sourcePath, targetPath: targetPath });
1381
+ });
1131
1382
  });
1132
- });
1133
- watcher.on('error', function (err) { return console.error('[Watcher] error:', err); });
1134
- };
1135
- /**
1136
- * 生成新的 app.json 文件
1137
- */
1138
- var genreNewAppJson = function (outputPageJsonPath, mainAppJsonPath, manifestList) {
1383
+ };
1384
+ return DistWatcher;
1385
+ }());
1386
+ var genreNewAppJson = function (outputPageJsonPath, appJson, manifestList) {
1139
1387
  try {
1140
- var appJson = uniReadFile(mainAppJsonPath);
1141
1388
  var newAppJSon = genreFullMainAppJsonByManifestList(__assign({ subPackages: [] }, appJson), manifestList);
1142
1389
  writeFiles(outputPageJsonPath, newAppJSon);
1143
1390
  }
@@ -1145,9 +1392,6 @@ var genreNewAppJson = function (outputPageJsonPath, mainAppJsonPath, manifestLis
1145
1392
  console.error("[AppJSON] Genre failed:", error);
1146
1393
  }
1147
1394
  };
1148
- /**
1149
- * 处理主应用服务端逻辑
1150
- */
1151
1395
  var createMainAppServer = function (manifestJson) {
1152
1396
  var mfeServer = WsServer.getInstance(function (opt) {
1153
1397
  var type = opt.type, data = opt.data;
@@ -1156,9 +1400,8 @@ var createMainAppServer = function (manifestJson) {
1156
1400
  var manifestPath = path.join(process.env.UNI_OUTPUT_DIR, data.appCode, MANIFEST_NAME);
1157
1401
  try {
1158
1402
  var manifestChildJson = uniReadFile(manifestPath);
1159
- genreNewAppJson(outputPageJsonPath, outputPageJsonPath, [
1160
- manifestChildJson,
1161
- ]);
1403
+ var mainAppJson = uniReadFile(outputPageJsonPath);
1404
+ genreNewAppJson(outputPageJsonPath, mainAppJson, [manifestChildJson]);
1162
1405
  }
1163
1406
  catch (e) {
1164
1407
  console.error("[Server] Handle child change failed:", e);
@@ -1168,9 +1411,6 @@ var createMainAppServer = function (manifestJson) {
1168
1411
  mfeServer.createServer();
1169
1412
  return mfeServer;
1170
1413
  };
1171
- /**
1172
- * 处理子应用客户端逻辑
1173
- */
1174
1414
  var createMainAppClient = function (manifestJson, onInit) {
1175
1415
  var client = WsClientServer.getInstance(function (opt) {
1176
1416
  if (opt.type === E_WS_TYPE.INIT) {
@@ -1180,20 +1420,48 @@ var createMainAppClient = function (manifestJson, onInit) {
1180
1420
  client.connect(manifestJson.value.appCode);
1181
1421
  return client;
1182
1422
  };
1183
- /**
1184
- * 创建主应用插件
1185
- */
1186
1423
  var createMainAppPlugin = function (manifestJson) {
1187
1424
  var mainPwd = "";
1188
1425
  var isWatcherReady = false;
1189
1426
  var mfeClientServer;
1190
1427
  var fn = null;
1428
+ var isBuild = function () { return process.env.MFE_BUILD_MODE === EBuildMode.BUILD; };
1429
+ var isServe = function () { return manifestJson.value.isServe; };
1430
+ var isRoot = function () { return manifestJson.value.isRoot; };
1431
+ var isStartServer = function () {
1432
+ if (isBuild())
1433
+ return false;
1434
+ return isServe();
1435
+ };
1436
+ var watchFile = function () {
1437
+ var allManifest = getAppsManifestList(manifestJson.value.mode);
1438
+ var watchFileList = allManifest.map(function (item) { return item.filePath; });
1439
+ var watcher = createFileWatcher(watchFileList);
1440
+ watcher.on("change", function (path) {
1441
+ var manifestJson = uniFsReadJSONFile(path);
1442
+ var outputPageJsonPath = getMainAppJsonPath();
1443
+ var mainAppJson = uniFsReadJSONFile(outputPageJsonPath);
1444
+ genreNewAppJson(outputPageJsonPath, mainAppJson, [manifestJson]);
1445
+ });
1446
+ };
1447
+ var distWatcher = new DistWatcher();
1191
1448
  var serverPlugin = {
1192
1449
  name: "@dd-code:main-app:serve",
1193
1450
  config: function () {
1194
1451
  return __awaiter(this, void 0, void 0, function () {
1195
- return __generator(this, function (_a) {
1196
- if (manifestJson.value.isRoot) {
1452
+ var isServe, _a, start;
1453
+ return __generator(this, function (_b) {
1454
+ isServe = isStartServer();
1455
+ if (isBuild())
1456
+ return [2 /*return*/];
1457
+ if (!isServe) {
1458
+ if (!isBuild() && isRoot()) {
1459
+ _a = createHttpServer(), _a.server, start = _a.start;
1460
+ start();
1461
+ }
1462
+ return [2 /*return*/];
1463
+ }
1464
+ if (isRoot()) {
1197
1465
  createMainAppServer();
1198
1466
  }
1199
1467
  else {
@@ -1206,7 +1474,10 @@ var createMainAppPlugin = function (manifestJson) {
1206
1474
  });
1207
1475
  },
1208
1476
  closeBundle: function () {
1209
- if (!manifestJson.value.isRoot) {
1477
+ var isServe = isStartServer();
1478
+ if (!isServe)
1479
+ return;
1480
+ if (!isRoot()) {
1210
1481
  serverPlugin.initWatchChange();
1211
1482
  fn === null || fn === void 0 ? void 0 : fn();
1212
1483
  fn = null;
@@ -1215,9 +1486,8 @@ var createMainAppPlugin = function (manifestJson) {
1215
1486
  initWatchChange: function () {
1216
1487
  if (isWatcherReady)
1217
1488
  return;
1218
- watchDistChangeAndSyncFile(mainPwd, function () {
1489
+ distWatcher.start(mainPwd, function () {
1219
1490
  isWatcherReady = true;
1220
- // console.log(`[Watcher] Ready watching: ${process.env.MFE_SOURCE_OUTPUT_DIR}`);
1221
1491
  }, function (change) {
1222
1492
  fn = function () {
1223
1493
  return mfeClientServer.sendMessage(E_WS_TYPE.CHANGE, __assign(__assign({}, change), { appCode: manifestJson.value.appCode }));
@@ -1238,18 +1508,43 @@ var createMainAppPlugin = function (manifestJson) {
1238
1508
  };
1239
1509
  return [
1240
1510
  serverPlugin,
1511
+ {
1512
+ name: "@dd-code:main-app:watch",
1513
+ closeBundle: function () {
1514
+ return __awaiter(this, void 0, void 0, function () {
1515
+ return __generator(this, function (_a) {
1516
+ if (isBuild())
1517
+ return [2 /*return*/];
1518
+ if (isServe())
1519
+ return [2 /*return*/];
1520
+ if (!checkIsBuildInChild())
1521
+ return [2 /*return*/];
1522
+ // if (!isServe) return;
1523
+ watchFile === null || watchFile === void 0 ? void 0 : watchFile();
1524
+ watchFile = null;
1525
+ return [2 /*return*/];
1526
+ });
1527
+ });
1528
+ },
1529
+ },
1241
1530
  {
1242
1531
  name: "@dd-code:main-app",
1243
1532
  enforce: "post",
1244
1533
  closeBundle: function () {
1245
1534
  return __awaiter(this, void 0, void 0, function () {
1246
- var _a, outputPageJsonPath, manifestList, mainAppJsonPath;
1535
+ var _a, outputPageJsonPath, manifestList, mainAppJsonPath, mainAppJson;
1247
1536
  return __generator(this, function (_b) {
1248
1537
  _a = filterManifestJsonListAndMainPageJson(__spreadArray(__spreadArray([], manifestJson.dependencies, true), [
1249
1538
  manifestJson.value,
1250
1539
  ], false)), outputPageJsonPath = _a.outputPageJsonPath, manifestList = _a.manifestList;
1251
- mainAppJsonPath = getMainAppJSon(manifestJson.value.mode, ROOT_APP_CODE);
1252
- genreNewAppJson(outputPageJsonPath, mainAppJsonPath, manifestList);
1540
+ if (!isRoot() && !isServe() && checkIsBuildInChild()) {
1541
+ return [2 /*return*/];
1542
+ }
1543
+ mainAppJsonPath = !isRoot()
1544
+ ? getNodeModuleMainAppJSon(manifestJson.value.mode, ROOT_APP_CODE)
1545
+ : getMainAppJsonPath();
1546
+ mainAppJson = uniReadFile(mainAppJsonPath);
1547
+ genreNewAppJson(outputPageJsonPath, mainAppJson, manifestList);
1253
1548
  return [2 /*return*/];
1254
1549
  });
1255
1550
  });
@@ -1265,8 +1560,18 @@ var createMpWeixinUniPlugin = function (options) {
1265
1560
  name: "@dd-code:genre-params",
1266
1561
  enforce: "pre",
1267
1562
  config: function (config) {
1268
- currentManifestJson.setEnv(config.mode);
1269
- resetOutDir(currentManifestJson, config);
1563
+ return __awaiter(this, void 0, void 0, function () {
1564
+ return __generator(this, function (_a) {
1565
+ switch (_a.label) {
1566
+ case 0:
1567
+ currentManifestJson.setEnv(config.mode);
1568
+ return [4 /*yield*/, resetOutDir(currentManifestJson, config)];
1569
+ case 1:
1570
+ _a.sent();
1571
+ return [2 /*return*/];
1572
+ }
1573
+ });
1574
+ });
1270
1575
  },
1271
1576
  },
1272
1577
  createAppsAssetsPlugin(currentManifestJson),