@dd-code/uni-tools 1.0.8 → 1.0.10

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,20 @@ 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
+ };
231
265
 
232
266
  var UniCdnManager = /** @class */ (function () {
233
267
  function UniCdnManager() {
@@ -260,10 +294,19 @@ var cdn = new UniCdnManager();
260
294
 
261
295
  // CDN 文件保存路径
262
296
  var SAVE_CDN_FILE_PATH = path.join(process.cwd(), "node_modules/@dd-code/uni-files");
297
+ path.join(process.cwd(), "node_modules/@dd-code/__main-pwd.txt");
298
+ path.join(process.cwd(), "node_modules/@dd-code/manifest-list.json");
263
299
  path.join(process.cwd(), "node_modules/@dd-code/current-files");
300
+ // 发布目录路径
301
+ var PUBLISH_PATH = path.join(process.cwd(), "dist/publish");
264
302
  // Manifest 文件名
265
303
  var MANIFEST_NAME = "mfe-uni-manifest.json";
266
- var ROOT_APP_CODE = "main"; //"__MFE_APP_ROOT__";
304
+ var ROOT_APP_CODE = "__MFE_APP_ROOT__";
305
+ var EBuildMode;
306
+ (function (EBuildMode) {
307
+ EBuildMode["BUILD"] = "build";
308
+ EBuildMode["SERVE"] = "serve";
309
+ })(EBuildMode || (EBuildMode = {}));
267
310
  // Manifest CDN 目录 URL 模板
268
311
  var MANIFEST_CND_DIR_URL = "{mode}/static-repository/mfe-uni/{code}/{appCode}";
269
312
  var getManifestCdnDirUrl = function (_a) {
@@ -354,6 +397,7 @@ var formatCliCommandConfig = function (mode) {
354
397
  code: viteEnv.MFE_UNI_CODE,
355
398
  mode: mode,
356
399
  cdn: viteEnv.MFE_CDN_HOST,
400
+ serve: viteEnv.MFE_UNI_SERVE, // 是否开启 serve 功能
357
401
  };
358
402
  };
359
403
  var checkIsRootManifest = function (manifest) {
@@ -361,12 +405,13 @@ var checkIsRootManifest = function (manifest) {
361
405
  };
362
406
  var WS_PORT = 3560;
363
407
  var WS_PATH = "/__mfe__ws__";
408
+ var HTTP_PATH = "/__mfe__http__";
364
409
  var E_WS_TYPE;
365
410
  (function (E_WS_TYPE) {
366
411
  E_WS_TYPE["INIT"] = "init_files";
367
412
  E_WS_TYPE["CHANGE"] = "change_files";
368
413
  })(E_WS_TYPE || (E_WS_TYPE = {}));
369
- var getMainAppJSon = function (mode, appCode) {
414
+ var getNodeModuleMainAppJSon = function (mode, appCode) {
370
415
  return path.join(SAVE_CDN_FILE_PATH, mode || "dev", appCode, "app.json");
371
416
  };
372
417
  var getMainAppJsonPath = function () {
@@ -422,10 +467,17 @@ var CliProgressManager = /** @class */ (function () {
422
467
  var CliProgressManager$1 = new CliProgressManager();
423
468
 
424
469
  var getDownloadedFilePath = function (conf) {
425
- return path.resolve(SAVE_CDN_FILE_PATH, conf.env, conf.appCode);
470
+ if (!conf.mode && !conf.env) {
471
+ throw new Error("appCode: ".concat(conf.appCode, " mode or env is required"));
472
+ }
473
+ if (!conf.appCode) {
474
+ throw new Error("appCode is required");
475
+ }
476
+ return path.resolve(SAVE_CDN_FILE_PATH, conf.mode || conf.env, conf.appCode);
426
477
  };
427
478
  var getNodeModulesEnvAppCodeFilePath = function (conf, fileName) {
428
- return path.resolve(getDownloadedFilePath(conf), fileName);
479
+ var savePath = getDownloadedFilePath(conf);
480
+ return path.resolve(savePath, fileName);
429
481
  };
430
482
  /**
431
483
  * 获取清单文件 URL 列表
@@ -594,19 +646,20 @@ var downloadProjectFiles = function (manifestList) { return __awaiter(void 0, vo
594
646
  }); };
595
647
 
596
648
  var checkDownloadFilesIsExpired = function (manifestList) {
597
- return manifestList.filter(function (conf) {
649
+ var filterList = manifestList.filter(function (conf) {
598
650
  var targetPath = getNodeModulesEnvAppCodeFilePath(conf, MANIFEST_NAME);
599
651
  var oldJson = uniReadFile(targetPath);
600
652
  var flag = !oldJson || (oldJson === null || oldJson === void 0 ? void 0 : oldJson.hash) !== conf.hash;
601
653
  return flag;
602
654
  });
655
+ return filterList;
603
656
  };
604
657
  var createManifestManager = function () {
605
658
  var envObj = process.env;
606
659
  var row = {
607
660
  code: "",
608
661
  mode: "",
609
- cdn: '',
662
+ cdn: "",
610
663
  hash: "",
611
664
  publicPath: "",
612
665
  appCode: "",
@@ -618,26 +671,29 @@ var createManifestManager = function () {
618
671
  get value() {
619
672
  return row;
620
673
  },
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
- });
674
+ setFiles: function (files) {
675
+ // const files = all.map((i) => {
676
+ // const filePath = path.resolve(outDir, i);
677
+ // const content = fs.readFileSync(filePath, "utf-8");
678
+ // const contentHash = generateSHA256(content).slice(0, 8);
679
+ // const dirName = path.dirname(i);
680
+ // const fileName = path.basename(i)
681
+ // const suffixName = dirName === "." ? "" : `${dirName}/`;
682
+ // return {
683
+ // fileName: i,
684
+ // fileUrl: `${suffixName}${contentHash}_${fileName}`,
685
+ // };
686
+ // });
631
687
  row.files = files;
632
688
  },
633
689
  setPagesJson: function (pagesJson) {
634
690
  row.pagesJson = pagesJson;
635
691
  },
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));
692
+ saveFile: function (filePath) {
693
+ // const files = row.files.filter((i) => i.fileName !== MANIFEST_NAME);
694
+ var newManifest = __assign(__assign({}, row), { isServe: undefined });
695
+ newManifest.hash = generateSHA256(JSON.stringify(__assign({}, newManifest)));
696
+ writeFiles(filePath, JSON.stringify(newManifest, null, 2));
641
697
  },
642
698
  setEnv: function (mode) {
643
699
  // const env = loadViteConfig(mode);
@@ -652,6 +708,7 @@ var createManifestManager = function () {
652
708
  row.isRoot = true;
653
709
  row.apps = mfeJson.apps;
654
710
  }
711
+ row.isServe = env.serve;
655
712
  row.publicPath = getManifestCdnDirUrl(row);
656
713
  },
657
714
  dependencies: [],
@@ -666,15 +723,86 @@ var createManifestManager = function () {
666
723
  };
667
724
  };
668
725
 
669
- var resetOutDir = function (currentManifestJson, config) {
726
+ var getMainProcess = function () { return __awaiter(void 0, void 0, void 0, function () {
727
+ var URL, mainProcess, result;
728
+ return __generator(this, function (_a) {
729
+ switch (_a.label) {
730
+ case 0:
731
+ URL = "http://localhost:".concat(WS_PORT).concat(HTTP_PATH, "/root-path");
732
+ return [4 /*yield*/, fetch(URL)];
733
+ case 1:
734
+ mainProcess = _a.sent();
735
+ return [4 /*yield*/, mainProcess.json()];
736
+ case 2:
737
+ result = _a.sent();
738
+ console.log(result, "mainProcess");
739
+ return [2 /*return*/, result];
740
+ }
741
+ });
742
+ }); };
743
+ var getMainProcessLoop = function () { return __awaiter(void 0, void 0, void 0, function () {
744
+ var mainProcess;
745
+ return __generator(this, function (_a) {
746
+ switch (_a.label) {
747
+ case 0:
748
+ _a.trys.push([0, 2, , 3]);
749
+ return [4 /*yield*/, getMainProcess()];
750
+ case 1:
751
+ mainProcess = _a.sent();
752
+ return [2 /*return*/, mainProcess];
753
+ case 2:
754
+ _a.sent();
755
+ return [3 /*break*/, 3];
756
+ case 3: return [2 /*return*/, new Promise(function (resolve) {
757
+ setTimeout(function () {
758
+ resolve(getMainProcessLoop());
759
+ }, 1000);
760
+ })];
761
+ }
762
+ });
763
+ }); };
764
+ var resetOutDir = function (currentManifestJson, config) { return __awaiter(void 0, void 0, void 0, function () {
765
+ var childBuild, currentManifest, mainProcess, exp;
670
766
  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
- };
767
+ return __generator(this, function (_b) {
768
+ switch (_b.label) {
769
+ case 0:
770
+ childBuild = process.env.MFE_TARGET_DIR === "root";
771
+ currentManifest = currentManifestJson.value;
772
+ if (!(!currentManifest.isRoot && childBuild && !currentManifest.isServe)) return [3 /*break*/, 2];
773
+ return [4 /*yield*/, getMainProcessLoop()];
774
+ case 1:
775
+ mainProcess = _b.sent();
776
+ // mainProcess.UNI_OUTPUT_DIR
777
+ config.build.outDir = "".concat(mainProcess.UNI_OUTPUT_DIR, "/").concat(currentManifest.appCode);
778
+ _b.label = 2;
779
+ case 2:
780
+ exp = new RegExp("/(".concat(currentManifest.appCode, ")/?"));
781
+ // http://localhost:3560/__mfe__http__/root-path
782
+ // if()
783
+ process.env.MFE_SOURCE_OUTPUT_DIR = config.build.outDir;
784
+ process.env.MFE_ROOT_OUTPUT_DIR = (_a = process.env.MFE_SOURCE_OUTPUT_DIR) === null || _a === void 0 ? void 0 : _a.replace(exp, "/").replace(/\/$/, "");
785
+ // if (!currentManifestJson.value.isRoot)
786
+ process.env.UNI_OUTPUT_DIR = process.env.MFE_ROOT_OUTPUT_DIR;
787
+ return [2 /*return*/];
788
+ }
789
+ });
790
+ }); };
677
791
 
