@dd-code/uni-tools 1.0.12 → 1.0.13

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/cli.js CHANGED
@@ -3,6 +3,7 @@
3
3
 
4
4
  var shared = require('@dd-code/shared');
5
5
  var path = require('path');
6
+ var fsExtra = require('fs-extra');
6
7
  var fs = require('fs');
7
8
  require('crypto');
8
9
  require('chokidar');
@@ -118,6 +119,17 @@ var loadViteConfig = function (mode) {
118
119
  var ROOT = process.cwd();
119
120
  return loadEnv(mode, ROOT, "MFE_");
120
121
  };
122
+ var unlinkDeepDirOrFile = function (filePath) {
123
+ try {
124
+ if (fsExtra.pathExistsSync(filePath)) {
125
+ // 同步检查是否存在
126
+ fsExtra.removeSync(filePath); // 同步递归删除
127
+ }
128
+ }
129
+ catch (err) {
130
+ console.error("删除文件夹失败:", err);
131
+ }
132
+ };
121
133
 
122
134
  // 项目 Git 子模块路径
123
135
  var PROJECT_GIT_PATH = "src/subtree";
@@ -253,6 +265,7 @@ var fetchAppsRepo = function () { return __awaiter(void 0, void 0, void 0, funct
253
265
  if (repoUrl) {
254
266
  var fileName = appCode.replace(/\//g, "_");
255
267
  var dir = PROJECT_GIT_PATH;
268
+ unlinkDeepDirOrFile(path.join(dir, fileName));
256
269
  checkAndgenreDir(dir);
257
270
  child_process.execSync("cd ".concat(dir, " && git clone ").concat(repoUrl, " ").concat(fileName), {
258
271
  stdio: "inherit",
package/dist/cli.mjs.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { program } from '@dd-code/shared';
3
3
  import path from 'path';
4
+ import fsExtra from 'fs-extra';
4
5
  import fs from 'fs';
5
6
  import 'crypto';
6
7
  import 'chokidar';
@@ -116,6 +117,17 @@ var loadViteConfig = function (mode) {
116
117
  var ROOT = process.cwd();
117
118
  return loadEnv(mode, ROOT, "MFE_");
118
119
  };
120
+ var unlinkDeepDirOrFile = function (filePath) {
121
+ try {
122
+ if (fsExtra.pathExistsSync(filePath)) {
123
+ // 同步检查是否存在
124
+ fsExtra.removeSync(filePath); // 同步递归删除
125
+ }
126
+ }
127
+ catch (err) {
128
+ console.error("删除文件夹失败:", err);
129
+ }
130
+ };
119
131
 
120
132
  // 项目 Git 子模块路径
121
133
  var PROJECT_GIT_PATH = "src/subtree";
@@ -251,6 +263,7 @@ var fetchAppsRepo = function () { return __awaiter(void 0, void 0, void 0, funct
251
263
  if (repoUrl) {
252
264
  var fileName = appCode.replace(/\//g, "_");
253
265
  var dir = PROJECT_GIT_PATH;
266
+ unlinkDeepDirOrFile(path.join(dir, fileName));
254
267
  checkAndgenreDir(dir);
255
268
  execSync("cd ".concat(dir, " && git clone ").concat(repoUrl, " ").concat(fileName), {
256
269
  stdio: "inherit",
package/dist/index.js CHANGED
@@ -1,17 +1,17 @@
1
1
  'use strict';
2
2
 
3
3
  var path = require('path');
4
+ var fsExtra = require('fs-extra');
4
5
  var fs = require('fs');
5
6
  var crypto = require('crypto');
6
7
  var chokidar = require('chokidar');
7
8
  var cliProgress = require('cli-progress');
8
9
  var chalk = require('chalk');
9
- var fsExtra = require('fs-extra');
10
+ require('child_process');
10
11
  var WebSocket = require('ws');
11
12
  var express = require('express');
12
13
  var http = require('http');
13
14
  var cors = require('cors');
14
- require('child_process');
15
15
 
16
16
  /******************************************************************************
17
17
  Copyright (c) Microsoft Corporation.
@@ -264,6 +264,17 @@ var createFileWatcher = function (filePath, opt) {
264
264
  };
265
265
  var checkIsBuildInChild = function () { return process.env.MFE_TARGET_DIR === "root"; };
266
266
  var checkIsInnerBuild = function () { return process.env.MFE_INNER_BUILD === "true"; };
267
+ var unlinkDeepDirOrFile = function (filePath) {
268
+ try {
269
+ if (fsExtra.pathExistsSync(filePath)) {
270
+ // 同步检查是否存在
271
+ fsExtra.removeSync(filePath); // 同步递归删除
272
+ }
273
+ }
274
+ catch (err) {
275
+ console.error("删除文件夹失败:", err);
276
+ }
277
+ };
267
278
 
268
279
  var UniCdnManager = /** @class */ (function () {
269
280
  function UniCdnManager() {
@@ -405,7 +416,7 @@ var formatCliCommandConfig = function (mode) {
405
416
  var checkIsRootManifest = function (manifest) {
406
417
  return manifest.isRoot || manifest.appCode === ROOT_APP_CODE;
407
418
  };
408
- var WS_PORT = 3560;
419
+ var WS_PORT = 3561;
409
420
  var WS_PATH = "/__mfe__ws__";
410
421
  var HTTP_PATH = "/__mfe__http__";
411
422
  var E_WS_TYPE;
@@ -481,18 +492,6 @@ var getNodeModulesEnvAppCodeFilePath = function (conf, fileName) {
481
492
  var savePath = getDownloadedFilePath(conf);
482
493
  return path.resolve(savePath, fileName);
483
494
  };
484
- /**
485
- * 获取清单文件 URL 列表
486
- * @description 根据环境和配置生成所有应用的清单文件 URL
487
- * @param {string} mode - 环境标识,默认为 'dev'
488
- * @returns {Array<Object>} 清单 URL 对象数组
489
- * @returns {string} returns[].url - 清单文件 URL
490
- * @returns {string} returns[].appCode - 应用代码
491
- * @returns {string} returns[].code - 项目代码
492
- * @example
493
- * const urls = getManifestJsonUrl('prod');
494
- * // 返回: [{ url: '...', appCode: 'main', code: 'my-project' }]
495
- */
496
495
  var getManifestJsonUrl = function (mode) { return __awaiter(void 0, void 0, void 0, function () {
497
496
  var _a, _b, isRoot, _c, code, apps, mfeJson, configApps, result;
498
497
  return __generator(this, function (_d) {
@@ -514,14 +513,11 @@ var getManifestJsonUrl = function (mode) { return __awaiter(void 0, void 0, void
514
513
  configApps = __spreadArray(__spreadArray([], configApps, true), [{ appCode: ROOT_APP_CODE }], false);
515
514
  _d.label = 4;
516
515
  case 4:
517
- // console.log(JSON, isRoot, "JSON");
518
- // debugger
519
- // const configApps = JSON.apps; // isRoot ? JSON.apps : [{ appCode: ROOT_APP_CODE }];
520
516
  apps = Array.from(new Set(__spreadArray([], (configApps || []).map(function (i) { return i.appCode; }), true)));
521
517
  return [3 /*break*/, 6];
522
518
  case 5:
523
519
  _d.sent();
524
- apps = []; // BASE_APP_CODE_LIST;
520
+ apps = [];
525
521
  return [3 /*break*/, 6];
526
522
  case 6:
527
523
  result = apps.map(function (appCode) {
@@ -563,24 +559,6 @@ var downloadManifestJson = function (urls) { return __awaiter(void 0, void 0, vo
563
559
  }
564
560
  });
565
561
  }); };
566
- /**
567
- * 下载项目文件
568
- * @description 根据清单列表并行下载所有项目文件到指定目录
569
- * @param {Array<Object>} manifestList - 清单数据数组
570
- * @param {string} manifestList[].env - 环境标识
571
- * @returns {Promise<void>} 下载完成
572
- * @example
573
- * await downloadProjectFiles([
574
- * { env: 'prod', files: [...] },
575
- * { env: 'test', files: [...] }
576
- * ]);
577
- */
578
- /**
579
- * 根据manifest文件下载所有相关文件
580
- * 用于微前端架构中的模块文件下载
581
- * @param {Object} manifestJson - manifest文件内容
582
- * @param {string} outDir - 输出目录
583
- */
584
562
  function downloadFilesByManifestJson(manifestJson, outDir, onDownload) {
585
563
  return __awaiter(this, void 0, void 0, function () {
586
564
  var cdn, appCode, publicPath, files, _a, _b, _c, _i, i, file, fileUrl, fileName, downloadUrl, content;
@@ -605,7 +583,6 @@ function downloadFilesByManifestJson(manifestJson, outDir, onDownload) {
605
583
  return [4 /*yield*/, fetchFileByPath(downloadUrl)];
606
584
  case 2:
607
585
  content = _d.sent();
608
- // console.log(path.join(outDir, appCode || "", fileName), 'path.join(outDir, appCode || "", fileName)');
609
586
  writeFiles(path.join(outDir, appCode || "", fileName), content);
610
587
  onDownload && onDownload(Number(i), file.length);
611
588
  _d.label = 3;
@@ -674,31 +651,17 @@ var createManifestManager = function () {
674
651
  return row;
675
652
  },
676
653
  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
- // });
689
654
  row.files = files;
690
655
  },
691
656
  setPagesJson: function (pagesJson) {
692
657
  row.pagesJson = pagesJson;
693
658
  },
694
659
  saveFile: function (filePath) {
695
- // const files = row.files.filter((i) => i.fileName !== MANIFEST_NAME);
696
660
  var newManifest = __assign(__assign({}, row), { isServe: undefined });
697
661
  newManifest.hash = generateSHA256(JSON.stringify(__assign({}, newManifest)));
698
662
  writeFiles(filePath, JSON.stringify(newManifest, null, 2));
699
663
  },
700
664
  setEnv: function (mode) {
701
- // const env = loadViteConfig(mode);
702
665
  var env = formatCliCommandConfig(mode);
703
666
  var mfeJson = getMfeJson();
704
667
  row.cdn = env.cdn;
@@ -717,11 +680,6 @@ var createManifestManager = function () {
717
680
  setDependencies: function (list) {
718
681
  this.dependencies = list;
719
682
  },
720
- // getFullManifestJsonList() {
721
- // const files = import.meta.globEager("./**/*.json");
722
- // console.log(files);
723
- // // return [...this.dependencies, this.value];
724
- // },
725
683
  };
726
684
  };
727
685
 
@@ -812,7 +770,6 @@ var addUniCopyPluginHook = function (_a) {
812
770
  var before = _a.before, after = _a.after;
813
771
  var FileWatcher = require("@dcloudio/uni-cli-shared/dist/watcher").FileWatcher;
814
772
  var originalCopy = FileWatcher.prototype.copy;
815
- // Hook copy方法
816
773
  FileWatcher.prototype.copy = function (from) {
817
774
  var to = this.to(from);
818
775
  var fromPath = this.from(from);
@@ -830,7 +787,23 @@ var copyFilesByTargetPath = function (sourcePath, targetPath) {
830
787
  fsExtra.ensureDirSync(targetDir);
831
788
  }
832
789
  catch (err) { }
833
- fsExtra.copySync(sourcePath, targetPath, { overwrite: true });
790
+ var shouldSkip = function () {
791
+ try {
792
+ var s = fs.statSync(sourcePath);
793
+ var t = fs.statSync(targetPath);
794
+ if (s.isDirectory() || t.isDirectory())
795
+ return false;
796
+ var sb = fs.readFileSync(sourcePath);
797
+ var tb = fs.readFileSync(targetPath);
798
+ return sb.length === tb.length && sb.equals(tb);
799
+ }
800
+ catch (_a) {
801
+ return false;
802
+ }
803
+ };
804
+ if (!shouldSkip()) {
805
+ fsExtra.copySync(sourcePath, targetPath, { overwrite: true });
806
+ }
834
807
  };
835
808
 
836
809
  var downloadFullApps = function (manifestJson) { return __awaiter(void 0, void 0, void 0, function () {
@@ -915,24 +888,18 @@ var getPagesJson = function (jsonFile, isFormat) {
915
888
  var platform = process.env.UNI_PLATFORM;
916
889
  initPreContext(platform);
917
890
  var context = getPreVueContext();
918
- // 使用uni的预处理器处理pages.json
919
891
  var processedJsonStr = preprocess(jsonFile, context, { type: "js" });
920
- // 解析为JSON对象
921
892
  var pagesConfig = eval("(".concat(processedJsonStr, ")"));
922
- // 针对微信小程序平台,处理特有的配置项
923
893
  if (isFormat && platform === "mp-weixin") {
924
894
  return transformToWeixinFormat(pagesConfig);
925
895
  }
926
896
  return pagesConfig;
927
897
  };
928
- // 将uni-app的pages.json转换为微信小程序格式
929
898
  var transformToWeixinFormat = function (uniPagesConfig) {
930
899
  var _a;
931
900
  var weixinConfig = __assign({ pages: [], window: {}, tabBar: null, subPackages: [], usingComponents: {} }, uniPagesConfig);
932
- // 处理globalStyle -> window
933
901
  if (uniPagesConfig.globalStyle) {
934
902
  var globalStyle = uniPagesConfig.globalStyle;
935
- // 基础窗口配置
936
903
  weixinConfig.window = {
937
904
  navigationBarBackgroundColor: globalStyle.navigationBarBackgroundColor || "#000000",
938
905
  navigationBarTextStyle: globalStyle.navigationBarTextStyle || "white",
@@ -942,30 +909,25 @@ var transformToWeixinFormat = function (uniPagesConfig) {
942
909
  enablePullDownRefresh: globalStyle.enablePullDownRefresh || false,
943
910
  onReachBottomDistance: globalStyle.onReachBottomDistance || 50,
944
911
  };
945
- // 处理微信小程序特有配置
946
912
  if (globalStyle.pageOrientation) {
947
913
  weixinConfig.window.pageOrientation = globalStyle.pageOrientation;
948
914
  }
949
915
  if (globalStyle.renderingMode) {
950
916
  weixinConfig.window.renderingMode = globalStyle.renderingMode;
951
917
  }
952
- // 处理usingComponents
953
918
  if (globalStyle.usingComponents) {
954
919
  weixinConfig.usingComponents = globalStyle.usingComponents;
955
920
  }
956
- // 处理微信小程序平台特定配置
957
921
  if (globalStyle["mp-weixin"]) {
958
922
  Object.assign(weixinConfig.window, globalStyle["mp-weixin"]);
959
923
  }
960
924
  }
961
- // 处理pages配置
962
925
  if (uniPagesConfig.pages) {
963
926
  weixinConfig.pages = uniPagesConfig.pages.map(function (page) {
964
927
  var weixinPage = page.path;
965
928
  return weixinPage;
966
929
  });
967
930
  }
968
- // 处理tabBar配置
969
931
  if (uniPagesConfig.tabBar) {
970
932
  weixinConfig.tabBar = __assign(__assign({}, uniPagesConfig.tabBar), { list: (_a = uniPagesConfig.tabBar.list) === null || _a === void 0 ? void 0 : _a.map(function (item) { return ({
971
933
  pagePath: item.pagePath,
@@ -974,7 +936,6 @@ var transformToWeixinFormat = function (uniPagesConfig) {
974
936
  selectedIconPath: item.selectedIconPath,
975
937
  }); }) });
976
938
  }
977
- // 处理分包配置
978
939
  if (uniPagesConfig.subPackages) {
979
940
  weixinConfig.subPackages = uniPagesConfig.subPackages.map(function (subPackage) {
980
941
  var _a;
@@ -984,11 +945,9 @@ var transformToWeixinFormat = function (uniPagesConfig) {
984
945
  });
985
946
  });
986
947
  }
987
- // 处理预下载规则
988
948
  if (uniPagesConfig.preloadRule) {
989
949
  weixinConfig.preloadRule = uniPagesConfig.preloadRule;
990
950
  }
991
- // 移除uni-app特有的配置项
992
951
  delete weixinConfig.globalStyle;
993
952
  delete weixinConfig.easycom;
994
953
  delete weixinConfig.condition;
@@ -1114,10 +1073,93 @@ var createManifestPlugin = function (manifestJson) {
1114
1073
  };
1115
1074
  };
1116
1075
 
1076
+ var renderPagesJsonByArray = function (appPages, pageJson) {
1077
+ var _loop_1 = function (app) {
1078
+ var _a = getPagesJson(JSON.stringify((app === null || app === void 0 ? void 0 : app.pagesJson) || {}), true).pages, pages = _a === void 0 ? [] : _a;
1079
+ var currentTemp = {
1080
+ root: app.appCode,
1081
+ pages: __spreadArray([], pages, true),
1082
+ };
1083
+ pageJson.subPackages = pageJson.subPackages.filter(function (i) { return i.root !== currentTemp.root; });
1084
+ pageJson.subPackages.push(currentTemp);
1085
+ pageJson.subPackages = pageJson.subPackages.filter(function (i) { return i.pages.length; });
1086
+ };
1087
+ for (var _i = 0, appPages_1 = appPages; _i < appPages_1.length; _i++) {
1088
+ var app = appPages_1[_i];
1089
+ _loop_1(app);
1090
+ }
1091
+ if (!pageJson.tabBar) {
1092
+ delete pageJson.tabBar;
1093
+ }
1094
+ return pageJson;
1095
+ };
1096
+ var genreFullMainAppJsonByManifestList = function (appJson, manifestList) {
1097
+ return renderPagesJsonByArray(manifestList, appJson);
1098
+ };
1099
+ var genreNewAppJson = function (outputPageJsonPath, appJson, manifestList) {
1100
+ var newAppJSon = genreFullMainAppJsonByManifestList(__assign({ subPackages: [] }, appJson), manifestList);
1101
+ var old = uniFsReadJSONFile(outputPageJsonPath) || {};
1102
+ var nextStr = JSON.stringify(newAppJSon);
1103
+ var oldStr = JSON.stringify(old);
1104
+ if (nextStr !== oldStr) {
1105
+ writeFiles(outputPageJsonPath, newAppJSon);
1106
+ }
1107
+ };
1108
+
1109
+ var getAppsManifestList = function (mode) {
1110
+ var _a;
1111
+ var manifest = formatCliCommandConfig(mode);
1112
+ if (!manifest.isRoot) {
1113
+ return [];
1114
+ }
1115
+ if (manifest.serve) {
1116
+ return [];
1117
+ }
1118
+ var mfeJson = getMfeJson();
1119
+ if (!((_a = mfeJson === null || mfeJson === void 0 ? void 0 : mfeJson.apps) === null || _a === void 0 ? void 0 : _a.length)) {
1120
+ throw new Error("mfeJson.apps is empty");
1121
+ }
1122
+ var apps = ((mfeJson === null || mfeJson === void 0 ? void 0 : mfeJson.apps) || []).map(function (_a) {
1123
+ var appCode = _a.appCode;
1124
+ return {
1125
+ appCode: appCode,
1126
+ filePath: "".concat(process.env.UNI_OUTPUT_DIR, "/").concat(appCode, "/").concat(MANIFEST_NAME),
1127
+ };
1128
+ });
1129
+ return apps;
1130
+ };
1131
+ var startDistWatcher = function (mainPwd, onReady, onChange) {
1132
+ var root = process.env.MFE_SOURCE_OUTPUT_DIR;
1133
+ if (!root)
1134
+ return;
1135
+ var filePath = path.resolve(root);
1136
+ checkAndgenreDir(filePath);
1137
+ var parentDir = path.dirname(filePath);
1138
+ var watcher = createFileWatcher(parentDir);
1139
+ var isTargetFile = function (p) {
1140
+ return p.startsWith(filePath + path.sep) || p === filePath;
1141
+ };
1142
+ watcher.on("ready", onReady);
1143
+ ["add", "change", "unlink"].forEach(function (evt) {
1144
+ // @ts-ignore
1145
+ watcher.on(evt, function (p) {
1146
+ if (!isTargetFile(p))
1147
+ return;
1148
+ var rel = path.relative(filePath, p);
1149
+ var sourcePath = p;
1150
+ var targetPath = path.join(mainPwd, rel);
1151
+ if (["add", "change"].includes(evt)) {
1152
+ copyFilesByTargetPath(sourcePath, targetPath);
1153
+ }
1154
+ onChange === null || onChange === void 0 ? void 0 : onChange({ type: evt, p: p, sourcePath: sourcePath, targetPath: targetPath });
1155
+ });
1156
+ });
1157
+ };
1158
+
1117
1159
  var app = null;
1118
1160
  var createHttpServer = function () {
1119
1161
  if (app)
1120
- return app;
1162
+ return { server: app, start: function () { } };
1121
1163
  app = express();
1122
1164
  var server = http.createServer(app);
1123
1165
  app.get("".concat(HTTP_PATH, "/root-path"), function (req, res) {
@@ -1289,37 +1331,6 @@ var WsClientServer = /** @class */ (function () {
1289
1331
  // export const mfeServer = new WsServer();
1290
1332
  // export const mfeClientServer = new WsClientServer();
1291
1333
 
1292
- // export const addRunningAppToSave = (appCode, filePath: string) => {
1293
- // const content = uniReadFile(SERVE_MPWEIXIN_MANIFEST);
1294
- // if (content) {
1295
- // content[appCode] = filePath;
1296
- // }
1297
- // writeFiles(SERVE_MPWEIXIN_MANIFEST, JSON.stringify(content, null, 2));
1298
- // };
1299
- var getAppsManifestList = function (mode) {
1300
- var _a;
1301
- var manifest = formatCliCommandConfig(mode);
1302
- if (!manifest.isRoot) {
1303
- return [];
1304
- }
1305
- if (manifest.serve) {
1306
- return [];
1307
- }
1308
- var mfeJson = getMfeJson();
1309
- if (!((_a = mfeJson === null || mfeJson === void 0 ? void 0 : mfeJson.apps) === null || _a === void 0 ? void 0 : _a.length)) {
1310
- throw new Error("mfeJson.apps is empty");
1311
- }
1312
- var apps = ((mfeJson === null || mfeJson === void 0 ? void 0 : mfeJson.apps) || []).map(function (_a) {
1313
- var appCode = _a.appCode;
1314
- return {
1315
- appCode: appCode,
1316
- filePath: "".concat(process.env.UNI_OUTPUT_DIR, "/").concat(appCode, "/").concat(MANIFEST_NAME),
1317
- };
1318
- });
1319
- // console.log(apps);
1320
- return apps;
1321
- };
1322
-
1323
1334
  var filterManifestJsonListAndMainPageJson = function (manifestJsonList) {
1324
1335
  var outputPageJsonPath = getMainAppJsonPath();
1325
1336
  return {
@@ -1327,71 +1338,7 @@ var filterManifestJsonListAndMainPageJson = function (manifestJsonList) {
1327
1338
  manifestList: manifestJsonList.filter(function (item) { return !checkIsRootManifest(item); }),
1328
1339
  };
1329
1340
  };
1330
- var renderPagesJsonByArray = function (appPages, pageJson) {
1331
- var _loop_1 = function (app) {
1332
- var _a = getPagesJson(JSON.stringify((app === null || app === void 0 ? void 0 : app.pagesJson) || {}), true).pages, pages = _a === void 0 ? [] : _a;
1333
- var currentTemp = {
1334
- root: app.appCode,
1335
- pages: __spreadArray([], pages, true),
1336
- };
1337
- pageJson.subPackages = pageJson.subPackages.filter(function (i) { return i.root !== currentTemp.root; });
1338
- pageJson.subPackages.push(currentTemp);
1339
- pageJson.subPackages = pageJson.subPackages.filter(function (i) { return i.pages.length; });
1340
- };
1341
- for (var _i = 0, appPages_1 = appPages; _i < appPages_1.length; _i++) {
1342
- var app = appPages_1[_i];
1343
- _loop_1(app);
1344
- }
1345
- if (!pageJson.tabBar) {
1346
- delete pageJson.tabBar;
1347
- }
1348
- return pageJson;
1349
- };
1350
- var genreFullMainAppJsonByManifestList = function (appJson, manifestList) {
1351
- return renderPagesJsonByArray(manifestList, appJson);
1352
- };
1353
- var DistWatcher = /** @class */ (function () {
1354
- function DistWatcher() {
1355
- }
1356
- DistWatcher.prototype.start = function (mainPwd, onReady, onChange) {
1357
- var root = process.env.MFE_SOURCE_OUTPUT_DIR;
1358
- if (!root)
1359
- return;
1360
- var filePath = path.resolve(root);
1361
- checkAndgenreDir(filePath);
1362
- var parentDir = path.dirname(filePath);
1363
- var watcher = createFileWatcher(parentDir);
1364
- var isTargetFile = function (p) {
1365
- return p.startsWith(filePath + path.sep) || p === filePath;
1366
- };
1367
- watcher.on("ready", onReady);
1368
- ["add", "change", "unlink"].forEach(function (evt) {
1369
- // @ts-ignore
1370
- watcher.on(evt, function (p) {
1371
- if (!isTargetFile(p))
1372
- return;
1373
- var rel = path.relative(filePath, p);
1374
- var sourcePath = p;
1375
- var targetPath = path.join(mainPwd, rel);
1376
- if (["add", "change"].includes(evt)) {
1377
- copyFilesByTargetPath(sourcePath, targetPath);
1378
- }
1379
- onChange === null || onChange === void 0 ? void 0 : onChange({ type: evt, p: p, sourcePath: sourcePath, targetPath: targetPath });
1380
- });
1381
- });
1382
- };
1383
- return DistWatcher;
1384
- }());
1385
- var genreNewAppJson = function (outputPageJsonPath, appJson, manifestList) {
1386
- try {
1387
- var newAppJSon = genreFullMainAppJsonByManifestList(__assign({ subPackages: [] }, appJson), manifestList);
1388
- writeFiles(outputPageJsonPath, newAppJSon);
1389
- }
1390
- catch (error) {
1391
- console.error("[AppJSON] Genre failed:", error);
1392
- }
1393
- };
1394
- var createMainAppServer = function (manifestJson) {
1341
+ var createMainAppServer = function () {
1395
1342
  var mfeServer = WsServer.getInstance(function (opt) {
1396
1343
  var type = opt.type, data = opt.data;
1397
1344
  if (type === E_WS_TYPE.CHANGE) {
@@ -1420,17 +1367,36 @@ var createMainAppClient = function (manifestJson, onInit) {
1420
1367
  return client;
1421
1368
  };
1422
1369
  var createMainAppPlugin = function (manifestJson) {
1423
- var mainPwd = "";
1424
- var isWatcherReady = false;
1425
- var mfeClientServer;
1426
- var fn = null;
1370
+ var state = {
1371
+ mainPwd: "",
1372
+ isWatcherReady: false,
1373
+ mfeClientServer: undefined,
1374
+ fn: null,
1375
+ };
1427
1376
  var isBuild = function () { return process.env.MFE_BUILD_MODE === EBuildMode.BUILD; };
1428
1377
  var isServe = function () { return manifestJson.value.isServe; };
1429
1378
  var isRoot = function () { return manifestJson.value.isRoot; };
1430
- var isStartServer = function () {
1431
- if (isBuild())
1432
- return false;
1433
- return isServe();
1379
+ var initSync = function () {
1380
+ if (state.isWatcherReady)
1381
+ return;
1382
+ startDistWatcher(state.mainPwd, function () {
1383
+ state.isWatcherReady = true;
1384
+ }, function (change) {
1385
+ state.fn = function () {
1386
+ return state.mfeClientServer.sendMessage(E_WS_TYPE.CHANGE, __assign(__assign({}, change), { appCode: manifestJson.value.appCode }));
1387
+ };
1388
+ });
1389
+ };
1390
+ var copyAppDistModule = function (_a) {
1391
+ var pwd = _a.pwd;
1392
+ if (!process.env.MFE_SOURCE_OUTPUT_DIR) {
1393
+ console.error("[Plugin] MFE_SOURCE_OUTPUT_DIR not defined");
1394
+ return;
1395
+ }
1396
+ state.mainPwd = path.join(pwd, manifestJson.value.appCode);
1397
+ var targetPath = state.mainPwd;
1398
+ var sourcePath = process.env.MFE_SOURCE_OUTPUT_DIR;
1399
+ copyFilesByTargetPath(sourcePath, targetPath);
1434
1400
  };
1435
1401
  var watchFile = function () {
1436
1402
  var allManifest = getAppsManifestList(manifestJson.value.mode);
@@ -1443,70 +1409,53 @@ var createMainAppPlugin = function (manifestJson) {
1443
1409
  genreNewAppJson(outputPageJsonPath, mainAppJson, [manifestJson]);
1444
1410
  });
1445
1411
  };
1446
- var distWatcher = new DistWatcher();
1447
- var serverPlugin = {
1412
+ var createServePlugin = function () { return ({
1448
1413
  name: "@dd-code:main-app:serve",
1449
1414
  config: function () {
1450
1415
  return __awaiter(this, void 0, void 0, function () {
1451
- var isServe, _a, start;
1452
- return __generator(this, function (_b) {
1453
- isServe = isStartServer();
1454
- if (isBuild())
1455
- return [2 /*return*/];
1456
- if (!isServe) {
1457
- if (!isBuild() && isRoot()) {
1458
- _a = createHttpServer(), _a.server, start = _a.start;
1459
- start();
1460
- }
1416
+ var start;
1417
+ return __generator(this, function (_a) {
1418
+ if (isBuild()) {
1461
1419
  return [2 /*return*/];
1462
1420
  }
1463
1421
  if (isRoot()) {
1422
+ if (!isServe()) {
1423
+ start = createHttpServer().start;
1424
+ start();
1425
+ return [2 /*return*/];
1426
+ }
1464
1427
  createMainAppServer();
1428
+ // const subs = findLocalSubApps();
1429
+ // if (subs.length) {
1430
+ // startLocalSubApps(subs, "mp-weixin", manifestJson.value.mode);
1431
+ // }
1465
1432
  }
1466
1433
  else {
1467
- mfeClientServer = createMainAppClient(manifestJson, function (data) {
1468
- serverPlugin.copyAppDistModule(data);
1434
+ state.mfeClientServer = createMainAppClient(manifestJson, function (data) {
1435
+ copyAppDistModule(data);
1469
1436
  });
1470
1437
  }
1471
1438
  return [2 /*return*/];
1472
1439
  });
1473
1440
  });
1474
1441
  },
1475
- closeBundle: function () {
1476
- var isServe = isStartServer();
1477
- if (!isServe)
1478
- return;
1479
- if (!isRoot()) {
1480
- serverPlugin.initWatchChange();
1481
- fn === null || fn === void 0 ? void 0 : fn();
1482
- fn = null;
1483
- }
1484
- },
1485
- initWatchChange: function () {
1486
- if (isWatcherReady)
1487
- return;
1488
- distWatcher.start(mainPwd, function () {
1489
- isWatcherReady = true;
1490
- }, function (change) {
1491
- fn = function () {
1492
- return mfeClientServer.sendMessage(E_WS_TYPE.CHANGE, __assign(__assign({}, change), { appCode: manifestJson.value.appCode }));
1493
- };
1494
- });
1495
- },
1496
- copyAppDistModule: function (_a) {
1497
- var pwd = _a.pwd;
1498
- if (!process.env.MFE_SOURCE_OUTPUT_DIR) {
1499
- console.error("[Plugin] MFE_SOURCE_OUTPUT_DIR not defined");
1500
- return;
1501
- }
1502
- mainPwd = path.join(pwd, manifestJson.value.appCode);
1503
- var targetPath = mainPwd;
1504
- var sourcePath = process.env.MFE_SOURCE_OUTPUT_DIR;
1505
- copyFilesByTargetPath(sourcePath, targetPath);
1506
- },
1507
- };
1442
+ }); };
1508
1443
  return [
1509
- serverPlugin,
1444
+ createServePlugin(),
1445
+ {
1446
+ name: "@dd-code:main-app:sync",
1447
+ closeBundle: function () {
1448
+ var _a;
1449
+ var start = isServe();
1450
+ if (!start || isBuild())
1451
+ return;
1452
+ if (isRoot())
1453
+ return;
1454
+ initSync();
1455
+ (_a = state.fn) === null || _a === void 0 ? void 0 : _a.call(state);
1456
+ state.fn = null;
1457
+ },
1458
+ },
1510
1459
  {
1511
1460
  name: "@dd-code:main-app:watch",
1512
1461
  closeBundle: function () {
@@ -1518,7 +1467,6 @@ var createMainAppPlugin = function (manifestJson) {
1518
1467
  return [2 /*return*/];
1519
1468
  if (!checkIsBuildInChild())
1520
1469
  return [2 /*return*/];
1521
- // if (!isServe) return;
1522
1470
  watchFile === null || watchFile === void 0 ? void 0 : watchFile();
1523
1471
  watchFile = null;
1524
1472
  return [2 /*return*/];
@@ -1564,6 +1512,8 @@ var createMpWeixinUniPlugin = function (options) {
1564
1512
  switch (_a.label) {
1565
1513
  case 0:
1566
1514
  currentManifestJson.setEnv(config.mode);
1515
+ // 清空 PUBLISH_PATH 目录
1516
+ unlinkDeepDirOrFile(PUBLISH_PATH);
1567
1517
  return [4 /*yield*/, resetOutDir(currentManifestJson, config)];
1568
1518
  case 1:
1569
1519
  _a.sent();
package/dist/index.mjs.js CHANGED
@@ -1,15 +1,15 @@
1
1
  import path from 'path';
2
+ import fsExtra from 'fs-extra';
2
3
  import fs from 'fs';
3
4
  import crypto from 'crypto';
4
5
  import chokidar from 'chokidar';
5
6
  import { MultiBar, Presets } from 'cli-progress';
6
7
  import chalk from 'chalk';
7
- import fsExtra from 'fs-extra';
8
+ import 'child_process';
8
9
  import WebSocket, { WebSocketServer } from 'ws';
9
10
  import express from 'express';
10
11
  import http from 'http';
11
12
  import cors from 'cors';
12
- import 'child_process';
13
13
 
14
14
  /******************************************************************************
15
15
  Copyright (c) Microsoft Corporation.
@@ -262,6 +262,17 @@ var createFileWatcher = function (filePath, opt) {
262
262
  };
263
263
  var checkIsBuildInChild = function () { return process.env.MFE_TARGET_DIR === "root"; };
264
264
  var checkIsInnerBuild = function () { return process.env.MFE_INNER_BUILD === "true"; };
265
+ var unlinkDeepDirOrFile = function (filePath) {
266
+ try {
267
+ if (fsExtra.pathExistsSync(filePath)) {
268
+ // 同步检查是否存在
269
+ fsExtra.removeSync(filePath); // 同步递归删除
270
+ }
271
+ }
272
+ catch (err) {
273
+ console.error("删除文件夹失败:", err);
274
+ }
275
+ };
265
276
 
266
277
  var UniCdnManager = /** @class */ (function () {
267
278
  function UniCdnManager() {
@@ -403,7 +414,7 @@ var formatCliCommandConfig = function (mode) {
403
414
  var checkIsRootManifest = function (manifest) {
404
415
  return manifest.isRoot || manifest.appCode === ROOT_APP_CODE;
405
416
  };
406
- var WS_PORT = 3560;
417
+ var WS_PORT = 3561;
407
418
  var WS_PATH = "/__mfe__ws__";
408
419
  var HTTP_PATH = "/__mfe__http__";
409
420
  var E_WS_TYPE;
@@ -479,18 +490,6 @@ var getNodeModulesEnvAppCodeFilePath = function (conf, fileName) {
479
490
  var savePath = getDownloadedFilePath(conf);
480
491
  return path.resolve(savePath, fileName);
481
492
  };
482
- /**
483
- * 获取清单文件 URL 列表
484
- * @description 根据环境和配置生成所有应用的清单文件 URL
485
- * @param {string} mode - 环境标识,默认为 'dev'
486
- * @returns {Array<Object>} 清单 URL 对象数组
487
- * @returns {string} returns[].url - 清单文件 URL
488
- * @returns {string} returns[].appCode - 应用代码
489
- * @returns {string} returns[].code - 项目代码
490
- * @example
491
- * const urls = getManifestJsonUrl('prod');
492
- * // 返回: [{ url: '...', appCode: 'main', code: 'my-project' }]
493
- */
494
493
  var getManifestJsonUrl = function (mode) { return __awaiter(void 0, void 0, void 0, function () {
495
494
  var _a, _b, isRoot, _c, code, apps, mfeJson, configApps, result;
496
495
  return __generator(this, function (_d) {
@@ -512,14 +511,11 @@ var getManifestJsonUrl = function (mode) { return __awaiter(void 0, void 0, void
512
511
  configApps = __spreadArray(__spreadArray([], configApps, true), [{ appCode: ROOT_APP_CODE }], false);
513
512
  _d.label = 4;
514
513
  case 4:
515
- // console.log(JSON, isRoot, "JSON");
516
- // debugger
517
- // const configApps = JSON.apps; // isRoot ? JSON.apps : [{ appCode: ROOT_APP_CODE }];
518
514
  apps = Array.from(new Set(__spreadArray([], (configApps || []).map(function (i) { return i.appCode; }), true)));
519
515
  return [3 /*break*/, 6];
520
516
  case 5:
521
517
  _d.sent();
522
- apps = []; // BASE_APP_CODE_LIST;
518
+ apps = [];
523
519
  return [3 /*break*/, 6];
524
520
  case 6:
525
521
  result = apps.map(function (appCode) {
@@ -561,24 +557,6 @@ var downloadManifestJson = function (urls) { return __awaiter(void 0, void 0, vo
561
557
  }
562
558
  });
563
559
  }); };
564
- /**
565
- * 下载项目文件
566
- * @description 根据清单列表并行下载所有项目文件到指定目录
567
- * @param {Array<Object>} manifestList - 清单数据数组
568
- * @param {string} manifestList[].env - 环境标识
569
- * @returns {Promise<void>} 下载完成
570
- * @example
571
- * await downloadProjectFiles([
572
- * { env: 'prod', files: [...] },
573
- * { env: 'test', files: [...] }
574
- * ]);
575
- */
576
- /**
577
- * 根据manifest文件下载所有相关文件
578
- * 用于微前端架构中的模块文件下载
579
- * @param {Object} manifestJson - manifest文件内容
580
- * @param {string} outDir - 输出目录
581
- */
582
560
  function downloadFilesByManifestJson(manifestJson, outDir, onDownload) {
583
561
  return __awaiter(this, void 0, void 0, function () {
584
562
  var cdn, appCode, publicPath, files, _a, _b, _c, _i, i, file, fileUrl, fileName, downloadUrl, content;
@@ -603,7 +581,6 @@ function downloadFilesByManifestJson(manifestJson, outDir, onDownload) {
603
581
  return [4 /*yield*/, fetchFileByPath(downloadUrl)];
604
582
  case 2:
605
583
  content = _d.sent();
606
- // console.log(path.join(outDir, appCode || "", fileName), 'path.join(outDir, appCode || "", fileName)');
607
584
  writeFiles(path.join(outDir, appCode || "", fileName), content);
608
585
  onDownload && onDownload(Number(i), file.length);
609
586
  _d.label = 3;
@@ -672,31 +649,17 @@ var createManifestManager = function () {
672
649
  return row;
673
650
  },
674
651
  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
- // });
687
652
  row.files = files;
688
653
  },
689
654
  setPagesJson: function (pagesJson) {
690
655
  row.pagesJson = pagesJson;
691
656
  },
692
657
  saveFile: function (filePath) {
693
- // const files = row.files.filter((i) => i.fileName !== MANIFEST_NAME);
694
658
  var newManifest = __assign(__assign({}, row), { isServe: undefined });
695
659
  newManifest.hash = generateSHA256(JSON.stringify(__assign({}, newManifest)));
696
660
  writeFiles(filePath, JSON.stringify(newManifest, null, 2));
697
661
  },
698
662
  setEnv: function (mode) {
699
- // const env = loadViteConfig(mode);
700
663
  var env = formatCliCommandConfig(mode);
701
664
  var mfeJson = getMfeJson();
702
665
  row.cdn = env.cdn;
@@ -715,11 +678,6 @@ var createManifestManager = function () {
715
678
  setDependencies: function (list) {
716
679
  this.dependencies = list;
717
680
  },
718
- // getFullManifestJsonList() {
719
- // const files = import.meta.globEager("./**/*.json");
720
- // console.log(files);
721
- // // return [...this.dependencies, this.value];
722
- // },
723
681
  };
724
682
  };
725
683
 
@@ -810,7 +768,6 @@ var addUniCopyPluginHook = function (_a) {
810
768
  var before = _a.before, after = _a.after;
811
769
  var FileWatcher = require("@dcloudio/uni-cli-shared/dist/watcher").FileWatcher;
812
770
  var originalCopy = FileWatcher.prototype.copy;
813
- // Hook copy方法
814
771
  FileWatcher.prototype.copy = function (from) {
815
772
  var to = this.to(from);
816
773
  var fromPath = this.from(from);
@@ -828,7 +785,23 @@ var copyFilesByTargetPath = function (sourcePath, targetPath) {
828
785
  fsExtra.ensureDirSync(targetDir);
829
786
  }
830
787
  catch (err) { }
831
- fsExtra.copySync(sourcePath, targetPath, { overwrite: true });
788
+ var shouldSkip = function () {
789
+ try {
790
+ var s = fs.statSync(sourcePath);
791
+ var t = fs.statSync(targetPath);
792
+ if (s.isDirectory() || t.isDirectory())
793
+ return false;
794
+ var sb = fs.readFileSync(sourcePath);
795
+ var tb = fs.readFileSync(targetPath);
796
+ return sb.length === tb.length && sb.equals(tb);
797
+ }
798
+ catch (_a) {
799
+ return false;
800
+ }
801
+ };
802
+ if (!shouldSkip()) {
803
+ fsExtra.copySync(sourcePath, targetPath, { overwrite: true });
804
+ }
832
805
  };
833
806
 
834
807
  var downloadFullApps = function (manifestJson) { return __awaiter(void 0, void 0, void 0, function () {
@@ -913,24 +886,18 @@ var getPagesJson = function (jsonFile, isFormat) {
913
886
  var platform = process.env.UNI_PLATFORM;
914
887
  initPreContext(platform);
915
888
  var context = getPreVueContext();
916
- // 使用uni的预处理器处理pages.json
917
889
  var processedJsonStr = preprocess(jsonFile, context, { type: "js" });
918
- // 解析为JSON对象
919
890
  var pagesConfig = eval("(".concat(processedJsonStr, ")"));
920
- // 针对微信小程序平台,处理特有的配置项
921
891
  if (isFormat && platform === "mp-weixin") {
922
892
  return transformToWeixinFormat(pagesConfig);
923
893
  }
924
894
  return pagesConfig;
925
895
  };
926
- // 将uni-app的pages.json转换为微信小程序格式
927
896
  var transformToWeixinFormat = function (uniPagesConfig) {
928
897
  var _a;
929
898
  var weixinConfig = __assign({ pages: [], window: {}, tabBar: null, subPackages: [], usingComponents: {} }, uniPagesConfig);
930
- // 处理globalStyle -> window
931
899
  if (uniPagesConfig.globalStyle) {
932
900
  var globalStyle = uniPagesConfig.globalStyle;
933
- // 基础窗口配置
934
901
  weixinConfig.window = {
935
902
  navigationBarBackgroundColor: globalStyle.navigationBarBackgroundColor || "#000000",
936
903
  navigationBarTextStyle: globalStyle.navigationBarTextStyle || "white",
@@ -940,30 +907,25 @@ var transformToWeixinFormat = function (uniPagesConfig) {
940
907
  enablePullDownRefresh: globalStyle.enablePullDownRefresh || false,
941
908
  onReachBottomDistance: globalStyle.onReachBottomDistance || 50,
942
909
  };
943
- // 处理微信小程序特有配置
944
910
  if (globalStyle.pageOrientation) {
945
911
  weixinConfig.window.pageOrientation = globalStyle.pageOrientation;
946
912
  }
947
913
  if (globalStyle.renderingMode) {
948
914
  weixinConfig.window.renderingMode = globalStyle.renderingMode;
949
915
  }
950
- // 处理usingComponents
951
916
  if (globalStyle.usingComponents) {
952
917
  weixinConfig.usingComponents = globalStyle.usingComponents;
953
918
  }
954
- // 处理微信小程序平台特定配置
955
919
  if (globalStyle["mp-weixin"]) {
956
920
  Object.assign(weixinConfig.window, globalStyle["mp-weixin"]);
957
921
  }
958
922
  }
959
- // 处理pages配置
960
923
  if (uniPagesConfig.pages) {
961
924
  weixinConfig.pages = uniPagesConfig.pages.map(function (page) {
962
925
  var weixinPage = page.path;
963
926
  return weixinPage;
964
927
  });
965
928
  }
966
- // 处理tabBar配置
967
929
  if (uniPagesConfig.tabBar) {
968
930
  weixinConfig.tabBar = __assign(__assign({}, uniPagesConfig.tabBar), { list: (_a = uniPagesConfig.tabBar.list) === null || _a === void 0 ? void 0 : _a.map(function (item) { return ({
969
931
  pagePath: item.pagePath,
@@ -972,7 +934,6 @@ var transformToWeixinFormat = function (uniPagesConfig) {
972
934
  selectedIconPath: item.selectedIconPath,
973
935
  }); }) });
974
936
  }
975
- // 处理分包配置
976
937
  if (uniPagesConfig.subPackages) {
977
938
  weixinConfig.subPackages = uniPagesConfig.subPackages.map(function (subPackage) {
978
939
  var _a;
@@ -982,11 +943,9 @@ var transformToWeixinFormat = function (uniPagesConfig) {
982
943
  });
983
944
  });
984
945
  }
985
- // 处理预下载规则
986
946
  if (uniPagesConfig.preloadRule) {
987
947
  weixinConfig.preloadRule = uniPagesConfig.preloadRule;
988
948
  }
989
- // 移除uni-app特有的配置项
990
949
  delete weixinConfig.globalStyle;
991
950
  delete weixinConfig.easycom;
992
951
  delete weixinConfig.condition;
@@ -1112,10 +1071,93 @@ var createManifestPlugin = function (manifestJson) {
1112
1071
  };
1113
1072
  };
1114
1073
 
1074
+ var renderPagesJsonByArray = function (appPages, pageJson) {
1075
+ var _loop_1 = function (app) {
1076
+ var _a = getPagesJson(JSON.stringify((app === null || app === void 0 ? void 0 : app.pagesJson) || {}), true).pages, pages = _a === void 0 ? [] : _a;
1077
+ var currentTemp = {
1078
+ root: app.appCode,
1079
+ pages: __spreadArray([], pages, true),
1080
+ };
1081
+ pageJson.subPackages = pageJson.subPackages.filter(function (i) { return i.root !== currentTemp.root; });
1082
+ pageJson.subPackages.push(currentTemp);
1083
+ pageJson.subPackages = pageJson.subPackages.filter(function (i) { return i.pages.length; });
1084
+ };
1085
+ for (var _i = 0, appPages_1 = appPages; _i < appPages_1.length; _i++) {
1086
+ var app = appPages_1[_i];
1087
+ _loop_1(app);
1088
+ }
1089
+ if (!pageJson.tabBar) {
1090
+ delete pageJson.tabBar;
1091
+ }
1092
+ return pageJson;
1093
+ };
1094
+ var genreFullMainAppJsonByManifestList = function (appJson, manifestList) {
1095
+ return renderPagesJsonByArray(manifestList, appJson);
1096
+ };
1097
+ var genreNewAppJson = function (outputPageJsonPath, appJson, manifestList) {
1098
+ var newAppJSon = genreFullMainAppJsonByManifestList(__assign({ subPackages: [] }, appJson), manifestList);
1099
+ var old = uniFsReadJSONFile(outputPageJsonPath) || {};
1100
+ var nextStr = JSON.stringify(newAppJSon);
1101
+ var oldStr = JSON.stringify(old);
1102
+ if (nextStr !== oldStr) {
1103
+ writeFiles(outputPageJsonPath, newAppJSon);
1104
+ }
1105
+ };
1106
+
1107
+ var getAppsManifestList = function (mode) {
1108
+ var _a;
1109
+ var manifest = formatCliCommandConfig(mode);
1110
+ if (!manifest.isRoot) {
1111
+ return [];
1112
+ }
1113
+ if (manifest.serve) {
1114
+ return [];
1115
+ }
1116
+ var mfeJson = getMfeJson();
1117
+ if (!((_a = mfeJson === null || mfeJson === void 0 ? void 0 : mfeJson.apps) === null || _a === void 0 ? void 0 : _a.length)) {
1118
+ throw new Error("mfeJson.apps is empty");
1119
+ }
1120
+ var apps = ((mfeJson === null || mfeJson === void 0 ? void 0 : mfeJson.apps) || []).map(function (_a) {
1121
+ var appCode = _a.appCode;
1122
+ return {
1123
+ appCode: appCode,
1124
+ filePath: "".concat(process.env.UNI_OUTPUT_DIR, "/").concat(appCode, "/").concat(MANIFEST_NAME),
1125
+ };
1126
+ });
1127
+ return apps;
1128
+ };
1129
+ var startDistWatcher = function (mainPwd, onReady, onChange) {
1130
+ var root = process.env.MFE_SOURCE_OUTPUT_DIR;
1131
+ if (!root)
1132
+ return;
1133
+ var filePath = path.resolve(root);
1134
+ checkAndgenreDir(filePath);
1135
+ var parentDir = path.dirname(filePath);
1136
+ var watcher = createFileWatcher(parentDir);
1137
+ var isTargetFile = function (p) {
1138
+ return p.startsWith(filePath + path.sep) || p === filePath;
1139
+ };
1140
+ watcher.on("ready", onReady);
1141
+ ["add", "change", "unlink"].forEach(function (evt) {
1142
+ // @ts-ignore
1143
+ watcher.on(evt, function (p) {
1144
+ if (!isTargetFile(p))
1145
+ return;
1146
+ var rel = path.relative(filePath, p);
1147
+ var sourcePath = p;
1148
+ var targetPath = path.join(mainPwd, rel);
1149
+ if (["add", "change"].includes(evt)) {
1150
+ copyFilesByTargetPath(sourcePath, targetPath);
1151
+ }
1152
+ onChange === null || onChange === void 0 ? void 0 : onChange({ type: evt, p: p, sourcePath: sourcePath, targetPath: targetPath });
1153
+ });
1154
+ });
1155
+ };
1156
+
1115
1157
  var app = null;
1116
1158
  var createHttpServer = function () {
1117
1159
  if (app)
1118
- return app;
1160
+ return { server: app, start: function () { } };
1119
1161
  app = express();
1120
1162
  var server = http.createServer(app);
1121
1163
  app.get("".concat(HTTP_PATH, "/root-path"), function (req, res) {
@@ -1287,37 +1329,6 @@ var WsClientServer = /** @class */ (function () {
1287
1329
  // export const mfeServer = new WsServer();
1288
1330
  // export const mfeClientServer = new WsClientServer();
1289
1331
 
1290
- // export const addRunningAppToSave = (appCode, filePath: string) => {
1291
- // const content = uniReadFile(SERVE_MPWEIXIN_MANIFEST);
1292
- // if (content) {
1293
- // content[appCode] = filePath;
1294
- // }
1295
- // writeFiles(SERVE_MPWEIXIN_MANIFEST, JSON.stringify(content, null, 2));
1296
- // };
1297
- var getAppsManifestList = function (mode) {
1298
- var _a;
1299
- var manifest = formatCliCommandConfig(mode);
1300
- if (!manifest.isRoot) {
1301
- return [];
1302
- }
1303
- if (manifest.serve) {
1304
- return [];
1305
- }
1306
- var mfeJson = getMfeJson();
1307
- if (!((_a = mfeJson === null || mfeJson === void 0 ? void 0 : mfeJson.apps) === null || _a === void 0 ? void 0 : _a.length)) {
1308
- throw new Error("mfeJson.apps is empty");
1309
- }
1310
- var apps = ((mfeJson === null || mfeJson === void 0 ? void 0 : mfeJson.apps) || []).map(function (_a) {
1311
- var appCode = _a.appCode;
1312
- return {
1313
- appCode: appCode,
1314
- filePath: "".concat(process.env.UNI_OUTPUT_DIR, "/").concat(appCode, "/").concat(MANIFEST_NAME),
1315
- };
1316
- });
1317
- // console.log(apps);
1318
- return apps;
1319
- };
1320
-
1321
1332
  var filterManifestJsonListAndMainPageJson = function (manifestJsonList) {
1322
1333
  var outputPageJsonPath = getMainAppJsonPath();
1323
1334
  return {
@@ -1325,71 +1336,7 @@ var filterManifestJsonListAndMainPageJson = function (manifestJsonList) {
1325
1336
  manifestList: manifestJsonList.filter(function (item) { return !checkIsRootManifest(item); }),
1326
1337
  };
1327
1338
  };
1328
- var renderPagesJsonByArray = function (appPages, pageJson) {
1329
- var _loop_1 = function (app) {
1330
- var _a = getPagesJson(JSON.stringify((app === null || app === void 0 ? void 0 : app.pagesJson) || {}), true).pages, pages = _a === void 0 ? [] : _a;
1331
- var currentTemp = {
1332
- root: app.appCode,
1333
- pages: __spreadArray([], pages, true),
1334
- };
1335
- pageJson.subPackages = pageJson.subPackages.filter(function (i) { return i.root !== currentTemp.root; });
1336
- pageJson.subPackages.push(currentTemp);
1337
- pageJson.subPackages = pageJson.subPackages.filter(function (i) { return i.pages.length; });
1338
- };
1339
- for (var _i = 0, appPages_1 = appPages; _i < appPages_1.length; _i++) {
1340
- var app = appPages_1[_i];
1341
- _loop_1(app);
1342
- }
1343
- if (!pageJson.tabBar) {
1344
- delete pageJson.tabBar;
1345
- }
1346
- return pageJson;
1347
- };
1348
- var genreFullMainAppJsonByManifestList = function (appJson, manifestList) {
1349
- return renderPagesJsonByArray(manifestList, appJson);
1350
- };
1351
- var DistWatcher = /** @class */ (function () {
1352
- function DistWatcher() {
1353
- }
1354
- DistWatcher.prototype.start = function (mainPwd, onReady, onChange) {
1355
- var root = process.env.MFE_SOURCE_OUTPUT_DIR;
1356
- if (!root)
1357
- return;
1358
- var filePath = path.resolve(root);
1359
- checkAndgenreDir(filePath);
1360
- var parentDir = path.dirname(filePath);
1361
- var watcher = createFileWatcher(parentDir);
1362
- var isTargetFile = function (p) {
1363
- return p.startsWith(filePath + path.sep) || p === filePath;
1364
- };
1365
- watcher.on("ready", onReady);
1366
- ["add", "change", "unlink"].forEach(function (evt) {
1367
- // @ts-ignore
1368
- watcher.on(evt, function (p) {
1369
- if (!isTargetFile(p))
1370
- return;
1371
- var rel = path.relative(filePath, p);
1372
- var sourcePath = p;
1373
- var targetPath = path.join(mainPwd, rel);
1374
- if (["add", "change"].includes(evt)) {
1375
- copyFilesByTargetPath(sourcePath, targetPath);
1376
- }
1377
- onChange === null || onChange === void 0 ? void 0 : onChange({ type: evt, p: p, sourcePath: sourcePath, targetPath: targetPath });
1378
- });
1379
- });
1380
- };
1381
- return DistWatcher;
1382
- }());
1383
- var genreNewAppJson = function (outputPageJsonPath, appJson, manifestList) {
1384
- try {
1385
- var newAppJSon = genreFullMainAppJsonByManifestList(__assign({ subPackages: [] }, appJson), manifestList);
1386
- writeFiles(outputPageJsonPath, newAppJSon);
1387
- }
1388
- catch (error) {
1389
- console.error("[AppJSON] Genre failed:", error);
1390
- }
1391
- };
1392
- var createMainAppServer = function (manifestJson) {
1339
+ var createMainAppServer = function () {
1393
1340
  var mfeServer = WsServer.getInstance(function (opt) {
1394
1341
  var type = opt.type, data = opt.data;
1395
1342
  if (type === E_WS_TYPE.CHANGE) {
@@ -1418,17 +1365,36 @@ var createMainAppClient = function (manifestJson, onInit) {
1418
1365
  return client;
1419
1366
  };
1420
1367
  var createMainAppPlugin = function (manifestJson) {
1421
- var mainPwd = "";
1422
- var isWatcherReady = false;
1423
- var mfeClientServer;
1424
- var fn = null;
1368
+ var state = {
1369
+ mainPwd: "",
1370
+ isWatcherReady: false,
1371
+ mfeClientServer: undefined,
1372
+ fn: null,
1373
+ };
1425
1374
  var isBuild = function () { return process.env.MFE_BUILD_MODE === EBuildMode.BUILD; };
1426
1375
  var isServe = function () { return manifestJson.value.isServe; };
1427
1376
  var isRoot = function () { return manifestJson.value.isRoot; };
1428
- var isStartServer = function () {
1429
- if (isBuild())
1430
- return false;
1431
- return isServe();
1377
+ var initSync = function () {
1378
+ if (state.isWatcherReady)
1379
+ return;
1380
+ startDistWatcher(state.mainPwd, function () {
1381
+ state.isWatcherReady = true;
1382
+ }, function (change) {
1383
+ state.fn = function () {
1384
+ return state.mfeClientServer.sendMessage(E_WS_TYPE.CHANGE, __assign(__assign({}, change), { appCode: manifestJson.value.appCode }));
1385
+ };
1386
+ });
1387
+ };
1388
+ var copyAppDistModule = function (_a) {
1389
+ var pwd = _a.pwd;
1390
+ if (!process.env.MFE_SOURCE_OUTPUT_DIR) {
1391
+ console.error("[Plugin] MFE_SOURCE_OUTPUT_DIR not defined");
1392
+ return;
1393
+ }
1394
+ state.mainPwd = path.join(pwd, manifestJson.value.appCode);
1395
+ var targetPath = state.mainPwd;
1396
+ var sourcePath = process.env.MFE_SOURCE_OUTPUT_DIR;
1397
+ copyFilesByTargetPath(sourcePath, targetPath);
1432
1398
  };
1433
1399
  var watchFile = function () {
1434
1400
  var allManifest = getAppsManifestList(manifestJson.value.mode);
@@ -1441,70 +1407,53 @@ var createMainAppPlugin = function (manifestJson) {
1441
1407
  genreNewAppJson(outputPageJsonPath, mainAppJson, [manifestJson]);
1442
1408
  });
1443
1409
  };
1444
- var distWatcher = new DistWatcher();
1445
- var serverPlugin = {
1410
+ var createServePlugin = function () { return ({
1446
1411
  name: "@dd-code:main-app:serve",
1447
1412
  config: function () {
1448
1413
  return __awaiter(this, void 0, void 0, function () {
1449
- var isServe, _a, start;
1450
- return __generator(this, function (_b) {
1451
- isServe = isStartServer();
1452
- if (isBuild())
1453
- return [2 /*return*/];
1454
- if (!isServe) {
1455
- if (!isBuild() && isRoot()) {
1456
- _a = createHttpServer(), _a.server, start = _a.start;
1457
- start();
1458
- }
1414
+ var start;
1415
+ return __generator(this, function (_a) {
1416
+ if (isBuild()) {
1459
1417
  return [2 /*return*/];
1460
1418
  }
1461
1419
  if (isRoot()) {
1420
+ if (!isServe()) {
1421
+ start = createHttpServer().start;
1422
+ start();
1423
+ return [2 /*return*/];
1424
+ }
1462
1425
  createMainAppServer();
1426
+ // const subs = findLocalSubApps();
1427
+ // if (subs.length) {
1428
+ // startLocalSubApps(subs, "mp-weixin", manifestJson.value.mode);
1429
+ // }
1463
1430
  }
1464
1431
  else {
1465
- mfeClientServer = createMainAppClient(manifestJson, function (data) {
1466
- serverPlugin.copyAppDistModule(data);
1432
+ state.mfeClientServer = createMainAppClient(manifestJson, function (data) {
1433
+ copyAppDistModule(data);
1467
1434
  });
1468
1435
  }
1469
1436
  return [2 /*return*/];
1470
1437
  });
1471
1438
  });
1472
1439
  },
1473
- closeBundle: function () {
1474
- var isServe = isStartServer();
1475
- if (!isServe)
1476
- return;
1477
- if (!isRoot()) {
1478
- serverPlugin.initWatchChange();
1479
- fn === null || fn === void 0 ? void 0 : fn();
1480
- fn = null;
1481
- }
1482
- },
1483
- initWatchChange: function () {
1484
- if (isWatcherReady)
1485
- return;
1486
- distWatcher.start(mainPwd, function () {
1487
- isWatcherReady = true;
1488
- }, function (change) {
1489
- fn = function () {
1490
- return mfeClientServer.sendMessage(E_WS_TYPE.CHANGE, __assign(__assign({}, change), { appCode: manifestJson.value.appCode }));
1491
- };
1492
- });
1493
- },
1494
- copyAppDistModule: function (_a) {
1495
- var pwd = _a.pwd;
1496
- if (!process.env.MFE_SOURCE_OUTPUT_DIR) {
1497
- console.error("[Plugin] MFE_SOURCE_OUTPUT_DIR not defined");
1498
- return;
1499
- }
1500
- mainPwd = path.join(pwd, manifestJson.value.appCode);
1501
- var targetPath = mainPwd;
1502
- var sourcePath = process.env.MFE_SOURCE_OUTPUT_DIR;
1503
- copyFilesByTargetPath(sourcePath, targetPath);
1504
- },
1505
- };
1440
+ }); };
1506
1441
  return [
1507
- serverPlugin,
1442
+ createServePlugin(),
1443
+ {
1444
+ name: "@dd-code:main-app:sync",
1445
+ closeBundle: function () {
1446
+ var _a;
1447
+ var start = isServe();
1448
+ if (!start || isBuild())
1449
+ return;
1450
+ if (isRoot())
1451
+ return;
1452
+ initSync();
1453
+ (_a = state.fn) === null || _a === void 0 ? void 0 : _a.call(state);
1454
+ state.fn = null;
1455
+ },
1456
+ },
1508
1457
  {
1509
1458
  name: "@dd-code:main-app:watch",
1510
1459
  closeBundle: function () {
@@ -1516,7 +1465,6 @@ var createMainAppPlugin = function (manifestJson) {
1516
1465
  return [2 /*return*/];
1517
1466
  if (!checkIsBuildInChild())
1518
1467
  return [2 /*return*/];
1519
- // if (!isServe) return;
1520
1468
  watchFile === null || watchFile === void 0 ? void 0 : watchFile();
1521
1469
  watchFile = null;
1522
1470
  return [2 /*return*/];
@@ -1562,6 +1510,8 @@ var createMpWeixinUniPlugin = function (options) {
1562
1510
  switch (_a.label) {
1563
1511
  case 0:
1564
1512
  currentManifestJson.setEnv(config.mode);
1513
+ // 清空 PUBLISH_PATH 目录
1514
+ unlinkDeepDirOrFile(PUBLISH_PATH);
1565
1515
  return [4 /*yield*/, resetOutDir(currentManifestJson, config)];
1566
1516
  case 1:
1567
1517
  _a.sent();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dd-code/uni-tools",
3
- "version": "1.0.12",
3
+ "version": "1.0.13",
4
4
  "description": "Universal tools for code utilities",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",