@tmsfe/tmskit 0.0.48 → 0.0.52

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.cjs.js CHANGED
@@ -31,7 +31,7 @@ var require$$4$2 = require('ansi-colors');
31
31
  var require$$5 = require('chokidar');
32
32
  var require$$6 = require('readable-stream');
33
33
  var require$$7 = require('vinyl-file');
34
- var require$$8 = require('vinyl');
34
+ var require$$8$1 = require('vinyl');
35
35
  var require$$9 = require('anymatch');
36
36
  var require$$11 = require('glob-parent');
37
37
  var require$$2$1 = require('plugin-error');
@@ -72,7 +72,7 @@ var require$$4__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$4$2);
72
72
  var require$$5__default = /*#__PURE__*/_interopDefaultLegacy(require$$5);
73
73
  var require$$6__default = /*#__PURE__*/_interopDefaultLegacy(require$$6);
74
74
  var require$$7__default = /*#__PURE__*/_interopDefaultLegacy(require$$7);
75
- var require$$8__default = /*#__PURE__*/_interopDefaultLegacy(require$$8);
75
+ var require$$8__default = /*#__PURE__*/_interopDefaultLegacy(require$$8$1);
76
76
  var require$$9__default = /*#__PURE__*/_interopDefaultLegacy(require$$9);
77
77
  var require$$11__default = /*#__PURE__*/_interopDefaultLegacy(require$$11);
78
78
  var require$$2__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$2$1);
@@ -80,14 +80,29 @@ var require$$10__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$10$1);
80
80
  var require$$12__default = /*#__PURE__*/_interopDefaultLegacy(require$$12$1);
81
81
  var require$$1__default$9 = /*#__PURE__*/_interopDefaultLegacy(require$$1$9);
82
82
 
83
+ function getAugmentedNamespace(n) {
84
+ if (n.__esModule) return n;
85
+ var a = Object.defineProperty({}, '__esModule', {value: true});
86
+ Object.keys(n).forEach(function (k) {
87
+ var d = Object.getOwnPropertyDescriptor(n, k);
88
+ Object.defineProperty(a, k, d.get ? d : {
89
+ enumerable: true,
90
+ get: function () {
91
+ return n[k];
92
+ }
93
+ });
94
+ });
95
+ return a;
96
+ }
97
+
83
98
  var src$3 = {};
84
99
 
85
100
  const chalk$5 = require$$3__default;
86
101
  const moment$1 = require$$1__default;
87
-
88
102
  /**
89
103
  * 本文件提供无依赖的在终端打印彩色文字的方法。
90
104
  */
105
+
91
106
  const resetCfg = decodeURIComponent('%1B%5B0m'); // \033[0m转义后的字符按,用来还原属性
92
107
 
93
108
  /**
@@ -95,78 +110,88 @@ const resetCfg = decodeURIComponent('%1B%5B0m'); // \033[0m转义后的字符按
95
110
  * @param {String} message 需要打印的文字信息
96
111
  * @returns {undefined} 无
97
112
  */
113
+
98
114
  const fail$a = (message = '') => {
99
115
  const redStyleConfig = decodeURIComponent('%1B%5B41%3B30m'); // \033[41;30m转义后的字符按,console时输出红色文字
116
+
100
117
  const greenFontStyleConfig = decodeURIComponent('%1B%5B41%3B37m'); // \033[41;30m转义后的字符按,console时输出红底白色文字
118
+
101
119
  console.log(`${moment$1().format('YYYY-MM-DD HH:mm:ss')}`, `${redStyleConfig} ERROR ${greenFontStyleConfig} ${message}${resetCfg}`); // eslint-disable-line no-console
102
120
  };
103
-
104
121
  /**
105
122
  * 打印绿底黑字格式的文字
106
123
  * @param {String} message 需要打印的文字信息
107
124
  * @returns {undefined} 无
108
125
  */
126
+
127
+
109
128
  const succeed$2 = (message = '') => {
110
129
  const greenStyleConfig = decodeURIComponent('%1B%5B42%3B30m'); // \033[42;30m转义后的字符按,console时输出绿色文字
130
+
111
131
  const greenFontStyleConfig = decodeURIComponent('%1B%5B40%3B32m'); // \033[40;32m转义后的字符按,console时输出绿色文字
132
+
112
133
  console.log(`${moment$1().format('YYYY-MM-DD HH:mm:ss')}`, `${greenStyleConfig} Success ${greenFontStyleConfig} ${message}${resetCfg}`); // eslint-disable-line no-console
113
134
  };
114
-
115
135
  /**
116
136
  * 打印warn提示
117
137
  * @param {String} message 需要打印的文字信息
118
138
  * @returns {undefined} 无
119
139
  */
140
+
141
+
120
142
  const warn$2 = message => {
121
143
  console.log(`${moment$1().format('YYYY-MM-DD HH:mm:ss')}`, chalk$5.yellow(message));
122
144
  };
123
- const info$k = (...args) => console.log(`${moment$1().format('YYYY-MM-DD HH:mm:ss')}`, ...args);
145
+
146
+ const info$l = (...args) => console.log(`${moment$1().format('YYYY-MM-DD HH:mm:ss')}`, ...args);
147
+
124
148
  const infoNoTime$1 = (...args) => console.log(...args);
149
+
125
150
  var log$1 = {
126
151
  fail: fail$a,
127
152
  succeed: succeed$2,
128
153
  warn: warn$2,
129
- info: info$k,
154
+ info: info$l,
130
155
  infoNoTime: infoNoTime$1
131
156
  };
132
157
 
133
158
  const ora$2 = require$$0__default;
134
159
  const path$h = require$$1__default$1;
135
- const fs$j = require$$0__default$1;
160
+ const fs$k = require$$0__default$1;
136
161
  const shelljs$7 = require$$0__default$2;
137
162
  const glob = require$$4__default;
138
163
  const {
139
- info: info$j
164
+ info: info$k
140
165
  } = log$1;
141
166
  const shelljsOptions = {
142
167
  slient: true,
143
168
  async: false
144
- };
169
+ }; // 获取当前目录
145
170
 
146
- // 获取当前目录
147
171
  const cwd = process.cwd();
148
- function resolve$k(...args) {
172
+
173
+ function resolve$l(...args) {
149
174
  return path$h.resolve(cwd, ...args);
150
175
  }
151
-
152
176
  /**
153
177
  * 判断变量是否是一个数组
154
178
  * @param { unknown } obj 变量
155
179
  * @returns { boolean } 是否是一个数组
156
180
  */
181
+
157
182
  function isObject(obj) {
158
183
  return Object.prototype.toString.call(obj) === '[object Object]';
159
184
  }
160
-
161
185
  /**
162
186
  * 判断变量是否是一个对象
163
187
  * @param { unknown } obj 变量
164
188
  * @returns { boolean } 是否是一个对象
165
189
  */
190
+
191
+
166
192
  function isArray(obj) {
167
193
  return Object.prototype.toString.call(obj) === '[object Array]';
168
194
  }
169
-
170
195
  /**
171
196
  * 下载模块代码
172
197
  * @param { string } url 模块地址
@@ -174,13 +199,16 @@ function isArray(obj) {
174
199
  * @param { string } branch 分支名
175
200
  * @returns { undefined } no return
176
201
  */
202
+
203
+
177
204
  function downloadRepoForGit$1(url, dest, branch) {
178
205
  const cwd = process.cwd();
179
206
  return new Promise((resolve, reject) => {
180
207
  // 如果目标目录不存在
181
- if (fs$j.existsSync(dest)) {
208
+ if (fs$k.existsSync(dest)) {
182
209
  shelljs$7.rm('-rf', path$h.join(dest));
183
210
  }
211
+
184
212
  shelljs$7.mkdir('-p', dest);
185
213
  shelljs$7.cd(dest);
186
214
  shelljs$7.exec(`git clone ${url} ${dest} --branch ${branch} --depth 1`, {
@@ -189,18 +217,20 @@ function downloadRepoForGit$1(url, dest, branch) {
189
217
  if (code !== 0) {
190
218
  reject(stderr);
191
219
  }
220
+
192
221
  shelljs$7.cd(cwd);
193
222
  resolve();
194
223
  });
195
224
  });
196
225
  }
197
-
198
226
  /**
199
227
  * pull模块代码
200
228
  * @param { string } dest 下载代码的路径
201
229
  * @param { string } branch 分支名
202
230
  * @returns { undefined } no return
203
231
  */
232
+
233
+
204
234
  function pullRepoForGit$1(dest, branch) {
205
235
  const cwd = process.cwd();
206
236
  return new Promise((resolve, reject) => {
@@ -212,18 +242,20 @@ function pullRepoForGit$1(dest, branch) {
212
242
  if (code !== 0) {
213
243
  reject(stderr);
214
244
  }
245
+
215
246
  shelljs$7.cd(cwd);
216
247
  resolve();
217
248
  });
218
249
  });
219
250
  }
220
-
221
251
  /**
222
252
  * npm 下载依赖
223
253
  * @param {string} dir 下载npm的目录
224
254
  * @param {object} npm npm的配置 (见下获取npm源入参)
225
255
  * @returns
226
256
  */
257
+
258
+
227
259
  function npmInstall$3(dir, npmConfig) {
228
260
  return new Promise((resolve, reject) => {
229
261
  const registry = getNpmRegistry(npmConfig);
@@ -234,12 +266,11 @@ function npmInstall$3(dir, npmConfig) {
234
266
  if (code !== 0) {
235
267
  reject(stderr);
236
268
  }
269
+
237
270
  resolve();
238
271
  });
239
272
  });
240
- }
241
-
242
- // 获取npm源
273
+ } // 获取npm源
243
274
  // 入参:{
244
275
  // registry: "https://registry.npmjs.org/",
245
276
  // scope: {
@@ -247,26 +278,31 @@ function npmInstall$3(dir, npmConfig) {
247
278
  // }
248
279
  // }
249
280
  // 出参: --@tencent:registry=http://mirrors.tencent.com/npm/ --registry=https://registry.npmjs.org/
281
+
282
+
250
283
  function getNpmRegistry(npmConfig = {}) {
251
284
  let resRegistry = '';
285
+
252
286
  if (npmConfig.registry) {
253
287
  resRegistry = ` --registry=${npmConfig.registry}`;
254
288
  }
289
+
255
290
  if (isObject(npmConfig.scope)) {
256
291
  Object.keys(npmConfig.scope).forEach(key => {
257
292
  resRegistry += ` --${key}:registry=${npmConfig.scope[key]}`;
258
293
  });
259
294
  }
295
+
260
296
  return resRegistry;
261
297
  }
262
-
263
298
  /**
264
299
  * 计算各项任务耗时
265
300
  * @param {Number} start 任务开始时间
266
301
  * @returns {Undefined} 无需返回值
267
302
  */
268
- const cost = start => Date.now() - start;
269
303
 
304
+
305
+ const cost = start => Date.now() - start;
270
306
  /**
271
307
  * 创建构建子任务
272
308
  * @param {Function} task 子任务执行函数
@@ -274,11 +310,13 @@ const cost = start => Date.now() - start;
274
310
  * @param {String} endText 任务结束后提示语
275
311
  * @returns {Undefined} 无需返回值
276
312
  */
313
+
314
+
277
315
  function createTask$7(task, startText, endText) {
278
316
  return async (...args) => {
279
317
  const start = Date.now();
280
318
  const spinner = ora$2();
281
- info$j(startText);
319
+ info$k(startText);
282
320
  spinner.start();
283
321
  const result = await task(...args);
284
322
  endText && spinner.succeed(`${endText}, 耗时${cost(start) / 1000}s`);
@@ -286,32 +324,35 @@ function createTask$7(task, startText, endText) {
286
324
  return result;
287
325
  };
288
326
  }
289
-
290
327
  /**
291
328
  * 字符串驼峰化处理
292
329
  * @param {String} str 需要处理的字符串
293
330
  * @returns {String} 经过驼峰处理的字符串
294
331
  */
332
+
295
333
  const camelize = str => str.replace(/-(\w)/g, (a, c) => c ? c.toUpperCase() : '');
334
+
296
335
  const mergeMap$1 = function (obj, src) {
297
336
  for (const [k, v] of src) {
298
337
  obj.set(k, v);
299
338
  }
339
+
300
340
  return obj;
301
341
  };
342
+
302
343
  const relativeCwdPath$1 = function (file) {
303
344
  return path$h.relative(process.cwd(), file);
304
345
  };
305
-
306
346
  /**
307
347
  * 从一个对象中,检索出去几个字段
308
348
  * @param {*} obj
309
349
  * @param {*} name
310
350
  * @returns
311
351
  */
352
+
353
+
312
354
  const filterField$8 = (obj, filterNames = []) => {
313
- const newObj = {
314
- ...obj
355
+ const newObj = { ...obj
315
356
  };
316
357
  filterNames.forEach(name => {
317
358
  if (newObj[name]) {
@@ -319,46 +360,50 @@ const filterField$8 = (obj, filterNames = []) => {
319
360
  }
320
361
  });
321
362
  return newObj;
322
- };
363
+ }; // 检索出文件列表
364
+
323
365
 
324
- // 检索出文件列表
325
366
  function findFiles(globPath, filter = []) {
326
367
  return new Promise((resolve, reject) => {
327
368
  glob(globPath, filter, (err, files) => {
328
369
  if (err) {
329
370
  reject(err);
330
371
  }
372
+
331
373
  resolve(files);
332
374
  });
333
375
  });
334
- }
376
+ } // 获取绝对路径
377
+
335
378
 
336
- // 获取绝对路径
337
379
  function getAbsolutePath$6(pathDir, cwd = '') {
338
380
  let newPath = pathDir;
339
- newPath = newPath.startsWith('/') ? newPath : resolve$k(cwd, newPath);
381
+ newPath = newPath.startsWith('/') ? newPath : resolve$l(cwd, newPath);
340
382
  newPath = newPath.endsWith('/') ? newPath.slice(0, newPath.length - 1) : newPath;
341
383
  return newPath;
342
- }
384
+ } // 版本比较 => 1(大于), 0(等于), -1(小于)
385
+
343
386
 
344
- // 版本比较 => 1(大于), 0(等于), -1(小于)
345
387
  function versionCompare(v1, v2) {
346
388
  // 将两个版本号拆成数组
347
389
  const arr1 = v1.split('.');
348
390
  const arr2 = v2.split('.');
349
- const minLength = Math.min(arr1.length, arr2.length);
350
- // 依次比较版本号每一位大小
391
+ const minLength = Math.min(arr1.length, arr2.length); // 依次比较版本号每一位大小
392
+
351
393
  for (let i = 0; i < minLength; i++) {
352
394
  if (parseInt(arr1[i], 10) !== parseInt(arr2[i], 10)) {
353
395
  return parseInt(arr1[i], 10) > parseInt(arr2[i], 10) ? 1 : -1;
354
396
  }
355
- }
356
- // 若前几位分隔相同,则按分隔数比较。
397
+ } // 若前几位分隔相同,则按分隔数比较。
398
+
399
+
357
400
  if (arr1.length === arr2.length) {
358
401
  return 0;
359
402
  }
403
+
360
404
  return arr1.length > arr2.length ? 1 : -1;
361
405
  }