792
+ var addUniCopyPluginHook = function (_a) {
793
+ var before = _a.before, after = _a.after;
794
+ var FileWatcher = require("@dcloudio/uni-cli-shared/dist/watcher").FileWatcher;
795
+ var originalCopy = FileWatcher.prototype.copy;
796
+ // Hook copy方法
797
+ FileWatcher.prototype.copy = function (from) {
798
+ var to = this.to(from);
799
+ var fromPath = this.from(from);
800
+ before === null || before === void 0 ? void 0 : before(fromPath, to);
801
+ var result = originalCopy.call(this, from);
802
+ after === null || after === void 0 ? void 0 : after(fromPath, to);
803
+ return result;
804
+ };
805
+ };
678
806
  var copyFilesByTargetPath = function (sourcePath, targetPath) {
679
807
  if (!fs.existsSync(sourcePath))
680
808
  return;
@@ -851,42 +979,140 @@ var transformToWeixinFormat = function (uniPagesConfig) {
851
979
  return weixinConfig;
852
980
  };
853
981
 
982
+ // import { addRunningAppToSave } from "../running-core";
983
+ var CollectFiles = /** @class */ (function () {
984
+ function CollectFiles() {
985
+ this.callbackFiles = [];
986
+ this.callbackFiles = [];
987
+ this.emitted = new Map();
988
+ this.outDir = "";
989
+ }
990
+ Object.defineProperty(CollectFiles.prototype, "collectedBuildFiles", {
991
+ get: function () {
992
+ return Array.from(this.emitted.values());
993
+ },
994
+ enumerable: false,
995
+ configurable: true
996
+ });
997
+ CollectFiles.prototype.collectBoundleFile = function (bundles) {
998
+ var _this = this;
999
+ Object.keys(bundles).forEach(function (key) {
1000
+ var boundle = bundles[key];
1001
+ var fileName = boundle.fileName, source = boundle.source, code = boundle.code;
1002
+ var fileInfo = genreFileInfoRow({ fileName: fileName, source: code || source });
1003
+ _this.emitted.set(fileName, fileInfo);
1004
+ });
1005
+ };
1006
+ CollectFiles.prototype.addManifestFile = function () {
1007
+ this.emitted.set(MANIFEST_NAME, {
1008
+ fileName: MANIFEST_NAME,
1009
+ fileUrl: MANIFEST_NAME,
1010
+ });
1011
+ };
1012
+ CollectFiles.prototype.collectCopyFiles = function () {
1013
+ var _this = this;
1014
+ this.callbackFiles.forEach(function (_a) {
1015
+ var abs = _a.abs, filePath = _a.filePath;
1016
+ try {
1017
+ var stat = fs.statSync(abs);
1018
+ if (stat.isFile()) {
1019
+ var fileInfo = genreFileInfoRow({
1020
+ fileName: filePath,
1021
+ source: fs.readFileSync(abs, "utf8"),
1022
+ });
1023
+ _this.emitted.set(filePath, fileInfo);
1024
+ }
1025
+ else if (stat.isDirectory()) {
1026
+ var files = walkDir(abs);
1027
+ files.forEach(function (file) {
1028
+ var absFilePath = path.resolve(abs, file);
1029
+ var fullFileName = path.join(filePath, file);
1030
+ _this.emitted.set(fullFileName, genreFileInfoRow({
1031
+ fileName: fullFileName,
1032
+ source: fs.readFileSync(absFilePath, "utf8"),
1033
+ }));
1034
+ });
1035
+ }
1036
+ }
1037
+ catch (e) {
1038
+ console.log(e);
1039
+ }
1040
+ });
1041
+ this.addManifestFile();
1042
+ };
1043
+ CollectFiles.prototype.copyFilesToPublishDir = function () {
1044
+ var _this = this;
1045
+ this.collectedBuildFiles.forEach(function (_a) {
1046
+ var fileName = _a.fileName, fileUrl = _a.fileUrl;
1047
+ var sourcePath = path.resolve(_this.outDir, fileName);
1048
+ var targetPath = path.resolve(PUBLISH_PATH, fileUrl);
1049
+ copyFilesByTargetPath(sourcePath, targetPath);
1050
+ });
1051
+ };
1052
+ return CollectFiles;
1053
+ }());
854
1054
  var createManifestPlugin = function (manifestJson) {
855
- var emitted = new Set();
1055
+ var collectFiles = new CollectFiles();
856
1056
  return {
857
1057
  name: "@dd-code:genre-mainfest-file-list",
858
1058
  enforce: "post",
1059
+ config: function (config) {
1060
+ var _a;
1061
+ var outDir = ((_a = config.build) === null || _a === void 0 ? void 0 : _a.outDir) || "dist";
1062
+ collectFiles.outDir = outDir;
1063
+ addUniCopyPluginHook({
1064
+ after: function (fromPath, to) {
1065
+ collectFiles.callbackFiles.push({
1066
+ abs: fromPath,
1067
+ filePath: path.relative(outDir, to),
1068
+ });
1069
+ },
1070
+ });
1071
+ },
859
1072
  renderStart: function () {
860
1073
  var content = initPrePagesJson();
861
1074
  var json = getPagesJson(content);
862
1075
  manifestJson.setPagesJson(json);
863
1076
  },
864
1077
  writeBundle: function (_outputOptions, bundle) {
865
- Object.values(bundle).forEach(function (item) {
866
- if (item && item.fileName)
867
- emitted.add(item.fileName);
868
- });
1078
+ collectFiles.collectBoundleFile(bundle);
869
1079
  },
870
1080
  closeBundle: function () {
871
- var outDir = process.env.MFE_SOURCE_OUTPUT_DIR || "dist";
872
- var all = walkDir(outDir, emitted);
873
- manifestJson.setFiles(outDir, all);
874
1081
  var sourcePath = manifestJson.value.isRoot
875
1082
  ? process.env.MFE_ROOT_OUTPUT_DIR
876
1083
  : 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);
1084
+ var filePath = path.resolve(sourcePath, MANIFEST_NAME);
1085
+ collectFiles.collectCopyFiles();
1086
+ manifestJson.setFiles(collectFiles.collectedBuildFiles);
1087
+ manifestJson.saveFile(filePath);
1088
+ // console.log({ filePath }, "sourcePath");
1089
+ // addRunningAppToSave(manifestJson.value.appCode, filePath);
1090
+ setTimeout(function () {
1091
+ collectFiles.copyFilesToPublishDir();
1092
+ }, 0);
881
1093
  },
882
1094
  };
883
1095
  };
884
1096
 
1097
+ var app = null;
885
1098
  var createHttpServer = function () {
886
- var app = express();
1099
+ if (app)
1100
+ return app;
1101
+ app = express();
887
1102
  var server = http.createServer(app);
1103
+ app.get("".concat(HTTP_PATH, "/root-path"), function (req, res) {
1104
+ res.send(process.env);
1105
+ });
888
1106
  app.use(cors({ origin: "*" }));
889
- return server;
1107
+ return {
1108
+ server: server,
1109
+ start: function (type) {
1110
+ var originKey = type || "http";
1111
+ server.listen(WS_PORT, function () {
1112
+ console.log("[uni-".concat(originKey, "] ").concat(originKey, "://localhost:").concat(WS_PORT).concat(HTTP_PATH));
1113
+ });
1114
+ },
1115
+ };
890
1116
  };
891
1117
 
892
1118
  var WsServer = /** @class */ (function () {
@@ -895,19 +1121,25 @@ var WsServer = /** @class */ (function () {
895
1121
  this.httpServer = createHttpServer();
896
1122
  this.clientMap = new Map();
897
1123
  }
1124
+ WsServer.getInstance = function (handleMessage) {
1125
+ if (!WsServer.instance) {
1126
+ WsServer.instance = new WsServer(handleMessage);
1127
+ }
1128
+ else if (handleMessage) {
1129
+ WsServer.instance.handleMessage = handleMessage;
1130
+ }
1131
+ return WsServer.instance;
1132
+ };
898
1133
  WsServer.prototype.createServer = function () {
1134
+ if (this.wss)
1135
+ return; // 避免重复创建
899
1136
  this.wss = new WebSocket.WebSocketServer({
900
- server: this.httpServer, // 绑定到 Vite 的 HTTP 服务器
1137
+ server: this.httpServer.server, // 绑定到 Vite 的 HTTP 服务器
901
1138
  path: WS_PATH, // WS 连接路径,前端连接时用 ws://localhost:5173/__mfe__ws__
902
1139
  });
903
1140
  this.onMessage(this.handleMessage);
904
1141
  this.onConnection();
905
- this.start();
906
- };
907
- WsServer.prototype.start = function () {
908
- this.httpServer.listen(WS_PORT, function () {
909
- console.log("[uni-WS] \u72EC\u7ACB\u670D\u52A1\u5DF2\u542F\u52A8\uFF1Aws://localhost:".concat(WS_PORT).concat(WS_PATH));
910
- });
1142
+ this.httpServer.start('ws');
911
1143
  };
912
1144
  WsServer.prototype.onMessage = function (callback) {
913
1145
  // WebSocketServer 不支持直接监听 message,必须在 connection 后的 socket 上监听
@@ -939,6 +1171,7 @@ var WsServer = /** @class */ (function () {
939
1171
  // 拿到客户端传递的 appCode
940
1172
  var url = new URL(request.url, "http://".concat(request.headers.host));
941
1173
  var appCode = url.searchParams.get("appCode");
1174
+ console.log("[uni-WS] \u5BA2\u6237\u7AEF\u8FDE\u63A5 WS \u670D\u52A1\uFF0CappCode: ".concat(appCode));
942
1175
  if (!appCode)
943
1176
  return;
944
1177
  _this.clientMap.set(appCode, ws);
@@ -959,8 +1192,19 @@ var WsClientServer = /** @class */ (function () {
959
1192
  this.ws = null;
960
1193
  this.isConnected = false;
961
1194
  }
1195
+ WsClientServer.getInstance = function (handleMessage) {
1196
+ if (!WsClientServer.instance) {
1197
+ WsClientServer.instance = new WsClientServer(handleMessage);
1198
+ }
1199
+ else if (handleMessage) {
1200
+ WsClientServer.instance.handleMessage = handleMessage;
1201
+ }
1202
+ return WsClientServer.instance;
1203
+ };
962
1204
  WsClientServer.prototype.connect = function (appCode) {
963
1205
  var _this = this;
1206
+ if (this.isConnected && this.ws)
1207
+ return;
964
1208
  this.ws = new WebSocket("ws://localhost:".concat(WS_PORT).concat(WS_PATH, "?appCode=").concat(appCode));
965
1209
  this.ws.on("open", function () {
966
1210
  // console.log("客户端已连接 WS 服务");
@@ -977,7 +1221,11 @@ var WsClientServer = /** @class */ (function () {
977
1221
  _this.isConnected = false;
978
1222
  _this.retryConnect(appCode);
979
1223
  });
980
- this.onMessage(this.handleMessage);
1224
+ // 监听消息并使用当前的 handleMessage
1225
+ this.ws.on("message", function (message) {
1226
+ var _a;
1227
+ (_a = _this.handleMessage) === null || _a === void 0 ? void 0 : _a.call(_this, JSON.parse(message.toString()));
1228
+ });
981
1229
  };
982
1230
  WsClientServer.prototype.sendMessage = function (type, data) {
983
1231
  if (this.isConnected) {
@@ -993,9 +1241,9 @@ var WsClientServer = /** @class */ (function () {
993
1241
  // // console.log("收到消息", message);
994
1242
  // };
995
1243
  WsClientServer.prototype.onMessage = function (callback) {
996
- this.ws.on("message", function (message) {
997
- callback === null || callback === void 0 ? void 0 : callback(JSON.parse(message.toString()));
998
- });
1244
+ if (callback) {
1245
+ this.handleMessage = callback;
1246
+ }
999
1247
  };
1000
1248
  WsClientServer.prototype.retryConnect = function (appCode) {
1001
1249
  var _this = this;
@@ -1021,9 +1269,37 @@ var WsClientServer = /** @class */ (function () {
1021
1269
  // export const mfeServer = new WsServer();
1022
1270
  // export const mfeClientServer = new WsClientServer();
1023
1271
 
1024
- /**
1025
- * 过滤 Manifest 列表并获取主应用 app.json 路径
1026
- */
1272
+ // export const addRunningAppToSave = (appCode, filePath: string) => {
1273
+ // const content = uniReadFile(SERVE_MPWEIXIN_MANIFEST);
1274
+ // if (content) {
1275
+ // content[appCode] = filePath;
1276
+ // }
1277
+ // writeFiles(SERVE_MPWEIXIN_MANIFEST, JSON.stringify(content, null, 2));
1278
+ // };
1279
+ var getAppsManifestList = function (mode) {
1280
+ var _a;
1281
+ var manifest = formatCliCommandConfig(mode);
1282
+ if (!manifest.isRoot) {
1283
+ return [];
1284
+ }
1285
+ if (manifest.serve) {
1286
+ return [];
1287
+ }
1288
+ var mfeJson = getMfeJson();
1289
+ if (!((_a = mfeJson === null || mfeJson === void 0 ? void 0 : mfeJson.apps) === null || _a === void 0 ? void 0 : _a.length)) {
1290
+ throw new Error("mfeJson.apps is empty");
1291
+ }
1292
+ var apps = ((mfeJson === null || mfeJson === void 0 ? void 0 : mfeJson.apps) || []).map(function (_a) {
1293
+ var appCode = _a.appCode;
1294
+ return {
1295
+ appCode: appCode,
1296
+ filePath: "".concat(process.env.UNI_OUTPUT_DIR, "/").concat(appCode, "/").concat(MANIFEST_NAME),
1297
+ };
1298
+ });
1299
+ // console.log(apps);
1300
+ return apps;
1301
+ };
1302
+
1027
1303
  var filterManifestJsonListAndMainPageJson = function (manifestJsonList) {
1028
1304
  var outputPageJsonPath = getMainAppJsonPath();
1029
1305
  return {
@@ -1031,9 +1307,6 @@ var filterManifestJsonListAndMainPageJson = function (manifestJsonList) {
1031
1307
  manifestList: manifestJsonList.filter(function (item) { return !checkIsRootManifest(item); }),
1032
1308
  };
1033
1309
  };
1034
- /**
1035
- * 根据 Manifest 列表渲染 app.json 的 subPackages
1036
- */
1037
1310
  var renderPagesJsonByArray = function (appPages, pageJson) {
1038
1311
  var _loop_1 = function (app) {
1039
1312
  var _a = getPagesJson(JSON.stringify((app === null || app === void 0 ? void 0 : app.pagesJson) || {}), true).pages, pages = _a === void 0 ? [] : _a;
@@ -1041,7 +1314,6 @@ var renderPagesJsonByArray = function (appPages, pageJson) {
1041
1314
  root: app.appCode,
1042
1315
  pages: __spreadArray([], pages, true),
1043
1316
  };
1044
- // 移除旧的 subPackage 配置并添加新的
1045
1317
  pageJson.subPackages = pageJson.subPackages.filter(function (i) { return i.root !== currentTemp.root; });
1046
1318
  pageJson.subPackages.push(currentTemp);
1047
1319
  pageJson.subPackages = pageJson.subPackages.filter(function (i) { return i.pages.length; });
@@ -1055,62 +1327,43 @@ var renderPagesJsonByArray = function (appPages, pageJson) {
1055
1327
  }
1056
1328
  return pageJson;
1057
1329
  };
1058
- /**
1059
- * 生成完整的主应用 app.json
1060
- */
1061
1330
  var genreFullMainAppJsonByManifestList = function (appJson, manifestList) {
1062
1331
  return renderPagesJsonByArray(manifestList, appJson);
1063
1332
  };
1064
- /**
1065
- * 监听 dist 目录变化并同步文件
1066
- */
1067
- var watchDistChangeAndSyncFile = function (mainPwd, onReady, onChange) {
1068
- var root = process.env.MFE_SOURCE_OUTPUT_DIR;
1069
- if (!root) {
1070
- console.error("[Watcher] MFE_SOURCE_OUTPUT_DIR not set");
1071
- return;
1333
+ var DistWatcher = /** @class */ (function () {
1334
+ function DistWatcher() {
1072
1335
  }
1073
- var filePath = path.resolve(root);
1074
- // 确保目录存在,避免监听失效
1075
- checkAndgenreDir(filePath);
1076
- // 监听父级目录,过滤出目标目录下的变化,解决目录重建导致监听失效的问题
1077
- var parentDir = path.dirname(filePath);
1078
- var watcher = chokidar.watch(parentDir, {
1079
- persistent: true,
1080
- ignoreInitial: true,
1081
- usePolling: true,
1082
- interval: 100,
1083
- awaitWriteFinish: { stabilityThreshold: 200, pollInterval: 100 },
1084
- followSymlinks: true,
1085
- depth: 99
1086
- });
1087
- var isTargetFile = function (p) {
1088
- return p.startsWith(filePath + path.sep) || p === filePath;
1089
- };
1090
- watcher.on("ready", onReady);
1091
- ["add", "change", "unlink"].forEach(function (evt) {
1092
- // @ts-ignore
1093
- watcher.on(evt, function (p) {
1094
- if (!isTargetFile(p))
1095
- return;
1096
- var rel = path.relative(filePath, p);
1097
- var sourcePath = p;
1098
- var targetPath = path.join(mainPwd, rel);
1099
- // 仅文件内容变化才执行复制操作,目录变化由构建工具处理
1100
- if (["add", "change"].includes(evt)) {
1101
- copyFilesByTargetPath(sourcePath, targetPath);
1102
- }
1103
- onChange === null || onChange === void 0 ? void 0 : onChange({ type: evt, p: p, sourcePath: sourcePath, targetPath: targetPath });
1336
+ DistWatcher.prototype.start = function (mainPwd, onReady, onChange) {
1337
+ var root = process.env.MFE_SOURCE_OUTPUT_DIR;
1338
+ if (!root)
1339
+ return;
1340
+ var filePath = path.resolve(root);
1341
+ checkAndgenreDir(filePath);
1342
+ var parentDir = path.dirname(filePath);
1343
+ var watcher = createFileWatcher(parentDir);
1344
+ var isTargetFile = function (p) {
1345
+ return p.startsWith(filePath + path.sep) || p === filePath;
1346
+ };
1347
+ watcher.on("ready", onReady);
1348
+ ["add", "change", "unlink"].forEach(function (evt) {
1349
+ // @ts-ignore
1350
+ watcher.on(evt, function (p) {
1351
+ if (!isTargetFile(p))
1352
+ return;
1353
+ var rel = path.relative(filePath, p);
1354
+ var sourcePath = p;
1355
+ var targetPath = path.join(mainPwd, rel);
1356
+ if (["add", "change"].includes(evt)) {
1357
+ copyFilesByTargetPath(sourcePath, targetPath);
1358
+ }
1359
+ onChange === null || onChange === void 0 ? void 0 : onChange({ type: evt, p: p, sourcePath: sourcePath, targetPath: targetPath });
1360
+ });
1104
1361
  });
1105
- });
1106
- watcher.on('error', function (err) { return console.error('[Watcher] error:', err); });
1107
- };
1108
- /**
1109
- * 生成新的 app.json 文件
1110
- */
1111
- var genreNewAppJson = function (outputPageJsonPath, mainAppJsonPath, manifestList) {
1362
+ };
1363
+ return DistWatcher;
1364
+ }());
1365
+ var genreNewAppJson = function (outputPageJsonPath, appJson, manifestList) {
1112
1366
  try {
1113
- var appJson = uniReadFile(mainAppJsonPath);
1114
1367
  var newAppJSon = genreFullMainAppJsonByManifestList(__assign({ subPackages: [] }, appJson), manifestList);
1115
1368
  writeFiles(outputPageJsonPath, newAppJSon);
1116
1369
  }
@@ -1118,20 +1371,16 @@ var genreNewAppJson = function (outputPageJsonPath, mainAppJsonPath, manifestLis
1118
1371
  console.error("[AppJSON] Genre failed:", error);
1119
1372
  }
1120
1373
  };
1121
- /**
1122
- * 处理主应用服务端逻辑
1123
- */
1124
1374
  var createMainAppServer = function (manifestJson) {
1125
- var mfeServer = new WsServer(function (opt) {
1375
+ var mfeServer = WsServer.getInstance(function (opt) {
1126
1376
  var type = opt.type, data = opt.data;
1127
1377
  if (type === E_WS_TYPE.CHANGE) {
1128
1378
  var outputPageJsonPath = getMainAppJsonPath();
1129
1379
  var manifestPath = path.join(process.env.UNI_OUTPUT_DIR, data.appCode, MANIFEST_NAME);
1130
1380
  try {
1131
1381
  var manifestChildJson = uniReadFile(manifestPath);
1132
- genreNewAppJson(outputPageJsonPath, outputPageJsonPath, [
1133
- manifestChildJson,
1134
- ]);
1382
+ var mainAppJson = uniReadFile(outputPageJsonPath);
1383
+ genreNewAppJson(outputPageJsonPath, mainAppJson, [manifestChildJson]);
1135
1384
  }
1136
1385
  catch (e) {
1137
1386
  console.error("[Server] Handle child change failed:", e);
@@ -1141,11 +1390,8 @@ var createMainAppServer = function (manifestJson) {
1141
1390
  mfeServer.createServer();
1142
1391
  return mfeServer;
1143
1392
  };
1144
- /**
1145
- * 处理子应用客户端逻辑
1146
- */
1147
1393
  var createMainAppClient = function (manifestJson, onInit) {
1148
- var client = new WsClientServer(function (opt) {
1394
+ var client = WsClientServer.getInstance(function (opt) {
1149
1395
  if (opt.type === E_WS_TYPE.INIT) {
1150
1396
  onInit(opt.data);
1151
1397
  }
@@ -1153,19 +1399,44 @@ var createMainAppClient = function (manifestJson, onInit) {
1153
1399
  client.connect(manifestJson.value.appCode);
1154
1400
  return client;
1155
1401
  };
1156
- /**
1157
- * 创建主应用插件
1158
- */
1159
1402
  var createMainAppPlugin = function (manifestJson) {
1160
1403
  var mainPwd = "";
1161
1404
  var isWatcherReady = false;
1162
1405
  var mfeClientServer;
1163
1406
  var fn = null;
1407
+ var isBuild = function () { return process.env.MFE_BUILD_MODE === EBuildMode.BUILD; };
1408
+ var isServe = function () { return manifestJson.value.isServe; };
1409
+ var isStartServer = function () {
1410
+ if (isBuild())
1411
+ return false;
1412
+ return isServe();
1413
+ };
1414
+ var watchFile = function () {
1415
+ var allManifest = getAppsManifestList(manifestJson.value.mode);
1416
+ var watchFileList = allManifest.map(function (item) { return item.filePath; });
1417
+ var watcher = createFileWatcher(watchFileList);
1418
+ watcher.on("change", function (path) {
1419
+ var manifestJson = uniFsReadJSONFile(path);
1420
+ var outputPageJsonPath = getMainAppJsonPath();
1421
+ var mainAppJson = uniFsReadJSONFile(outputPageJsonPath);
1422
+ genreNewAppJson(outputPageJsonPath, mainAppJson, [manifestJson]);
1423
+ });
1424
+ };
1425
+ var distWatcher = new DistWatcher();
1164
1426
  var serverPlugin = {
1165
1427
  name: "@dd-code:main-app:serve",
1166
1428
  config: function () {
1167
1429
  return __awaiter(this, void 0, void 0, function () {
1168
- return __generator(this, function (_a) {
1430
+ var isServe, _a, start;
1431
+ return __generator(this, function (_b) {
1432
+ isServe = isStartServer();
1433
+ if (!isServe) {
1434
+ if (!isBuild() && manifestJson.value.isRoot) {
1435
+ _a = createHttpServer(), _a.server, start = _a.start;
1436
+ start();
1437
+ }
1438
+ return [2 /*return*/];
1439
+ }
1169
1440
  if (manifestJson.value.isRoot) {
1170
1441
  createMainAppServer();
1171
1442
  }
@@ -1179,6 +1450,9 @@ var createMainAppPlugin = function (manifestJson) {
1179
1450
  });
1180
1451
  },
1181
1452
  closeBundle: function () {
1453
+ var isServe = isStartServer();
1454
+ if (!isServe)
1455
+ return;
1182
1456
  if (!manifestJson.value.isRoot) {
1183
1457
  serverPlugin.initWatchChange();
1184
1458
  fn === null || fn === void 0 ? void 0 : fn();
@@ -1188,9 +1462,8 @@ var createMainAppPlugin = function (manifestJson) {
1188
1462
  initWatchChange: function () {
1189
1463
  if (isWatcherReady)
1190
1464
  return;
1191
- watchDistChangeAndSyncFile(mainPwd, function () {
1465
+ distWatcher.start(mainPwd, function () {
1192
1466
  isWatcherReady = true;
1193
- // console.log(`[Watcher] Ready watching: ${process.env.MFE_SOURCE_OUTPUT_DIR}`);
1194
1467
  }, function (change) {
1195
1468
  fn = function () {
1196
1469
  return mfeClientServer.sendMessage(E_WS_TYPE.CHANGE, __assign(__assign({}, change), { appCode: manifestJson.value.appCode }));
@@ -1211,18 +1484,38 @@ var createMainAppPlugin = function (manifestJson) {
1211
1484
  };
1212
1485
  return [
1213
1486
  serverPlugin,
1487
+ {
1488
+ name: "@dd-code:main-app:watch",
1489
+ closeBundle: function () {
1490
+ return __awaiter(this, void 0, void 0, function () {
1491
+ return __generator(this, function (_a) {
1492
+ if (isBuild())
1493
+ return [2 /*return*/];
1494
+ if (isServe())
1495
+ return [2 /*return*/];
1496
+ // if (!isServe) return;
1497
+ watchFile === null || watchFile === void 0 ? void 0 : watchFile();
1498
+ watchFile = null;
1499
+ return [2 /*return*/];
1500
+ });
1501
+ });
1502
+ },
1503
+ },
1214
1504
  {
1215
1505
  name: "@dd-code:main-app",
1216
1506
  enforce: "post",
1217
1507
  closeBundle: function () {
1218
1508
  return __awaiter(this, void 0, void 0, function () {
1219
- var _a, outputPageJsonPath, manifestList, mainAppJsonPath;
1509
+ var _a, outputPageJsonPath, manifestList, mainAppJsonPath, mainAppJson;
1220
1510
  return __generator(this, function (_b) {
1221
1511
  _a = filterManifestJsonListAndMainPageJson(__spreadArray(__spreadArray([], manifestJson.dependencies, true), [
1222
1512
  manifestJson.value,
1223
1513
  ], false)), outputPageJsonPath = _a.outputPageJsonPath, manifestList = _a.manifestList;
1224
- mainAppJsonPath = getMainAppJSon(manifestJson.value.mode, ROOT_APP_CODE);
1225
- genreNewAppJson(outputPageJsonPath, mainAppJsonPath, manifestList);
1514
+ mainAppJsonPath = !manifestJson.value.isRoot
1515
+ ? getNodeModuleMainAppJSon(manifestJson.value.mode, ROOT_APP_CODE)
1516
+ : getMainAppJsonPath();
1517
+ mainAppJson = uniReadFile(mainAppJsonPath);
1518
+ genreNewAppJson(outputPageJsonPath, mainAppJson, manifestList);
1226
1519
  return [2 /*return*/];
1227
1520
  });
1228
1521
  });
@@ -1238,8 +1531,18 @@ var createMpWeixinUniPlugin = function (options) {
1238
1531
  name: "@dd-code:genre-params",
1239
1532
  enforce: "pre",
1240
1533
  config: function (config) {
1241
- currentManifestJson.setEnv(config.mode);
1242
- resetOutDir(currentManifestJson, config);
1534
+ return __awaiter(this, void 0, void 0, function () {
1535
+ return __generator(this, function (_a) {
1536
+ switch (_a.label) {
1537
+ case 0:
1538
+ currentManifestJson.setEnv(config.mode);
1539
+ return [4 /*yield*/, resetOutDir(currentManifestJson, config)];
1540
+ case 1:
1541
+ _a.sent();
1542
+ return [2 /*return*/];
1543
+ }
1544
+ });
1545
+ });
1243
1546
  },
1244
1547
  },
1245
1548
  createAppsAssetsPlugin(currentManifestJson),