406
+
362
407
  function getGitUser$2() {
363
408
  const res = shelljs$7.exec('git config user.name', {
364
409
  async: false,
@@ -366,8 +411,9 @@ function getGitUser$2() {
366
411
  });
367
412
  return res.stdout;
368
413
  }
414
+
369
415
  var widgets = {
370
- resolve: resolve$k,
416
+ resolve: resolve$l,
371
417
  isObject,
372
418
  isArray,
373
419
  createTask: createTask$7,
@@ -388,63 +434,45 @@ var widgets = {
388
434
  var tmsMpconfig = {exports: {}};
389
435
 
390
436
  const path$g = require$$1__default$1;
391
- const os = require$$1__default$2;
437
+ const os = require$$1__default$2; // 用户目录
392
438
 
393
- // 用户目录
394
- const HOME_DIR = os.homedir();
439
+ const HOME_DIR = os.homedir(); // 所有文件的缓存目录
395
440
 
396
- // 所有文件的缓存目录
397
- const CACHE_DIR = path$g.resolve(HOME_DIR, '.tmskit');
441
+ const CACHE_DIR = path$g.resolve(HOME_DIR, '.tmskit'); // 版本管理的CDN地址
398
442
 
399
- // 版本管理的CDN地址
400
- const VERSION_URL = 'https://tms-web-1g1czzwka2fd06f2-1301126013.tcloudbaseapp.com/tmskit-template/version.json';
443
+ const VERSION_URL = 'https://tms-web-1g1czzwka2fd06f2-1301126013.tcloudbaseapp.com/tmskit-template/version.json'; // version缓存文件
401
444
 
402
- // version缓存文件
403
- const VERSION_CACHE_FILE = path$g.resolve(CACHE_DIR, 'version_cache_file.json');
445
+ const VERSION_CACHE_FILE = path$g.resolve(CACHE_DIR, 'version_cache_file.json'); // npm缓存文件
404
446
 
405
- // npm缓存文件
406
- const NPM_CACHE_FILE$1 = path$g.resolve(CACHE_DIR, 'npm_cache_file.json');
447
+ const NPM_CACHE_FILE$1 = path$g.resolve(CACHE_DIR, 'npm_cache_file.json'); // 脚手架模板代码所在目录
407
448
 
408
- // 脚手架模板代码所在目录
409
- const TEMPLATE_DIR$1 = path$g.resolve(CACHE_DIR, 'template');
449
+ const TEMPLATE_DIR$1 = path$g.resolve(CACHE_DIR, 'template'); // 第三方模块源码存放的临时缓存目录
410
450
 
411
- // 第三方模块源码存放的临时缓存目录
412
- const MODULE_CODE_DIR$2 = path$g.resolve(CACHE_DIR, 'modules_code');
451
+ const MODULE_CODE_DIR$2 = path$g.resolve(CACHE_DIR, 'modules_code'); // 缓存分包node_modules的目录
413
452
 
414
- // 缓存分包node_modules的目录
415
- const NODE_MODULES_DIR$2 = path$g.resolve(CACHE_DIR, 'node_modules');
453
+ const NODE_MODULES_DIR$2 = path$g.resolve(CACHE_DIR, 'node_modules'); // 扩展命令源码的存放处
416
454
 
417
- // 扩展命令源码的存放处
418
- const EXTEND_CMD$1 = path$g.resolve(CACHE_DIR, 'cmd');
455
+ const EXTEND_CMD$1 = path$g.resolve(CACHE_DIR, 'cmd'); // 创建模板的名称
419
456
 
420
- // 创建模板的名称
421
- const TEMPLATE_NAME$1 = 'tmskit-template';
457
+ const TEMPLATE_NAME$1 = 'tmskit-template'; // 脚手架模板的远程地址
422
458
 
423
- // 脚手架模板的远程地址
424
- const TEMPLATE_URL$1 = 'http://tms-web-1g1czzwka2fd06f2-1301126013.tcloudbaseapp.com/tmskit-template/tmskit-template.zip';
459
+ const TEMPLATE_URL$1 = 'http://tms-web-1g1czzwka2fd06f2-1301126013.tcloudbaseapp.com/tmskit-template/tmskit-template.zip'; // 脚手架的名称
425
460
 
426
- // 脚手架的名称
427
- const TMS_NAME$1 = 'tmskit';
461
+ const TMS_NAME$1 = 'tmskit'; // 脚手架的配置名称
428
462
 
429
- // 脚手架的配置名称
430
463
  const TMS_CONFIG_FILENAME = 'tms.config.js';
431
- const TMS_PRIVATE_FILENAME = 'tms.private.config.js';
464
+ const TMS_PRIVATE_FILENAME = 'tms.private.config.js'; // 模块代码的默认在modules子目录
432
465
 
433
- // 模块代码的默认在modules子目录
434
- const DEFAULT_MODULE_DIR = 'modules';
466
+ const DEFAULT_MODULE_DIR = 'modules'; // 模块代码的默认在modules子目录
435
467
 
436
- // 模块代码的默认在modules子目录
437
- const DEFAULT_CLOUD_MODULE_DIR = './cloud';
468
+ const DEFAULT_CLOUD_MODULE_DIR = './cloud'; // 模块的配置文件的名称
438
469
 
439
- // 模块的配置文件的名称
440
- const MODULE_CONFIG_FILENAME = 'module.config.json';
470
+ const MODULE_CONFIG_FILENAME = 'module.config.json'; // 默认的webpack entry
441
471
 
442
- // 默认的webpack entry
443
472
  const DEFAULT_WEBPACK_ENTRY = {
444
473
  app: path$g.resolve(process.cwd(), 'app')
445
- };
474
+ }; // 默认从源码拷贝到编译后的配置
446
475
 
447
- // 默认从源码拷贝到编译后的配置
448
476
  const DEFAULT_COPY_CONFIG$2 = ['package.json', 'sitemap.json', 'project.config.json'];
449
477
  const ENV = {
450
478
  dev: 'development',
@@ -494,7 +522,6 @@ var constant = {
494
522
  VERSION_URL
495
523
  };
496
524
 
497
- // tmsConfig默认配置项
498
525
  var defaultTmsConfig = {
499
526
  // 全局的环境配置项
500
527
  envData: {},
@@ -503,16 +530,22 @@ var defaultTmsConfig = {
503
530
  cloudDir: 'cloud',
504
531
  // 第三方依赖代码需要拷贝到本项目的
505
532
  dependencies: {},
533
+
506
534
  /** 编译输出文件夹位置 */
507
535
  outputDir: 'dist',
536
+
508
537
  /** 是否在编译前清空输出目录 */
509
538
  cleanOutputDirBeforeCompile: true,
539
+
510
540
  /** 源码监听路径 */
511
541
  sourceDir: './',
542
+
512
543
  /** 静态资源目录 */
513
544
  static: [],
545
+
514
546
  /** 监听扩展文件 */
515
547
  watchExtendFiles: [],
548
+
516
549
  /** 上传是的配置 https://developers.weixin.qq.com/miniprogram/dev/devtools/ci.html#%E7%BC%96%E8%AF%91%E8%AE%BE%E7%BD%AE */
517
550
  upload: {
518
551
  setting: {
@@ -525,6 +558,7 @@ var defaultTmsConfig = {
525
558
  autoPrefixWXSS: true
526
559
  }
527
560
  },
561
+
528
562
  /** 预览的配置 https://developers.weixin.qq.com/miniprogram/dev/devtools/ci.html#%E9%A2%84%E8%A7%88 */
529
563
  preview: {
530
564
  setting: {
@@ -544,6 +578,7 @@ var defaultTmsConfig = {
544
578
 
545
579
  const global$c = {
546
580
  data: {},
581
+
547
582
  setData(...args) {
548
583
  if (args.length === 1) {
549
584
  Object.keys(args[0]).forEach(k => {
@@ -556,9 +591,11 @@ const global$c = {
556
591
  this.data[name] = value;
557
592
  }
558
593
  },
594
+
559
595
  getData(name) {
560
596
  return this.data[name];
561
597
  }
598
+
562
599
  };
563
600
  var global_1 = {
564
601
  global: global$c
@@ -567,6 +604,7 @@ var global_1 = {
567
604
  /**
568
605
  * 用来读取处理tms.config.js与module.config.json字段
569
606
  */
607
+
570
608
  (function (module) {
571
609
  /* eslint-disable no-param-reassign, no-nested-ternary */
572
610
  const loadash = require$$0__default$3;
@@ -592,75 +630,85 @@ var global_1 = {
592
630
  const {
593
631
  fail
594
632
  } = log$1;
595
-
596
633
  /**
597
634
  * 读取tms.config.js
598
635
  * @param {string} configPath tms.config.js的路径
599
636
  */
637
+
600
638
  const readTmsConfig = function (configPath) {
601
639
  const tmsConfigPath = configPath ? `${configPath}/${TMS_CONFIG_FILENAME}` : resolve(TMS_CONFIG_FILENAME);
640
+
602
641
  if (!fs.existsSync(tmsConfigPath)) {
603
642
  fail(`${path.dirname(tmsConfigPath)}没有找到tms.config.js,请进行配置`);
604
643
  process.exit(1);
605
644
  }
645
+
606
646
  const env = global.getData('commandName');
647
+
607
648
  const tmsConfigFn = require(tmsConfigPath);
649
+
608
650
  const tmsConfig = typeof tmsConfigFn === 'function' ? tmsConfigFn({
609
651
  env
610
- }) : tmsConfigFn;
652
+ }) : tmsConfigFn; // 合并默认值
611
653
 
612
- // 合并默认值
613
654
  return loadash.mergeWith({}, defaultTmsConfig$1, tmsConfig);
614
655
  };
615
-
616
656
  /**
617
657
  * 读取tms.private.config.js
618
658
  * @param {string} configPath tms.private.config.js的路径
619
659
  */
660
+
661
+
620
662
  const readTmsPrivateCf = function (configPath) {
621
663
  let tmsPrivateCf = {};
622
664
  const tmsPrivatePath = configPath ? `${configPath}/${TMS_PRIVATE_FILENAME}` : resolve(TMS_PRIVATE_FILENAME);
665
+
623
666
  if (fs.existsSync(tmsPrivatePath)) {
624
667
  const env = global.getData('commandName');
668
+
625
669
  const tmsPrivateFn = require(tmsPrivatePath);
670
+
626
671
  tmsPrivateCf = typeof tmsPrivateFn === 'function' ? tmsPrivateFn({
627
672
  env
628
673
  }) : tmsPrivateFn;
629
674
  }
675
+
630
676
  return tmsPrivateCf;
631
677
  };
632
-
633
678
  /**
634
679
  * 获取tms.config.js, tms.private.config.js的配置项
635
680
  * @param {string} configPath config.js的路径
636
681
  * @returns
637
682
  */
683
+
684
+
638
685
  const getTmsConfig = configPath => {
639
686
  const tmsPrivateCf = readTmsPrivateCf(configPath);
640
687
  const tmsConfig = readTmsConfig(configPath);
641
688
  const modules = {};
689
+
642
690
  if (Array.isArray(tmsConfig.modules)) {
643
691
  modules.all = tmsConfig.modules;
644
692
  tmsConfig.modules = modules;
645
- }
646
- // 使用自定义的合并策略:
693
+ } // 使用自定义的合并策略:
647
694
  // 1. 对 templateVars 字段做浅合并(即把 tms.config.js 中的和 tms.private.config.js 中的对象合并,
648
695
  // 如果存在同名字段则以 tms.private.config.js 中的为准)。
649
696
  // 2. 对数组(并且数组元素为对象的情况)执行拼接
697
+
698
+
650
699
  const res = loadash.mergeWith({}, tmsConfig, tmsPrivateCf, (objValue, srcValue, key) => {
651
700
  if (key === 'templateVars') {
652
- return {
653
- ...(objValue || {}),
701
+ return { ...(objValue || {}),
654
702
  ...(srcValue || {})
655
703
  };
656
704
  }
705
+
657
706
  if (Array.isArray(objValue) && objValue[0] && isObject(objValue[0])) {
658
707
  return objValue.concat(srcValue);
659
708
  }
660
709
  });
661
710
  return res;
662
711
  };
663
-
664
712
  /**
665
713
  * 根据moduleNames获取modules
666
714
  * @param { object } tmsConfig
@@ -668,39 +716,48 @@ var global_1 = {
668
716
  * @param {boolean} errorIsQuit 找不到配置文件是否退出
669
717
  * @returns
670
718
  */
719
+
720
+
671
721
  const getModulesByModuleNames = function (tmsConfig, moduleNames = []) {
672
722
  const targetModules = [];
673
723
  moduleNames.forEach(moduleName => {
674
724
  const module = tmsConfig.modules.all.find(module => module.moduleName === moduleName);
725
+
675
726
  if (!module) {
676
727
  throw new Error(`你启动的模块${moduleName}在tms.config.js的modules.all中没有注册`);
677
728
  }
729
+
678
730
  targetModules.push(module);
679
731
  });
680
732
  return targetModules;
681
733
  };
682
-
683
734
  /**
684
735
  * 适配处理module.config.json的字段
685
736
  * @param { object } fileContent module.config.json的内容
686
737
  * @param { string } appName 小程序的名称
687
738
  */
739
+
740
+
688
741
  function adaptMpCgContent(fileContent, appName) {
689
742
  const handleContent = function (appName, current) {
690
743
  let res = current;
744
+
691
745
  if (appName && current.mpConfig && current.mpConfig[appName]) {
692
- res = {
693
- ...current,
746
+ res = { ...current,
694
747
  ...current.mpConfig[appName]
695
748
  };
696
749
  }
750
+
697
751
  delete res.mpConfig;
698
752
  delete res.isSubpackages;
699
753
  return res;
700
754
  };
755
+
701
756
  let content = fileContent;
757
+
702
758
  if (isArray(content)) {
703
759
  let i = content.length - 1;
760
+
704
761
  while (i >= 0) {
705
762
  content[i] = handleContent(appName, content[i]);
706
763
  i--; // eslint-disable-line
@@ -708,20 +765,23 @@ var global_1 = {
708
765
  } else {
709
766
  content = handleContent(appName, content);
710
767
  }
768
+
711
769
  return content;
712
770
  }
771
+
713
772
  const adaptSubPackages = function (moduleConfig, appName) {
714
773
  const {
715
774
  subPackages
716
775
  } = moduleConfig;
717
776
  return adaptMpCgContent(subPackages, appName);
718
777
  };
719
-
720
778
  /**
721
779
  * 获取模块module.config.json中的配置信息
722
780
  * @param {array} modules 用户要编译的模块列表
723
781
  * @param { string } appName 小程序的名称
724
782
  */
783
+
784
+
725
785
  function getModulesConfig(modules = [], tmsConfig) {
726
786
  const {
727
787
  appName
@@ -730,56 +790,57 @@ var global_1 = {
730
790
  modules.forEach(moduleItem => {
731
791
  const moduleConfigPath = resolve(moduleItem.path, MODULE_CONFIG_FILENAME);
732
792
  let moduleConfig;
793
+
733
794
  try {
734
795
  // 模板渲染:先将 module.config.json 转为字符串,然后通过 preprocess 渲染
735
796
  const moduleConfigJsonStr = fs.readFileSync(moduleConfigPath, 'utf-8');
736
- const preprocessedStr = pp.preprocess(moduleConfigJsonStr, tmsConfig.templateVars || {}, 'json');
737
- // fs.writeFileSync(resolve(moduleConfigPath), moduleConfigJsonStr, 'utf8');
797
+ const preprocessedStr = pp.preprocess(moduleConfigJsonStr, tmsConfig.templateVars || {}, 'json'); // fs.writeFileSync(resolve(moduleConfigPath), moduleConfigJsonStr, 'utf8');
798
+
738
799
  moduleConfig = JSON5.parse(preprocessedStr);
739
800
  } catch (e) {
740
801
  throw new Error(`${moduleConfigPath}json解析报错: ${e}`);
741
- }
802
+ } // 兼容历史逻辑,后续可删除--- start
803
+
742
804
 
743
- // 兼容历史逻辑,后续可删除--- start
744
805
  const subPackages = adaptSubPackages(moduleConfig, appName);
745
- moduleConfig = {
746
- ...(isObject(moduleConfig) ? moduleConfig : {}),
806
+ moduleConfig = { ...(isObject(moduleConfig) ? moduleConfig : {}),
747
807
  subPackages
748
- };
749
- // 兼容逻辑--- end
808
+ }; // 兼容逻辑--- end
809
+
750
810
  modulesConfig.push(moduleConfig);
751
811
  });
752
812
  return modulesConfig;
753
813
  }
754
-
755
814
  /**
756
815
  * 获取分包内容 (读取module.config.json的配置项)
757
816
  * @param {array} modules
758
817
  * @returns
759
818
  */
819
+
820
+
760
821
  const getSubPackages = modules => {
761
822
  const newSubPackages = [];
762
823
  modules.forEach(module => {
763
824
  (module.subPackages || []).forEach(subPackage => {
764
- newSubPackages.push({
765
- ...subPackage
825
+ newSubPackages.push({ ...subPackage
766
826
  });
767
827
  });
768
828
  });
769
829
  return newSubPackages;
770
830
  };
771
-
772
831
  /**
773
832
  * 获取分包的root字段
774
833
  * @param {*} modulePath 模块的编译路径
775
834
  * @param {*} root 分包的root字段
776
835
  * @returns
777
836
  */
837
+
838
+
778
839
  const getSubPackageRoot = function (modulePath, root) {
779
840
  return root.startsWith(modulePath) ? root : `${modulePath}/${root}`;
780
- };
841
+ }; // 获取分包的源码路径
842
+
781
843
 
782
- // 获取分包的源码路径
783
844
  const getSubPackageSrcPath = function (tmsConfig, module, subPackage) {
784
845
  const srcModulePath = getAbsolutePath(module.path);
785
846
  const buildModulePath = resolve(tmsConfig.outputDir, module.modulePath);
@@ -789,37 +850,39 @@ var global_1 = {
789
850
  const srcSubPackagePath = path.join(srcModulePath, subPackageRelativeModule);
790
851
  return srcSubPackagePath;
791
852
  };
853
+
792
854
  const checkModuleItem = (tmsConfig, tmsModuleItem, moduleConfig) => {
793
- const newModuleItem = {
794
- ...tmsModuleItem,
855
+ const newModuleItem = { ...tmsModuleItem,
795
856
  ...moduleConfig
796
- };
857
+ }; // 参数校验-模块源码路径
797
858
 
798
- // 参数校验-模块源码路径
799
859
  if (!newModuleItem.path) {
800
860
  throw new Error(`${newModuleItem.moduleName}模块没有找到path字段,请检查tms.config.js的modules.all>module>path路径`);
801
- }
861
+ } // 参数校验-模块编译路径
862
+
802
863
 
803
- // 参数校验-模块编译路径
804
864
  if (!newModuleItem.modulePath) {
805
865
  throw new Error(`${newModuleItem.moduleName}模块的module.config.json中没有找到modulePath字段`);
806
- }
807
- // 参数校验-分包校验
866
+ } // 参数校验-分包校验
867
+
868
+
808
869
  for (const subPackage of newModuleItem.subPackages) {
809
870
  if (!subPackage.root) {
810
871
  throw new Error(`${newModuleItem.moduleName}模块的module.config.json中没有找到${subPackage.name}分包的root字段`);
811
- }
872
+ } // 参数校验-判断分包源码目录是否存在
873
+
812
874
 
813
- // 参数校验-判断分包源码目录是否存在
814
875
  const subPackageSrcPath = getSubPackageSrcPath(tmsConfig, newModuleItem, subPackage);
876
+
815
877
  if (!subPackageSrcPath || !fs.existsSync(subPackageSrcPath)) {
816
878
  throw new Error(`没有找到${newModuleItem.moduleName}模块的${subPackage.name}分包源码:${subPackageSrcPath}`);
817
879
  }
880
+
818
881
  subPackage.path = subPackageSrcPath;
819
882
  }
883
+
820
884
  return newModuleItem;
821
885
  };
822
-
823
886
  /**
824
887
  * 获取所有的模块,合并模块的依赖模块
825
888
  * @param { object } tmsConfig
@@ -827,40 +890,54 @@ var global_1 = {
827
890
  * @param {boolean} errorIsQuit 找不到配置文件是否退出
828
891
  * @returns
829
892
  */
893
+
894
+
830
895
  const getModulesByMergeDepModules = (tmsConfig, modules, errorIsQuit = false) => {
831
896
  const allModules = new Map();
897
+
832
898
  function dfs(tmsConfig, modules) {
833
899
  modules.forEach(moduleItem => {
834
900
  if (!moduleItem.path) {
835
901
  throw new Error(`${moduleItem.moduleName}模块没有找到path字段,请检查tms.config.js的modules.all>module>path路径`);
836
902
  }
903
+
837
904
  const moduleConfigPath = resolve(moduleItem.path, MODULE_CONFIG_FILENAME);
905
+
838
906
  if (!fs.existsSync(moduleConfigPath)) {
839
907
  if (!allModules.has(moduleItem.moduleName)) {
840
908
  allModules.set(moduleItem.moduleName, moduleItem);
841
909
  }
910
+
842
911
  if (errorIsQuit) {
843
912
  throw new Error(`${moduleItem.moduleName}模块的配置文件module.config.json在${moduleItem.path}目录下没有找到 ${moduleConfigPath}`);
844
913
  }
914
+
845
915
  return;
846
916
  }
917
+
847
918
  const [moduleConfig = {}] = getModulesConfig([moduleItem], tmsConfig);
919
+
848
920
  if (!allModules.has(moduleItem.moduleName)) {
849
921
  allModules.set(moduleItem.moduleName, checkModuleItem(tmsConfig, moduleItem, moduleConfig));
850
922
  const dependenciesModules = getModulesByModuleNames(tmsConfig, moduleConfig === null || moduleConfig === void 0 ? void 0 : moduleConfig.dependencies);
923
+
851
924
  if (dependenciesModules.length) {
852
925
  dfs(tmsConfig, dependenciesModules);
853
926
  }
854
927
  }
855
928
  });
856
929
  }
930
+
857
931
  dfs(tmsConfig, modules);
858
932
  const modulesArr = [];
933
+
859
934
  for (const module of allModules.values()) {
860
935
  modulesArr.push(module);
861
936
  }
937
+
862
938
  return modulesArr;
863
939
  };
940
+
864
941
  module.exports = {
865
942
  readTmsConfig,
866
943
  readTmsPrivateCf,
@@ -872,10 +949,10 @@ var global_1 = {
872
949
  };
873
950
  })(tmsMpconfig);
874
951
 
875
- const fs$i = require$$0__default$1;
952
+ const fs$j = require$$0__default$1;
876
953
  const path$f = require$$1__default$1;
877
954
  const {
878
- info: info$i
955
+ info: info$j
879
956
  } = log$1;
880
957
  const {
881
958
  relativeCwdPath
@@ -885,70 +962,77 @@ const {
885
962
  * @param {string} dirname 目录名
886
963
  * @returns
887
964
  */
888
- const isDirEmpty = dirname => fs$i.promises.readdir(dirname).then(files => files.length === 0);
889
965
 
890
- // 判断是否是文件
966
+ const isDirEmpty = dirname => fs$j.promises.readdir(dirname).then(files => files.length === 0); // 判断是否是文件
967
+
968
+
891
969
  const isFile = pathName => {
892
970
  try {
893
- const stat = fs$i.lstatSync(pathName);
971
+ const stat = fs$j.lstatSync(pathName);
894
972
  return stat.isFile();
895
973
  } catch {
896
974
  return false;
897
975
  }
898
976
  };
899
-
900
977
  /**
901
978
  * 确保目录存在,不存在就创建一个
902
979
  * @param {*} dirname 目录名
903
980
  */
981
+
982
+
904
983
  const ensureDirExist$6 = dirname => {
905
- if (!fs$i.existsSync(dirname)) {
906
- fs$i.mkdirSync(dirname, {
984
+ if (!fs$j.existsSync(dirname)) {
985
+ fs$j.mkdirSync(dirname, {
907
986
  recursive: true
908
987
  });
909
988
  }
910
- };
989
+ }; // 复制文件
990
+
911
991
 
912
- // 复制文件
913
992
  const copyFile = function (src, dest) {
914
- if (fs$i.existsSync(dest)) {
915
- fs$i.unlinkSync(dest);
993
+ if (fs$j.existsSync(dest)) {
994
+ fs$j.unlinkSync(dest);
916
995
  }
996
+
917
997
  const dir = path$f.dirname(dest);
918
998
  ensureDirExist$6(dir);
919
- fs$i.copyFileSync(src, dest);
920
- };
999
+ fs$j.copyFileSync(src, dest);
1000
+ }; // 判断文件内容是否一致,不一致再进行拷贝
1001
+
921
1002
 
922
- // 判断文件内容是否一致,不一致再进行拷贝
923
1003
  function diffContentCopyFile(originFile, destFile) {
924
- if (fs$i.existsSync(destFile)) {
925
- const depDestContent = fs$i.readFileSync(destFile, 'utf8');
926
- const depOriginContent = fs$i.readFileSync(originFile, 'utf8');
1004
+ if (fs$j.existsSync(destFile)) {
1005
+ const depDestContent = fs$j.readFileSync(destFile, 'utf8');
1006
+ const depOriginContent = fs$j.readFileSync(originFile, 'utf8');
1007
+
927
1008
  if (depDestContent !== depOriginContent) {
928
- info$i(`拷贝${relativeCwdPath(originFile)}内容到${relativeCwdPath(destFile)}`);
1009
+ info$j(`拷贝${relativeCwdPath(originFile)}内容到${relativeCwdPath(destFile)}`);
929
1010
  copyFile(originFile, destFile);
930
1011
  }
931
1012
  } else {
932
- info$i(`拷贝${relativeCwdPath(originFile)}内容到${relativeCwdPath(destFile)}`);
1013
+ info$j(`拷贝${relativeCwdPath(originFile)}内容到${relativeCwdPath(destFile)}`);
933
1014
  copyFile(originFile, destFile);
934
1015
  }
935
- }
1016
+ } // 添加后缀
1017
+
936
1018
 
937
- // 添加后缀
938
1019
  function ext(filePath, extensions) {
939
1020
  let newFilePath = filePath;
940
- let extPath = '';
941
- // try catch需要包裹:用来处理'./lib/timer'没有后缀的情况
1021
+ let extPath = ''; // try catch需要包裹:用来处理'./lib/timer'没有后缀的情况
1022
+
942
1023
  try {
943
- const stat = fs$i.lstatSync(newFilePath);
1024
+ const stat = fs$j.lstatSync(newFilePath);
1025
+
944
1026
  if (stat.isDirectory()) {
945
1027
  extPath = newFilePath[newFilePath.length - 1] === '/' ? 'index' : '/index';
946
1028
  newFilePath += extPath;
947
1029
  }
948
1030
  } catch (e) {}
1031
+
949
1032
  for (const ext of extensions) {
950
1033
  const file = newFilePath.endsWith(ext) ? newFilePath : newFilePath + ext;
951
- if (fs$i.existsSync(file)) {
1034
+
1035
+ if (fs$j.existsSync(file)) {
952
1036
  return {
953
1037
  ext,
954
1038
  extPath: extPath + ext,
@@ -956,31 +1040,38 @@ function ext(filePath, extensions) {
956
1040
  };
957
1041
  }
958
1042
  }
1043
+
959
1044
  return {
960
1045
  ext: '',
961
1046
  extPath,
962
1047
  file: filePath
963
1048
  };
964
- }
1049
+ } // 判断文件是否在某个目录
1050
+
965
1051
 
966
- // 判断文件是否在某个目录
967
1052
  const fileInDir = (dir, file) => {
968
- if (!fs$i.existsSync(dir) || !fs$i.existsSync(file)) {
1053
+ if (!fs$j.existsSync(dir) || !fs$j.existsSync(file)) {
969
1054
  return false;
970
1055
  }
1056
+
971
1057
  const relativePath = path$f.relative(dir, file);
1058
+
972
1059
  if (relativePath.startsWith('..')) {
973
1060
  return false;
974
1061
  }
1062
+
975
1063
  return true;
976
1064
  };
1065
+
977
1066
  function findAllFilesOfDir(dir) {
978
1067
  const list = [];
1068
+
979
1069
  function listFile(dir) {
980
- const arr = fs$i.readdirSync(dir);
1070
+ const arr = fs$j.readdirSync(dir);
981
1071
  arr.forEach(item => {
982
1072
  const fullPath = path$f.join(dir, item);
983
- const stats = fs$i.statSync(fullPath);
1073
+ const stats = fs$j.statSync(fullPath);
1074
+
984
1075
  if (stats.isDirectory()) {
985
1076
  listFile(fullPath);
986
1077
  } else {
@@ -989,9 +1080,11 @@ function findAllFilesOfDir(dir) {
989
1080
  });
990
1081
  return list;
991
1082
  }
1083
+
992
1084
  listFile(dir);
993
1085
  return list;
994
1086
  }
1087
+
995
1088
  var io$3 = {
996
1089
  isDirEmpty,
997
1090
  copyFile,
@@ -1005,24 +1098,28 @@ var io$3 = {
1005
1098
 
1006
1099
  const async = require$$0__default$4;
1007
1100
  const ejs = require$$1__default$4;
1101
+
1008
1102
  const render$1 = (files, metalsmith, next) => {
1009
1103
  const keys = Object.keys(files);
1010
1104
  const metadata = metalsmith.metadata();
1105
+
1011
1106
  const run = (file, next) => {
1012
1107
  const str = files[file].contents.toString();
1013
- const newStr = ejs.render(str, metadata);
1014
- // eslint-disable-next-line
1108
+ const newStr = ejs.render(str, metadata); // eslint-disable-next-line
1109
+
1015
1110
  files[file].contents = Buffer.from(newStr);
1016
1111
  next();
1017
1112
  };
1113
+
1018
1114
  async.each(keys, run, next);
1019
1115
  };
1116
+
1020
1117
  var render_1 = render$1;
1021
1118
 
1022
- const fs$h = require$$0__default$1;
1119
+ const fs$i = require$$0__default$1;
1023
1120
  const inquirer$1 = require$$1__default$5;
1024
1121
  const {
1025
- resolve: resolve$j
1122
+ resolve: resolve$k
1026
1123
  } = widgets;
1027
1124
  const {
1028
1125
  TEMPLATE_TKIT_DIR: TEMPLATE_TKIT_DIR$1
@@ -1032,13 +1129,17 @@ const {
1032
1129
  * @param {string} dir questions.json所在的目录
1033
1130
  * @returns {Array} inquirer 问题数组
1034
1131
  */
1132
+
1035
1133
  const parseTemplateQuestions = dir => {
1036
1134
  let prompts = [];
1037
- if (!fs$h.existsSync(`${dir}/questions.json`)) {
1135
+
1136
+ if (!fs$i.existsSync(`${dir}/questions.json`)) {
1038
1137
  return prompts;
1039
1138
  }
1139
+
1040
1140
  try {
1041
- const json = JSON.parse(fs$h.readFileSync(`${dir}/questions.json`));
1141
+ const json = JSON.parse(fs$i.readFileSync(`${dir}/questions.json`));
1142
+
1042
1143
  if (Array.isArray(json) && json.length > 0) {
1043
1144
  json.forEach((item, index) => {
1044
1145
  if (!isQuestionType(item)) {
@@ -1048,42 +1149,50 @@ const parseTemplateQuestions = dir => {
1048
1149
  } else {
1049
1150
  throw new Error('问题文件只能是数组');
1050
1151
  }
1152
+
1051
1153
  prompts = json;
1052
1154
  } catch (err) {
1053
1155
  throw new Error(`模板异常,${err.message}`);
1054
1156
  }
1157
+
1055
1158
  return prompts;
1056
1159
  };
1160
+
1057
1161
  const isQuestionType = result => {
1058
1162
  if (!('message' in result)) {
1059
1163
  return false;
1060
1164
  }
1165
+
1061
1166
  if (!('name' in result)) {
1062
1167
  return false;
1063
1168
  }
1169
+
1064
1170
  return true;
1065
1171
  };
1172
+
1066
1173
  const ask$1 = templateDir => (files, metalsmith, next) => {
1067
- const prompts = parseTemplateQuestions(resolve$j(templateDir, TEMPLATE_TKIT_DIR$1));
1174
+ const prompts = parseTemplateQuestions(resolve$k(templateDir, TEMPLATE_TKIT_DIR$1));
1068
1175
  const metadata = metalsmith.metadata();
1069
1176
  const filteredPrompts = prompts.filter(prompt => {
1070
1177
  if (metadata[prompt.name] && `${metadata[prompt.name]}`.trim() !== '') {
1071
1178
  return false;
1072
1179
  }
1180
+
1073
1181
  return true;
1074
1182
  });
1075
1183
  inquirer$1.prompt(filteredPrompts).then(res => {
1076
1184
  for (const prompt of filteredPrompts) {
1077
1185
  metadata[prompt.name] = res[prompt.name];
1078
1186
  }
1187
+
1079
1188
  next();
1080
1189
  }).catch(err => {
1081
1190
  next(err);
1082
1191
  });
1083
1192
  };
1193
+
1084
1194
  var ask_1 = ask$1;
1085
1195
 
1086
- // 在metal smith遍历时需要忽略的文件,这些文件会引起metalsmith的parse error
1087
1196
  const FILES_TO_IGNORE$1 = ['node_modules'];
1088
1197
  var ignoreFiles = FILES_TO_IGNORE$1;
1089
1198
 
@@ -1091,6 +1200,7 @@ const Metalsmith = require$$0__default$5;
1091
1200
  const render = render_1;
1092
1201
  const ask = ask_1;
1093
1202
  const FILES_TO_IGNORE = ignoreFiles;
1203
+
1094
1204
  const generator$1 = (buildDir, distDir, preMetadata = {}) => new Promise((resolve, reject) => {
1095
1205
  Metalsmith(buildDir).metadata(preMetadata).ignore(FILES_TO_IGNORE).clean(false).use(ask(buildDir)).source('./').destination(distDir).use(render).build(err => {
1096
1206
  if (err) {
@@ -1100,6 +1210,7 @@ const generator$1 = (buildDir, distDir, preMetadata = {}) => new Promise((resolv
1100
1210
  }
1101
1211
  });
1102
1212
  });
1213
+
1103
1214
  var generator_1 = generator$1;
1104
1215
 
1105
1216
  const request$1 = require$$0__default$6;
@@ -1107,6 +1218,7 @@ const {
1107
1218
  getGitUser: getGitUser$1
1108
1219
  } = widgets;
1109
1220
  const apiUrl = 'https://tim.map.qq.com/basic/tmskit/upload';
1221
+
1110
1222
  const report$b = (name, attrs = {}) => {
1111
1223
  try {
1112
1224
  const param = [];
@@ -1114,25 +1226,27 @@ const report$b = (name, attrs = {}) => {
1114
1226
  param[28] = 'tmskit';
1115
1227
  param[29] = getGitUser$1();
1116
1228
  param[30] = JSON.stringify(attrs);
1229
+
1117
1230
  for (let i = 0; i < 40; i++) {
1118
1231
  if (!param[i]) param[i] = null;
1119
1232
  }
1233
+
1120
1234
  ;
1121
1235
  request$1.post({
1122
1236
  url: apiUrl,
1123
1237
  json: {
1124
1238
  param
1125
1239
  }
1126
- }, () => {});
1127
- // (error, response, body) => {
1240
+ }, () => {}); // (error, response, body) => {
1128
1241
  // console.log('body:', body);
1129
1242
  // }
1130
1243
  } catch (e) {}
1131
1244
  };
1245
+
1132
1246
  var report_1 = report$b;
1133
1247
 
1134
1248
  const path$e = require$$1__default$1;
1135
- const fs$g = require$$0__default$1;
1249
+ const fs$h = require$$0__default$1;
1136
1250
  const shelljs$6 = require$$0__default$2;
1137
1251
  const inquirer = require$$1__default$5;
1138
1252
  const {
@@ -1143,27 +1257,27 @@ const {
1143
1257
  CREATE_TEMPLATE_QUESTION
1144
1258
  } = constant;
1145
1259
  const {
1146
- resolve: resolve$i
1260
+ resolve: resolve$j
1147
1261
  } = widgets;
1148
1262
  const io$2 = io$3;
1149
1263
  const {
1150
1264
  fail: fail$9,
1151
1265
  succeed: succeed$1,
1152
- info: info$h
1266
+ info: info$i
1153
1267
  } = log$1;
1154
1268
  const generator = generator_1;
1155
1269
  const request = require$$0__default$6;
1156
1270
  const unzip = require$$10__default;
1157
1271
  const report$a = report_1;
1158
-
1159
1272
  /**
1160
1273
  * 如果该目录下面存在文件,换个名字
1161
1274
  * @param { string } targetDir 当前文件夹
1162
1275
  * @returns { undefined }
1163
1276
  */
1277
+
1164
1278
  async function createProjectDir(targetDir) {
1165
1279
  // 如果目录非空或者已经存在,提示用户,做选择
1166
- if (fs$g.existsSync(targetDir)) {
1280
+ if (fs$h.existsSync(targetDir)) {
1167
1281
  if (!(await io$2.isDirEmpty(targetDir))) {
1168
1282
  fail$9('该目录名已经存在,换个项目名字吧~');
1169
1283
  process.exit(1);
@@ -1172,7 +1286,6 @@ async function createProjectDir(targetDir) {
1172
1286
  shelljs$6.mkdir('-p', targetDir);
1173
1287
  }
1174
1288
  }
1175
-
1176
1289
  /**
1177
1290
  * 下载和解压远程的小程序模板
1178
1291
  * @param {string} templateDir
@@ -1180,33 +1293,38 @@ async function createProjectDir(targetDir) {
1180
1293
  * @param {string} templateName
1181
1294
  * @returns
1182
1295
  */
1296
+
1297
+
1183
1298
  function downloadAndUnZipTemplate(templateDir, templateUrl, templateName) {
1184
1299
  return new Promise((resolve, reject) => {
1185
1300
  const localZipPath = `${templateDir}/${templateName}.zip`;
1186
- const stream = fs$g.createWriteStream(localZipPath);
1301
+ const stream = fs$h.createWriteStream(localZipPath);
1187
1302
  request(`${templateUrl}?v=${new Date().getTime()}`).pipe(stream).on('close', err => {
1188
1303
  if (err) {
1189
1304
  reject(err);
1190
1305
  return;
1191
1306
  }
1192
- fs$g.createReadStream(localZipPath).pipe(unzip.Extract({
1307
+
1308
+ fs$h.createReadStream(localZipPath).pipe(unzip.Extract({
1193
1309
  path: templateDir
1194
1310
  })).on('close', err => {
1195
1311
  if (err) {
1196
1312
  reject(err);
1197
1313
  return;
1198
1314
  }
1315
+
1199
1316
  resolve();
1200
1317
  });
1201
1318
  });
1202
1319
  });
1203
1320
  }
1204
-
1205
1321
  /**
1206
1322
  * 创建本地小程序运行环境
1207
1323
  * @param { string } projectType 项目类型
1208
1324
  * @param { string } projectName 项目名称
1209
1325
  */
1326
+
1327
+
1210
1328
  async function create(projectName) {
1211
1329
  const cwd = process.cwd();
1212
1330
  const targetDir = path$e.resolve(cwd, projectName);
@@ -1215,28 +1333,27 @@ async function create(projectName) {
1215
1333
  } = await inquirer.prompt(CREATE_TEMPLATE_QUESTION);
1216
1334
  report$a('create-start', {
1217
1335
  projectType
1218
- });
1336
+ }); // 创建项目目录
1219
1337
 
1220
- // 创建项目目录
1221
- await createProjectDir(targetDir);
1338
+ await createProjectDir(targetDir); // 新创建缓存目录
1222
1339
 
1223
- // 新创建缓存目录
1224
- if (fs$g.existsSync(TEMPLATE_DIR)) {
1340
+ if (fs$h.existsSync(TEMPLATE_DIR)) {
1225
1341
  shelljs$6.rm('-rf', TEMPLATE_DIR);
1226
1342
  }
1227
- fs$g.mkdirSync(TEMPLATE_DIR, {
1343
+
1344
+ fs$h.mkdirSync(TEMPLATE_DIR, {
1228
1345
  recursive: true
1229
- });
1346
+ }); // 下载和解压模板
1230
1347
 
1231
- // 下载和解压模板
1232
- await downloadAndUnZipTemplate(TEMPLATE_DIR, TEMPLATE_URL, TEMPLATE_NAME);
1348
+ await downloadAndUnZipTemplate(TEMPLATE_DIR, TEMPLATE_URL, TEMPLATE_NAME); // 生成模板(1. 询问问题, 2. ejs生成模板 3.生成到目标目录)
1233
1349
 
1234
- // 生成模板(1. 询问问题, 2. ejs生成模板 3.生成到目标目录)
1235
1350
  generator(path$e.join(TEMPLATE_DIR, TEMPLATE_NAME, projectType), targetDir).then(() => {
1236
1351
  shelljs$6.cd(projectName);
1237
- const hookFilePath = resolve$i(projectName, TEMPLATE_TKIT_DIR, 'hooks.js');
1238
- if (fs$g.existsSync(hookFilePath)) {
1352
+ const hookFilePath = resolve$j(projectName, TEMPLATE_TKIT_DIR, 'hooks.js');
1353
+
1354
+ if (fs$h.existsSync(hookFilePath)) {
1239
1355
  const hooks = require(hookFilePath);
1356
+
1240
1357
  if (hooks.afterCreate) {
1241
1358
  hooks.afterCreate.forEach(item => {
1242
1359
  if (typeof item === 'function') {
@@ -1248,20 +1365,23 @@ async function create(projectName) {
1248
1365
  }
1249
1366
  });
1250
1367
  }
1251
- shelljs$6.rm('-rf', resolve$i(projectName, TEMPLATE_TKIT_DIR));
1368
+
1369
+ shelljs$6.rm('-rf', resolve$j(projectName, TEMPLATE_TKIT_DIR));
1252
1370
  }
1371
+
1253
1372
  report$a('create-success', {
1254
1373
  projectType
1255
1374
  });
1256
1375
  succeed$1('项目创建完成.');
1257
1376
  }).catch(err => {
1258
1377
  fail$9(err.message);
1259
- info$h('详细的错误信息:', err);
1378
+ info$i('详细的错误信息:', err);
1260
1379
  });
1261
1380
  }
1381
+
1262
1382
  var create_1 = create;
1263
1383
 
1264
- const fs$f = require$$0__default$1;
1384
+ const fs$g = require$$0__default$1;
1265
1385
  const path$d = require$$1__default$1;
1266
1386
  const shellJs$3 = require$$0__default$2;
1267
1387
  const {
@@ -1274,24 +1394,26 @@ const {
1274
1394
  createTask: createTask$6
1275
1395
  } = widgets;
1276
1396
  const {
1277
- info: info$g,
1397
+ info: info$h,
1278
1398
  fail: fail$8
1279
1399
  } = log$1;
1280
-
1281
1400
  /**
1282
1401
  * 下载扩展命令的npm包
1283
1402
  * @param {string} npmName npm包名
1284
1403
  * @param {object} cmd {registry: 'http://mirrors.tencent.com/npm/'} 用户输入执行install-cmd的参数
1285
1404
  */
1405
+
1286
1406
  async function installCmd(npmName, cmd) {
1287
1407
  try {
1288
1408
  const cmdPackageJson = `${EXTEND_CMD}/package.json`;
1289
- if (!fs$f.existsSync(cmdPackageJson)) {
1409
+
1410
+ if (!fs$g.existsSync(cmdPackageJson)) {
1290
1411
  ensureDirExist$5(EXTEND_CMD);
1291
- fs$f.writeFileSync(cmdPackageJson, JSON.stringify({
1412
+ fs$g.writeFileSync(cmdPackageJson, JSON.stringify({
1292
1413
  dependencies: {}
1293
1414
  }, null, 2));
1294
1415
  }
1416
+
1295
1417
  shellJs$3.cd(EXTEND_CMD);
1296
1418
  await createTask$6(npmName => new Promise((resolve, reject) => {
1297
1419
  const registry = cmd.registry ? `--registry=${cmd.registry}` : '';
@@ -1302,25 +1424,28 @@ async function installCmd(npmName, cmd) {
1302
1424
  if (code !== 0) {
1303
1425
  reject(stderr);
1304
1426
  }
1427
+
1305
1428
  resolve();
1306
1429
  });
1307
1430
  }), `开始下载${npmName}`, `下载${npmName}完成`)(npmName);
1308
1431
  } catch (e) {
1309
1432
  fail$8('构建出现错误:');
1310
- info$g(e);
1433
+ info$h(e);
1311
1434
  process.exit(1);
1312
1435
  }
1313
1436
  }
1314
-
1315
1437
  /**
1316
1438
  * 加载扩展命令的npm包
1317
1439
  * @returns
1318
1440
  */
1441
+
1442
+
1319
1443
  function loadExtendCmd$1() {
1320
1444
  const cmdPackageJson = `${EXTEND_CMD}/package.json`;
1321
1445
  const cmdNpmDir = `${EXTEND_CMD}/node_modules`;
1322
- if (fs$f.existsSync(cmdPackageJson)) {
1323
- const content = fs$f.readFileSync(cmdPackageJson, 'utf8');
1446
+
1447
+ if (fs$g.existsSync(cmdPackageJson)) {
1448
+ const content = fs$g.readFileSync(cmdPackageJson, 'utf8');
1324
1449
  const json = JSON.parse(content);
1325
1450
  const deps = json.dependencies || {};
1326
1451
  const cmdConfigs = [];
@@ -1328,14 +1453,17 @@ function loadExtendCmd$1() {
1328
1453
  // 检索cmd的npm包
1329
1454
  if (!/^tmskit-cmd-|^@[^/]+\/tmskit-cmd-/.test(name)) return false;
1330
1455
  const cmdConfig = path$d.join(cmdNpmDir, name, 'tms.config.js');
1331
- if (fs$f.existsSync(cmdConfig)) {
1456
+
1457
+ if (fs$g.existsSync(cmdConfig)) {
1332
1458
  cmdConfigs.push(cmdConfig);
1333
1459
  }
1334
1460
  });
1335
1461
  return cmdConfigs;
1336
1462
  }
1463
+
1337
1464
  return [];
1338
1465
  }
1466
+
1339
1467
  var extendCmd = {
1340
1468
  installCmd,
1341
1469
  loadExtendCmd: loadExtendCmd$1
@@ -1347,29 +1475,119 @@ const {
1347
1475
  const {
1348
1476
  global: global$b
1349
1477
  } = global_1;
1478
+
1350
1479
  function handleError$9(error, isQuit = false) {
1351
1480
  const errMsg = typeof error === 'object' ? error.message : error;
1481
+
1352
1482
  if (isQuit) {
1353
1483
  fail$7(errMsg);
1354
1484
  process.exit(1);
1355
1485
  }
1356
- const isDev = global$b.getData('isDev');
1357
- if (isDev) {
1358
- fail$7(errMsg);
1359
- } else {
1360
- fail$7(errMsg);
1361
- process.exit(1);
1486
+
1487
+ const isDev = global$b.getData('isDev');
1488
+
1489
+ if (isDev) {
1490
+ fail$7(errMsg);
1491
+ } else {
1492
+ fail$7(errMsg);
1493
+ process.exit(1);
1494
+ }
1495
+ }
1496
+
1497
+ var handleError_1 = {
1498
+ handleError: handleError$9
1499
+ };
1500
+
1501
+ const {
1502
+ resolve: resolve$i
1503
+ } = require('../utils/widgets');
1504
+
1505
+ const {
1506
+ info: info$g
1507
+ } = require('../utils/log');
1508
+
1509
+ const fs$f = require('fs');
1510
+ /* eslint-disable no-param-reassign */
1511
+
1512
+ /**
1513
+ * 检查是否包含 meta-services 分包
1514
+ * @param {Object} appJson app.json配置对象
1515
+ * @returns {boolean}
1516
+ */
1517
+
1518
+
1519
+ function hasMetaServicesSubpackage(appJson) {
1520
+ return appJson.subpackages.some(s => s.root === 'modules/meta-services' || s.name === 'meta-services');
1521
+ }
1522
+ /**
1523
+ * 处理 agent 配置:根据是否包含 meta-services 分包来添加或删除 agent 配置
1524
+ * @param {Object} appJson app.json配置对象
1525
+ */
1526
+
1527
+
1528
+ function handleAgentConfig$1(appJson) {
1529
+ const hasMetaServices = hasMetaServicesSubpackage(appJson);
1530
+ console.log('🔍', hasMetaServices ? '包含' : '不包含', 'meta-services 分包');
1531
+
1532
+ if (hasMetaServices) {
1533
+ if (!appJson.agent) {
1534
+ try {
1535
+ appJson.agent = require(resolve$i('./agentConfig.json'));
1536
+ info$g('已从 agentConfig.json 加载 agent 配置');
1537
+ } catch (error) {
1538
+ info$g('未找到 agentConfig.json,删除 agent 配置');
1539
+ delete appJson.agent;
1540
+ }
1541
+ }
1542
+ } else if (appJson.agent) {
1543
+ delete appJson.agent;
1544
+ info$g('已移除 agent 配置');
1545
+ }
1546
+ }
1547
+ /**
1548
+ * 处理 project.config.json 中的 packOptions.include 配置
1549
+ * @param {Object} appJson app.json配置对象
1550
+ * @param {string} outputDir 输出目录
1551
+ */
1552
+
1553
+ function handleProjectConfigInclude$1(appJson, outputDir) {
1554
+ const projectConfigPath = resolve$i(outputDir, 'project.config.json');
1555
+ if (!fs$f.existsSync(projectConfigPath)) return;
1556
+
1557
+ const projectConfig = require(projectConfigPath);
1558
+
1559
+ const hasMetaServices = hasMetaServicesSubpackage(appJson);
1560
+ if (!projectConfig.packOptions) projectConfig.packOptions = {};
1561
+ if (!projectConfig.packOptions.include) projectConfig.packOptions.include = [];
1562
+ const existingIndex = projectConfig.packOptions.include.findIndex(item => item.type === 'folder' && item.value === 'modules/meta-services');
1563
+
1564
+ if (hasMetaServices && existingIndex === -1) {
1565
+ projectConfig.packOptions.include.push({
1566
+ type: 'folder',
1567
+ value: 'modules/meta-services'
1568
+ });
1569
+ info$g('已添加 meta-services 到 project.config.json');
1570
+ } else if (!hasMetaServices && existingIndex !== -1) {
1571
+ projectConfig.packOptions.include.splice(existingIndex, 1);
1572
+ info$g('已从 project.config.json 移除 meta-services');
1362
1573
  }
1574
+
1575
+ fs$f.writeFileSync(projectConfigPath, JSON.stringify(projectConfig, null, 2));
1363
1576
  }
1364
- var handleError_1 = {
1365
- handleError: handleError$9
1366
- };
1577
+
1578
+ var handleAgentConfig$2 = /*#__PURE__*/Object.freeze({
1579
+ __proto__: null,
1580
+ handleAgentConfig: handleAgentConfig$1,
1581
+ handleProjectConfigInclude: handleProjectConfigInclude$1
1582
+ });
1583
+
1584
+ var require$$8 = /*@__PURE__*/getAugmentedNamespace(handleAgentConfig$2);
1367
1585
 
1368
1586
  /**
1369
1587
  * 生成编译后的app.json
1370
1588
  */
1371
-
1372
1589
  /* eslint-disable no-param-reassign */
1590
+
1373
1591
  const fs$e = require$$0__default$1;
1374
1592
  const pp$1 = require$$1__default$3;
1375
1593
  const {
@@ -1391,37 +1609,45 @@ const {
1391
1609
  global: global$a
1392
1610
  } = global_1;
1393
1611
  const report$9 = report_1;
1394
-
1612
+ const {
1613
+ handleAgentConfig,
1614
+ handleProjectConfigInclude
1615
+ } = require$$8;
1395
1616
  /**
1396
1617
  * 更新appJson里面的主包配置
1397
1618
  * @param { object } appJson appJson信息
1398
1619
  * @param { array } mainPackages 小程序主包信息
1399
1620
  * @returns { object } appJson小程序主页配置信息
1400
1621
  */
1622
+
1401
1623
  function updateMainPackages(appJson, mainPackages = []) {
1402
1624
  let foundMainPackages = appJson.subpackages.filter(subpackage => mainPackages.includes(subpackage.name));
1625
+
1403
1626
  if (foundMainPackages.length === 0 && appJson.pages.length === 0) {
1404
1627
  // 没找到主包
1405
1628
  foundMainPackages = [appJson.subpackages[0]];
1406
- }
1407
- // 拼装 app.pages
1629
+ } // 拼装 app.pages
1630
+
1631
+
1408
1632
  foundMainPackages.forEach(subpackage => {
1409
1633
  if (!subpackage.allowNoPages && (!subpackage.pages || !subpackage.pages.length)) {
1410
1634
  fail$6(`主包 ${subpackage} 不能没有 pages`, foundMainPackages, subpackage);
1411
1635
  process.exit(-1);
1412
1636
  }
1637
+
1413
1638
  subpackage.pages.forEach(page => {
1414
1639
  const pagePath = `${subpackage.root}/${page}`;
1640
+
1415
1641
  if (!appJson.pages.includes(pagePath)) {
1416
1642
  appJson.pages.push(pagePath);
1417
1643
  }
1418
1644
  });
1645
+
1419
1646
  if (subpackage.plugins) {
1420
1647
  Object.assign(appJson.plugins, subpackage.plugins);
1421
1648
  }
1422
- });
1649
+ }); // 去掉 subpackages 中的主包配置
1423
1650
 
1424
- // 去掉 subpackages 中的主包配置
1425
1651
  const foundMainPackageNames = foundMainPackages.map(item => item.name);
1426
1652
  appJson.subpackages = appJson.subpackages.filter(subpackage => !foundMainPackageNames.includes(subpackage.name));
1427
1653
  return appJson;
@@ -1431,39 +1657,41 @@ function updateMainPackages(appJson, mainPackages = []) {
1431
1657
  * @param {string} sourceAppJsonPath app.json存在的源码路径
1432
1658
  * @returns
1433
1659
  */
1660
+
1661
+
1434
1662
  const getAppJsonContent = sourceAppJsonPath => {
1435
1663
  if (!fs$e.existsSync(sourceAppJsonPath)) {
1436
1664
  fail$6(`当前路径 ${sourceAppJsonPath} 没找到app.json`);
1437
1665
  process.exit(1);
1438
1666
  }
1439
- const appJson = JSON.parse(fs$e.readFileSync(sourceAppJsonPath), 'utf-8');
1440
- // 加入默认值
1667
+
1668
+ const appJson = JSON.parse(fs$e.readFileSync(sourceAppJsonPath), 'utf-8'); // 加入默认值
1669
+
1441
1670
  appJson.subpackages = appJson.subpackages || [];
1442
1671
  appJson.pages = appJson.pages || [];
1443
1672
  return appJson;
1444
1673
  };
1445
-
1446
1674
  /**
1447
1675
  * 处理合并subpackages后的appjson, 整理重复不合法的地方
1448
1676
  * @param {Object} appJson appjson
1449
1677
  */
1678
+
1679
+
1450
1680
  const fixAppJson = appJson => {
1451
1681
  const {
1452
1682
  subpackages
1453
- } = appJson;
1454
- // 创建插件映射,用于检测插件配置冲突
1455
- const pluginsMap = {};
1456
- // 记录app.json顶层的插件配置
1457
- Object.keys(appJson.plugins || {}).forEach(key => pluginsMap[key] = ['app.json']);
1683
+ } = appJson; // 创建插件映射,用于检测插件配置冲突
1684
+
1685
+ const pluginsMap = {}; // 记录app.json顶层的插件配置
1686
+
1687
+ Object.keys(appJson.plugins || {}).forEach(key => pluginsMap[key] = ['app.json']); // 处理每个分包的配置
1458
1688
 
1459
- // 处理每个分包的配置
1460
1689
  const subps = subpackages.map(subp => {
1461
1690
  // 需要从分包提取到app.json顶层的数组类型字段
1462
- const arrOfFileType = ['requiredBackgroundModes', 'embeddedAppIdList'];
1463
- // 需要从分包提取到app.json顶层的对象类型字段
1464
- const objOfFileType = ['preloadRule'];
1691
+ const arrOfFileType = ['requiredBackgroundModes', 'embeddedAppIdList']; // 需要从分包提取到app.json顶层的对象类型字段
1692
+
1693
+ const objOfFileType = ['preloadRule']; // 遍历分包中的每个配置项
1465
1694
 
1466
- // 遍历分包中的每个配置项
1467
1695
  Object.keys(subp).forEach(key => {
1468
1696
  // 处理插件配置,检查是否有重复配置的插件
1469
1697
  if (key === 'plugins') {
@@ -1471,15 +1699,15 @@ const fixAppJson = appJson => {
1471
1699
  // 记录每个插件被哪些地方配置
1472
1700
  pluginsMap[pk] ? pluginsMap[pk].push(`分包${subp.name}`) : pluginsMap[pk] = [`分包${subp.name}`];
1473
1701
  });
1474
- }
1702
+ } // 处理数组类型字段(如requiredBackgroundModes),合并到app.json顶层并去重
1703
+
1475
1704
 
1476
- // 处理数组类型字段(如requiredBackgroundModes),合并到app.json顶层并去重
1477
1705
  if (arrOfFileType.indexOf(key) > -1) {
1478
1706
  const preVal = appJson[key];
1479
1707
  preVal ? appJson[key] = Array.from(new Set(preVal.slice(0).concat(subp[key]))) : appJson[key] = subp[key].slice(0);
1480
- }
1708
+ } // 处理对象类型字段(如preloadRule),合并到app.json顶层,已存在的键值不覆盖
1709
+
1481
1710
 
1482
- // 处理对象类型字段(如preloadRule),合并到app.json顶层,已存在的键值不覆盖
1483
1711
  if (objOfFileType.indexOf(key) > -1) {
1484
1712
  const preloadRuleMap = appJson[key] || {};
1485
1713
  subp[key] && Object.keys(subp[key]).forEach(page => {
@@ -1489,46 +1717,45 @@ const fixAppJson = appJson => {
1489
1717
  });
1490
1718
  appJson[key] = preloadRuleMap;
1491
1719
  }
1492
- });
1720
+ }); // 从分包配置中移除已提取到顶层的字段以及一些构建相关的内部字段
1493
1721
 
1494
- // 从分包配置中移除已提取到顶层的字段以及一些构建相关的内部字段
1495
1722
  return filterField$7(subp, [...arrOfFileType, ...objOfFileType, 'dependencies', 'path']);
1496
- });
1723
+ }); // 检查插件配置冲突,如果同一个插件在多处配置则报错
1497
1724
 
1498
- // 检查插件配置冲突,如果同一个插件在多处配置则报错
1499
1725
  const pluginsErrMsg = Object.keys(pluginsMap).map(pk => {
1500
1726
  if (pluginsMap[pk].length > 1) {
1501
1727
  return `${pluginsMap[pk].join(',')}重复配置plugin(${pk});`;
1502
1728
  }
1729
+
1503
1730
  return '';
1504
1731
  }).reduce((pre, cur) => pre + cur, '');
1732
+
1505
1733
  if (pluginsErrMsg) {
1506
1734
  throw new Error(`plugins配置出现错误:${pluginsErrMsg}`);
1507
- }
1735
+ } // 用处理后的分包配置更新app.json的subpackages字段
1736
+
1508
1737
 
1509
- // 用处理后的分包配置更新app.json的subpackages字段
1510
1738
  appJson.subpackages = subps;
1511
1739
  };
1512
-
1513
1740
  /**
1514
1741
  * 合并分包配置,保留已有分包,添加新分包
1515
1742
  * @param {Array} existingPackages 现有的分包配置
1516
1743
  * @param {Array} newPackages 新的分包配置
1517
1744
  * @returns {Array} 合并后的分包配置
1518
1745
  */
1746
+
1747
+
1519
1748
  function mergeSubPackages(existingPackages, newPackages) {
1520
1749
  // 创建结果数组和root到索引的映射
1521
1750
  const resultPackages = [...existingPackages];
1522
- const rootMap = {};
1751
+ const rootMap = {}; // 建立现有分包的root映射
1523
1752
 
1524
- // 建立现有分包的root映射
1525
1753
  existingPackages.forEach((pkg, index) => {
1526
1754
  if (pkg.root) {
1527
1755
  rootMap[pkg.root] = index;
1528
1756
  }
1529
- });
1757
+ }); // 合并新分包
1530
1758
 
1531
- // 合并新分包
1532
1759
  newPackages.forEach(newPkg => {
1533
1760
  if (!newPkg.root) return; // 忽略没有root的分包
1534
1761
 
@@ -1542,40 +1769,45 @@ function mergeSubPackages(existingPackages, newPackages) {
1542
1769
  });
1543
1770
  return resultPackages;
1544
1771
  }
1545
-
1546
1772
  /**
1547
1773
  * 动态生成编译后的app.json
1548
1774
  * @param {object} tmsConfig
1549
1775
  * @param {array} modules 用户要编译的模块列表
1550
1776
  * @returns
1551
1777
  */
1778
+
1779
+
1552
1780
  async function buildOutputAppJson$3(tmsConfig, modules) {
1553
1781
  try {
1554
1782
  var _tmsConfig$hooks;
1783
+
1555
1784
  // 获取所有模块,合并模块依赖的模块
1556
- const modulesConfig = getModulesConfig(modules, tmsConfig, false);
1557
- // 获取所有的分包
1558
- const newSubPackages = getSubPackages$3(modulesConfig);
1559
- // 获取app.json的配置
1560
- let appJson = getAppJsonContent(resolve$h('./app.json'));
1785
+ const modulesConfig = getModulesConfig(modules, tmsConfig, false); // 获取所有的分包
1786
+
1787
+ const newSubPackages = getSubPackages$3(modulesConfig); // 获取app.json的配置
1788
+
1789
+ let appJson = getAppJsonContent(resolve$h('./app.json')); // 保留已有分包配置,合并新的分包配置
1561
1790
 
1562
- // 保留已有分包配置,合并新的分包配置
1563
1791
  const existingSubpackages = appJson.subpackages || [];
1564
1792
  appJson.subpackages = mergeSubPackages(existingSubpackages, newSubPackages);
1565
- appJson.subpackages.sort((item1, item2) => item1.root.localeCompare(item2.root));
1793
+ appJson.subpackages.sort((item1, item2) => item1.root.localeCompare(item2.root)); // 处理appJson中重复||冲突的地方
1566
1794
 
1567
- // 处理appJson中重复||冲突的地方
1568
- fixAppJson(appJson);
1569
- // 更新主包,需在subpackages处理完成后执行, pages/
1570
- updateMainPackages(appJson, tmsConfig.mainPackages);
1795
+ fixAppJson(appJson); // 处理 agent 配置:根据是否包含 meta-services 分包来添加或删除
1796
+
1797
+ handleAgentConfig(appJson); // 处理 project.config.json 中的 packOptions.include 配置
1798
+
1799
+ handleProjectConfigInclude(appJson, tmsConfig.outputDir); // 更新主包,需在subpackages处理完成后执行, pages/
1800
+
1801
+ updateMainPackages(appJson, tmsConfig.mainPackages); // 模板渲染:先将 app.json 转为字符串,然后通过 preprocess 渲染
1571
1802
 
1572
- // 模板渲染:先将 app.json 转为字符串,然后通过 preprocess 渲染
1573
1803
  const appJsonStr = JSON.stringify(appJson, null, 2);
1574
1804
  const preprocessedStr = pp$1.preprocess(appJsonStr, tmsConfig.templateVars || {}, 'json');
1575
1805
  fs$e.writeFileSync(resolve$h(`${tmsConfig.outputDir}/app.json`), preprocessedStr, 'utf8');
1576
1806
  appJson = JSON.parse(preprocessedStr);
1807
+
1577
1808
  if (typeof (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks = tmsConfig.hooks) === null || _tmsConfig$hooks === void 0 ? void 0 : _tmsConfig$hooks.updateAppJson) === 'function') {
1578
1809
  var _tmsConfig$hooks2;
1810
+
1579
1811
  await (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks2 = tmsConfig.hooks) === null || _tmsConfig$hooks2 === void 0 ? void 0 : _tmsConfig$hooks2.updateAppJson({
1580
1812
  tmsConfig: filterField$7(tmsConfig, ['gitAccount']),
1581
1813
  cmdOptions: global$a.getData('cmdOptions'),
@@ -1585,12 +1817,14 @@ async function buildOutputAppJson$3(tmsConfig, modules) {
1585
1817
  }));
1586
1818
  report$9('hooks:updateAppJson');
1587
1819
  }
1820
+
1588
1821
  return appJson;
1589
1822
  } catch (e) {
1590
1823
  handleError$8(`生成app.json出现错误: ${e}`);
1591
1824
  info$f(e);
1592
1825
  }
1593
1826
  }
1827
+
1594
1828
  var buildAppJson = {
1595
1829
  buildOutputAppJson: buildOutputAppJson$3
1596
1830
  };
@@ -1617,15 +1851,16 @@ const {
1617
1851
  const {
1618
1852
  global: global$9
1619
1853
  } = global_1;
1620
-
1621
1854
  /**
1622
1855
  * 处理用户没有clone git仓库权限问题,拼接tms.private.config.js的账号信息
1623
1856
  * @param {*} httpRepoUrl
1624
1857
  * @param {*} moduleName
1625
1858
  * @returns
1626
1859
  */
1860
+
1627
1861
  function replaceGitUrlAccount(httpRepoUrl, moduleName) {
1628
1862
  var _tmsConfig$gitAccount, _tmsConfig$gitAccount2, _tmsConfig$gitAccount3;
1863
+
1629
1864
  // 用户本地的私有项目配置(用来配置环境\模块信息\账号信息)
1630
1865
  const tmsConfig = global$9.getData('tmsConfig');
1631
1866
  let gitUrl = httpRepoUrl;
@@ -1636,12 +1871,13 @@ function replaceGitUrlAccount(httpRepoUrl, moduleName) {
1636
1871
  pass = ''
1637
1872
  } = (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$gitAccount = tmsConfig.gitAccount) === null || _tmsConfig$gitAccount === void 0 ? void 0 : _tmsConfig$gitAccount[moduleName]) || (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$gitAccount2 = tmsConfig.gitAccount) === null || _tmsConfig$gitAccount2 === void 0 ? void 0 : _tmsConfig$gitAccount2[httpRepoUrl]) || (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$gitAccount3 = tmsConfig.gitAccount) === null || _tmsConfig$gitAccount3 === void 0 ? void 0 : _tmsConfig$gitAccount3[group]) || {};
1638
1873
  const urlPrefixReg = /http(s)?:\/\//;
1874
+
1639
1875
  if (username && pass && urlPrefixReg.test(gitUrl)) {
1640
1876
  gitUrl = gitUrl.replace(urlPrefixReg, val => `${val}${encodeURIComponent(username)}:${encodeURIComponent(pass)}@`);
1641
1877
  }
1878
+
1642
1879
  return gitUrl;
1643
1880
  }
1644
-
1645
1881
  /**
1646
1882
  * 对克隆下来的模块进行相应的文件处理操作,比如收集处理模块信息,进行信息缓存等操作
1647
1883
  * @param { string } sourceDir 缓存文件夹
@@ -1649,28 +1885,33 @@ function replaceGitUrlAccount(httpRepoUrl, moduleName) {
1649
1885
  * @param { arrary } ignore
1650
1886
  * @returns { undefined } no return
1651
1887
  */
1888
+
1889
+
1652
1890
  function moveFile(sourceDir, targetDir, ignore = []) {
1653
1891
  if (fs$d.existsSync(targetDir)) {
1654
1892
  shelljs$5.rm('-rf', targetDir);
1655
- }
1656
- // 删除不是文件夹的文件
1893
+ } // 删除不是文件夹的文件
1894
+
1895
+
1657
1896
  return new Promise((resolve, reject) => {
1658
1897
  MetalSmith(__dirname).ignore(ignore).source(sourceDir).destination(targetDir).build(e => {
1659
1898
  if (e) {
1660
1899
  fail$5(`${sourceDir} moveFile ${targetDir}出现错误: ${e}`);
1661
1900
  reject(e);
1662
1901
  }
1902
+
1663
1903
  resolve();
1664
1904
  });
1665
1905
  });
1666
1906
  }
1667
-
1668
1907
  /**
1669
1908
  * 根据gitUrl 和 branch取md5值
1670
1909
  * @param {*} gitUrl
1671
1910
  * @param {*} branch
1672
1911
  * @returns
1673
1912
  */
1913
+
1914
+
1674
1915
  function md5ByGitUrlBranch(gitUrl, branch) {
1675
1916
  const newBranch = branch && typeof branch === 'string' ? branch : 'master';
1676
1917
  return crypto$2.createHash('md5').update(JSON.stringify({
@@ -1678,19 +1919,19 @@ function md5ByGitUrlBranch(gitUrl, branch) {
1678
1919
  branch: newBranch
1679
1920
  })).digest('hex');
1680
1921
  }
1681
-
1682
1922
  /**
1683
1923
  * 下载目标模块
1684
1924
  * @param { string } sourceDir 缓存文件夹
1685
1925
  * @param { string } targetDir 目标文件夹
1686
1926
  * @returns { array } modules 描述模块的列表
1687
1927
  */
1928
+
1929
+
1688
1930
  async function cloneModules$1(sourceDir, targetDir, modules) {
1689
- const cwd = process.cwd();
1690
- // 收集下载模块代码的任务
1691
- const downloadTasksMap = collectDownLoadTasksMap(sourceDir, targetDir, modules);
1931
+ const cwd = process.cwd(); // 收集下载模块代码的任务
1932
+
1933
+ const downloadTasksMap = collectDownLoadTasksMap(sourceDir, targetDir, modules); // 开始执行下载和移动代码的任务
1692
1934
 
1693
- // 开始执行下载和移动代码的任务
1694
1935
  const arrPromises = [];
1695
1936
  downloadTasksMap.forEach(({
1696
1937
  promiseTask,
@@ -1710,13 +1951,14 @@ async function cloneModules$1(sourceDir, targetDir, modules) {
1710
1951
  await Promise.all(arrPromises);
1711
1952
  shelljs$5.cd(cwd);
1712
1953
  }
1713
-
1714
1954
  /**
1715
1955
  * 收集下载模块代码的任务
1716
1956
  * @param { string } sourceDir 代码缓存文件夹
1717
1957
  * @param { string } targetDir 代码要放到的目标文件夹
1718
1958
  * @returns { array } modules 描述模块的列表
1719
1959
  */
1960
+
1961
+
1720
1962
  function collectDownLoadTasksMap(sourceDir, targetDir, modules) {
1721
1963
  // 下载代码任务 Map (key解释 缓存代码路径/md5(gitUrl,branch)
1722
1964
  // {
@@ -1731,6 +1973,7 @@ function collectDownLoadTasksMap(sourceDir, targetDir, modules) {
1731
1973
  // }
1732
1974
  // }
1733
1975
  const downloadTasksMap = new Map();
1976
+
1734
1977
  for (const moduleInfo of modules) {
1735
1978
  if (moduleInfo.repoInfo) {
1736
1979
  const {
@@ -1741,20 +1984,18 @@ function collectDownLoadTasksMap(sourceDir, targetDir, modules) {
1741
1984
  },
1742
1985
  path,
1743
1986
  moduleName
1744
- } = moduleInfo;
1745
-
1746
- // 处理仓库权限问题
1747
- const gitUrl = replaceGitUrlAccount(httpRepoUrl, moduleName);
1748
- // 根据gitUrlbranch计算md5
1749
- const md5Key = md5ByGitUrlBranch(gitUrl, branch);
1750
- // git源码临时存在的源目录
1751
- const sourcePath = resolve$g(sourceDir, md5Key);
1752
- // 模块源码要放到目标目录
1753
- const targetPath = resolve$g(targetDir, path);
1754
- // 从git源码仓库中找到模块源码路径 (一个仓库存在存放多个模块的情况)
1755
- const sourceModulePath = gitPath ? `${sourcePath}/${gitPath}` : sourcePath;
1756
-
1757
- // 下载完代码后,添加回调函数(主要将模块代码从临时目录移动代码到目标目录)
1987
+ } = moduleInfo; // 处理仓库权限问题
1988
+
1989
+ const gitUrl = replaceGitUrlAccount(httpRepoUrl, moduleName); // 根据gitUrl与branch计算md5
1990
+
1991
+ const md5Key = md5ByGitUrlBranch(gitUrl, branch); // git源码临时存在的源目录
1992
+
1993
+ const sourcePath = resolve$g(sourceDir, md5Key); // 模块源码要放到目标目录
1994
+
1995
+ const targetPath = resolve$g(targetDir, path); // 从git源码仓库中找到模块源码路径 (一个仓库存在存放多个模块的情况)
1996
+
1997
+ const sourceModulePath = gitPath ? `${sourcePath}/${gitPath}` : sourcePath; // 下载完代码后,添加回调函数(主要将模块代码从临时目录移动代码到目标目录)
1998
+
1758
1999
  const callback = {
1759
2000
  params: {
1760
2001
  sourceModulePath,
@@ -1764,15 +2005,18 @@ function collectDownLoadTasksMap(sourceDir, targetDir, modules) {
1764
2005
  if (fs$d.existsSync(targetPath)) {
1765
2006
  shelljs$5.rm('-rf', `${targetPath}/*`);
1766
2007
  }
2008
+
1767
2009
  await moveFile(`${sourceModulePath}`, targetPath, ['node_modules', '.git']);
1768
2010
  }
1769
2011
  };
2012
+
1770
2013
  if (downloadTasksMap.has(sourcePath)) {
1771
2014
  const task = downloadTasksMap.get(sourcePath);
1772
2015
  task.callbacks.push(callback);
1773
2016
  downloadTasksMap.set(sourcePath, task);
1774
2017
  } else {
1775
2018
  let promiseTask;
2019
+
1776
2020
  if (fs$d.existsSync(sourcePath) && fs$d.existsSync(`${sourcePath}/.git`)) {
1777
2021
  promiseTask = (gitUrl, sourcePath, branch, httpRepoUrl) => {
1778
2022
  info$e(`git pull:${httpRepoUrl} --branch: ${branch}`);
@@ -1787,6 +2031,7 @@ function collectDownLoadTasksMap(sourceDir, targetDir, modules) {
1787
2031
  return downloadRepoForGit(gitUrl, sourcePath, branch);
1788
2032
  };
1789
2033
  }
2034
+
1790
2035
  downloadTasksMap.set(sourcePath, {
1791
2036
  promiseTask,
1792
2037
  params: {
@@ -1800,15 +2045,17 @@ function collectDownLoadTasksMap(sourceDir, targetDir, modules) {
1800
2045
  }
1801
2046
  }
1802
2047
  }
2048
+
1803
2049
  return downloadTasksMap;
1804
2050
  }
1805
-
1806
2051
  /**
1807
2052
  * 检查远程模块的gitUrl与 branch是否有更新
1808
2053
  * @param {string} sourceDir 模块源码在缓存区的目录
1809
2054
  * @param {object} moduleInfo 模块的配置信息
1810
2055
  * @returns
1811
2056
  */
2057
+
2058
+
1812
2059
  function checkRemoteModGitUrlBranch(sourceDir, moduleInfo) {
1813
2060
  if (moduleInfo.repoInfo) {
1814
2061
  const {
@@ -1820,12 +2067,15 @@ function checkRemoteModGitUrlBranch(sourceDir, moduleInfo) {
1820
2067
  } = moduleInfo;
1821
2068
  const gitUrl = replaceGitUrlAccount(httpRepoUrl, moduleName);
1822
2069
  const md5Key = md5ByGitUrlBranch(gitUrl, buildGitTag);
2070
+
1823
2071
  if (!fs$d.existsSync(`${sourceDir}/${md5Key}`)) {
1824
2072
  return true;
1825
2073
  }
1826
2074
  }
2075
+
1827
2076
  return false;
1828
2077
  }
2078
+
1829
2079
  var cloneModules_1 = {
1830
2080
  cloneModules: cloneModules$1,
1831
2081
  checkRemoteModGitUrlBranch
@@ -1833,11 +2083,11 @@ var cloneModules_1 = {
1833
2083
 
1834
2084
  const ci = require$$0__default$7;
1835
2085
  const path$c = require$$1__default$1;
1836
-
1837
2086
  /**
1838
2087
  * 获取小程序ci的Project对象
1839
2088
  * @returns {Object} 小程序ci对象
1840
2089
  */
2090
+
1841
2091
  const getMpCi = ({
1842
2092
  appId,
1843
2093
  projectPath,
@@ -1845,7 +2095,9 @@ const getMpCi = ({
1845
2095
  privateKey = 'TODO'
1846
2096
  }) => {
1847
2097
  var _projectCg$packOption, _projectCg$packOption2;
2098
+
1848
2099
  const projectCg = require(path$c.join(projectPath, 'project.config.json'));
2100
+
1849
2101
  const ignores = (projectCg === null || projectCg === void 0 ? void 0 : (_projectCg$packOption = projectCg.packOptions) === null || _projectCg$packOption === void 0 ? void 0 : (_projectCg$packOption2 = _projectCg$packOption.ignore) === null || _projectCg$packOption2 === void 0 ? void 0 : _projectCg$packOption2.map(({
1850
2102
  value
1851
2103
  }) => value)) || [];
@@ -1857,21 +2109,22 @@ const getMpCi = ({
1857
2109
  ignores: ['node_modules/**/*', 'cloud/**/*', ...ignores]
1858
2110
  });
1859
2111
  };
1860
-
1861
2112
  /**
1862
2113
  * 格式化构建npm结果信息
1863
2114
  * @param {Array<String>} warning 构建时的告警信息
1864
2115
  * @returns {String} npm构建错误信息
1865
2116
  */
2117
+
2118
+
1866
2119
  const formatPackNpmWarning = warning => {
1867
2120
  if (!warning) {
1868
2121
  return '';
1869
2122
  }
2123
+
1870
2124
  const result = warning.map((it, index) => `${index + 1}. ${it.msg}
1871
2125
  \t@ ${it.jsPath}:${it.tips}`).join('---------------\n');
1872
2126
  return result;
1873
2127
  };
1874
-
1875
2128
  /**
1876
2129
  * 构建miniprogram_npm https://developers.weixin.qq.com/miniprogram/dev/devtools/ci.html#%E6%9E%84%E5%BB%BAnpm
1877
2130
  * * @param {object} {
@@ -1880,6 +2133,8 @@ const formatPackNpmWarning = warning => {
1880
2133
  * privateKey,
1881
2134
  * }
1882
2135
  */
2136
+
2137
+
1883
2138
  const buildMpNpm$1 = async ({
1884
2139
  appId,
1885
2140
  projectPath,
@@ -1894,12 +2149,13 @@ const buildMpNpm$1 = async ({
1894
2149
  ignores: ['cloud/**/*']
1895
2150
  });
1896
2151
  const packNpmMsg = formatPackNpmWarning(packNpmWarning);
2152
+
1897
2153
  if (packNpmMsg) {
1898
2154
  return Promise.reject(packNpmMsg);
1899
2155
  }
2156
+
1900
2157
  return Promise.resolve();
1901
2158
  };
1902
-
1903
2159
  /**
1904
2160
  * 预览小程序码 https://developers.weixin.qq.com/miniprogram/dev/devtools/ci.html#%E9%A2%84%E8%A7%88
1905
2161
  * @param {object} {
@@ -1910,6 +2166,8 @@ const buildMpNpm$1 = async ({
1910
2166
  * robot
1911
2167
  * }
1912
2168
  */
2169
+
2170
+
1913
2171
  const previewMp = async (params = {}) => {
1914
2172
  const {
1915
2173
  appId,
@@ -1928,7 +2186,6 @@ const previewMp = async (params = {}) => {
1928
2186
  onProgressUpdate: () => {}
1929
2187
  });
1930
2188
  };
1931
-
1932
2189
  /**
1933
2190
  * 上传小程序 https://developers.weixin.qq.com/miniprogram/dev/devtools/ci.html#%E4%B8%8A%E4%BC%A0
1934
2191
  * @param {object} {
@@ -1939,6 +2196,8 @@ const previewMp = async (params = {}) => {
1939
2196
  * desc
1940
2197
  * }
1941
2198
  */
2199
+
2200
+
1942
2201
  const uploadMp = async (params = {}) => {
1943
2202
  const {
1944
2203
  appId,
@@ -1957,6 +2216,7 @@ const uploadMp = async (params = {}) => {
1957
2216
  onProgressUpdate: () => {}
1958
2217
  });
1959
2218
  };
2219
+
1960
2220
  const getDevSourceMap = async (params = {}) => {
1961
2221
  const {
1962
2222
  appId,
@@ -1976,6 +2236,7 @@ const getDevSourceMap = async (params = {}) => {
1976
2236
  sourceMapSavePath
1977
2237
  });
1978
2238
  };
2239
+
1979
2240
  var mpCi$3 = {
1980
2241
  buildMpNpm: buildMpNpm$1,
1981
2242
  previewMp,
@@ -1991,31 +2252,42 @@ const {
1991
2252
  const {
1992
2253
  ensureDirExist: ensureDirExist$4
1993
2254
  } = io$3;
2255
+
1994
2256
  function getCache$1(projectDir, type) {
1995
2257
  var _content$projectDir;
2258
+
1996
2259
  const filePath = NPM_CACHE_FILE;
2260
+
1997
2261
  if (!fs$c.existsSync(filePath)) {
1998
2262
  return null;
1999
2263
  }
2264
+
2000
2265
  const content = require(filePath);
2266
+
2001
2267
  return content === null || content === void 0 ? void 0 : (_content$projectDir = content[projectDir]) === null || _content$projectDir === void 0 ? void 0 : _content$projectDir[type];
2002
2268
  }
2269
+
2003
2270
  function setCache$1(projectDir, type = 'miniprogram_npm', data) {
2004
2271
  const filePath = NPM_CACHE_FILE;
2272
+
2005
2273
  if (!fs$c.existsSync(filePath)) {
2006
2274
  const dir = path$b.dirname(filePath);
2007
2275
  ensureDirExist$4(dir);
2008
2276
  fs$c.writeFileSync(filePath, '{}');
2009
2277
  }
2278
+
2010
2279
  const content = require(filePath);
2280
+
2011
2281
  if (!content[projectDir]) {
2012
2282
  content[projectDir] = {};
2013
2283
  }
2284
+
2014
2285
  content[projectDir] = {
2015
2286
  [type]: data
2016
2287
  };
2017
2288
  fs$c.writeFileSync(filePath, JSON.stringify(content, null, 2));
2018
2289
  }
2290
+
2019
2291
  var cache = {
2020
2292
  setCache: setCache$1,
2021
2293
  getCache: getCache$1
@@ -2059,23 +2331,26 @@ const collectNpmTasksMap = (packageJsonFiles, cacheDir) => {
2059
2331
  // }
2060
2332
  // }
2061
2333
  const npmTasksMap = new Map();
2334
+
2062
2335
  for (const packageJsonPath of packageJsonFiles) {
2063
2336
  const packageContent = fs$b.readFileSync(packageJsonPath);
2064
2337
  let packageJson;
2338
+
2065
2339
  try {
2066
2340
  packageJson = JSON.parse(packageContent);
2067
2341
  } catch (e) {
2068
2342
  throw new Error(`${packageJsonPath}json解析出现错误:${e}`);
2069
2343
  }
2344
+
2070
2345
  const md5Obj = {
2071
2346
  dependencies: packageJson.dependencies || {}
2072
2347
  };
2348
+
2073
2349
  if (Object.keys(md5Obj.dependencies).length !== 0) {
2074
2350
  const md5Key = crypto$1.createHash('md5').update(JSON.stringify(md5Obj)).digest('hex');
2075
2351
  const cacheNMPath = path$a.join(cacheDir, md5Key);
2076
- const cacheNMTarFile = path$a.join(cacheNMPath, 'node_modules.tar.gz');
2352
+ const cacheNMTarFile = path$a.join(cacheNMPath, 'node_modules.tar.gz'); // 下载后,添加回调函数 (拷贝node_modules.tar.gz到编译目录并解压)
2077
2353
 
2078
- // 下载后,添加回调函数 (拷贝node_modules.tar.gz到编译目录并解压)
2079
2354
  const callback = {
2080
2355
  params: {
2081
2356
  cacheNMPath,
@@ -2086,8 +2361,7 @@ const collectNpmTasksMap = (packageJsonFiles, cacheDir) => {
2086
2361
  fn: async (cacheNMPath, cacheNMTarFile, packageJsonDir, shell) => {
2087
2362
  shell.cd(cacheNMPath);
2088
2363
  shell.cp('-Rf', cacheNMTarFile, `${packageJsonDir}/`);
2089
- const newShellJsOption = {
2090
- ...shellJsOption,
2364
+ const newShellJsOption = { ...shellJsOption,
2091
2365
  cwd: packageJsonDir
2092
2366
  };
2093
2367
  shell.cd(packageJsonDir);
@@ -2095,13 +2369,16 @@ const collectNpmTasksMap = (packageJsonFiles, cacheDir) => {
2095
2369
  shell.rm('-rf', './node_modules.tar.gz');
2096
2370
  }
2097
2371
  };
2372
+
2098
2373
  if (npmTasksMap.has(cacheNMPath)) {
2099
2374
  const task = npmTasksMap.get(cacheNMPath);
2100
2375
  task.callbacks.push(callback);
2101
2376
  npmTasksMap.set(cacheNMPath, task);
2102
2377
  } else {
2103
2378
  const missCache = !fsExtra.pathExistsSync(cacheNMPath) || !fsExtra.existsSync(cacheNMTarFile) || fsExtra.statSync(cacheNMTarFile).size < 512;
2379
+
2104
2380
  let promiseTask = () => Promise.resolve();
2381
+
2105
2382
  if (missCache) {
2106
2383
  promiseTask = (packageJsonPath, cacheNMPath, shell) => {
2107
2384
  fsExtra.emptydirSync(cacheNMPath);
@@ -2109,8 +2386,7 @@ const collectNpmTasksMap = (packageJsonFiles, cacheDir) => {
2109
2386
  log.info(`npm install: ${packageJsonPath}`);
2110
2387
  const tmsConfig = global$8.getData('tmsConfig');
2111
2388
  return npmInstall$2(cacheNMPath, tmsConfig.npm).then(() => {
2112
- const newShellJsOption = {
2113
- ...shellJsOption,
2389
+ const newShellJsOption = { ...shellJsOption,
2114
2390
  cwd: cacheNMPath
2115
2391
  };
2116
2392
  shell.cd(cacheNMPath);
@@ -2119,6 +2395,7 @@ const collectNpmTasksMap = (packageJsonFiles, cacheDir) => {
2119
2395
  });
2120
2396
  };
2121
2397
  }
2398
+
2122
2399
  npmTasksMap.set(cacheNMPath, {
2123
2400
  promiseTask,
2124
2401
  params: {
@@ -2131,18 +2408,17 @@ const collectNpmTasksMap = (packageJsonFiles, cacheDir) => {
2131
2408
  }
2132
2409
  }
2133
2410
  }
2411
+
2134
2412
  return npmTasksMap;
2135
- };
2413
+ }; // 遍历安装指定目录下所有项目的npm依赖
2414
+
2136
2415
 
2137
- // 遍历安装指定目录下所有项目的npm依赖
2138
2416
  const npmInstallAll$1 = async (subPackages, contextDir, cacheDir) => {
2139
2417
  const cwd = process.cwd();
2140
- const packageJsonFiles = await findAllPackageJson(subPackages, contextDir);
2418
+ const packageJsonFiles = await findAllPackageJson(subPackages, contextDir); // 收集npm install的任务
2141
2419
 
2142
- // 收集npm install的任务
2143
- const npmTasksMap = collectNpmTasksMap(packageJsonFiles, cacheDir);
2420
+ const npmTasksMap = collectNpmTasksMap(packageJsonFiles, cacheDir); // 开始执行npm install和回调(移动)的任务
2144
2421
 
2145
- // 开始执行npm install和回调(移动)的任务
2146
2422
  const arrPromises = [];
2147
2423
  npmTasksMap.forEach(({
2148
2424
  promiseTask,
@@ -2163,13 +2439,14 @@ const npmInstallAll$1 = async (subPackages, contextDir, cacheDir) => {
2163
2439
  shell.cd(cwd);
2164
2440
  return packageJsonFiles;
2165
2441
  };
2166
-
2167
2442
  /**
2168
2443
  * 递归查找指定条件的文件
2169
2444
  * @param {String} startPath 开始查找的根路径
2170
2445
  * @param {String} filter 匹配的字符串
2171
2446
  * @returns {Array<String>} 查找到的文件路径列表
2172
2447
  */
2448
+
2449
+
2173
2450
  const findFilesByFilter = (startPath, filter) => {
2174
2451
  const result = [];
2175
2452
  /**
@@ -2178,24 +2455,27 @@ const findFilesByFilter = (startPath, filter) => {
2178
2455
  * @param {String} filter 筛选器
2179
2456
  * @returns {Undefined} 无需返回值
2180
2457
  */
2458
+
2181
2459
  const find = (startPath, filter) => {
2182
2460
  // 目录不存在
2183
2461
  if (!fs$b.existsSync(startPath)) {
2184
2462
  log.fail(`${startPath}目录不存在`);
2185
2463
  process.exit(-1);
2186
2464
  return;
2187
- }
2465
+ } // 当前目录下的所有文件 / 文件夹
2466
+
2188
2467
 
2189
- // 当前目录下的所有文件 / 文件夹
2190
2468
  const exceptDir = ['node_modules', 'miniprogram_npm'];
2469
+
2191
2470
  if (exceptDir.find(item => startPath.indexOf(item) > -1)) {
2192
2471
  return;
2193
2472
  }
2473
+
2194
2474
  const files = fs$b.readdirSync(startPath);
2195
2475
  files.forEach(file => {
2196
2476
  const filename = path$a.join(startPath, file);
2197
- const stat = fs$b.lstatSync(filename);
2198
- // 当前文件是文件夹类型,继续递归
2477
+ const stat = fs$b.lstatSync(filename); // 当前文件是文件夹类型,继续递归
2478
+
2199
2479
  if (stat.isDirectory()) {
2200
2480
  find(filename, filter);
2201
2481
  } else if (filename.indexOf(filter) >= 0) {
@@ -2204,28 +2484,33 @@ const findFilesByFilter = (startPath, filter) => {
2204
2484
  }
2205
2485
  });
2206
2486
  };
2487
+
2207
2488
  find(startPath, filter);
2208
2489
  return result;
2209
2490
  };
2210
-
2211
2491
  /**
2212
2492
  * 找到项目中所有的package.json文件
2213
2493
  * @param {Array<String>} subRoots 需要安装npm依赖的路径
2214
2494
  * @param {String} contextDir 命令运行的目录
2215
2495
  * @returns {Array<String>} 找到的所有package.json文件的路径
2216
2496
  */
2497
+
2498
+
2217
2499
  const findAllPackageJson = (subRoots = [], contextDir) => {
2218
2500
  const packageJsonName = 'package.json'; // 查找文件名
2501
+
2219
2502
  const cwd = contextDir || dirPath;
2220
2503
  const result = [path$a.join(cwd, packageJsonName)]; // 默认填充根目录下的package.json
2221
2504
 
2222
2505
  subRoots.forEach(subRoot => {
2223
2506
  const toppath = path$a.join(cwd, subRoot.root); // 从该目录开始查找package.json文件
2507
+
2224
2508
  const list = findFilesByFilter(toppath, packageJsonName);
2225
2509
  result.push(...list);
2226
2510
  });
2227
2511
  return result;
2228
2512
  };
2513
+
2229
2514
  var npm = {
2230
2515
  npmInstallAll: npmInstallAll$1,
2231
2516
  findAllPackageJson,
@@ -2234,6 +2519,7 @@ var npm = {
2234
2519
 
2235
2520
  const crypto = require$$1__default$6;
2236
2521
  const fs$a = require$$0__default$1;
2522
+
2237
2523
  function fileMd5$1(filePath) {
2238
2524
  return new Promise((resolve, reject) => {
2239
2525
  const md5sum = crypto.createHash('md5');
@@ -2250,6 +2536,7 @@ function fileMd5$1(filePath) {
2250
2536
  });
2251
2537
  });
2252
2538
  }
2539
+
2253
2540
  var md5 = {
2254
2541
  fileMd5: fileMd5$1
2255
2542
  };
@@ -2265,25 +2552,30 @@ const shelljs$4 = require$$0__default$2;
2265
2552
  const {
2266
2553
  handleError: handleError$5
2267
2554
  } = handleError_1;
2555
+
2268
2556
  const getLatestVersion = npmName => {
2269
2557
  const data = shelljs$4.exec(`npm view ${npmName} version`);
2558
+
2270
2559
  if (data.code === 0) {
2271
2560
  return data.stdout;
2272
2561
  }
2562
+
2273
2563
  return '0.0.0';
2274
- };
2564
+ }; // 收集package.json
2565
+
2275
2566
 
2276
- // 收集package.json
2277
2567
  function collectPackageJson(subPackages, cwd, outputDir) {
2278
2568
  const packageJsonName = 'package.json'; // 查找文件名
2279
2569
  // 1.1根目录的package.json
2570
+
2280
2571
  const packageArr = [{
2281
2572
  srcPackageDir: path$9.join(cwd, packageJsonName),
2282
2573
  destNpmDir: resolve$f(outputDir, 'node_modules')
2283
- }];
2284
- // 1.2模块的package.json
2574
+ }]; // 1.2模块的package.json
2575
+
2285
2576
  subPackages.forEach(item => {
2286
2577
  const srcPackageDir = `${getAbsolutePath$5(item.path)}/package.json`;
2578
+
2287
2579
  if (fs$9.existsSync(srcPackageDir)) {
2288
2580
  packageArr.push({
2289
2581
  srcPackageDir,
@@ -2292,21 +2584,22 @@ function collectPackageJson(subPackages, cwd, outputDir) {
2292
2584
  }
2293
2585
  });
2294
2586
  return packageArr;
2295
- }
2587
+ } // 读取package.json的依赖
2588
+
2296
2589
 
2297
- // 读取package.json的依赖
2298
2590
  function readPackageDependencies(srcPackageDir) {
2299
2591
  const packageJson = fs$9.readFileSync(srcPackageDir, 'utf-8');
2300
2592
  let dependencies = {};
2593
+
2301
2594
  try {
2302
2595
  const json = packageJson ? JSON.parse(packageJson) : {};
2303
2596
  dependencies = (json === null || json === void 0 ? void 0 : json.dependencies) || {};
2304
2597
  } catch (e) {
2305
2598
  handleError$5(`解析${srcPackageDir}报错,请检查是否是正确的json配置项 ${e}`);
2306
2599
  }
2600
+
2307
2601
  return dependencies;
2308
2602
  }
2309
-
2310
2603
  /**
2311
2604
  * 检查package.json的依赖大于node_module的版本,则返回true
2312
2605
  * @param {*} subPackages 模块
@@ -2314,40 +2607,51 @@ function readPackageDependencies(srcPackageDir) {
2314
2607
  * @param {*} outputDir 待检查node_modules存放的目录 (eg: dist/node_modules)
2315
2608
  * @returns
2316
2609
  */
2610
+
2611
+
2317
2612
  const isDependenciesUpdate$1 = (subPackages, cwd, outputDir) => {
2318
2613
  // 步骤1. 收集package.json
2319
- const packageArr = collectPackageJson(subPackages, cwd, outputDir);
2320
- // 步骤2. 比较package.json的依赖与node_modules依赖的版本号
2614
+ const packageArr = collectPackageJson(subPackages, cwd, outputDir); // 步骤2. 比较package.json的依赖与node_modules依赖的版本号
2615
+
2321
2616
  return checkPackageVersion$1(packageArr);
2322
- };
2617
+ }; // 比较package.json的依赖与node_modules依赖的版本号
2618
+
2323
2619
 
2324
- // 比较package.json的依赖与node_modules依赖的版本号
2325
2620
  const checkPackageVersion$1 = packageArr => {
2326
2621
  for (const item of packageArr) {
2327
2622
  const dependencies = readPackageDependencies(item.srcPackageDir);
2328
2623
  const dependenciesKeys = Object.keys(dependencies);
2624
+
2329
2625
  for (const key of dependenciesKeys) {
2330
2626
  const depPath = path$9.join(item.destNpmDir, key);
2627
+
2331
2628
  if (!fs$9.existsSync(depPath)) {
2332
2629
  return true;
2333
2630
  }
2631
+
2334
2632
  const depPackagePath = path$9.join(depPath, 'package.json');
2633
+
2335
2634
  if (fs$9.existsSync(depPackagePath)) {
2336
2635
  const packageData = require(depPackagePath);
2636
+
2337
2637
  if (dependencies[key] === 'latest') {
2338
2638
  dependencies[key] = getLatestVersion(key);
2339
2639
  }
2640
+
2340
2641
  if (packageData.version === 'latest') {
2341
2642
  packageData.version = getLatestVersion(key);
2342
2643
  }
2644
+
2343
2645
  if (semver$1.lt(packageData.version, semver$1.minVersion(dependencies[key]).version)) {
2344
2646
  return true;
2345
2647
  }
2346
2648
  }
2347
2649
  }
2348
2650
  }
2651
+
2349
2652
  return false;
2350
2653
  };
2654
+
2351
2655
  var checkDependencies = {
2352
2656
  isDependenciesUpdate: isDependenciesUpdate$1,
2353
2657
  checkPackageVersion: checkPackageVersion$1
@@ -2388,12 +2692,15 @@ const {
2388
2692
  const {
2389
2693
  isDependenciesUpdate
2390
2694
  } = checkDependencies;
2695
+
2391
2696
  async function install$3(tmsConfig, subPackages, useCache = true) {
2392
2697
  var _tmsConfig$hooks;
2393
- const cwd = process.cwd();
2394
- // 加npm install之前的钩子
2698
+
2699
+ const cwd = process.cwd(); // 加npm install之前的钩子
2700
+
2395
2701
  if (typeof (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks = tmsConfig.hooks) === null || _tmsConfig$hooks === void 0 ? void 0 : _tmsConfig$hooks.beforeNpmInstall) === 'function') {
2396
2702
  var _tmsConfig$hooks2;
2703
+
2397
2704
  info$d('—————— 执行beforeNpmInstall ————');
2398
2705
  await (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks2 = tmsConfig.hooks) === null || _tmsConfig$hooks2 === void 0 ? void 0 : _tmsConfig$hooks2.beforeNpmInstall({
2399
2706
  tmsConfig: filterField$6(tmsConfig, ['gitAccount']),
@@ -2401,9 +2708,8 @@ async function install$3(tmsConfig, subPackages, useCache = true) {
2401
2708
  }));
2402
2709
  info$d('—————— 执行beforeNpmInstall 完成 ————');
2403
2710
  }
2404
- const npmInstallRes = await createTask$5(npmInstall$1, '小程序 开始npm install', '小程序npm install 完成')(tmsConfig, subPackages, useCache);
2711
+ const npmInstallRes = await createTask$5(npmInstall$1, '小程序 开始npm install', '小程序npm install 完成')(tmsConfig, subPackages, useCache); // 如果npm install 没有命中缓存,则说明node_module有更新,此时必须构建miniprogram_npm
2405
2712
 
2406
- // 如果npm install 没有命中缓存,则说明node_module有更新,此时必须构建miniprogram_npm
2407
2713
  if (!npmInstallRes.isCache) {
2408
2714
  // 构建miniprogram_npm, 不使用缓存
2409
2715
  await createTask$5(mpCiInstall, '开始构建miniprogram_npm', '构建miniprogram_npm 完成')(tmsConfig, subPackages, false);
@@ -2411,8 +2717,10 @@ async function install$3(tmsConfig, subPackages, useCache = true) {
2411
2717
  // 构建miniprogram_npm
2412
2718
  await createTask$5(mpCiInstall, '开始构建miniprogram_npm', '构建miniprogram_npm 完成')(tmsConfig, subPackages, useCache);
2413
2719
  }
2720
+
2414
2721
  shelljs$3.cd(cwd);
2415
2722
  }
2723
+
2416
2724
  async function npmInstall$1(tmsConfig, subPackages, useCache) {
2417
2725
  // 如果依赖没有更新和使用缓存数据(则命中缓存)
2418
2726
  if (!isDependenciesUpdate(subPackages, resolve$e('./'), tmsConfig.outputDir) && useCache) {
@@ -2420,8 +2728,9 @@ async function npmInstall$1(tmsConfig, subPackages, useCache) {
2420
2728
  return {
2421
2729
  isCache: true
2422
2730
  };
2423
- }
2424
- // 拷贝模块的package.json到编译输出目录
2731
+ } // 拷贝模块的package.json到编译输出目录
2732
+
2733
+
2425
2734
  subPackages.forEach(item => {
2426
2735
  const outputModuleDir = resolve$e(`${tmsConfig.outputDir}/${item.root}`);
2427
2736
  io$1.ensureDirExist(outputModuleDir);
@@ -2432,17 +2741,20 @@ async function npmInstall$1(tmsConfig, subPackages, useCache) {
2432
2741
  return {
2433
2742
  isCache: false
2434
2743
  };
2435
- }
2744
+ } // 构建miniprogram_npm
2745
+
2436
2746
 
2437
- // 构建miniprogram_npm
2438
2747
  async function mpCiInstall(tmsConfig, subPackages, useCache) {
2439
2748
  const packageJsonFiles = [];
2440
2749
  const rootPackFile = resolve$e(`${tmsConfig.outputDir}/package.json`);
2750
+
2441
2751
  if (fs$8.existsSync(rootPackFile)) {
2442
2752
  packageJsonFiles.push(rootPackFile);
2443
2753
  }
2754
+
2444
2755
  subPackages.forEach(item => {
2445
2756
  const packageJsonFile = resolve$e(`${tmsConfig.outputDir}/${item.root}/package.json`);
2757
+
2446
2758
  if (fs$8.existsSync(packageJsonFile)) {
2447
2759
  packageJsonFiles.push(packageJsonFile);
2448
2760
  }
@@ -2452,27 +2764,29 @@ async function mpCiInstall(tmsConfig, subPackages, useCache) {
2452
2764
  success: 1,
2453
2765
  doing: 2
2454
2766
  };
2767
+
2455
2768
  if (useCache) {
2456
2769
  let flag = true;
2457
2770
  await Promise.all(packageJsonFiles.map(async item => {
2458
2771
  const packageDir = path$8.dirname(item);
2459
2772
  const mpDir = resolve$e(`${packageDir}/miniprogram_npm`);
2460
2773
  const md5Value = await getMNPMd5(packageDir);
2461
- const preCache = getCache(mpDir, 'miniprogram_npm');
2462
- // console.log('miniprogram_npm', preCache, md5Value);
2774
+ const preCache = getCache(mpDir, 'miniprogram_npm'); // console.log('miniprogram_npm', preCache, md5Value);
2463
2775
  // 上一次构建成功 && 上次md5与当前本地的miniprogram_npm的md5 一致,才可以进入缓存
2776
+
2464
2777
  if ((preCache === null || preCache === void 0 ? void 0 : preCache.status) !== statusMap.success || (preCache === null || preCache === void 0 ? void 0 : preCache.md5) !== md5Value) {
2465
2778
  flag = false;
2466
2779
  }
2467
2780
  }));
2468
2781
  isCache = flag;
2469
2782
  }
2783
+
2470
2784
  if (isCache) {
2471
2785
  info$d('miniprogram_npm命中缓存');
2472
2786
  return;
2473
- }
2787
+ } // 即将构建,在cache中标记开始
2788
+
2474
2789
 
2475
- // 即将构建,在cache中标记开始
2476
2790
  await Promise.all(packageJsonFiles.map(async item => {
2477
2791
  const packageDir = path$8.dirname(item);
2478
2792
  const mpDir = resolve$e(`${packageDir}/miniprogram_npm`);
@@ -2485,9 +2799,8 @@ async function mpCiInstall(tmsConfig, subPackages, useCache) {
2485
2799
  appId: tmsConfig.appId,
2486
2800
  projectPath: resolve$e('./'),
2487
2801
  privateKey: tmsConfig.privateKey
2488
- });
2802
+ }); // 构建成功后,计算md5写入cache
2489
2803
 
2490
- // 构建成功后,计算md5写入cache
2491
2804
  await Promise.all(packageJsonFiles.map(async item => {
2492
2805
  const packageDir = path$8.dirname(item);
2493
2806
  const mpDir = resolve$e(`${packageDir}/miniprogram_npm`);
@@ -2497,15 +2810,16 @@ async function mpCiInstall(tmsConfig, subPackages, useCache) {
2497
2810
  status: statusMap.success
2498
2811
  });
2499
2812
  }));
2500
- }
2813
+ } // 计算miniprogram_npm压缩文件的md5值
2814
+
2501
2815
 
2502
- // 计算miniprogram_npm压缩文件的md5值
2503
2816
  async function getMNPMd5(cwd) {
2504
2817
  const shellJsOption = {
2505
2818
  async: false,
2506
2819
  silent: true
2507
2820
  };
2508
2821
  shelljs$3.cd(cwd);
2822
+
2509
2823
  if (fs$8.existsSync('miniprogram_npm')) {
2510
2824
  shelljs$3.exec('tar -cvf ./miniprogram_npm.tar.gz ./miniprogram_npm', {
2511
2825
  cwd,
@@ -2516,8 +2830,10 @@ async function getMNPMd5(cwd) {
2516
2830
  shelljs$3.rm('-rf', tarDir);
2517
2831
  return md5Value;
2518
2832
  }
2833
+
2519
2834
  return '';
2520
2835
  }
2836
+
2521
2837
  var install_1 = install$3;
2522
2838
 
2523
2839
  const shelljs$2 = require$$0__default$2;
@@ -2546,7 +2862,6 @@ const {
2546
2862
  info: info$c
2547
2863
  } = log$1;
2548
2864
  const install$2 = install_1;
2549
-
2550
2865
  /**
2551
2866
  * 拷贝相关配置文件到编译输出目录
2552
2867
  * @param { object } tmsConfig
@@ -2554,6 +2869,7 @@ const install$2 = install_1;
2554
2869
  * @param { array } defaultFiles 默认需要拷贝的配置项
2555
2870
  * @returns
2556
2871
  */
2872
+
2557
2873
  const cpFilesToOutput = function (tmsConfig, defaultFiles) {
2558
2874
  const outputDir = resolve$d(tmsConfig.outputDir);
2559
2875
  io.ensureDirExist(outputDir);
@@ -2563,28 +2879,26 @@ const cpFilesToOutput = function (tmsConfig, defaultFiles) {
2563
2879
  }
2564
2880
  });
2565
2881
  };
2882
+
2566
2883
  async function task(tmsConfig, targetModules) {
2567
2884
  // 下载和移动代码
2568
- await createTask$4(cloneModules, '开始下载模块代码', '下载模块代码码完成')(MODULE_CODE_DIR$1, resolve$d('./'), targetModules);
2885
+ await createTask$4(cloneModules, '开始下载模块代码', '下载模块代码码完成')(MODULE_CODE_DIR$1, resolve$d('./'), targetModules); // 获取所有模块,合并模块依赖的模块
2569
2886
 
2570
- // 获取所有模块,合并模块依赖的模块
2571
- const newModules = getModulesByMergeDepModules$2(tmsConfig, targetModules, true);
2572
- // 获取所有的分包
2573
- const newSubPackages = getSubPackages$2(newModules);
2887
+ const newModules = getModulesByMergeDepModules$2(tmsConfig, targetModules, true); // 获取所有的分包
2574
2888
 
2575
- // 拷贝相关配置文件到输出目录
2576
- await createTask$4(cpFilesToOutput, '开始拷贝文件到编译输出目录', '拷贝文件到编译输出目录完成')(tmsConfig, DEFAULT_COPY_CONFIG$1);
2889
+ const newSubPackages = getSubPackages$2(newModules); // 拷贝相关配置文件到输出目录
2577
2890
 
2578
- // install
2579
- await install$2(tmsConfig, newSubPackages, true);
2891
+ await createTask$4(cpFilesToOutput, '开始拷贝文件到编译输出目录', '拷贝文件到编译输出目录完成')(tmsConfig, DEFAULT_COPY_CONFIG$1); // install
2892
+
2893
+ await install$2(tmsConfig, newSubPackages, true); // 动态生成编译后的app.json;
2580
2894
 
2581
- // 动态生成编译后的app.json;
2582
2895
  await createTask$4(buildOutputAppJson$2, '开始生成编译后的app.json', '生成编译后的app.json完成')(tmsConfig, newModules);
2583
2896
  return {
2584
2897
  modules: newModules,
2585
2898
  subPackages: newSubPackages
2586
2899
  };
2587
2900
  }
2901
+
2588
2902
  async function init$3(tmsConfig, targetModules) {
2589
2903
  try {
2590
2904
  const taskRes = await task(tmsConfig, targetModules);
@@ -2596,9 +2910,11 @@ async function init$3(tmsConfig, targetModules) {
2596
2910
  process.exit(1);
2597
2911
  }
2598
2912
  }
2913
+
2599
2914
  var init_1 = init$3;
2600
2915
 
2601
2916
  /* eslint-disable no-param-reassign */
2917
+
2602
2918
  function mpProjectJson$1() {
2603
2919
  return function ({
2604
2920
  vinyl,
@@ -2609,9 +2925,11 @@ function mpProjectJson$1() {
2609
2925
  contents = contents.replace(/"miniprogramRoot"[^,]+,/g, '');
2610
2926
  vinyl.contents = Buffer.from(contents);
2611
2927
  }
2928
+
2612
2929
  next();
2613
2930
  };
2614
2931
  }
2932
+
2615
2933
  var mpProjectJson_1 = mpProjectJson$1;
2616
2934
 
2617
2935
  /* eslint-disable @typescript-eslint/no-require-imports */
@@ -2620,15 +2938,15 @@ const pp = require$$1__default$3;
2620
2938
  const path$7 = require$$1__default$1;
2621
2939
  const chalk$4 = require$$3__default;
2622
2940
  /* eslint-enable @typescript-eslint/no-require-imports */
2623
-
2624
2941
  // 允许渲染的文件类型列表
2625
- const TEMPLATE_FILE_EXTENSIONS = ['.json', '.js', '.ts', '.wxml', '.wxss', '.wxs', '.css', '.less', '.scss'];
2626
2942
 
2943
+ const TEMPLATE_FILE_EXTENSIONS = ['.json', '.js', '.ts', '.wxml', '.wxss', '.wxs', '.css', '.less', '.scss'];
2627
2944
  /**
2628
2945
  * 获取预处理器类型
2629
2946
  * @param {string} extName 文件扩展名
2630
2947
  * @returns {string} 预处理器类型
2631
2948
  */
2949
+
2632
2950
  const getPreprocessType = extName => {
2633
2951
  const type = extName.replace('.', '');
2634
2952
  if (type === 'wxml') return 'html';
@@ -2636,7 +2954,6 @@ const getPreprocessType = extName => {
2636
2954
  if (type === 'wxss') return 'css';
2637
2955
  return type;
2638
2956
  };
2639
-
2640
2957
  /**
2641
2958
  * 获取错误上下文信息
2642
2959
  * @param {string} content 文件内容
@@ -2644,67 +2961,80 @@ const getPreprocessType = extName => {
2644
2961
  * @param {number} contextLines 上下文行数
2645
2962
  * @returns {string} 格式化的错误上下文
2646
2963
  */
2964
+
2965
+
2647
2966
  const getErrorContext = (content, errorLine, contextLines = 2) => {
2648
2967
  const lines = content.split('\n');
2649
2968
  const start = Math.max(1, errorLine - contextLines);
2650
2969
  const end = Math.min(lines.length, errorLine + contextLines);
2651
2970
  let context = '';
2971
+
2652
2972
  for (let i = start; i <= end; i++) {
2653
2973
  const marker = i === errorLine ? ' >> ' : ' ';
2654
2974
  context += `${marker}${i}| ${lines[i - 1]}\n`;
2655
2975
  }
2976
+
2656
2977
  return context;
2657
2978
  };
2658
-
2659
2979
  /**
2660
2980
  * 打印错误信息
2661
2981
  * @param {string} filePath 文件路径
2662
2982
  * @param {string} context 错误上下文
2663
2983
  * @param {Error} error 错误对象
2664
2984
  */
2985
+
2986
+
2665
2987
  const printError = (filePath, context, error) => {
2666
2988
  console.error(`${chalk$4.yellow('渲染模板出错,请检查处理:')}\n${chalk$4.yellow('文件:')}\n${chalk$4.yellow(filePath)}\n${chalk$4.yellow('错误位置:')}\n${chalk$4.gray(context)}\n${chalk$4.red('错误信息:')}\n${chalk$4.red(error.message)}\n${chalk$4.gray('--------------------------------')}`);
2667
2989
  };
2668
-
2669
2990
  /**
2670
2991
  * 模板渲染插件
2671
2992
  * @param {Object} tmsConfig 配置对象
2672
2993
  * @returns {Object} through2 转换流
2673
2994
  */
2995
+
2996
+
2674
2997
  var tmsTemplateRender = function tmsTemplateRender(tmsConfig) {
2675
2998
  return through$1.obj((file, encoding, callback) => {
2676
2999
  if (!file.isBuffer()) {
2677
3000
  return callback(null, file);
2678
3001
  }
3002
+
2679
3003
  const extName = path$7.extname(file.path).toLowerCase();
3004
+
2680
3005
  if (!TEMPLATE_FILE_EXTENSIONS.includes(extName)) {
2681
3006
  return callback(null, file);
2682
3007
  }
3008
+
2683
3009
  const content = file.contents.toString(encoding);
3010
+
2684
3011
  try {
2685
3012
  const vars = tmsConfig.templateVars || {};
2686
- const ppType = getPreprocessType(extName);
2687
- // 手动检查 @echo 引用的变量是否存在
3013
+ const ppType = getPreprocessType(extName); // 手动检查 @echo 引用的变量是否存在
3014
+
2688
3015
  const echoPattern = /\/\* @echo (\w+) \*\//g;
2689
3016
  let match;
3017
+
2690
3018
  while ((match = echoPattern.exec(content)) !== null) {
2691
- const variableName = match[1];
2692
- // eslint-disable-next-line no-prototype-builtins
3019
+ const variableName = match[1]; // eslint-disable-next-line no-prototype-builtins
3020
+
2693
3021
  if (!vars.hasOwnProperty(variableName)) {
2694
3022
  const error = new Error(`变量 ${variableName} 未定义`);
2695
3023
  error.line = content.substring(0, match.index).split('\n').length;
2696
3024
  throw error;
2697
3025
  }
2698
3026
  }
2699
- const rendered = pp.preprocess(content, vars, ppType);
2700
- // eslint-disable-next-line no-param-reassign
3027
+
3028
+ const rendered = pp.preprocess(content, vars, ppType); // eslint-disable-next-line no-param-reassign
3029
+
2701
3030
  file.contents = Buffer.from(rendered);
2702
3031
  } catch (err) {
2703
3032
  const context = getErrorContext(content, err.line || 1);
2704
- printError(file.path, context, err);
2705
- // 直接抛出异常,中断编译流程
3033
+ printError(file.path, context, err); // 直接抛出异常,中断编译流程
3034
+
2706
3035
  throw new Error(`模板渲染失败: ${file.path}\n${err.message}`);
2707
3036
  }
3037
+
2708
3038
  callback(null, file);
2709
3039
  });
2710
3040
  };
@@ -2724,11 +3054,13 @@ const through = require$$0__default$8;
2724
3054
  const {
2725
3055
  fail: fail$3
2726
3056
  } = log$1;
3057
+
2727
3058
  const getTargetFile$2 = (sourceFile, module, outputDir) => {
2728
3059
  const sourceFileRelativeModule = path$6.relative(resolve$c(module.from), sourceFile);
2729
3060
  const targetFile = resolve$c(outputDir, module.to, sourceFileRelativeModule);
2730
3061
  return targetFile;
2731
3062
  };
3063
+
2732
3064
  const addPlugins = function (tmsConfig, srcPipe, pluginParams) {
2733
3065
  const {
2734
3066
  plugins = []
@@ -2750,6 +3082,7 @@ const addPlugins = function (tmsConfig, srcPipe, pluginParams) {
2750
3082
  this.push(vinyl);
2751
3083
  }))), srcPipe);
2752
3084
  };
3085
+
2753
3086
  var compile$1 = function (tmsConfig, {
2754
3087
  glob,
2755
3088
  destPath,
@@ -2763,15 +3096,12 @@ var compile$1 = function (tmsConfig, {
2763
3096
  taskFn: (sourceFile, targetPath) => {
2764
3097
  const newGlobValue = Array.isArray(sourceFile) ? sourceFile : glob;
2765
3098
  const newDestPath = targetPath ? targetPath : destPath;
2766
- let srcPipe = src$2(newGlobValue, {
2767
- ...srcOption
2768
- });
3099
+ let srcPipe = src$2(newGlobValue, { ...srcOption
3100
+ }); // 在文件读取后,插件处理之前先加入模板渲染插件
2769
3101
 
2770
- // 在文件读取后,插件处理之前先加入模板渲染插件
2771
3102
  const templateRender = tmsTemplateRender;
2772
- srcPipe = srcPipe.pipe(templateRender(tmsConfig));
3103
+ srcPipe = srcPipe.pipe(templateRender(tmsConfig)); // 后续步骤继续执行其他插件
2773
3104
 
2774
- // 后续步骤继续执行其他插件
2775
3105
  const pluginParams = {
2776
3106
  module,
2777
3107
  isDev
@@ -2787,6 +3117,7 @@ var compile$1 = function (tmsConfig, {
2787
3117
 
2788
3118
  /* eslint-disable */
2789
3119
  // 该文件源于npm包 gulp-watch 但内部有bug, 故源码进行单独修改
3120
+
2790
3121
  const assign = require$$0__default$a;
2791
3122
  const path$5 = require$$1__default$1;
2792
3123
  const PluginError = require$$2__default$1;
@@ -2802,52 +3133,69 @@ const anymatch = require$$9__default;
2802
3133
  const pathIsAbsolute = require$$10__default$1;
2803
3134
  const globParent = require$$11__default;
2804
3135
  const slash = require$$12__default;
3136
+
2805
3137
  function normalizeGlobs(globs) {
2806
3138
  if (!globs) {
2807
3139
  throw new PluginError('gulp-watch', 'glob argument required');
2808
3140
  }
3141
+
2809
3142
  if (typeof globs === 'string') {
2810
3143
  globs = [globs];
2811
3144
  }
3145
+
2812
3146
  if (!Array.isArray(globs)) {
2813
3147
  throw new PluginError('gulp-watch', `glob should be String or Array, not ${typeof globs}`);
2814
3148
  }
3149
+
2815
3150
  return globs;
2816
3151
  }
3152
+
2817
3153
  function watch$3(globs, opts, cb) {
2818
3154
  globs = normalizeGlobs(globs);
3155
+
2819
3156
  if (typeof opts === 'function') {
2820
3157
  cb = opts;
2821
3158
  opts = {};
2822
3159
  }
3160
+
2823
3161
  opts = assign({}, watch$3._defaultOptions, opts);
3162
+
2824
3163
  cb = cb || function () {};
3164
+
2825
3165
  function resolveFilepath(filepath) {
2826
3166
  if (pathIsAbsolute(filepath)) {
2827
3167
  return path$5.normalize(filepath);
2828
3168
  }
3169
+
2829
3170
  return path$5.resolve(opts.cwd || process.cwd(), filepath);
2830
3171
  }
3172
+
2831
3173
  function resolveGlob(glob) {
2832
3174
  let mod = '';
3175
+
2833
3176
  if (glob[0] === '!') {
2834
3177
  mod = glob[0];
2835
3178
  glob = glob.slice(1);
2836
3179
  }
3180
+
2837
3181
  return mod + slash(resolveFilepath(glob));
2838
3182
  }
3183
+
2839
3184
  globs = globs.map(resolveGlob);
2840
3185
  const baseForced = Boolean(opts.base);
2841
3186
  const outputStream = new Duplex({
2842
3187
  objectMode: true,
2843
3188
  allowHalfOpen: true
2844
3189
  });
3190
+
2845
3191
  outputStream._write = function _write(file, enc, done) {
2846
3192
  cb(file);
2847
3193
  this.push(file);
2848
3194
  done();
2849
3195
  };
3196
+
2850
3197
  outputStream._read = function _read() {};
3198
+
2851
3199
  const watcher = chokidar.watch(globs, opts);
2852
3200
  opts.events.forEach(ev => {
2853
3201
  watcher.on(ev, processEvent.bind(undefined, ev));
@@ -2855,72 +3203,86 @@ function watch$3(globs, opts, cb) {
2855
3203
  ['add', 'change', 'unlink', 'addDir', 'unlinkDir', 'error', 'ready', 'raw'].forEach(ev => {
2856
3204
  watcher.on(ev, outputStream.emit.bind(outputStream, ev));
2857
3205
  });
3206
+
2858
3207
  outputStream.add = function add(newGlobs) {
2859
3208
  newGlobs = normalizeGlobs(newGlobs).map(resolveGlob);
2860
3209
  watcher.add(newGlobs);
2861
3210
  globs.push.apply(globs, newGlobs);
2862
3211
  };
3212
+
2863
3213
  outputStream.unwatch = watcher.unwatch.bind(watcher);
3214
+
2864
3215
  outputStream.close = function () {
2865
3216
  watcher.close();
2866
3217
  this.emit('end');
2867
3218
  };
3219
+
2868
3220
  function processEvent(event, filepath) {
2869
3221
  filepath = resolveFilepath(filepath);
2870
3222
  const fileOpts = assign({}, opts);
2871
3223
  let glob;
2872
3224
  let currentFilepath = filepath;
3225
+
2873
3226
  while (!(glob = globs[anymatch(globs, currentFilepath, true)]) && currentFilepath !== (currentFilepath = path$5.dirname(currentFilepath))) {} // eslint-disable-line no-empty-blocks/no-empty-blocks
2874
3227
 
3228
+
2875
3229
  if (!glob) {
2876
3230
  console.error('[gulp-watch]没有匹配到glob');
2877
3231
  return;
2878
3232
  }
3233
+
2879
3234
  if (!baseForced) {
2880
3235
  fileOpts.base = path$5.normalize(globParent(glob));
2881
- }
3236
+ } // Do not stat deleted files
3237
+
2882
3238
 
2883
- // Do not stat deleted files
2884
3239
  if (event === 'unlink' || event === 'unlinkDir' || event === 'addDir') {
2885
3240
  fileOpts.path = filepath;
2886
3241
  write(event, null, new File(fileOpts));
2887
3242
  return;
2888
- }
3243
+ } // Workaround for early read
3244
+
2889
3245
 
2890
- // Workaround for early read
2891
3246
  setTimeout(() => {
2892
3247
  vinyl.read(filepath, fileOpts).then(file => {
2893
3248
  write(event, null, file);
2894
3249
  });
2895
3250
  }, opts.readDelay);
2896
3251
  }
3252
+
2897
3253
  function write(event, err, file) {
2898
3254
  if (err) {
2899
3255
  outputStream.emit('error', err);
2900
3256
  return;
2901
3257
  }
3258
+
2902
3259
  if (opts.verbose) {
2903
3260
  log(event, file);
2904
3261
  }
3262
+
2905
3263
  file.event = event;
2906
3264
  outputStream.push(file);
2907
3265
  cb(file);
2908
3266
  }
3267
+
2909
3268
  function log(event, file) {
2910
3269
  event = event[event.length - 1] === 'e' ? `${event}d` : `${event}ed`;
2911
3270
  const msg = [colors.magenta(file.relative), 'was', event];
3271
+
2912
3272
  if (opts.name) {
2913
3273
  msg.unshift(`${colors.cyan(opts.name)} saw`);
2914
3274
  }
3275
+
2915
3276
  fancyLog.info.apply(null, msg);
2916
3277
  }
2917
- return outputStream;
2918
- }
2919
3278
 
2920
- // This is not part of the public API as that would lead to global state (singleton) pollution,
3279
+ return outputStream;
3280
+ } // This is not part of the public API as that would lead to global state (singleton) pollution,
2921
3281
  // and allow unexpected interference between unrelated modules that make use of gulp-watch.
2922
3282
  // This can be useful for unit tests and root application configuration, though.
2923
3283
  // Avoid modifying gulp-watch's default options inside a library/reusable package, please.
3284
+
3285
+
2924
3286
  watch$3._defaultOptions = {
2925
3287
  events: ['add', 'change', 'unlink'],
2926
3288
  ignoreInitial: true,
@@ -2969,6 +3331,7 @@ const TIP_MAP = {
2969
3331
  check: () => true
2970
3332
  }
2971
3333
  };
3334
+
2972
3335
  const logTip = (fileName, sourceFile, targetFile, tipMap) => {
2973
3336
  try {
2974
3337
  for (const item in tipMap) {
@@ -2977,18 +3340,20 @@ const logTip = (fileName, sourceFile, targetFile, tipMap) => {
2977
3340
  return;
2978
3341
  }
2979
3342
  }
3343
+
2980
3344
  info$b(`${fileName}有更新`);
2981
3345
  } catch (e) {
2982
3346
  fail$2(`${sourceFile}文件更新提示出现错误: ${e.message}`);
2983
3347
  }
2984
3348
  };
3349
+
2985
3350
  const getTargetFile$1 = (sourceFile, module, outputDir) => {
2986
3351
  const sourceFileRelativeModule = path$4.relative(resolve$b(module.from), sourceFile);
2987
3352
  return resolve$b(outputDir, module.to, sourceFileRelativeModule);
2988
3353
  };
3354
+
2989
3355
  var watch_1 = function (globValue, watchOptions, callback, module) {
2990
- watch$2(globValue, {
2991
- // readDelay: 100,
3356
+ watch$2(globValue, { // readDelay: 100,
2992
3357
  ...watchOptions
2993
3358
  }, async vinyl => {
2994
3359
  const sourceFile = vinyl.history[0];
@@ -2996,16 +3361,19 @@ var watch_1 = function (globValue, watchOptions, callback, module) {
2996
3361
  const sourceFileName = sourceFileDirArr.slice(sourceFileDirArr.length - 2).join('/');
2997
3362
  const tmsConfig = global$6.getData('tmsConfig');
2998
3363
  let targetFile = getTargetFile$1(sourceFile, module, tmsConfig.outputDir);
3364
+
2999
3365
  if (module.custom) {
3000
3366
  const filePath = sourceFile.replace(/\\/g, '/').replace(module.from, '');
3001
3367
  targetFile = path$4.join(module.to, filePath);
3002
3368
  }
3369
+
3003
3370
  if (vinyl.event === 'unlink' || vinyl.event === 'unlinkDir') {
3004
3371
  info$b(`删除${sourceFileName}`);
3005
3372
  shellJs$2.rm('-rf', targetFile);
3006
3373
  updateFileHook(tmsConfig, sourceFile, targetFile, vinyl.event);
3007
3374
  return;
3008
3375
  }
3376
+
3009
3377
  await runCallback({
3010
3378
  tmsConfig,
3011
3379
  sourceFile,
@@ -3015,9 +3383,9 @@ var watch_1 = function (globValue, watchOptions, callback, module) {
3015
3383
  });
3016
3384
  logTip(sourceFileName, sourceFile, targetFile, TIP_MAP);
3017
3385
  });
3018
- };
3386
+ }; // 开始执行watch 文件的 callback函数
3387
+
3019
3388
 
3020
- // 开始执行watch 文件的 callback函数
3021
3389
  async function runCallback({
3022
3390
  tmsConfig,
3023
3391
  sourceFile,
@@ -3037,11 +3405,12 @@ async function runCallback({
3037
3405
  await callback([sourceFile], path$4.dirname(targetFile));
3038
3406
  await updateFileHook(tmsConfig, sourceFile, targetFile, type);
3039
3407
  }
3040
- }
3408
+ } // 执行源码文件更新的钩子
3409
+
3041
3410
 
3042
- // 执行源码文件更新的钩子
3043
3411
  async function updateFileHook(tmsConfig, sourceFile, targetFile, type) {
3044
3412
  var _tmsConfig$hooks;
3413
+
3045
3414
  if (typeof (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks = tmsConfig.hooks) === null || _tmsConfig$hooks === void 0 ? void 0 : _tmsConfig$hooks.updateFile) === 'function') {
3046
3415
  await tmsConfig.hooks.updateFile({
3047
3416
  tmsConfig: filterField$5(tmsConfig, ['gitAccount']),
@@ -3084,10 +3453,10 @@ const {
3084
3453
  global: global$5
3085
3454
  } = global_1;
3086
3455
  const watchEvents = ['add', 'change', 'unlink', 'addDir', 'unlinkDir'];
3456
+
3087
3457
  var dev$4 = async (tmsConfig, modules, isDev = true) => {
3088
- const compileTasksMap = new Map();
3458
+ const compileTasksMap = new Map(); // 监听根目录的文件
3089
3459
 
3090
- // 监听根目录的文件
3091
3460
  mergeMap(compileTasksMap, compile(tmsConfig, {
3092
3461
  glob: DEFAULT_COPY_CONFIG.map(item => resolve$a(item)),
3093
3462
  module: {
@@ -3099,9 +3468,8 @@ var dev$4 = async (tmsConfig, modules, isDev = true) => {
3099
3468
  allowEmpty: true
3100
3469
  },
3101
3470
  isDev
3102
- }));
3471
+ })); // 监听extendFiles
3103
3472
 
3104
- // 监听extendFiles
3105
3473
  if (tmsConfig.watchExtendFiles.length) {
3106
3474
  tmsConfig.watchExtendFiles.forEach(item => {
3107
3475
  mergeMap(compileTasksMap, compile(tmsConfig, {
@@ -3118,19 +3486,19 @@ var dev$4 = async (tmsConfig, modules, isDev = true) => {
3118
3486
  isDev
3119
3487
  }));
3120
3488
  });
3121
- }
3489
+ } // 监听模块的文件
3490
+
3122
3491
 
3123
- // 监听模块的文件
3124
3492
  for (let moduleItem of modules) {
3125
3493
  // 处理默认参数
3126
- moduleItem = {
3127
- ...{
3494
+ moduleItem = { ...{
3128
3495
  exclude: []
3129
3496
  },
3130
3497
  ...moduleItem
3131
3498
  };
3132
3499
  const srcModulePath = getAbsolutePath$3(moduleItem.path);
3133
3500
  const buildModulePath = resolve$a(tmsConfig.outputDir, moduleItem.modulePath);
3501
+
3134
3502
  if (isDev) {
3135
3503
  // 监听模块配置文件
3136
3504
  watch$1([`${srcModulePath}/**/module.config.json`], {
@@ -3140,12 +3508,15 @@ var dev$4 = async (tmsConfig, modules, isDev = true) => {
3140
3508
  to: buildModulePath
3141
3509
  });
3142
3510
  }
3511
+
3143
3512
  const excludes = moduleItem.exclude.map(ePath => {
3144
3513
  const newPath = getAbsolutePath$3(ePath, srcModulePath);
3145
3514
  const ext = path$3.extname(ePath).slice(1);
3515
+
3146
3516
  if (ext) {
3147
3517
  return `!${resolve$a(srcModulePath, newPath)}`;
3148
3518
  }
3519
+
3149
3520
  return `!${resolve$a(srcModulePath, newPath)}/**/*`;
3150
3521
  });
3151
3522
  const moduleConfigPath = `${srcModulePath}/**/module.config.json`;
@@ -3162,20 +3533,22 @@ var dev$4 = async (tmsConfig, modules, isDev = true) => {
3162
3533
  },
3163
3534
  isDev
3164
3535
  }));
3165
- }
3536
+ } // static静态资源目录
3537
+
3166
3538
 
3167
- // static静态资源目录
3168
3539
  if (tmsConfig !== null && tmsConfig !== void 0 && tmsConfig.static && (tmsConfig === null || tmsConfig === void 0 ? void 0 : tmsConfig.static.length) > 0) {
3169
3540
  for (const item of tmsConfig.static) {
3170
3541
  item.from = getAbsolutePath$3(item.from);
3171
3542
  item.to = getAbsolutePath$3(item.to);
3172
3543
  let glob = {};
3173
3544
  const ext = path$3.extname(item.from).slice(1);
3545
+
3174
3546
  if (ext) {
3175
3547
  glob = [item.from];
3176
3548
  } else {
3177
3549
  glob = [`${item.from}/**/*`];
3178
3550
  }
3551
+
3179
3552
  const from = fs$6.lstatSync(item.from).isFile() ? path$3.dirname(item.from) : item.from;
3180
3553
  mergeMap(compileTasksMap, compile(tmsConfig, {
3181
3554
  glob,
@@ -3191,17 +3564,21 @@ var dev$4 = async (tmsConfig, modules, isDev = true) => {
3191
3564
  }));
3192
3565
  }
3193
3566
  }
3567
+
3194
3568
  let sTime;
3195
3569
  let eTime;
3196
3570
  const spinner = ora$1();
3571
+
3197
3572
  function start(cb) {
3198
3573
  info$a('启动编译...');
3199
3574
  spinner.start();
3200
3575
  sTime = new Date().getTime();
3201
3576
  cb();
3202
3577
  }
3578
+
3203
3579
  async function end(cb) {
3204
3580
  var _tmsConfig$hooks;
3581
+
3205
3582
  if (isDev) {
3206
3583
  // 监听app.json
3207
3584
  watch$1([resolve$a('app.json')], {
@@ -3210,8 +3587,8 @@ var dev$4 = async (tmsConfig, modules, isDev = true) => {
3210
3587
  }, async () => await buildOutputAppJson$1(tmsConfig, modules, isDev), {
3211
3588
  from: resolve$a(),
3212
3589
  to: resolve$a(tmsConfig.outputDir)
3213
- });
3214
- // 监听其他文件
3590
+ }); // 监听其他文件
3591
+
3215
3592
  compileTasksMap.forEach(({
3216
3593
  taskFn,
3217
3594
  module
@@ -3224,9 +3601,12 @@ var dev$4 = async (tmsConfig, modules, isDev = true) => {
3224
3601
  } else {
3225
3602
  await buildOutputAppJson$1(tmsConfig, modules, isDev);
3226
3603
  }
3604
+
3227
3605
  eTime = new Date().getTime() - sTime;
3606
+
3228
3607
  if (typeof (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks = tmsConfig.hooks) === null || _tmsConfig$hooks === void 0 ? void 0 : _tmsConfig$hooks.afterFirstCompile) === 'function') {
3229
3608
  var _tmsConfig$hooks2;
3609
+
3230
3610
  await (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks2 = tmsConfig.hooks) === null || _tmsConfig$hooks2 === void 0 ? void 0 : _tmsConfig$hooks2.afterFirstCompile({
3231
3611
  isDev,
3232
3612
  tmsConfig: filterField$4(tmsConfig, ['gitAccount']),
@@ -3235,17 +3615,19 @@ var dev$4 = async (tmsConfig, modules, isDev = true) => {
3235
3615
  }));
3236
3616
  report$7('hooks:afterCompile');
3237
3617
  }
3618
+
3238
3619
  spinner.succeed(chalk$3.green(`首次编译完成, 耗时${eTime / 1000}s, 微信开发者工具打开项目即可预览。`));
3239
3620
  spinner.stop();
3240
3621
  cb();
3241
3622
  }
3623
+
3242
3624
  const compileTasks = [];
3243
3625
  compileTasksMap.forEach(({
3244
3626
  taskFn
3245
3627
  }) => {
3246
3628
  compileTasks.push(taskFn);
3247
- });
3248
- // 一次性完成编译任务(编译完成后再添加watch任务-封装到end函数里面)
3629
+ }); // 一次性完成编译任务(编译完成后再添加watch任务-封装到end函数里面)
3630
+
3249
3631
  series$1(start, parallel$1(...compileTasks), end)();
3250
3632
  };
3251
3633
 
@@ -3273,14 +3655,13 @@ const {
3273
3655
  MODULE_CODE_DIR,
3274
3656
  NODE_MODULES_DIR
3275
3657
  } = constant;
3276
- const report$6 = report_1;
3277
- // const { recommendVersion } = require('../../../core/recommendVersion');
3278
-
3658
+ const report$6 = report_1; // const { recommendVersion } = require('../../../core/recommendVersion');
3279
3659
  // 用户编译分包时,需要将dist中其他分包(主包不能删除)的内容删除,否则其他分包的内容混入到主包(导致主包的体积超2M)
3660
+
3280
3661
  function delOtherPackages(tmsConfig, targetSubPackages) {
3281
3662
  // 获取所有模块,合并模块依赖的模块
3282
- const allModules = getModulesByMergeDepModules$1(tmsConfig, tmsConfig.modules.all);
3283
- // 获取所有的分包
3663
+ const allModules = getModulesByMergeDepModules$1(tmsConfig, tmsConfig.modules.all); // 获取所有的分包
3664
+
3284
3665
  const allSubPackages = getSubPackages$1(allModules);
3285
3666
  const targetSubPackagesName = targetSubPackages.map(item => item.name);
3286
3667
  allSubPackages.forEach(item => {
@@ -3288,38 +3669,42 @@ function delOtherPackages(tmsConfig, targetSubPackages) {
3288
3669
  const moduleRootDir = resolve$9(`${tmsConfig.outputDir}/${item.root}`);
3289
3670
  shelljs$1.rm('-rf', `${moduleRootDir}/*`, {
3290
3671
  silent: true
3291
- });
3292
- // 解决微信开发者工具(dist/app.json: ["subpackages"][0]["root"] 字段需为 目录)错误 - 提前创建该目录
3672
+ }); // 解决微信开发者工具(dist/app.json: ["subpackages"][0]["root"] 字段需为 目录)错误 - 提前创建该目录
3293
3673
  // io.ensureDirExist(moduleRootDir);
3294
3674
  }
3295
3675
  });
3296
3676
  }
3677
+
3297
3678
  async function dev$3(tmsConfig, targetModules) {
3298
3679
  var _tmsConfig$hooks;
3680
+
3299
3681
  const {
3300
3682
  noCache
3301
3683
  } = global$4.getData('cmdOptions');
3684
+
3302
3685
  if (noCache) {
3303
3686
  if (tmsConfig.cleanOutputDirBeforeCompile !== false) {
3304
3687
  shelljs$1.rm('-rf', resolve$9(tmsConfig.outputDir));
3305
3688
  }
3689
+
3306
3690
  shelljs$1.rm('-rf', MODULE_CODE_DIR);
3307
3691
  shelljs$1.rm('-rf', NODE_MODULES_DIR);
3308
- }
3309
- // 推荐tmskit的版本
3692
+ } // 推荐tmskit的版本
3310
3693
  // await recommendVersion();
3311
-
3312
3694
  // 初始化操作
3695
+
3696
+
3313
3697
  const {
3314
3698
  subPackages,
3315
3699
  modules: newModules
3316
- } = await init$2(tmsConfig, targetModules);
3700
+ } = await init$2(tmsConfig, targetModules); // 在启动开发环境前主动执行生成 app.json
3317
3701
 
3318
- // 在启动开发环境前主动执行生成 app.json
3319
3702
  await buildOutputAppJson(tmsConfig, newModules);
3320
3703
  info$9('当前dev启动的有效模块', newModules.map(item => item.moduleName).sort());
3704
+
3321
3705
  if (typeof (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks = tmsConfig.hooks) === null || _tmsConfig$hooks === void 0 ? void 0 : _tmsConfig$hooks.beforeFirstCompile) === 'function') {
3322
3706
  var _tmsConfig$hooks2;
3707
+
3323
3708
  await (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks2 = tmsConfig.hooks) === null || _tmsConfig$hooks2 === void 0 ? void 0 : _tmsConfig$hooks2.beforeFirstCompile({
3324
3709
  isDev: true,
3325
3710
  tmsConfig: filterField$3(tmsConfig, ['gitAccount']),
@@ -3331,9 +3716,11 @@ async function dev$3(tmsConfig, targetModules) {
3331
3716
  delOtherPackages(tmsConfig, subPackages);
3332
3717
  compileDev(tmsConfig, newModules, true);
3333
3718
  }
3719
+
3334
3720
  var dev_1 = dev$3;
3335
3721
 
3336
3722
  const dev$2 = dev$4;
3723
+
3337
3724
  var build$2 = async (tmsConfig, newModules, isDev) => {
3338
3725
  dev$2(tmsConfig, newModules, isDev);
3339
3726
  };
@@ -3352,19 +3739,24 @@ const report$5 = report_1;
3352
3739
  const {
3353
3740
  global: global$3
3354
3741
  } = global_1;
3742
+
3355
3743
  async function build$1(tmsConfig, targetModules) {
3356
3744
  var _tmsConfig$hooks;
3745
+
3357
3746
  // 开始构建前,清理输出目录
3358
3747
  if (tmsConfig.cleanOutputDirBeforeCompile !== false) {
3359
3748
  await shelljs.rm('-rf', resolve$8(tmsConfig.outputDir));
3360
3749
  }
3750
+
3361
3751
  const {
3362
3752
  modules: newModules
3363
3753
  } = await init$1(tmsConfig, targetModules);
3364
3754
  info$8('当前build有效模块', newModules.map(item => item.moduleName).sort());
3365
3755
  const isDev = false;
3756
+
3366
3757
  if (typeof (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks = tmsConfig.hooks) === null || _tmsConfig$hooks === void 0 ? void 0 : _tmsConfig$hooks.beforeFirstCompile) === 'function') {
3367
3758
  var _tmsConfig$hooks2;
3759
+
3368
3760
  await (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks2 = tmsConfig.hooks) === null || _tmsConfig$hooks2 === void 0 ? void 0 : _tmsConfig$hooks2.beforeFirstCompile({
3369
3761
  isDev,
3370
3762
  tmsConfig: filterField$2(tmsConfig, ['gitAccount']),
@@ -3375,6 +3767,7 @@ async function build$1(tmsConfig, targetModules) {
3375
3767
  }
3376
3768
  compileBuild(tmsConfig, newModules, isDev);
3377
3769
  }
3770
+
3378
3771
  var build_1 = build$1;
3379
3772
 
3380
3773
  const moment = require$$1__default;
@@ -3387,32 +3780,39 @@ const {
3387
3780
  const {
3388
3781
  ensureDirExist: ensureDirExist$3
3389
3782
  } = io$3;
3783
+
3390
3784
  function getAllSize$2(data = {}) {
3391
3785
  let allSize;
3786
+
3392
3787
  for (const item of data === null || data === void 0 ? void 0 : data.subPackageInfo) {
3393
3788
  if (item.name === '__FULL__') {
3394
3789
  allSize = item.size;
3395
3790
  break;
3396
3791
  }
3397
3792
  }
3793
+
3398
3794
  return allSize;
3399
3795
  }
3796
+
3400
3797
  const getDesc$3 = (desc = '') => {
3401
3798
  const user = getGitUser();
3402
3799
  const date = moment().format('YYYY-MM-DD HH:mm:ss');
3403
3800
  return `构建描述:${desc}; 构建人: ${user}; 构建时间:${date}`;
3404
3801
  };
3802
+
3405
3803
  const outputInfo$2 = (infoOutput, data) => {
3406
3804
  const outPath = getAbsolutePath$2(infoOutput);
3407
3805
  const dir = path$2.dirname(outPath);
3408
3806
  ensureDirExist$3(dir);
3409
3807
  fs$5.writeFileSync(outPath, JSON.stringify(data, null, 2));
3410
3808
  };
3809
+
3411
3810
  const getDetaultVersion = () => {
3412
3811
  const version = moment().format('gggg,mm').split(',');
3413
3812
  version.push('0');
3414
3813
  return version.join('.');
3415
3814
  };
3815
+
3416
3816
  var utils = {
3417
3817
  getAllSize: getAllSize$2,
3418
3818
  getDesc: getDesc$3,
@@ -3443,13 +3843,12 @@ const {
3443
3843
  getDesc: getDesc$2
3444
3844
  } = utils;
3445
3845
  const report$4 = report_1;
3846
+
3446
3847
  const handleParams$2 = (tmsConfig, cmdOptions) => {
3447
- const params = {
3448
- ...(tmsConfig.preview ? tmsConfig.preview : {}),
3848
+ const params = { ...(tmsConfig.preview ? tmsConfig.preview : {}),
3449
3849
  ...cmdOptions
3450
3850
  };
3451
- return {
3452
- ...params,
3851
+ return { ...params,
3453
3852
  appId: params.appId || tmsConfig.appId,
3454
3853
  projectPath: resolve$7(tmsConfig.outputDir),
3455
3854
  privateKey: params.privateKey || tmsConfig.privateKey,
@@ -3458,18 +3857,22 @@ const handleParams$2 = (tmsConfig, cmdOptions) => {
3458
3857
  qrcodeOutputDest: getAbsolutePath$1(params.qrcodeOutputDest || '')
3459
3858
  };
3460
3859
  };
3461
-
3462
3860
  /**
3463
3861
  * 预览
3464
3862
  * @params {object} tmsConfig
3465
3863
  * @param {object} cmdOptions {qrcodeFormat: 'base64', qrcodeOutputDest: './a.txt', robot: 2, infoOutput: './a.txt' }
3466
3864
  */
3865
+
3866
+
3467
3867
  async function preview$1(tmsConfig, cmdOptions) {
3468
3868
  try {
3469
3869
  var _tmsConfig$hooks;
3870
+
3470
3871
  const params = handleParams$2(tmsConfig, cmdOptions);
3872
+
3471
3873
  if (typeof (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks = tmsConfig.hooks) === null || _tmsConfig$hooks === void 0 ? void 0 : _tmsConfig$hooks.beforePreview) === 'function') {
3472
3874
  var _tmsConfig$hooks2;
3875
+
3473
3876
  await (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks2 = tmsConfig.hooks) === null || _tmsConfig$hooks2 === void 0 ? void 0 : _tmsConfig$hooks2.beforePreview({
3474
3877
  tmsConfig: filterField$1(tmsConfig, ['gitAccount']),
3475
3878
  cmdOptions: global$2.getData('cmdOptions'),
@@ -3477,28 +3880,33 @@ async function preview$1(tmsConfig, cmdOptions) {
3477
3880
  }));
3478
3881
  report$4('hooks:beforePreview');
3479
3882
  }
3883
+
3480
3884
  ;
3481
- const previewRes = await createTask$3(mpCi$2.previewMp, '正在构建预览码', '构建预览码完成')({
3482
- ...params
3885
+ const previewRes = await createTask$3(mpCi$2.previewMp, '正在构建预览码', '构建预览码完成')({ ...params
3483
3886
  });
3484
3887
  const allSize = getAllSize$1(previewRes);
3888
+
3485
3889
  if (params.infoOutput) {
3486
3890
  let qrcodeBase64 = '';
3891
+
3487
3892
  if (params.qrcodeFormat === 'base64' && fs$4.existsSync(params.qrcodeOutputDest)) {
3488
3893
  qrcodeBase64 = fs$4.readFileSync(params.qrcodeOutputDest, 'utf8');
3489
3894
  }
3895
+
3490
3896
  outputInfo$1(params.infoOutput, {
3491
3897
  sourceCode: params.projectPath,
3492
3898
  qrcodeBase64,
3493
3899
  ...previewRes
3494
3900
  });
3495
3901
  }
3902
+
3496
3903
  info$7('预览包大小:', `${allSize}k`);
3497
3904
  } catch (e) {
3498
3905
  console.log('详细错误:', e);
3499
3906
  handleError$4(`预览错误: ${e.message}`, true);
3500
3907
  }
3501
3908
  }
3909
+
3502
3910
  var preview_1 = preview$1;
3503
3911
 
3504
3912
  const mpCi$1 = mpCi$3;
@@ -3522,16 +3930,17 @@ const {
3522
3930
  getDesc: getDesc$1
3523
3931
  } = utils;
3524
3932
  const report$3 = report_1;
3933
+
3525
3934
  const handleParams$1 = (tmsConfig, cmdOptions) => {
3526
- const params = {
3527
- ...(tmsConfig.upload ? tmsConfig.upload : {}),
3935
+ const params = { ...(tmsConfig.upload ? tmsConfig.upload : {}),
3528
3936
  ...cmdOptions
3529
3937
  };
3938
+
3530
3939
  if (!params.version) {
3531
3940
  throw new Error('请指定传入版本号 eg: tmskit run upload --version 2022.28.5');
3532
3941
  }
3533
- return {
3534
- ...params,
3942
+
3943
+ return { ...params,
3535
3944
  appId: params.appId || tmsConfig.appId,
3536
3945
  projectPath: resolve$6(tmsConfig.outputDir),
3537
3946
  privateKey: params.privateKey || tmsConfig.privateKey,
@@ -3539,18 +3948,22 @@ const handleParams$1 = (tmsConfig, cmdOptions) => {
3539
3948
  desc: params.desc || getDesc$1(params.desc)
3540
3949
  };
3541
3950
  };
3542
-
3543
3951
  /**
3544
3952
  * 上传
3545
3953
  * @param {object} tmsConfig
3546
3954
  * @param {object} cmdOptions {version: '2022.28.5', desc: '', robot: 2, infoOutput: './a.txt' }
3547
3955
  */
3956
+
3957
+
3548
3958
  async function upload$1(tmsConfig, cmdOptions) {
3549
3959
  try {
3550
3960
  var _tmsConfig$hooks;
3961
+
3551
3962
  const params = handleParams$1(tmsConfig, cmdOptions);
3963
+
3552
3964
  if (typeof (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks = tmsConfig.hooks) === null || _tmsConfig$hooks === void 0 ? void 0 : _tmsConfig$hooks.beforeUpload) === 'function') {
3553
3965
  var _tmsConfig$hooks2;
3966
+
3554
3967
  await (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks2 = tmsConfig.hooks) === null || _tmsConfig$hooks2 === void 0 ? void 0 : _tmsConfig$hooks2.beforeUpload({
3555
3968
  tmsConfig: filterField(tmsConfig, ['gitAccount']),
3556
3969
  cmdOptions: global$1.getData('cmdOptions'),
@@ -3558,23 +3971,26 @@ async function upload$1(tmsConfig, cmdOptions) {
3558
3971
  }));
3559
3972
  report$3('hooks:beforeUpload');
3560
3973
  }
3974
+
3561
3975
  ;
3562
- const uploadRes = await createTask$2(mpCi$1.uploadMp, '正在上传小程序代码', '上传小程序代码完成')({
3563
- ...params
3976
+ const uploadRes = await createTask$2(mpCi$1.uploadMp, '正在上传小程序代码', '上传小程序代码完成')({ ...params
3564
3977
  });
3565
3978
  const allSize = getAllSize(uploadRes);
3979
+
3566
3980
  if (params.infoOutput) {
3567
3981
  outputInfo(params.infoOutput, {
3568
3982
  sourceCode: params.projectPath,
3569
3983
  ...uploadRes
3570
3984
  });
3571
3985
  }
3986
+
3572
3987
  info$6(`上传包大小: ${allSize}k; 上传包版本: ${params.version}`);
3573
3988
  } catch (e) {
3574
3989
  console.log('详细错误:', e);
3575
3990
  handleError$3(`上传错误: ${e.message}`, true);
3576
3991
  }
3577
3992
  }
3993
+
3578
3994
  var upload_1 = upload$1;
3579
3995
 
3580
3996
  const mpCi = mpCi$3;
@@ -3592,9 +4008,9 @@ const {
3592
4008
  getDesc
3593
4009
  } = utils;
3594
4010
  const report$2 = report_1;
4011
+
3595
4012
  const handleParams = (tmsConfig, cmdOptions) => {
3596
- const params = {
3597
- ...(tmsConfig.upload ? tmsConfig.upload : {}),
4013
+ const params = { ...(tmsConfig.upload ? tmsConfig.upload : {}),
3598
4014
  ...cmdOptions
3599
4015
  };
3600
4016
  return {
@@ -3607,18 +4023,18 @@ const handleParams = (tmsConfig, cmdOptions) => {
3607
4023
  desc: params.desc || getDesc(params.desc)
3608
4024
  };
3609
4025
  };
3610
-
3611
4026
  /**
3612
4027
  * 获取sourcemap
3613
4028
  * @param {object} tmsConfig
3614
4029
  * @param {object} cmdOptions {version: '2022.28.5', desc: '', robot: 2, infoOutput: './a.txt' }
3615
4030
  */
4031
+
4032
+
3616
4033
  async function sourcemap$1(tmsConfig, cmdOptions) {
3617
4034
  try {
3618
4035
  const params = handleParams(tmsConfig, cmdOptions);
3619
4036
  report$2('sourcemap');
3620
- await createTask$1(mpCi.getDevSourceMap, '正在获取小程序代码sourcemap', '获取小程序代码sourcemap完成')({
3621
- ...params
4037
+ await createTask$1(mpCi.getDevSourceMap, '正在获取小程序代码sourcemap', '获取小程序代码sourcemap完成')({ ...params
3622
4038
  });
3623
4039
  info$5(`sourcemap文件已保存到${params.sourceMapSavePath}`);
3624
4040
  } catch (e) {
@@ -3626,27 +4042,28 @@ async function sourcemap$1(tmsConfig, cmdOptions) {
3626
4042
  handleError$2(`获取sourcemap错误: ${e.message}`, true);
3627
4043
  }
3628
4044
  }
4045
+
3629
4046
  var sourcemap_1 = sourcemap$1;
3630
4047
 
3631
4048
  const {
3632
4049
  resolve: resolve$4,
3633
4050
  getAbsolutePath
3634
- } = widgets;
4051
+ } = widgets; // 处理tms.config.cloudModules的兼容数据
3635
4052
 
3636
- // 处理tms.config.cloudModules的兼容数据
3637
4053
  function getTmsCloudModules(tmsConfig) {
3638
4054
  const {
3639
4055
  cloudModules
3640
4056
  } = tmsConfig;
4057
+
3641
4058
  if (Array.isArray(tmsConfig.cloudModules)) {
3642
4059
  return {
3643
4060
  all: [...tmsConfig.cloudModules],
3644
4061
  include: []
3645
4062
  };
3646
4063
  }
4064
+
3647
4065
  return cloudModules;
3648
4066
  }
3649
-
3650
4067
  /**
3651
4068
  * 获取需要监听的云函数
3652
4069
  * @param {*} tmsConfig {}
@@ -3654,17 +4071,21 @@ function getTmsCloudModules(tmsConfig) {
3654
4071
  * @returns
3655
4072
  * [{ name: '', sourcePath: '', targetPath: ''}]
3656
4073
  */
4074
+
4075
+
3657
4076
  function getCloudsOfListen$2(tmsConfig, cmdOptions) {
3658
4077
  var _cmdOptions$cloud;
4078
+
3659
4079
  // 获取tmsconfig配置的云函数的配置项
3660
4080
  const cloudModules = getTmsCloudModules(tmsConfig);
3661
- let includeClouds = (cmdOptions === null || cmdOptions === void 0 ? void 0 : (_cmdOptions$cloud = cmdOptions.cloud) === null || _cmdOptions$cloud === void 0 ? void 0 : _cmdOptions$cloud.split(',')) || cloudModules.include || [];
4081
+ let includeClouds = (cmdOptions === null || cmdOptions === void 0 ? void 0 : (_cmdOptions$cloud = cmdOptions.cloud) === null || _cmdOptions$cloud === void 0 ? void 0 : _cmdOptions$cloud.split(',')) || cloudModules.include || []; // 如果没有配置include, 默认使用所有的数据云函数列表
3662
4082
 
3663
- // 如果没有配置include, 默认使用所有的数据云函数列表
3664
4083
  if (includeClouds.length === 0) {
3665
4084
  includeClouds = cloudModules.all.map(item => item.name);
3666
4085
  }
4086
+
3667
4087
  const result = [];
4088
+
3668
4089
  for (const item of cloudModules.all) {
3669
4090
  if (includeClouds.includes(item.name)) {
3670
4091
  result.push({
@@ -3674,38 +4095,45 @@ function getCloudsOfListen$2(tmsConfig, cmdOptions) {
3674
4095
  });
3675
4096
  }
3676
4097
  }
4098
+
3677
4099
  return result;
3678
4100
  }
4101
+
3679
4102
  var getClouds = getCloudsOfListen$2;
3680
4103
 
3681
4104
  const fs$3 = require$$0__default$1;
3682
-
3683
4105
  /**
3684
4106
  * 检查云函数的配置项
3685
4107
  * @param {*} tmsConfig
3686
4108
  */
4109
+
3687
4110
  function checkCloudConfig$2(tmsConfig) {
3688
4111
  if (!tmsConfig.cloudModules) {
3689
4112
  return '你没有在tms.config.js的cloudModules注册云函数';
3690
4113
  }
4114
+
3691
4115
  if (!tmsConfig.cloudDir) {
3692
4116
  return '你没有在tms.config.js配置云函数编译目录cloudDir';
3693
4117
  }
4118
+
3694
4119
  return;
3695
4120
  }
3696
-
3697
4121
  /**
3698
4122
  * 检查云函数源码目录是否存在
3699
4123
  * @param {Array} clouds [{name: '', sourcePath: '', targetPath: ''}]
3700
4124
  */
4125
+
4126
+
3701
4127
  function checkSrcPathIsExist$1(clouds) {
3702
4128
  for (const item of clouds) {
3703
4129
  if (!fs$3.existsSync(item.sourcePath)) {
3704
4130
  return `${item.name}云函数的${item.sourcePath}目录不存在, 请检查tms.config.js>cloudModules>all云函数的配置目录`;
3705
4131
  }
3706
4132
  }
4133
+
3707
4134
  return;
3708
4135
  }
4136
+
3709
4137
  var check$2 = {
3710
4138
  checkCloudConfig: checkCloudConfig$2,
3711
4139
  checkSrcPathIsExist: checkSrcPathIsExist$1
@@ -3732,21 +4160,23 @@ const {
3732
4160
  const {
3733
4161
  checkCloudConfig: checkCloudConfig$1
3734
4162
  } = check$2;
4163
+
3735
4164
  var link = async (tmsConfig, cmdOptions) => {
3736
4165
  try {
3737
4166
  ensureDirExist$2(resolve$3(tmsConfig.cloudDir));
3738
- checkCloudConfig$1(tmsConfig);
4167
+ checkCloudConfig$1(tmsConfig); // 获取需要监听的云函数列表
4168
+
4169
+ const clouds = getCloudsOfListen$1(tmsConfig, cmdOptions); // 打印启动云函数列表
3739
4170
 
3740
- // 获取需要监听的云函数列表
3741
- const clouds = getCloudsOfListen$1(tmsConfig, cmdOptions);
3742
- // 打印启动云函数列表
3743
4171
  info$4('当前启动云函数列表:', clouds.map(item => item.name).sort());
3744
4172
  clouds.forEach(item => {
3745
4173
  if (!fs$2.existsSync(item.sourcePath)) {
3746
4174
  warn(`云函数${item.sourcePath}不存在`);
3747
4175
  return;
3748
4176
  }
4177
+
3749
4178
  const stat = fs$2.lstatSync(item.targetPath);
4179
+
3750
4180
  if (!stat.isSymbolicLink()) {
3751
4181
  fs$2.symlinkSync(item.sourcePath, item.targetPath);
3752
4182
  }
@@ -3770,16 +4200,18 @@ const {
3770
4200
  const {
3771
4201
  info: info$3
3772
4202
  } = log$1;
3773
-
3774
4203
  /**
3775
4204
  * npm install
3776
4205
  * @param {array} clouds [{name: '', sourcePath: '', targetPath: ''}]
3777
4206
  */
4207
+
3778
4208
  const runInstall$1 = async (clouds, tmsConfig) => {
3779
4209
  const promises = [];
4210
+
3780
4211
  for (const item of clouds) {
3781
4212
  ensureDirExist$1(item.targetPath);
3782
4213
  const packageFilePath = resolve$2(item.sourcePath, 'package.json');
4214
+
3783
4215
  if (fs$1.existsSync(packageFilePath)) {
3784
4216
  shellJs$1.cp('-Rf', resolve$2(packageFilePath), item.targetPath);
3785
4217
  promises.push(() => {
@@ -3790,6 +4222,7 @@ const runInstall$1 = async (clouds, tmsConfig) => {
3790
4222
  }
3791
4223
  await Promise.all(promises.map(item => item()));
3792
4224
  };
4225
+
3793
4226
  var install$1 = {
3794
4227
  runInstall: runInstall$1
3795
4228
  };
@@ -3827,13 +4260,13 @@ const {
3827
4260
  const {
3828
4261
  runInstall
3829
4262
  } = install$1;
3830
-
3831
4263
  /**
3832
4264
  * 获取云函数的编译任务
3833
4265
  * @param {array} clouds [{name: '', sourcePath: '', targetPath: ''}]
3834
4266
  * @param {object} srcOption gulp.src的参数
3835
4267
  * @returns Map {'${sourcePath}': {taskFn: () => {}, targetPath: 'xxx'}}
3836
4268
  */
4269
+
3837
4270
  const getCompileTasks = (clouds, srcOption) => {
3838
4271
  const compileTasksMap = new Map();
3839
4272
  clouds.forEach(item => {
@@ -3851,16 +4284,18 @@ const getCompileTasks = (clouds, srcOption) => {
3851
4284
  });
3852
4285
  return compileTasksMap;
3853
4286
  };
4287
+
3854
4288
  const getTargetFile = (sourceFile, sourcePath, targetPath) => {
3855
4289
  const sourceFileRelativeModule = path$1.relative(sourcePath, sourceFile);
3856
4290
  const targetFile = resolve$1(targetPath, sourceFileRelativeModule);
3857
4291
  return targetFile;
3858
4292
  };
3859
-
3860
4293
  /**
3861
4294
  * 开始启动编译
3862
4295
  * @param {Map} compileTasksMap {'${sourcePath}': {taskFn: () => {}, targetPath: 'xxx'}}
3863
4296
  */
4297
+
4298
+
3864
4299
  const runCompile = (compileTasksMap, callback) => {
3865
4300
  async function end(next) {
3866
4301
  // 监听其他文件
@@ -3876,16 +4311,16 @@ const runCompile = (compileTasksMap, callback) => {
3876
4311
  callback && callback();
3877
4312
  next();
3878
4313
  }
4314
+
3879
4315
  const compileTasksArr = [];
3880
4316
  compileTasksMap.forEach(({
3881
4317
  taskFn
3882
4318
  }) => {
3883
4319
  compileTasksArr.push(taskFn);
3884
- });
3885
- // 一次性完成编译任务(编译完成后再添加watch任务-封装到end函数里面)
4320
+ }); // 一次性完成编译任务(编译完成后再添加watch任务-封装到end函数里面)
4321
+
3886
4322
  series(parallel(...compileTasksArr), end)();
3887
4323
  };
3888
-
3889
4324
  /**
3890
4325
  * 监听文件变动
3891
4326
  * @param {*} sourcePath 云函数的源码目录
@@ -3893,53 +4328,55 @@ const runCompile = (compileTasksMap, callback) => {
3893
4328
  * @param {*} callback 监听到变动的回调
3894
4329
  * @param {*} targetPath 云函数的编译目录
3895
4330
  */
4331
+
4332
+
3896
4333
  const runWatch = (sourcePath, watchOptions, callback, targetPath) => {
3897
- watch(sourcePath, {
3898
- ...watchOptions
4334
+ watch(sourcePath, { ...watchOptions
3899
4335
  }, vinyl => {
3900
4336
  const sourceFile = vinyl.history[0];
3901
4337
  const sourceFileDirArr = sourceFile.replace(/\\/g, '/').split('/');
3902
4338
  const sourceFileName = sourceFileDirArr.slice(sourceFileDirArr.length - 2).join('/');
3903
4339
  const targetFile = getTargetFile(sourceFile, sourcePath, targetPath);
4340
+
3904
4341
  if (vinyl.event === 'unlink' || vinyl.event === 'unlinkDir') {
3905
4342
  info$2(`删除${sourceFileName}`);
3906
4343
  shellJs.rm('-rf', targetFile);
3907
4344
  return;
3908
4345
  }
4346
+
3909
4347
  info$2(`${sourceFileName}有更新`);
3910
4348
  return callback([sourceFile], path$1.dirname(targetFile));
3911
4349
  });
3912
4350
  };
4351
+
3913
4352
  var dev$1 = async (tmsConfig, cmdOptions) => {
3914
4353
  try {
3915
4354
  const sTime = new Date().getTime();
3916
4355
  const spinner = ora();
3917
- spinner.start();
4356
+ spinner.start(); // 检查云函数的配置项
3918
4357
 
3919
- // 检查云函数的配置项
3920
4358
  const configErrMsg = checkCloudConfig(tmsConfig);
4359
+
3921
4360
  if (configErrMsg) {
3922
4361
  throw new Error(configErrMsg);
3923
- }
4362
+ } // 确保云函数的编译目录存在
3924
4363
 
3925
- // 确保云函数的编译目录存在
3926
- ensureDirExist(resolve$1(tmsConfig.cloudDir));
3927
4364
 
3928
- // 获取需要监听的云函数列表
3929
- const clouds = getCloudsOfListen(tmsConfig, cmdOptions);
3930
- // 检查云函数源码目录是否存在
4365
+ ensureDirExist(resolve$1(tmsConfig.cloudDir)); // 获取需要监听的云函数列表
4366
+
4367
+ const clouds = getCloudsOfListen(tmsConfig, cmdOptions); // 检查云函数源码目录是否存在
4368
+
3931
4369
  const srcNotExistErrMsg = checkSrcPathIsExist(clouds);
4370
+
3932
4371
  if (srcNotExistErrMsg) {
3933
4372
  throw new Error(srcNotExistErrMsg);
3934
- }
4373
+ } // 打印启动云函数列表
3935
4374
 
3936
- // 打印启动云函数列表
3937
- info$2('当前启动云函数列表:', clouds.map(item => item.name).sort());
3938
4375
 
3939
- // npm install
3940
- await createTask(runInstall, '开始npm install', 'npm install完成')(clouds, tmsConfig);
4376
+ info$2('当前启动云函数列表:', clouds.map(item => item.name).sort()); // npm install
4377
+
4378
+ await createTask(runInstall, '开始npm install', 'npm install完成')(clouds, tmsConfig); // 获取云函数列表的编译任务
3941
4379
 
3942
- // 获取云函数列表的编译任务
3943
4380
  const compileTasksMap = getCompileTasks(clouds, {
3944
4381
  allowEmpty: true
3945
4382
  });
@@ -3978,11 +4415,13 @@ const {
3978
4415
  getSubPackages,
3979
4416
  getModulesByModuleNames
3980
4417
  } = tmsMpconfig.exports;
4418
+
3981
4419
  const handleModuleArg = cmdOptions => {
3982
4420
  // 单模块或多模块开发-用户通过脚手架参数指定的模块
3983
4421
  if (typeof cmdOptions.module === 'string') {
3984
4422
  return cmdOptions.module.split(',');
3985
4423
  }
4424
+
3986
4425
  return [];
3987
4426
  };
3988
4427
  /**
@@ -3991,38 +4430,47 @@ const handleModuleArg = cmdOptions => {
3991
4430
  * @param {Object} modulePrivateCfg 私有配置里的模块
3992
4431
  * @param {Array} moduleAll 当前小程序全部模块
3993
4432
  */
4433
+
4434
+
3994
4435
  const getSpecificModuleNames = (moduleArg, modules) => {
3995
4436
  if (moduleArg.length > 0) {
3996
4437
  return moduleArg;
3997
4438
  }
4439
+
3998
4440
  const {
3999
4441
  all,
4000
4442
  include,
4001
4443
  exclude,
4002
4444
  blockRemote
4003
- } = modules;
4004
- // 单模块或多模块开发-用户在tms.private.js指定的模块
4445
+ } = modules; // 单模块或多模块开发-用户在tms.private.js指定的模块
4446
+
4005
4447
  if ((include === null || include === void 0 ? void 0 : include.length) > 0) {
4006
4448
  return include;
4007
4449
  }
4450
+
4008
4451
  if ((exclude === null || exclude === void 0 ? void 0 : exclude.length) > 0) {
4009
4452
  return all.filter(module => !exclude.includes(module.moduleName)).map(item => item.moduleName);
4010
4453
  }
4454
+
4011
4455
  if (blockRemote === true) {
4012
4456
  return all.filter(module => module.repoInfo === undefined).map(item => item.moduleName);
4013
4457
  }
4458
+
4014
4459
  return all.map(item => item.moduleName);
4015
4460
  };
4461
+
4016
4462
  async function run(commandName, cmdOptions) {
4017
- global.setData('commandName', commandName);
4018
- // 用户本地的配置
4463
+ global.setData('commandName', commandName); // 用户本地的配置
4464
+
4019
4465
  const tmsConfig = getTmsConfig$1();
4466
+
4020
4467
  try {
4021
4468
  // 缓存数据
4022
4469
  global.setData({
4023
4470
  cmdOptions,
4024
4471
  tmsConfig
4025
4472
  });
4473
+
4026
4474
  if (commandName === 'cloud-link') {
4027
4475
  cloudLink(tmsConfig, cmdOptions);
4028
4476
  report$1('run:cloud-link', {
@@ -4030,6 +4478,7 @@ async function run(commandName, cmdOptions) {
4030
4478
  });
4031
4479
  return;
4032
4480
  }
4481
+
4033
4482
  if (commandName === 'cloud-dev') {
4034
4483
  cloudDev(tmsConfig, cmdOptions);
4035
4484
  report$1('run:cloud-dev', {
@@ -4037,6 +4486,7 @@ async function run(commandName, cmdOptions) {
4037
4486
  });
4038
4487
  return;
4039
4488
  }
4489
+
4040
4490
  otherCommands(tmsConfig, commandName, cmdOptions);
4041
4491
  } catch (error) {
4042
4492
  const errMsg = typeof error === 'object' ? error.message : error;
@@ -4049,18 +4499,18 @@ async function run(commandName, cmdOptions) {
4049
4499
  process.exit(1);
4050
4500
  }
4051
4501
  }
4502
+
4052
4503
  function otherCommands(tmsConfig, commandName, cmdOptions) {
4053
4504
  // 处理module参数
4054
- const specificModuleNames = getSpecificModuleNames(handleModuleArg(cmdOptions), tmsConfig.modules);
4505
+ const specificModuleNames = getSpecificModuleNames(handleModuleArg(cmdOptions), tmsConfig.modules); // moduleNames => ['home', 'car']
4055
4506
 
4056
- // moduleNames => ['home', 'car']
4057
4507
  const moduleNames = [...new Set([...specificModuleNames])];
4058
- const modules = getModulesByModuleNames(tmsConfig, moduleNames, false);
4508
+ const modules = getModulesByModuleNames(tmsConfig, moduleNames, false); // 获取所有模块,合并模块依赖的模块
4509
+
4510
+ const newModules = getModulesByMergeDepModules(tmsConfig, modules, false); // 获取所有的分包
4059
4511
 
4060
- // 获取所有模块,合并模块依赖的模块
4061
- const newModules = getModulesByMergeDepModules(tmsConfig, modules, false);
4062
- // 获取所有的分包
4063
4512
  const subPackages = getSubPackages(newModules);
4513
+
4064
4514
  switch (commandName) {
4065
4515
  case 'init':
4066
4516
  init(tmsConfig, newModules);
@@ -4068,6 +4518,7 @@ function otherCommands(tmsConfig, commandName, cmdOptions) {
4068
4518
  appName: tmsConfig.appName
4069
4519
  });
4070
4520
  return;
4521
+
4071
4522
  case 'dev':
4072
4523
  global.setData('isDev', true);
4073
4524
  dev(tmsConfig, newModules);
@@ -4075,12 +4526,14 @@ function otherCommands(tmsConfig, commandName, cmdOptions) {
4075
4526
  appName: tmsConfig.appName
4076
4527
  });
4077
4528
  return;
4529
+
4078
4530
  case 'install':
4079
4531
  install(tmsConfig, subPackages, false);
4080
4532
  report$1('run:install', {
4081
4533
  appName: tmsConfig.appName
4082
4534
  });
4083
4535
  return;
4536
+
4084
4537
  case 'build':
4085
4538
  global.setData('isDev', false);
4086
4539
  build(tmsConfig, newModules);
@@ -4088,28 +4541,33 @@ function otherCommands(tmsConfig, commandName, cmdOptions) {
4088
4541
  appName: tmsConfig.appName
4089
4542
  });
4090
4543
  return;
4544
+
4091
4545
  case 'preview':
4092
4546
  preview(tmsConfig, cmdOptions);
4093
4547
  report$1('run:preview', {
4094
4548
  appName: tmsConfig.appName
4095
4549
  });
4096
4550
  return;
4551
+
4097
4552
  case 'upload':
4098
4553
  upload(tmsConfig, cmdOptions);
4099
4554
  report$1('run:upload', {
4100
4555
  appName: tmsConfig.appName
4101
4556
  });
4102
4557
  return;
4558
+
4103
4559
  case 'sourcemap':
4104
4560
  sourcemap(tmsConfig);
4105
4561
  report$1('run:sourcemap', {
4106
4562
  appName: tmsConfig.appName
4107
4563
  });
4108
4564
  return;
4565
+
4109
4566
  default:
4110
4567
  return;
4111
4568
  }
4112
4569
  }
4570
+
4113
4571
  var run_1 = run;
4114
4572
 
4115
4573
  var entry = [{
@@ -4179,8 +4637,7 @@ var entry = [{
4179
4637
  action: cmdOptions => {
4180
4638
  run_1('cloud-dev', cmdOptions);
4181
4639
  }
4182
- }
4183
- // {
4640
+ } // {
4184
4641
  // command: 'cloud-link',
4185
4642
  // description: '云函数开发',
4186
4643
  // options: [
@@ -4195,7 +4652,7 @@ var entry = [{
4195
4652
 
4196
4653
  var require$$12 = {
4197
4654
  name: "@tmsfe/tmskit",
4198
- version: "0.0.48",
4655
+ version: "0.0.52",
4199
4656
  description: "tmskit",
4200
4657
  main: "dist/index.cjs",
4201
4658
  bin: {
@@ -4254,7 +4711,7 @@ var require$$12 = {
4254
4711
  lodash: "^4.17.21",
4255
4712
  metalsmith: "^2.3.0",
4256
4713
  minimatch: "^5.1.0",
4257
- "miniprogram-ci": "2.1.14",
4714
+ "miniprogram-ci": "1.8.25",
4258
4715
  moment: "^2.29.2",
4259
4716
  "object-assign": "^4.0.1",
4260
4717
  ora: "^5.4.1",
@@ -4290,13 +4747,13 @@ const {
4290
4747
  } = log$1;
4291
4748
  const requiredVersion = packageJson.engines.node;
4292
4749
  const packName = packageJson.name;
4293
-
4294
4750
  /**
4295
4751
  * 检查node版本
4296
4752
  * @param {String} wanted 希望的node版本
4297
4753
  * @param {String} id 某node特性
4298
4754
  * @returns {Undefined} 无需返回值
4299
4755
  */
4756
+
4300
4757
  const checkNodeVersion = (wanted, id) => {
4301
4758
  if (!semver.satisfies(process.version, wanted, {
4302
4759
  includePrerelease: true
@@ -4305,15 +4762,17 @@ const checkNodeVersion = (wanted, id) => {
4305
4762
  process.exit(1);
4306
4763
  }
4307
4764
  };
4308
-
4309
4765
  /**
4310
4766
  * 检查运行环境
4311
4767
  */
4768
+
4769
+
4312
4770
  function check$1() {
4313
4771
  // 执行操作前检查node版本
4314
4772
  // 旧版本node直接提示升级,退出脚本
4315
4773
  checkNodeVersion(requiredVersion, packName);
4316
4774
  }
4775
+
4317
4776
  var check_1 = check$1;
4318
4777
 
4319
4778
  /* eslint-disable no-param-reassign */
@@ -4341,9 +4800,8 @@ const {
4341
4800
  const report = report_1;
4342
4801
  check();
4343
4802
  const program = new commander.Command(TMS_NAME);
4344
- program.version(`${TMS_NAME} ${require$$12.version}`, '-v, -V, --version');
4803
+ program.version(`${TMS_NAME} ${require$$12.version}`, '-v, -V, --version'); // 注册命令底层实现
4345
4804
 
4346
- // 注册命令底层实现
4347
4805
  function registerCommand(program, commands) {
4348
4806
  commands.forEach(cmd => {
4349
4807
  if (cmd.type === 'parent') {
@@ -4354,53 +4812,56 @@ function registerCommand(program, commands) {
4354
4812
  program.addCommand(childProgram);
4355
4813
  } else {
4356
4814
  var _cmd$options;
4815
+
4357
4816
  const command = program.command(cmd.command);
4358
4817
  cmd.usage && command.usage(cmd.usage);
4359
4818
  cmd.description && command.description(cmd.description);
4360
- (_cmd$options = cmd.options) === null || _cmd$options === void 0 ? void 0 : _cmd$options.forEach(opt => command.option(...opt));
4361
- // 上报
4819
+ (_cmd$options = cmd.options) === null || _cmd$options === void 0 ? void 0 : _cmd$options.forEach(opt => command.option(...opt)); // 上报
4820
+
4362
4821
  command.hook('preAction', thisCommand => {
4363
4822
  report(`${thisCommand._name}-pre`);
4364
- });
4365
- // 上报
4823
+ }); // 上报
4824
+
4366
4825
  command.hook('postAction', thisCommand => {
4367
4826
  report(`${thisCommand._name}-post`);
4368
4827
  });
4369
4828
  command.action(cmd.action);
4370
4829
  }
4371
4830
  });
4372
- }
4831
+ } // 注册扩展命令
4832
+
4373
4833
 
4374
- // 注册扩展命令
4375
4834
  function registerExtendCommand(program, configPath) {
4376
4835
  const tmsConfig = getTmsConfig(configPath);
4836
+
4377
4837
  if (tmsConfig !== null && tmsConfig !== void 0 && tmsConfig.commands) {
4378
4838
  const commands = typeof tmsConfig.commands === 'function' ? tmsConfig.commands() : tmsConfig.commands;
4839
+
4379
4840
  if (Array.isArray(commands)) {
4380
4841
  registerCommand(program, commands);
4381
4842
  }
4382
4843
  }
4383
- }
4384
- // 注册所有的命令
4844
+ } // 注册所有的命令
4845
+
4846
+
4385
4847
  function registerAllCmds(program, commands) {
4386
4848
  // 注册脚手架内部命令
4387
- registerCommand(program, commands);
4849
+ registerCommand(program, commands); // 注册npm包扩展命令
4388
4850
 
4389
- // 注册npm包扩展命令
4390
4851
  const cmdConfigs = loadExtendCmd();
4391
4852
  cmdConfigs.forEach(cmdConfig => {
4392
4853
  registerExtendCommand(program, path.dirname(cmdConfig));
4393
- });
4854
+ }); // 注册当前目录扩展命令
4394
4855
 
4395
- // 注册当前目录扩展命令
4396
4856
  const tmsConfigPath = resolve('./tms.config.js');
4857
+
4397
4858
  if (fs.existsSync(tmsConfigPath)) {
4398
4859
  registerExtendCommand(program, path.dirname(tmsConfigPath));
4399
4860
  }
4400
4861
  }
4401
- registerAllCmds(program, commands);
4402
4862
 
4403
- // 捕获未注册的命令
4863
+ registerAllCmds(program, commands); // 捕获未注册的命令
4864
+
4404
4865
  program.arguments('<command>').option('-c, --config <value>', '配置', value => {
4405
4866
  // 注册指定配置的扩展命令
4406
4867
  registerExtendCommand(program, path.dirname(resolve(value)));
@@ -4415,10 +4876,12 @@ program.arguments('<command>').option('-c, --config <value>', '配置', value =>
4415
4876
  program.on('--help', () => {
4416
4877
  infoNoTime(`Run ${chalk.cyan(`${TMS_NAME} <command> --help`)} for detailed usage of given command.`);
4417
4878
  });
4879
+
4418
4880
  if (!process.argv.slice(2).length) {
4419
4881
  program.outputHelp();
4420
4882
  process.exit(-1);
4421
4883
  }
4884
+
4422
4885
  program.parse(process.argv);
4423
4886
  var src = src$3;
4424
4887