@tmsfe/tmskit 0.0.20 → 0.0.23

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
@@ -1,101 +1,84 @@
1
1
  'use strict';
2
2
 
3
- var require$$0 = require('chalk');
3
+ var require$$3 = require('chalk');
4
4
  var require$$1 = require('moment');
5
- var require$$0$1 = require('commander');
6
- var require$$1$1 = require('leven');
7
- var require$$2 = require('ora');
8
- var require$$1$2 = require('path');
9
- var require$$0$2 = require('fs');
10
- var require$$0$3 = require('shelljs');
11
- var require$$6 = require('glob-ignore');
12
- var require$$0$4 = require('async');
5
+ var require$$0 = require('ora');
6
+ var require$$1$1 = require('path');
7
+ var require$$0$1 = require('fs');
8
+ var require$$2 = require('shelljs');
9
+ var require$$4 = require('glob-ignore');
10
+ var require$$1$2 = require('os');
11
+ var require$$0$2 = require('lodash');
12
+ var require$$0$3 = require('async');
13
13
  var require$$1$3 = require('ejs');
14
14
  var require$$1$4 = require('inquirer');
15
- var require$$0$5 = require('metalsmith');
16
- var require$$9 = require('request');
15
+ var require$$0$4 = require('metalsmith');
16
+ var require$$0$5 = require('request');
17
17
  var require$$10 = require('unzipper');
18
- var require$$0$6 = require('lodash');
19
18
  var require$$1$5 = require('crypto');
20
- var require$$0$7 = require('miniprogram-ci');
19
+ var require$$0$6 = require('miniprogram-ci');
21
20
  var require$$1$6 = require('fs-extra');
22
21
  var require$$1$7 = require('semver');
23
- var require$$0$8 = require('strip-comments');
24
- var require$$0$9 = require('through2');
25
- var require$$1$8 = require('precinct');
26
- var require$$1$9 = require('htmlparser2');
27
- var require$$0$a = require('gulp');
28
- var require$$0$b = require('object-assign');
29
- var require$$3 = require('fancy-log');
22
+ var require$$0$7 = require('gulp');
23
+ var require$$2$1 = require('minimatch');
24
+ var require$$3$1 = require('gulp-if');
25
+ var require$$6 = require('through2');
26
+ var require$$0$8 = require('object-assign');
27
+ var require$$3$2 = require('fancy-log');
30
28
  var require$$4$1 = require('ansi-colors');
31
29
  var require$$5 = require('chokidar');
32
30
  var require$$6$1 = require('readable-stream');
33
- var require$$7$1 = require('vinyl-file');
31
+ var require$$7 = require('vinyl-file');
34
32
  var require$$8 = require('vinyl');
35
- var require$$9$1 = require('anymatch');
33
+ var require$$9 = require('anymatch');
36
34
  var require$$11 = require('glob-parent');
37
- var require$$2$1 = require('plugin-error');
35
+ var require$$2$2 = require('plugin-error');
38
36
  var require$$10$1 = require('path-is-absolute');
39
- var require$$12 = require('slash');
37
+ var require$$12$1 = require('slash');
38
+ var require$$1$8 = require('commander');
40
39
 
41
40
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
42
41
 
43
- var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
42
+ var require$$3__default = /*#__PURE__*/_interopDefaultLegacy(require$$3);
44
43
  var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1);
45
- var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
44
+ var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
46
45
  var require$$1__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$1$1);
46
+ var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
47
47
  var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2);
48
+ var require$$4__default = /*#__PURE__*/_interopDefaultLegacy(require$$4);
48
49
  var require$$1__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$1$2);
49
50
  var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$2);
50
51
  var require$$0__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$0$3);
51
- var require$$6__default = /*#__PURE__*/_interopDefaultLegacy(require$$6);
52
- var require$$0__default$4 = /*#__PURE__*/_interopDefaultLegacy(require$$0$4);
53
52
  var require$$1__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$1$3);
54
53
  var require$$1__default$4 = /*#__PURE__*/_interopDefaultLegacy(require$$1$4);
54
+ var require$$0__default$4 = /*#__PURE__*/_interopDefaultLegacy(require$$0$4);
55
55
  var require$$0__default$5 = /*#__PURE__*/_interopDefaultLegacy(require$$0$5);
56
- var require$$9__default = /*#__PURE__*/_interopDefaultLegacy(require$$9);
57
56
  var require$$10__default = /*#__PURE__*/_interopDefaultLegacy(require$$10);
58
- var require$$0__default$6 = /*#__PURE__*/_interopDefaultLegacy(require$$0$6);
59
57
  var require$$1__default$5 = /*#__PURE__*/_interopDefaultLegacy(require$$1$5);
60
- var require$$0__default$7 = /*#__PURE__*/_interopDefaultLegacy(require$$0$7);
58
+ var require$$0__default$6 = /*#__PURE__*/_interopDefaultLegacy(require$$0$6);
61
59
  var require$$1__default$6 = /*#__PURE__*/_interopDefaultLegacy(require$$1$6);
62
60
  var require$$1__default$7 = /*#__PURE__*/_interopDefaultLegacy(require$$1$7);
61
+ var require$$0__default$7 = /*#__PURE__*/_interopDefaultLegacy(require$$0$7);
62
+ var require$$2__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$2$1);
63
+ var require$$3__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$3$1);
64
+ var require$$6__default = /*#__PURE__*/_interopDefaultLegacy(require$$6);
63
65
  var require$$0__default$8 = /*#__PURE__*/_interopDefaultLegacy(require$$0$8);
64
- var require$$0__default$9 = /*#__PURE__*/_interopDefaultLegacy(require$$0$9);
65
- var require$$1__default$8 = /*#__PURE__*/_interopDefaultLegacy(require$$1$8);
66
- var require$$1__default$9 = /*#__PURE__*/_interopDefaultLegacy(require$$1$9);
67
- var require$$0__default$a = /*#__PURE__*/_interopDefaultLegacy(require$$0$a);
68
- var require$$0__default$b = /*#__PURE__*/_interopDefaultLegacy(require$$0$b);
69
- var require$$3__default = /*#__PURE__*/_interopDefaultLegacy(require$$3);
70
- var require$$4__default = /*#__PURE__*/_interopDefaultLegacy(require$$4$1);
66
+ var require$$3__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$3$2);
67
+ var require$$4__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$4$1);
71
68
  var require$$5__default = /*#__PURE__*/_interopDefaultLegacy(require$$5);
72
69
  var require$$6__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$6$1);
73
- var require$$7__default = /*#__PURE__*/_interopDefaultLegacy(require$$7$1);
70
+ var require$$7__default = /*#__PURE__*/_interopDefaultLegacy(require$$7);
74
71
  var require$$8__default = /*#__PURE__*/_interopDefaultLegacy(require$$8);
75
- var require$$9__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$9$1);
72
+ var require$$9__default = /*#__PURE__*/_interopDefaultLegacy(require$$9);
76
73
  var require$$11__default = /*#__PURE__*/_interopDefaultLegacy(require$$11);
77
- var require$$2__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$2$1);
74
+ var require$$2__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$2$2);
78
75
  var require$$10__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$10$1);
79
- var require$$12__default = /*#__PURE__*/_interopDefaultLegacy(require$$12);
80
-
81
- function getAugmentedNamespace(n) {
82
- if (n.__esModule) return n;
83
- var a = Object.defineProperty({}, '__esModule', {value: true});
84
- Object.keys(n).forEach(function (k) {
85
- var d = Object.getOwnPropertyDescriptor(n, k);
86
- Object.defineProperty(a, k, d.get ? d : {
87
- enumerable: true,
88
- get: function () {
89
- return n[k];
90
- }
91
- });
92
- });
93
- return a;
94
- }
76
+ var require$$12__default = /*#__PURE__*/_interopDefaultLegacy(require$$12$1);
77
+ var require$$1__default$8 = /*#__PURE__*/_interopDefaultLegacy(require$$1$8);
95
78
 
96
79
  var src$2 = {};
97
80
 
98
- const chalk$4 = require$$0__default;
81
+ const chalk$4 = require$$3__default;
99
82
  const moment = require$$1__default;
100
83
  /**
101
84
  * 本文件提供无依赖的在终端打印彩色文字的方法。
@@ -109,7 +92,7 @@ const resetCfg = decodeURIComponent('%1B%5B0m'); // \033[0m转义后的字符按
109
92
  * @returns {undefined} 无
110
93
  */
111
94
 
112
- const fail$a = (message = '') => {
95
+ const fail$9 = (message = '') => {
113
96
  const redStyleConfig = decodeURIComponent('%1B%5B41%3B30m'); // \033[41;30m转义后的字符按,console时输出红色文字
114
97
 
115
98
  const greenFontStyleConfig = decodeURIComponent('%1B%5B41%3B37m'); // \033[41;30m转义后的字符按,console时输出红底白色文字
@@ -143,24 +126,24 @@ const warn$2 = message => {
143
126
 
144
127
  const info$d = (...args) => console.log(`${moment().format('YYYY-MM-DD HH:mm:ss')}`, ...args);
145
128
 
129
+ const infoNoTime$2 = (...args) => console.log(...args);
130
+
146
131
  var log$1 = {
147
- fail: fail$a,
132
+ fail: fail$9,
148
133
  succeed: succeed$2,
149
134
  warn: warn$2,
150
- info: info$d
135
+ info: info$d,
136
+ infoNoTime: infoNoTime$2
151
137
  };
152
138
 
153
- const program$1 = require$$0__default$1;
154
- const leven = require$$1__default$1;
155
- const ora$1 = require$$2__default;
156
- const path$e = require$$1__default$2;
157
- const fs$g = require$$0__default$2;
158
- const shelljs$7 = require$$0__default$3;
159
- const glob$1 = require$$6__default;
139
+ const ora$1 = require$$0__default;
140
+ const path$f = require$$1__default$1;
141
+ const fs$g = require$$0__default$1;
142
+ const shelljs$9 = require$$2__default;
143
+ const glob = require$$4__default;
160
144
  const {
161
145
  info: info$c
162
146
  } = log$1;
163
- const chalk$3 = require$$0__default;
164
147
  const shelljsOptions = {
165
148
  slient: true,
166
149
  async: false
@@ -168,37 +151,15 @@ const shelljsOptions = {
168
151
 
169
152
  const cwd = process.cwd();
170
153
 
171
- function resolve$f(...args) {
172
- return path$e.resolve(cwd, ...args);
154
+ function resolve$e(...args) {
155
+ return path$f.resolve(cwd, ...args);
173
156
  }
174
- /**
175
- * 用户输入命令时,进行提示
176
- * @param {String} unknownCommand 非预期的命令
177
- * @returns {Undefined} 无需返回值
178
- */
179
-
180
- const suggestCommands$1 = unknownCommand => {
181
- const availableCommands = program$1.commands.map(cmd => cmd._name);
182
- let suggestion;
183
- availableCommands.forEach(cmd => {
184
- const isBestMatch = leven(cmd, unknownCommand) < leven(suggestion || '', unknownCommand);
185
-
186
- if (leven(cmd, unknownCommand) < 3 && isBestMatch) {
187
- suggestion = cmd;
188
- }
189
- });
190
-
191
- if (suggestion) {
192
- info$c(` ${chalk$3.red(`Did you mean ${chalk$3.yellow(suggestion)}?`)}`);
193
- }
194
- };
195
157
  /**
196
158
  * 判断变量是否是一个数组
197
159
  * @param { unknown } obj 变量
198
160
  * @returns { boolean } 是否是一个数组
199
161
  */
200
162
 
201
-
202
163
  function isObject(obj) {
203
164
  return Object.prototype.toString.call(obj) === '[object Object]';
204
165
  }
@@ -226,19 +187,19 @@ function downloadRepoForGit$1(url, dest, branch) {
226
187
  return new Promise((resolve, reject) => {
227
188
  // 如果目标目录不存在
228
189
  if (fs$g.existsSync(dest)) {
229
- shelljs$7.rm('-rf', path$e.join(dest));
190
+ shelljs$9.rm('-rf', path$f.join(dest));
230
191
  }
231
192
 
232
- shelljs$7.mkdir('-p', dest);
233
- shelljs$7.cd(dest);
234
- shelljs$7.exec(`git clone ${url} ${dest} --branch ${branch} --depth 1`, {
193
+ shelljs$9.mkdir('-p', dest);
194
+ shelljs$9.cd(dest);
195
+ shelljs$9.exec(`git clone ${url} ${dest} --branch ${branch} --depth 1`, {
235
196
  silent: true
236
197
  }, (code, stdout, stderr) => {
237
198
  if (code !== 0) {
238
199
  reject(stderr);
239
200
  }
240
201
 
241
- shelljs$7.cd(cwd);
202
+ shelljs$9.cd(cwd);
242
203
  resolve();
243
204
  });
244
205
  });
@@ -254,30 +215,32 @@ function downloadRepoForGit$1(url, dest, branch) {
254
215
  function pullRepoForGit$1(dest, branch) {
255
216
  const cwd = process.cwd();
256
217
  return new Promise((resolve, reject) => {
257
- shelljs$7.cd(dest);
258
- shelljs$7.exec('git config pull.rebase false', shelljsOptions);
259
- shelljs$7.exec(`git pull origin ${branch}`, {
218
+ shelljs$9.cd(dest);
219
+ shelljs$9.exec('git config pull.rebase false', shelljsOptions);
220
+ shelljs$9.exec(`git pull origin ${branch}`, {
260
221
  silent: true
261
222
  }, (code, stdout, stderr) => {
262
223
  if (code !== 0) {
263
224
  reject(stderr);
264
225
  }
265
226
 
266
- shelljs$7.cd(cwd);
227
+ shelljs$9.cd(cwd);
267
228
  resolve();
268
229
  });
269
230
  });
270
231
  }
271
232
  /**
272
233
  * npm 下载依赖
273
- * @param {*} dir
234
+ * @param {string} dir 下载npm的目录
235
+ * @param {object} npm npm的配置 (见下获取npm源入参)
274
236
  * @returns
275
237
  */
276
238
 
277
239
 
278
- function npmInstall$2(dir) {
240
+ function npmInstall$2(dir, npmConfig) {
279
241
  return new Promise((resolve, reject) => {
280
- shelljs$7.exec('npm install --production --registry http://mirrors.tencent.com/npm/', {
242
+ const registry = getNpmRegistry(npmConfig);
243
+ shelljs$9.exec(`npm install --production ${registry}`, {
281
244
  cwd: dir,
282
245
  silent: true
283
246
  }, (code, stdout, stderr) => {
@@ -288,6 +251,30 @@ function npmInstall$2(dir) {
288
251
  resolve();
289
252
  });
290
253
  });
254
+ } // 获取npm源
255
+ // 入参:{
256
+ // registry: "https://registry.npmjs.org/",
257
+ // scope: {
258
+ // "@tencent": "http://mirrors.tencent.com/npm/"
259
+ // }
260
+ // }
261
+ // 出参: --@tencent:registry=http://mirrors.tencent.com/npm/ --registry=https://registry.npmjs.org/
262
+
263
+
264
+ function getNpmRegistry(npmConfig = {}) {
265
+ let resRegistry = '';
266
+
267
+ if (npmConfig.registry) {
268
+ resRegistry = ` --registry=${npmConfig.registry}`;
269
+ }
270
+
271
+ if (isObject(npmConfig.scope)) {
272
+ Object.keys(npmConfig.scope).forEach(key => {
273
+ resRegistry += ` --${key}:registry=${npmConfig.scope[key]}`;
274
+ });
275
+ }
276
+
277
+ return resRegistry;
291
278
  }
292
279
  /**
293
280
  * 计算各项任务耗时
@@ -306,7 +293,7 @@ const cost = start => Date.now() - start;
306
293
  */
307
294
 
308
295
 
309
- function createTask$2(task, startText, endText) {
296
+ function createTask$3(task, startText, endText) {
310
297
  return async (...args) => {
311
298
  const start = Date.now();
312
299
  const spinner = ora$1();
@@ -328,18 +315,14 @@ const camelize = str => str.replace(/-(\w)/g, (a, c) => c ? c.toUpperCase() : ''
328
315
 
329
316
  const mergeMap$1 = function (obj, src) {
330
317
  for (const [k, v] of src) {
331
- if (obj.has(k)) {
332
- obj.set(k, obj.get(k) + v);
333
- } else {
334
- obj.set(k, v);
335
- }
318
+ obj.set(k, v);
336
319
  }
337
320
 
338
321
  return obj;
339
322
  };
340
323
 
341
324
  const relativeCwdPath$1 = function (file) {
342
- return path$e.relative(process.cwd(), file);
325
+ return path$f.relative(process.cwd(), file);
343
326
  };
344
327
  /**
345
328
  * 从一个对象中,检索出去几个字段
@@ -349,7 +332,7 @@ const relativeCwdPath$1 = function (file) {
349
332
  */
350
333
 
351
334
 
352
- const filterField$4 = (obj, filterNames = []) => {
335
+ const filterField$5 = (obj, filterNames = []) => {
353
336
  const newObj = { ...obj
354
337
  };
355
338
  filterNames.forEach(name => {
@@ -363,7 +346,7 @@ const filterField$4 = (obj, filterNames = []) => {
363
346
 
364
347
  function findFiles(globPath, filter = []) {
365
348
  return new Promise((resolve, reject) => {
366
- glob$1(globPath, filter, (err, files) => {
349
+ glob(globPath, filter, (err, files) => {
367
350
  if (err) {
368
351
  reject(err);
369
352
  }
@@ -371,40 +354,79 @@ function findFiles(globPath, filter = []) {
371
354
  resolve(files);
372
355
  });
373
356
  });
357
+ } // 获取绝对路径
358
+
359
+
360
+ function getAbsolutePath$3(pathDir, cwd = '') {
361
+ let newPath = pathDir;
362
+ newPath = newPath.startsWith('/') ? newPath : resolve$e(cwd, newPath);
363
+ newPath = newPath.endsWith('/') ? newPath.slice(0, newPath.length - 1) : newPath;
364
+ return newPath;
365
+ } // 版本比较 => 1(大于), 0(等于), -1(小于)
366
+
367
+
368
+ function versionCompare$1(v1, v2) {
369
+ // 将两个版本号拆成数组
370
+ const arr1 = v1.split('.');
371
+ const arr2 = v2.split('.');
372
+ const minLength = Math.min(arr1.length, arr2.length); // 依次比较版本号每一位大小
373
+
374
+ for (let i = 0; i < minLength; i++) {
375
+ if (parseInt(arr1[i], 10) !== parseInt(arr2[i], 10)) {
376
+ return parseInt(arr1[i], 10) > parseInt(arr2[i], 10) ? 1 : -1;
377
+ }
378
+ } // 若前几位分隔相同,则按分隔数比较。
379
+
380
+
381
+ if (arr1.length === arr2.length) {
382
+ return 0;
383
+ }
384
+
385
+ return arr1.length > arr2.length ? 1 : -1;
374
386
  }
375
387
 
376
388
  var widgets = {
377
- resolve: resolve$f,
389
+ resolve: resolve$e,
378
390
  isObject,
379
391
  isArray,
380
- createTask: createTask$2,
392
+ createTask: createTask$3,
381
393
  downloadRepoForGit: downloadRepoForGit$1,
382
394
  pullRepoForGit: pullRepoForGit$1,
383
- suggestCommands: suggestCommands$1,
384
395
  camelize,
385
396
  npmInstall: npmInstall$2,
386
397
  mergeMap: mergeMap$1,
387
398
  relativeCwdPath: relativeCwdPath$1,
388
- filterField: filterField$4,
389
- findFiles
399
+ filterField: filterField$5,
400
+ findFiles,
401
+ getAbsolutePath: getAbsolutePath$3,
402
+ getNpmRegistry,
403
+ versionCompare: versionCompare$1
390
404
  };
391
405
 
392
- const path$d = require('path');
393
-
394
- const os = require('os'); // 用户目录
406
+ var tmsMpconfig = {exports: {}};
395
407
 
408
+ const path$e = require$$1__default$1;
409
+ const os = require$$1__default$2; // 用户目录
396
410
 
397
411
  const HOME_DIR = os.homedir(); // 所有文件的缓存目录
398
412
 
399
- const CACHE_DIR$3 = path$d.resolve(HOME_DIR, '.tmskit'); // 缓存文件
413
+ const CACHE_DIR = path$e.resolve(HOME_DIR, '.tmskit'); // 版本管理的CDN地址
414
+
415
+ const VERSION_URL$1 = 'https://tms-web-1g1czzwka2fd06f2-1301126013.tcloudbaseapp.com/tmskit-template/version.json'; // version缓存文件
400
416
 
401
- const CACHE_FILE$1 = 'cache_file.json'; // 脚手架模板代码所在目录
417
+ const VERSION_CACHE_FILE$1 = path$e.resolve(CACHE_DIR, 'version_cache_file.json'); // npm缓存文件
402
418
 
403
- const TEMPLATE_DIR$1 = path$d.resolve(CACHE_DIR$3, 'template'); // 模板的名称
419
+ const NPM_CACHE_FILE$1 = path$e.resolve(CACHE_DIR, 'npm_cache_file.json'); // 脚手架模板代码所在目录
404
420
 
405
- const TEMPLATE_NAME$1 = 'tmskit-template'; // 第三方模块源码存放的临时缓存目录
421
+ const TEMPLATE_DIR$1 = path$e.resolve(CACHE_DIR, 'template'); // 第三方模块源码存放的临时缓存目录
406
422
 
407
- const MODULE_CODE_DIR$1 = path$d.resolve(CACHE_DIR$3, 'modules_code'); // 脚手架模板的远程地址
423
+ const MODULE_CODE_DIR$2 = path$e.resolve(CACHE_DIR, 'modules_code'); // 缓存分包node_modules的目录
424
+
425
+ const NODE_MODULES_DIR$2 = path$e.resolve(CACHE_DIR, 'node_modules'); // 扩展命令源码的存放处
426
+
427
+ const EXTEND_CMD$1 = path$e.resolve(CACHE_DIR, 'cmd'); // 创建模板的名称
428
+
429
+ const TEMPLATE_NAME$1 = 'tmskit-template'; // 脚手架模板的远程地址
408
430
 
409
431
  const TEMPLATE_URL$1 = 'https://tms-web-1g1czzwka2fd06f2-1301126013.tcloudbaseapp.com/tmskit-template/tmskit-template.zip'; // 脚手架的名称
410
432
 
@@ -420,10 +442,10 @@ const DEFAULT_CLOUD_MODULE_DIR = './cloud'; // 模块的配置文件的名称
420
442
  const MODULE_CONFIG_FILENAME = 'module.config.json'; // 默认的webpack entry
421
443
 
422
444
  const DEFAULT_WEBPACK_ENTRY = {
423
- app: path$d.resolve(process.cwd(), 'app')
445
+ app: path$e.resolve(process.cwd(), 'app')
424
446
  }; // 默认从源码拷贝到编译后的配置
425
447
 
426
- const DEFAULT_COPY_CONFIG$2 = ['package.json', 'sitemap.json'];
448
+ const DEFAULT_COPY_CONFIG$2 = ['package.json', 'sitemap.json', 'project.config.json'];
427
449
  const ENV = {
428
450
  dev: 'development',
429
451
  prod: 'production'
@@ -439,208 +461,561 @@ const CREATE_TEMPLATE_QUESTION$1 = [{
439
461
  }, {
440
462
  name: '小程序模块',
441
463
  value: 'mp-module'
464
+ }, {
465
+ name: '构建工具扩展命令',
466
+ value: 'cmd'
467
+ }, {
468
+ name: '构建工具编译插件',
469
+ value: 'plugin'
442
470
  }]
443
471
  }];
472
+ var constant = {
473
+ HOME_DIR,
474
+ CACHE_DIR,
475
+ NPM_CACHE_FILE: NPM_CACHE_FILE$1,
476
+ VERSION_CACHE_FILE: VERSION_CACHE_FILE$1,
477
+ TEMPLATE_DIR: TEMPLATE_DIR$1,
478
+ TEMPLATE_NAME: TEMPLATE_NAME$1,
479
+ TMS_NAME: TMS_NAME$1,
480
+ TMS_CONFIG_FILENAME,
481
+ TMS_PRIVATE_FILENAME,
482
+ DEFAULT_MODULE_DIR,
483
+ MODULE_CONFIG_FILENAME,
484
+ EXTEND_CMD: EXTEND_CMD$1,
485
+ DEFAULT_WEBPACK_ENTRY,
486
+ DEFAULT_COPY_CONFIG: DEFAULT_COPY_CONFIG$2,
487
+ MODULE_CODE_DIR: MODULE_CODE_DIR$2,
488
+ NODE_MODULES_DIR: NODE_MODULES_DIR$2,
489
+ ENV,
490
+ TEMPLATE_TKIT_DIR: TEMPLATE_TKIT_DIR$2,
491
+ DEFAULT_CLOUD_MODULE_DIR,
492
+ CREATE_TEMPLATE_QUESTION: CREATE_TEMPLATE_QUESTION$1,
493
+ TEMPLATE_URL: TEMPLATE_URL$1,
494
+ VERSION_URL: VERSION_URL$1
495
+ };
444
496
 
445
- var constant = /*#__PURE__*/Object.freeze({
446
- __proto__: null,
447
- HOME_DIR: HOME_DIR,
448
- CACHE_DIR: CACHE_DIR$3,
449
- CACHE_FILE: CACHE_FILE$1,
450
- TEMPLATE_DIR: TEMPLATE_DIR$1,
451
- TEMPLATE_NAME: TEMPLATE_NAME$1,
452
- TMS_NAME: TMS_NAME$1,
453
- TMS_CONFIG_FILENAME: TMS_CONFIG_FILENAME,
454
- TMS_PRIVATE_FILENAME: TMS_PRIVATE_FILENAME,
455
- DEFAULT_MODULE_DIR: DEFAULT_MODULE_DIR,
456
- MODULE_CONFIG_FILENAME: MODULE_CONFIG_FILENAME,
457
- DEFAULT_WEBPACK_ENTRY: DEFAULT_WEBPACK_ENTRY,
458
- DEFAULT_COPY_CONFIG: DEFAULT_COPY_CONFIG$2,
459
- MODULE_CODE_DIR: MODULE_CODE_DIR$1,
460
- ENV: ENV,
461
- TEMPLATE_TKIT_DIR: TEMPLATE_TKIT_DIR$2,
462
- DEFAULT_CLOUD_MODULE_DIR: DEFAULT_CLOUD_MODULE_DIR,
463
- CREATE_TEMPLATE_QUESTION: CREATE_TEMPLATE_QUESTION$1,
464
- TEMPLATE_URL: TEMPLATE_URL$1
465
- });
466
-
467
- var require$$4 = /*@__PURE__*/getAugmentedNamespace(constant);
468
-
469
- const fs$f = require$$0__default$2;
470
- const path$c = require$$1__default$2;
471
- const {
472
- info: info$b
473
- } = log$1;
474
- const {
475
- relativeCwdPath
476
- } = widgets;
477
- /**
478
- * 判断目录是否为空
479
- * @param {string} dirname 目录名
480
- * @returns
481
- */
497
+ var defaultTmsConfig = {
498
+ // 全局的环境配置项
499
+ envData: {},
500
+ // 模块配置信息
501
+ modules: {},
502
+ cloudDir: 'cloud',
503
+ // 第三方依赖代码需要拷贝到本项目的
504
+ dependencies: {},
482
505
 
483
- const isDirEmpty = dirname => fs$f.promises.readdir(dirname).then(files => files.length === 0); // 判断是否是文件
506
+ /** 编译输出文件夹位置 */
507
+ outputDir: 'dist',
484
508
 
509
+ /** 源码监听路径 */
510
+ sourceDir: './',
485
511
 
486
- const isFile = pathName => {
487
- try {
488
- const stat = fs$f.lstatSync(pathName);
489
- return stat.isFile();
490
- } catch {
491
- return false;
492
- }
512
+ /** 静态资源目录 */
513
+ static: []
493
514
  };
515
+
494
516
  /**
495
- * 确保目录存在,不存在就创建一个
496
- * @param {*} dirname 目录名
517
+ * 用来读取处理tms.config.js与module.config.json字段
497
518
  */
498
519
 
520
+ (function (module) {
521
+ /* eslint-disable no-param-reassign, no-nested-ternary */
522
+ const loadash = require$$0__default$2;
523
+ const fs = require$$0__default$1;
524
+ const path = require$$1__default$1;
525
+ const {
526
+ TMS_CONFIG_FILENAME,
527
+ MODULE_CONFIG_FILENAME,
528
+ TMS_PRIVATE_FILENAME
529
+ } = constant;
530
+ const {
531
+ resolve,
532
+ isObject,
533
+ isArray,
534
+ getAbsolutePath
535
+ } = widgets;
536
+ const defaultTmsConfig$1 = defaultTmsConfig;
537
+ const {
538
+ fail
539
+ } = log$1;
540
+ /**
541
+ * 读取tms.config.js
542
+ * @param {string} configPath tms.config.js的路径
543
+ */
499
544
 
500
- const ensureDirExist$2 = dirname => {
501
- if (!fs$f.existsSync(dirname)) {
502
- fs$f.mkdirSync(dirname, {
503
- recursive: true
504
- });
505
- }
506
- }; // 复制文件
507
-
508
-
509
- const copyFile = function (src, dest) {
510
- if (fs$f.existsSync(dest)) {
511
- fs$f.unlinkSync(dest);
512
- }
513
-
514
- const dir = path$c.dirname(dest);
515
- ensureDirExist$2(dir);
516
- fs$f.copyFileSync(src, dest);
517
- }; // 判断文件内容是否一致,不一致再进行拷贝
518
-
519
-
520
- function diffContentCopyFile$3(originFile, destFile) {
521
- if (fs$f.existsSync(destFile)) {
522
- const depDestContent = fs$f.readFileSync(destFile, 'utf8');
523
- const depOriginContent = fs$f.readFileSync(originFile, 'utf8');
545
+ const readTmsConfig = function (configPath) {
546
+ const tmsConfigPath = configPath ? `${configPath}/${TMS_CONFIG_FILENAME}` : resolve(TMS_CONFIG_FILENAME);
524
547
 
525
- if (depDestContent !== depOriginContent) {
526
- info$b(`拷贝${relativeCwdPath(originFile)}内容到${relativeCwdPath(destFile)}`);
527
- copyFile(originFile, destFile);
548
+ if (!fs.existsSync(tmsConfigPath)) {
549
+ fail(`${path.dirname(tmsConfigPath)}没有找到tms.config.js,请进行配置`);
550
+ process.exit(1);
528
551
  }
529
- } else {
530
- info$b(`拷贝${relativeCwdPath(originFile)}内容到${relativeCwdPath(destFile)}`);
531
- copyFile(originFile, destFile);
532
- }
533
- } // 添加后缀
534
552
 
553
+ const tmsConfigFn = require(tmsConfigPath);
535
554
 
536
- function ext$3(filePath, extensions) {
537
- let newFilePath = filePath;
538
- let extPath = ''; // try catch需要包裹:用来处理'./lib/timer'没有后缀的情况
555
+ const tmsConfig = typeof tmsConfigFn === 'function' ? tmsConfigFn() : tmsConfigFn; // 合并默认值
539
556
 
540
- try {
541
- const stat = fs$f.lstatSync(newFilePath);
557
+ return loadash.mergeWith({}, defaultTmsConfig$1, tmsConfig);
558
+ };
559
+ /**
560
+ * 读取tms.private.config.js
561
+ * @param {string} configPath tms.private.config.js的路径
562
+ */
542
563
 
543
- if (stat.isDirectory()) {
544
- extPath = newFilePath[newFilePath.length - 1] === '/' ? 'index' : '/index';
545
- newFilePath += extPath;
546
- }
547
- } catch (e) {}
548
564
 
549
- for (const ext of extensions) {
550
- const file = newFilePath.endsWith(ext) ? newFilePath : newFilePath + ext;
565
+ const readTmsPrivateCf = function (configPath) {
566
+ let tmsPrivateCf = {};
567
+ const tmsPrivatePath = configPath ? `${configPath}/${TMS_PRIVATE_FILENAME}` : resolve(TMS_PRIVATE_FILENAME);
551
568
 
552
- if (fs$f.existsSync(file)) {
553
- return {
554
- ext,
555
- extPath: extPath + ext,
556
- file
557
- };
569
+ if (fs.existsSync(tmsPrivatePath)) {
570
+ const tmsPrivateFn = require(tmsPrivatePath);
571
+
572
+ tmsPrivateCf = typeof tmsPrivateFn === 'function' ? tmsPrivateFn() : tmsPrivateFn;
558
573
  }
559
- }
560
574
 
561
- return {
562
- ext: '',
563
- extPath,
564
- file: filePath
575
+ return tmsPrivateCf;
565
576
  };
566
- } // 判断文件是否在某个目录
577
+ /**
578
+ * 获取tms.config.js, tms.private.config.js的配置项
579
+ * @param {string} configPath config.js的路径
580
+ * @returns
581
+ */
567
582
 
568
583
 
569
- const fileInDir$3 = (dir, file) => {
570
- if (!fs$f.existsSync(dir) || !fs$f.existsSync(file)) {
571
- return false;
572
- }
584
+ const getTmsConfig = configPath => {
585
+ const tmsPrivateCf = readTmsPrivateCf(configPath);
586
+ const tmsConfig = readTmsConfig(configPath);
587
+ const modules = {};
573
588
 
574
- const relativePath = path$c.relative(dir, file);
589
+ if (Array.isArray(tmsConfig.modules)) {
590
+ modules.all = tmsConfig.modules;
591
+ tmsConfig.modules = modules;
592
+ } // 合并默认值
575
593
 
576
- if (relativePath.startsWith('..')) {
577
- return false;
578
- }
579
594
 
580
- return true;
581
- };
595
+ const res = loadash.mergeWith(tmsConfig, tmsPrivateCf, (objValue, srcValue) => {
596
+ if (loadash.isArray(objValue) && objValue[0] && loadash.isObject(objValue[0])) {
597
+ return objValue.concat(srcValue);
598
+ }
599
+ });
600
+ return res;
601
+ };
602
+ /**
603
+ * 根据moduleNames获取modules
604
+ * @param { object } tmsConfig
605
+ * @param { array } moduleNames
606
+ * @param {boolean} errorIsQuit 找不到配置文件是否退出
607
+ * @returns
608
+ */
582
609
 
583
- function findAllFilesOfDir$1(dir) {
584
- const list = [];
585
610
 
586
- function listFile(dir) {
587
- const arr = fs$f.readdirSync(dir);
588
- arr.forEach(item => {
589
- const fullPath = path$c.join(dir, item);
590
- const stats = fs$f.statSync(fullPath);
611
+ const getModulesByModuleNames = function (tmsConfig, moduleNames = []) {
612
+ const targetModules = [];
613
+ moduleNames.forEach(moduleName => {
614
+ const module = tmsConfig.modules.all.find(module => module.moduleName === moduleName);
591
615
 
592
- if (stats.isDirectory()) {
593
- listFile(fullPath);
594
- } else {
595
- list.push(fullPath);
616
+ if (!module) {
617
+ throw new Error(`你启动的模块${moduleName}在tms.config.js的modules.all中没有注册`);
596
618
  }
597
- });
598
- return list;
599
- }
600
619
 
601
- listFile(dir);
602
- return list;
603
- }
620
+ targetModules.push(module);
621
+ });
622
+ return targetModules;
623
+ };
624
+ /**
625
+ * 适配处理module.config.json的字段
626
+ * @param { object } fileContent module.config.json的内容
627
+ * @param { string } appName 小程序的名称
628
+ */
604
629
 
605
- var io$3 = {
606
- isDirEmpty,
607
- copyFile,
608
- diffContentCopyFile: diffContentCopyFile$3,
609
- ensureDirExist: ensureDirExist$2,
610
- ext: ext$3,
611
- fileInDir: fileInDir$3,
612
- isFile,
613
- findAllFilesOfDir: findAllFilesOfDir$1
614
- };
615
630
 
616
- const async = require$$0__default$4;
617
- const ejs = require$$1__default$3;
631
+ function adaptMpCgContent(fileContent, appName) {
632
+ const handleContent = function (appName, current) {
633
+ let res = current;
618
634
 
619
- const render$1 = (files, metalsmith, next) => {
620
- const keys = Object.keys(files);
621
- const metadata = metalsmith.metadata();
635
+ if (appName && current.mpConfig && current.mpConfig[appName]) {
636
+ res = { ...current,
637
+ ...current.mpConfig[appName]
638
+ };
639
+ }
622
640
 
623
- const run = (file, next) => {
624
- const str = files[file].contents.toString();
625
- const newStr = ejs.render(str, metadata); // eslint-disable-next-line
641
+ delete res.mpConfig;
642
+ delete res.isSubpackages;
643
+ return res;
644
+ };
626
645
 
627
- files[file].contents = Buffer.from(newStr);
628
- next();
629
- };
646
+ let content = fileContent;
647
+
648
+ if (isArray(content)) {
649
+ let i = content.length - 1;
650
+
651
+ while (i >= 0) {
652
+ content[i] = handleContent(appName, content[i]);
653
+ i--; // eslint-disable-line
654
+ }
655
+ } else {
656
+ content = handleContent(appName, content);
657
+ }
658
+
659
+ return content;
660
+ }
661
+
662
+ const adaptDependencies = function (dependencies, subPackages) {
663
+ const newDependencies = dependencies || [];
664
+ subPackages.forEach(item => {
665
+ if (item.dependencies) {
666
+ dependencies = newDependencies.concat(item.dependencies);
667
+ }
668
+ });
669
+ return newDependencies;
670
+ };
671
+
672
+ const adaptSubPackages = function (moduleConfig, appName) {
673
+ const subPackages = isObject(moduleConfig) && moduleConfig.subPackages ? moduleConfig.subPackages : isObject(moduleConfig) ? [moduleConfig] : moduleConfig;
674
+ return adaptMpCgContent(subPackages, appName);
675
+ };
676
+ /**
677
+ * 获取模块module.config.json中的配置信息
678
+ * @param {array} modules 用户要编译的模块列表
679
+ * @param { string } appName 小程序的名称
680
+ */
681
+
682
+
683
+ function getModulesConfig(modules = [], appName) {
684
+ const modulesConfig = [];
685
+ modules.forEach(moduleItem => {
686
+ const moduleConfigPath = resolve(moduleItem.path, MODULE_CONFIG_FILENAME);
687
+ let moduleConfig;
688
+
689
+ try {
690
+ moduleConfig = JSON.parse(fs.readFileSync(moduleConfigPath, 'utf-8'));
691
+ } catch (e) {
692
+ throw new Error(`${moduleConfigPath}json解析报错: ${e}`);
693
+ } // 兼容历史逻辑,后续可删除--- start
694
+
695
+
696
+ const subPackages = adaptSubPackages(moduleConfig, appName);
697
+ const dependencies = adaptDependencies(moduleConfig.dependencies, subPackages);
698
+ moduleConfig = { ...(isObject(moduleConfig) ? moduleConfig : {}),
699
+ subPackages,
700
+ dependencies
701
+ }; // 兼容逻辑--- end
702
+
703
+ modulesConfig.push(moduleConfig);
704
+ });
705
+ return modulesConfig;
706
+ }
707
+ /**
708
+ * 获取分包内容 (读取module.config.json的配置项)
709
+ * @param {array} modules
710
+ * @returns
711
+ */
712
+
713
+
714
+ const getSubPackages = modules => {
715
+ const newSubPackages = [];
716
+ modules.forEach(module => {
717
+ (module.subPackages || []).forEach(subPackage => {
718
+ newSubPackages.push({ ...subPackage
719
+ });
720
+ });
721
+ });
722
+ return newSubPackages;
723
+ };
724
+ /**
725
+ * 获取分包的root字段
726
+ * @param {*} modulePath 模块的编译路径
727
+ * @param {*} root 分包的root字段
728
+ * @returns
729
+ */
730
+
731
+
732
+ const getSubPackageRoot = function (modulePath, root) {
733
+ return root.startsWith(modulePath) ? root : `${modulePath}/${root}`;
734
+ }; // 获取分包的源码路径
735
+
736
+
737
+ const getSubPackageSrcPath = function (tmsConfig, module, subPackage) {
738
+ const srcModulePath = getAbsolutePath(module.path);
739
+ const buildModulePath = resolve(tmsConfig.outputDir, module.modulePath);
740
+ const subPackageRoot = getSubPackageRoot(module.modulePath, subPackage.root);
741
+ const buildSubPackagePath = resolve(tmsConfig.outputDir, subPackageRoot);
742
+ const subPackageRelativeModule = path.relative(buildModulePath, buildSubPackagePath);
743
+ const srcSubPackagePath = path.join(srcModulePath, subPackageRelativeModule);
744
+ return srcSubPackagePath;
745
+ };
746
+
747
+ const checkModuleItem = (tmsConfig, tmsModuleItem, moduleConfig) => {
748
+ const newModuleItem = { ...tmsModuleItem,
749
+ ...moduleConfig
750
+ }; // 兼容逻辑
751
+
752
+ if (!newModuleItem.moduleName) newModuleItem.moduleName = newModuleItem.name;
753
+ delete newModuleItem.name; // 参数校验-模块源码路径
754
+
755
+ if (!newModuleItem.path) {
756
+ throw new Error(`${newModuleItem.moduleName}模块没有找到path字段,请检查tms.config.js的modules.all>module>path路径`);
757
+ } // 参数校验-模块编译路径
758
+
759
+
760
+ if (!newModuleItem.modulePath) {
761
+ throw new Error(`${newModuleItem.moduleName}模块的module.config.json中没有找到modulePath字段`);
762
+ } // 参数校验-分包校验
763
+
764
+
765
+ for (const subPackage of newModuleItem.subPackages) {
766
+ if (!subPackage.root) {
767
+ throw new Error(`${newModuleItem.moduleName}模块的module.config.json中没有找到${subPackage.name}分包的root字段`);
768
+ } // 参数校验-判断分包源码目录是否存在
769
+
770
+
771
+ const subPackageSrcPath = getSubPackageSrcPath(tmsConfig, newModuleItem, subPackage);
772
+
773
+ if (!subPackageSrcPath || !fs.existsSync(subPackageSrcPath)) {
774
+ throw new Error(`没有找到${newModuleItem.moduleName}模块的${subPackage.name}分包源码:${subPackageSrcPath}`);
775
+ }
776
+
777
+ subPackage.path = subPackageSrcPath;
778
+ }
779
+
780
+ return newModuleItem;
781
+ };
782
+ /**
783
+ * 获取所有的模块,合并模块的依赖模块
784
+ * @param { object } tmsConfig
785
+ * @param {array} modules
786
+ * @param {boolean} errorIsQuit 找不到配置文件是否退出
787
+ * @returns
788
+ */
789
+
790
+
791
+ const getModulesByMergeDepModules = (tmsConfig, modules, errorIsQuit = false) => {
792
+ const allModules = new Map();
793
+
794
+ function dfs(tmsConfig, modules) {
795
+ modules.forEach(moduleItem => {
796
+ const moduleConfigPath = resolve(moduleItem.path, MODULE_CONFIG_FILENAME);
797
+
798
+ if (!fs.existsSync(moduleConfigPath)) {
799
+ if (!allModules.has(moduleItem.moduleName)) {
800
+ allModules.set(moduleItem.moduleName, moduleItem);
801
+ }
802
+
803
+ if (errorIsQuit) {
804
+ throw new Error(`${moduleItem.moduleName}模块的配置文件module.config.json在${moduleItem.path}目录下没有找到`);
805
+ }
806
+
807
+ return;
808
+ }
809
+
810
+ const [moduleConfig = {}] = getModulesConfig([moduleItem], tmsConfig.appName);
811
+
812
+ if (!allModules.has(moduleItem.moduleName)) {
813
+ allModules.set(moduleItem.moduleName, checkModuleItem(tmsConfig, moduleItem, moduleConfig));
814
+ const dependenciesModules = getModulesByModuleNames(tmsConfig, moduleConfig === null || moduleConfig === void 0 ? void 0 : moduleConfig.dependencies);
815
+
816
+ if (dependenciesModules.length) {
817
+ dfs(tmsConfig, dependenciesModules);
818
+ }
819
+ }
820
+ });
821
+ }
822
+
823
+ dfs(tmsConfig, modules);
824
+ const modulesArr = [];
825
+
826
+ for (const module of allModules.values()) {
827
+ modulesArr.push(module);
828
+ }
829
+
830
+ return modulesArr;
831
+ };
832
+
833
+ module.exports = {
834
+ readTmsConfig,
835
+ readTmsPrivateCf,
836
+ getModulesConfig,
837
+ getModulesByModuleNames,
838
+ getSubPackages,
839
+ getModulesByMergeDepModules,
840
+ getTmsConfig
841
+ };
842
+ })(tmsMpconfig);
843
+
844
+ const fs$f = require$$0__default$1;
845
+ const path$d = require$$1__default$1;
846
+ const {
847
+ info: info$b
848
+ } = log$1;
849
+ const {
850
+ relativeCwdPath
851
+ } = widgets;
852
+ /**
853
+ * 判断目录是否为空
854
+ * @param {string} dirname 目录名
855
+ * @returns
856
+ */
857
+
858
+ const isDirEmpty = dirname => fs$f.promises.readdir(dirname).then(files => files.length === 0); // 判断是否是文件
859
+
860
+
861
+ const isFile = pathName => {
862
+ try {
863
+ const stat = fs$f.lstatSync(pathName);
864
+ return stat.isFile();
865
+ } catch {
866
+ return false;
867
+ }
868
+ };
869
+ /**
870
+ * 确保目录存在,不存在就创建一个
871
+ * @param {*} dirname 目录名
872
+ */
873
+
874
+
875
+ const ensureDirExist$4 = dirname => {
876
+ if (!fs$f.existsSync(dirname)) {
877
+ fs$f.mkdirSync(dirname, {
878
+ recursive: true
879
+ });
880
+ }
881
+ }; // 复制文件
882
+
883
+
884
+ const copyFile = function (src, dest) {
885
+ if (fs$f.existsSync(dest)) {
886
+ fs$f.unlinkSync(dest);
887
+ }
888
+
889
+ const dir = path$d.dirname(dest);
890
+ ensureDirExist$4(dir);
891
+ fs$f.copyFileSync(src, dest);
892
+ }; // 判断文件内容是否一致,不一致再进行拷贝
893
+
894
+
895
+ function diffContentCopyFile(originFile, destFile) {
896
+ if (fs$f.existsSync(destFile)) {
897
+ const depDestContent = fs$f.readFileSync(destFile, 'utf8');
898
+ const depOriginContent = fs$f.readFileSync(originFile, 'utf8');
899
+
900
+ if (depDestContent !== depOriginContent) {
901
+ info$b(`拷贝${relativeCwdPath(originFile)}内容到${relativeCwdPath(destFile)}`);
902
+ copyFile(originFile, destFile);
903
+ }
904
+ } else {
905
+ info$b(`拷贝${relativeCwdPath(originFile)}内容到${relativeCwdPath(destFile)}`);
906
+ copyFile(originFile, destFile);
907
+ }
908
+ } // 添加后缀
909
+
910
+
911
+ function ext(filePath, extensions) {
912
+ let newFilePath = filePath;
913
+ let extPath = ''; // try catch需要包裹:用来处理'./lib/timer'没有后缀的情况
914
+
915
+ try {
916
+ const stat = fs$f.lstatSync(newFilePath);
917
+
918
+ if (stat.isDirectory()) {
919
+ extPath = newFilePath[newFilePath.length - 1] === '/' ? 'index' : '/index';
920
+ newFilePath += extPath;
921
+ }
922
+ } catch (e) {}
923
+
924
+ for (const ext of extensions) {
925
+ const file = newFilePath.endsWith(ext) ? newFilePath : newFilePath + ext;
926
+
927
+ if (fs$f.existsSync(file)) {
928
+ return {
929
+ ext,
930
+ extPath: extPath + ext,
931
+ file
932
+ };
933
+ }
934
+ }
935
+
936
+ return {
937
+ ext: '',
938
+ extPath,
939
+ file: filePath
940
+ };
941
+ } // 判断文件是否在某个目录
942
+
943
+
944
+ const fileInDir = (dir, file) => {
945
+ if (!fs$f.existsSync(dir) || !fs$f.existsSync(file)) {
946
+ return false;
947
+ }
948
+
949
+ const relativePath = path$d.relative(dir, file);
950
+
951
+ if (relativePath.startsWith('..')) {
952
+ return false;
953
+ }
954
+
955
+ return true;
956
+ };
957
+
958
+ function findAllFilesOfDir(dir) {
959
+ const list = [];
960
+
961
+ function listFile(dir) {
962
+ const arr = fs$f.readdirSync(dir);
963
+ arr.forEach(item => {
964
+ const fullPath = path$d.join(dir, item);
965
+ const stats = fs$f.statSync(fullPath);
966
+
967
+ if (stats.isDirectory()) {
968
+ listFile(fullPath);
969
+ } else {
970
+ list.push(fullPath);
971
+ }
972
+ });
973
+ return list;
974
+ }
975
+
976
+ listFile(dir);
977
+ return list;
978
+ }
979
+
980
+ var io$3 = {
981
+ isDirEmpty,
982
+ copyFile,
983
+ diffContentCopyFile,
984
+ ensureDirExist: ensureDirExist$4,
985
+ ext,
986
+ fileInDir,
987
+ isFile,
988
+ findAllFilesOfDir
989
+ };
990
+
991
+ const async = require$$0__default$3;
992
+ const ejs = require$$1__default$3;
993
+
994
+ const render$1 = (files, metalsmith, next) => {
995
+ const keys = Object.keys(files);
996
+ const metadata = metalsmith.metadata();
997
+
998
+ const run = (file, next) => {
999
+ const str = files[file].contents.toString();
1000
+ const newStr = ejs.render(str, metadata); // eslint-disable-next-line
1001
+
1002
+ files[file].contents = Buffer.from(newStr);
1003
+ next();
1004
+ };
630
1005
 
631
1006
  async.each(keys, run, next);
632
1007
  };
633
1008
 
634
1009
  var render_1 = render$1;
635
1010
 
636
- const fs$e = require$$0__default$2;
637
- const inquirer$1 = require$$1__default$4;
1011
+ const fs$e = require$$0__default$1;
1012
+ const inquirer$2 = require$$1__default$4;
638
1013
  const {
639
- resolve: resolve$e
1014
+ resolve: resolve$d
640
1015
  } = widgets;
641
1016
  const {
642
1017
  TEMPLATE_TKIT_DIR: TEMPLATE_TKIT_DIR$1
643
- } = require$$4;
1018
+ } = constant;
644
1019
  /**
645
1020
  * 获取模板内的问题
646
1021
  * @param {string} dir questions.json所在的目录
@@ -688,7 +1063,7 @@ const isQuestionType = result => {
688
1063
  };
689
1064
 
690
1065
  const ask$1 = templateDir => (files, metalsmith, next) => {
691
- const prompts = parseTemplateQuestions(resolve$e(templateDir, TEMPLATE_TKIT_DIR$1));
1066
+ const prompts = parseTemplateQuestions(resolve$d(templateDir, TEMPLATE_TKIT_DIR$1));
692
1067
  const metadata = metalsmith.metadata();
693
1068
  const filteredPrompts = prompts.filter(prompt => {
694
1069
  if (metadata[prompt.name] && `${metadata[prompt.name]}`.trim() !== '') {
@@ -697,7 +1072,7 @@ const ask$1 = templateDir => (files, metalsmith, next) => {
697
1072
 
698
1073
  return true;
699
1074
  });
700
- inquirer$1.prompt(filteredPrompts).then(res => {
1075
+ inquirer$2.prompt(filteredPrompts).then(res => {
701
1076
  for (const prompt of filteredPrompts) {
702
1077
  metadata[prompt.name] = res[prompt.name];
703
1078
  }
@@ -713,7 +1088,7 @@ var ask_1 = ask$1;
713
1088
  const FILES_TO_IGNORE$1 = ['node_modules'];
714
1089
  var ignoreFiles = FILES_TO_IGNORE$1;
715
1090
 
716
- const Metalsmith = require$$0__default$5;
1091
+ const Metalsmith = require$$0__default$4;
717
1092
  const render = render_1;
718
1093
  const ask = ask_1;
719
1094
  const FILES_TO_IGNORE = ignoreFiles;
@@ -730,29 +1105,68 @@ const generator$1 = (buildDir, distDir, preMetadata = {}) => new Promise((resolv
730
1105
 
731
1106
  var generator_1 = generator$1;
732
1107
 
733
- const path$b = require$$1__default$2;
734
- const fs$d = require$$0__default$2;
735
- const shelljs$6 = require$$0__default$3;
736
- const inquirer = require$$1__default$4;
1108
+ const request$2 = require$$0__default$5;
1109
+ const shelljs$8 = require$$2__default;
1110
+ const apiUrl = 'https://tim.map.qq.com/basic/tmskit/upload';
1111
+
1112
+ function getGitUser() {
1113
+ const res = shelljs$8.exec('git config user.name', {
1114
+ async: false,
1115
+ silent: true
1116
+ });
1117
+ return res.stdout;
1118
+ }
1119
+
1120
+ const report$8 = (name, attrs = {}) => {
1121
+ try {
1122
+ const param = [];
1123
+ param[27] = name;
1124
+ param[28] = 'tmskit';
1125
+ param[29] = getGitUser();
1126
+ param[30] = JSON.stringify(attrs);
1127
+
1128
+ for (let i = 0; i < 40; i++) {
1129
+ if (!param[i]) param[i] = null;
1130
+ }
1131
+
1132
+ ;
1133
+ request$2.post({
1134
+ url: apiUrl,
1135
+ json: {
1136
+ param
1137
+ }
1138
+ }); // (error, response, body) => {
1139
+ // console.log('body:', body);
1140
+ // }
1141
+ } catch (e) {}
1142
+ };
1143
+
1144
+ var report_1 = report$8;
1145
+
1146
+ const path$c = require$$1__default$1;
1147
+ const fs$d = require$$0__default$1;
1148
+ const shelljs$7 = require$$2__default;
1149
+ const inquirer$1 = require$$1__default$4;
737
1150
  const {
738
1151
  TEMPLATE_DIR,
739
1152
  TEMPLATE_URL,
740
1153
  TEMPLATE_NAME,
741
1154
  TEMPLATE_TKIT_DIR,
742
1155
  CREATE_TEMPLATE_QUESTION
743
- } = require$$4;
1156
+ } = constant;
744
1157
  const {
745
- resolve: resolve$d
1158
+ resolve: resolve$c
746
1159
  } = widgets;
747
1160
  const io$2 = io$3;
748
1161
  const {
749
- fail: fail$9,
1162
+ fail: fail$8,
750
1163
  succeed: succeed$1,
751
1164
  info: info$a
752
1165
  } = log$1;
753
1166
  const generator = generator_1;
754
- const request = require$$9__default;
1167
+ const request$1 = require$$0__default$5;
755
1168
  const unzip = require$$10__default;
1169
+ const report$7 = report_1;
756
1170
  /**
757
1171
  * 如果该目录下面存在文件,换个名字
758
1172
  * @param { string } targetDir 当前文件夹
@@ -763,11 +1177,11 @@ async function createProjectDir(targetDir) {
763
1177
  // 如果目录非空或者已经存在,提示用户,做选择
764
1178
  if (fs$d.existsSync(targetDir)) {
765
1179
  if (!(await io$2.isDirEmpty(targetDir))) {
766
- fail$9('该目录名已经存在,换个项目名字吧~');
1180
+ fail$8('该目录名已经存在,换个项目名字吧~');
767
1181
  process.exit(1);
768
1182
  }
769
1183
  } else {
770
- shelljs$6.mkdir('-p', targetDir);
1184
+ shelljs$7.mkdir('-p', targetDir);
771
1185
  }
772
1186
  }
773
1187
  /**
@@ -783,7 +1197,7 @@ function downloadAndUnZipTemplate(templateDir, templateUrl, templateName) {
783
1197
  return new Promise((resolve, reject) => {
784
1198
  const localZipPath = `${templateDir}/${templateName}.zip`;
785
1199
  const stream = fs$d.createWriteStream(localZipPath);
786
- request(`${templateUrl}?v=${new Date().getTime()}`).pipe(stream).on('close', err => {
1200
+ request$1(`${templateUrl}?v=${new Date().getTime()}`).pipe(stream).on('close', err => {
787
1201
  if (err) {
788
1202
  reject(err);
789
1203
  return;
@@ -811,15 +1225,18 @@ function downloadAndUnZipTemplate(templateDir, templateUrl, templateName) {
811
1225
 
812
1226
  async function create(projectName) {
813
1227
  const cwd = process.cwd();
814
- const targetDir = path$b.resolve(cwd, projectName);
1228
+ const targetDir = path$c.resolve(cwd, projectName);
815
1229
  const {
816
1230
  projectType
817
- } = await inquirer.prompt(CREATE_TEMPLATE_QUESTION); // 创建项目目录
1231
+ } = await inquirer$1.prompt(CREATE_TEMPLATE_QUESTION);
1232
+ report$7('create-start', {
1233
+ projectType
1234
+ }); // 创建项目目录
818
1235
 
819
1236
  await createProjectDir(targetDir); // 新创建缓存目录
820
1237
 
821
1238
  if (fs$d.existsSync(TEMPLATE_DIR)) {
822
- shelljs$6.rm('-rf', TEMPLATE_DIR);
1239
+ shelljs$7.rm('-rf', TEMPLATE_DIR);
823
1240
  }
824
1241
 
825
1242
  fs$d.mkdirSync(TEMPLATE_DIR, {
@@ -828,9 +1245,9 @@ async function create(projectName) {
828
1245
 
829
1246
  await downloadAndUnZipTemplate(TEMPLATE_DIR, TEMPLATE_URL, TEMPLATE_NAME); // 生成模板(1. 询问问题, 2. ejs生成模板 3.生成到目标目录)
830
1247
 
831
- generator(path$b.join(TEMPLATE_DIR, TEMPLATE_NAME, projectType), targetDir).then(() => {
832
- shelljs$6.cd(projectName);
833
- const hookFilePath = resolve$d(projectName, TEMPLATE_TKIT_DIR, 'hooks.js');
1248
+ generator(path$c.join(TEMPLATE_DIR, TEMPLATE_NAME, projectType), targetDir).then(() => {
1249
+ shelljs$7.cd(projectName);
1250
+ const hookFilePath = resolve$c(projectName, TEMPLATE_TKIT_DIR, 'hooks.js');
834
1251
 
835
1252
  if (fs$d.existsSync(hookFilePath)) {
836
1253
  const hooks = require(hookFilePath);
@@ -838,296 +1255,119 @@ async function create(projectName) {
838
1255
  if (hooks.afterCreate) {
839
1256
  hooks.afterCreate.forEach(item => {
840
1257
  if (typeof item === 'function') {
841
- item.call(null, shelljs$6, {
1258
+ item.call(null, shelljs$7, {
842
1259
  projectName
843
1260
  });
844
1261
  } else {
845
- shelljs$6.exec(item);
1262
+ shelljs$7.exec(item);
846
1263
  }
847
1264
  });
848
1265
  }
849
1266
 
850
- shelljs$6.rm('-rf', resolve$d(projectName, TEMPLATE_TKIT_DIR));
1267
+ shelljs$7.rm('-rf', resolve$c(projectName, TEMPLATE_TKIT_DIR));
851
1268
  }
852
1269
 
1270
+ report$7('create-success', {
1271
+ projectType
1272
+ });
853
1273
  succeed$1('项目创建完成.');
854
1274
  }).catch(err => {
855
- fail$9(err.message);
1275
+ fail$8(err.message);
856
1276
  info$a('详细的错误信息:', err);
857
1277
  });
858
1278
  }
859
1279
 
860
1280
  var create_1 = create;
861
1281
 
862
- var tmsMpconfig = {exports: {}};
863
-
864
- var defaultTmsConfig = {
865
- // 全局的环境配置项
866
- envData: {},
867
- // 模块配置信息
868
- modules: {},
869
- cloudDir: 'cloud',
870
- // 第三方依赖代码需要拷贝到本项目的
871
- dependencies: {},
872
-
873
- /** 编译输出文件夹位置 */
874
- outputDir: 'dist',
875
-
876
- /** 源码监听路径 */
877
- sourceDir: './',
878
-
879
- /** 静态资源目录 */
880
- static: []
881
- };
882
-
1282
+ const fs$c = require$$0__default$1;
1283
+ const path$b = require$$1__default$1;
1284
+ const shellJs$1 = require$$2__default;
1285
+ const {
1286
+ ensureDirExist: ensureDirExist$3
1287
+ } = io$3;
1288
+ const {
1289
+ EXTEND_CMD
1290
+ } = constant;
1291
+ const {
1292
+ createTask: createTask$2
1293
+ } = widgets;
1294
+ const {
1295
+ info: info$9,
1296
+ fail: fail$7
1297
+ } = log$1;
883
1298
  /**
884
- * 用来读取处理tms.config.js与module.config.json字段
1299
+ * 下载扩展命令的npm包
1300
+ * @param {string} npmName npm包名
1301
+ * @param {object} cmd {registry: 'http://mirrors.tencent.com/npm/'} 用户输入执行install-cmd的参数
885
1302
  */
886
1303
 
887
- (function (module) {
888
- /* eslint-disable no-param-reassign, no-nested-ternary */
889
- const loadash = require$$0__default$6;
890
- const fs = require$$0__default$2;
891
- const {
892
- TMS_CONFIG_FILENAME,
893
- MODULE_CONFIG_FILENAME,
894
- TMS_PRIVATE_FILENAME
895
- } = require$$4;
896
- const {
897
- resolve,
898
- isObject,
899
- isArray
900
- } = widgets;
901
- const defaultTmsConfig$1 = defaultTmsConfig;
902
- const {
903
- fail
904
- } = log$1;
905
- /**
906
- * 读取tms.config.js
907
- * @param env {string} 环境变量
908
- */
909
-
910
- const readTmsConfig = function (env) {
911
- const tmsConfigPath = resolve(TMS_CONFIG_FILENAME);
912
-
913
- if (!fs.existsSync(tmsConfigPath)) {
914
- fail('当前执行目录没有tms.config.js的配置项,请进行配置');
915
- process.exit(1);
916
- }
917
-
918
- const tmsConfigFn = require(tmsConfigPath);
919
-
920
- const tmsConfig = tmsConfigFn({
921
- env
922
- }); // 合并默认值
923
-
924
- return loadash.mergeWith(defaultTmsConfig$1, tmsConfig);
925
- };
926
- /**
927
- * 读取tms.private.config.js
928
- */
929
-
930
-
931
- const readTmsPrivateCf = function () {
932
- let tmsPrivateCf = {};
933
- const tmsPrivatePath = resolve(TMS_PRIVATE_FILENAME);
934
-
935
- if (fs.existsSync(tmsPrivatePath)) {
936
- tmsPrivateCf = require(tmsPrivatePath);
937
- }
938
-
939
- return tmsPrivateCf;
940
- };
941
- /**
942
- * 从tms.config.json中检索用户传入的有效modules
943
- * @param { object } tmsConfig
944
- * @param { array } modules
945
- * @returns
946
- */
947
-
948
-
949
- const checkModules = function (tmsConfig, modules, isQuit = false) {
950
- const targetModules = [];
951
- modules.forEach(moduleName => {
952
- const module = tmsConfig.modules.all.find(module => module.moduleName === moduleName);
953
- module && targetModules.push(module);
954
- });
955
-
956
- if (targetModules.length === 0) {
957
- fail(`你启动的模块无效${modules.join(',')}无效,请检查tms.config.json>modules>${modules.join(',')}
958
- >name字段与module.config.json的name字段是否一致`);
959
- isQuit && process.exit(1);
960
- }
961
-
962
- return targetModules;
963
- };
964
- /**
965
- * 适配处理module.config.json的字段
966
- * @param { object } fileContent module.config.json的内容
967
- * @param { string } appName 小程序的名称
968
- */
969
-
970
-
971
- function adaptMpCgContent(fileContent, appName) {
972
- const handleContent = function (appName, current) {
973
- let res = current;
974
-
975
- if (appName && current.mpConfig && current.mpConfig[appName]) {
976
- res = { ...current,
977
- ...current.mpConfig[appName]
978
- };
979
- }
980
-
981
- delete res.mpConfig;
982
- delete res.isSubpackages;
983
- return res;
984
- };
985
-
986
- let content = fileContent;
987
-
988
- if (isArray(content)) {
989
- let i = content.length - 1;
1304
+ async function installCmd(npmName, cmd) {
1305
+ try {
1306
+ const cmdPackageJson = `${EXTEND_CMD}/package.json`;
990
1307
 
991
- while (i >= 0) {
992
- content[i] = handleContent(appName, content[i]);
993
- i--; // eslint-disable-line
994
- }
995
- } else {
996
- content = handleContent(appName, content);
1308
+ if (!fs$c.existsSync(cmdPackageJson)) {
1309
+ ensureDirExist$3(EXTEND_CMD);
1310
+ fs$c.writeFileSync(cmdPackageJson, JSON.stringify({
1311
+ dependencies: {}
1312
+ }, null, 2));
997
1313
  }
998
1314
 
999
- return content;
1000
- }
1001
- /**
1002
- * 获取模块module.config.json中的配置信息
1003
- * @param {array} modules 用户要编译的模块列表
1004
- * @param { string } appName 小程序的名称
1005
- * @param {boolean} notFindIsQuit 找不到配置文件是否退出
1006
- */
1007
-
1008
-
1009
- function getModulesConfig(modules = [], appName, notFindIsQuit) {
1010
- const modulesConfig = [];
1011
- modules.forEach(moduleItem => {
1012
- if (!moduleItem.path) {
1013
- throw new Error(`${moduleItem.moduleName}模块路径配置没有找到`);
1014
- }
1015
-
1016
- const moduleConfigPath = resolve(moduleItem.path, MODULE_CONFIG_FILENAME);
1017
-
1018
- if (!fs.existsSync(moduleConfigPath)) {
1019
- if (notFindIsQuit) {
1020
- throw new Error(`${moduleItem.moduleName}模块的配置文件module.config.json在${moduleItem.path}目录下没有找到`);
1315
+ shellJs$1.cd(EXTEND_CMD);
1316
+ await createTask$2(npmName => new Promise((resolve, reject) => {
1317
+ const registry = cmd.registry ? `--registry=${cmd.registry}` : '';
1318
+ shellJs$1.exec(`npm install --save ${npmName} ${registry}`, {
1319
+ cwd: EXTEND_CMD,
1320
+ silent: true
1321
+ }, (code, stdout, stderr) => {
1322
+ if (code !== 0) {
1323
+ reject(stderr);
1021
1324
  }
1022
1325
 
1023
- return;
1024
- }
1025
-
1026
- let moduleConfig;
1027
-
1028
- try {
1029
- moduleConfig = JSON.parse(fs.readFileSync(moduleConfigPath, 'utf-8'));
1030
- } catch (e) {
1031
- throw new Error(`${moduleConfigPath}json解析报错: ${e}`);
1032
- } // 兼容历史逻辑,后续可删除--- start
1033
-
1034
-
1035
- if (!moduleItem.moduleName) moduleItem.moduleName = moduleItem.name;
1036
- delete moduleItem.name;
1037
- let subPackages = isObject(moduleConfig) && moduleConfig.subPackages ? moduleConfig.subPackages : isObject(moduleConfig) ? [moduleConfig] : moduleConfig;
1038
- subPackages = adaptMpCgContent(subPackages, appName);
1039
- let dependencies = moduleConfig.dependencies || [];
1040
- subPackages.forEach(item => {
1041
- item.path = moduleItem.path;
1042
-
1043
- if (item.dependencies) {
1044
- dependencies = dependencies.concat(item.dependencies);
1045
- }
1326
+ resolve();
1046
1327
  });
1047
- moduleItem.subPackages = subPackages;
1048
- moduleItem.dependencies = dependencies; // 兼容逻辑--- end
1049
-
1050
- modulesConfig.push(moduleItem);
1051
- });
1052
- return modulesConfig;
1328
+ }), `开始下载${npmName}`, `下载${npmName}完成`)(npmName);
1329
+ } catch (e) {
1330
+ fail$7('构建出现错误:');
1331
+ info$9(e);
1332
+ process.exit(1);
1053
1333
  }
1054
- /**
1055
- * 获取分包内容 (读取module.config.json的配置项)
1056
- * @param {array} modules
1057
- * @returns
1058
- */
1059
-
1060
-
1061
- const getSubPackages = modules => {
1062
- const newSubPackages = [];
1063
- modules.forEach(module => {
1064
- (module.subPackages || []).forEach(item => {
1065
- newSubPackages.push({
1066
- path: module.path,
1067
- ...item
1068
- });
1069
- });
1070
- });
1071
- return newSubPackages;
1072
- };
1073
- /**
1074
- * 获取所有的模块,合并模块的依赖模块
1075
- * @param { object } tmsConfig
1076
- * @param {array} modules
1077
- * @param {boolean} notFindIsQuit 找不到配置文件是否退出
1078
- * @returns
1079
- */
1080
-
1081
-
1082
- const getModulesByMergeDepModules = (tmsConfig, modules, notFindIsQuit = false) => {
1083
- const allModules = new Map();
1084
-
1085
- function dfs(tmsConfig, modules) {
1086
- modules.forEach(moduleItem => {
1087
- const [moduleConfig = {}] = getModulesConfig([moduleItem], tmsConfig.appName, notFindIsQuit);
1088
-
1089
- if (!allModules.has(moduleItem.moduleName)) {
1090
- allModules.set(moduleItem.moduleName, { ...moduleItem,
1091
- ...moduleConfig
1092
- });
1093
- const dependenciesModules = [];
1094
- ((moduleConfig === null || moduleConfig === void 0 ? void 0 : moduleConfig.dependencies) || []).forEach(dependenciesModule => {
1095
- tmsConfig.modules.all.forEach(module => {
1096
- if (dependenciesModule === module.moduleName) {
1097
- dependenciesModules.push({ ...module
1098
- });
1099
- }
1100
- });
1101
- });
1334
+ }
1335
+ /**
1336
+ * 加载扩展命令的npm包
1337
+ * @returns
1338
+ */
1102
1339
 
1103
- if (dependenciesModules.length) {
1104
- dfs(tmsConfig, dependenciesModules);
1105
- }
1106
- }
1107
- });
1108
- }
1109
1340
 
1110
- dfs(tmsConfig, modules);
1111
- const modulesArr = [];
1341
+ function loadExtendCmd$1() {
1342
+ const cmdPackageJson = `${EXTEND_CMD}/package.json`;
1343
+ const cmdNpmDir = `${EXTEND_CMD}/node_modules`;
1112
1344
 
1113
- for (const module of allModules.values()) {
1114
- modulesArr.push(module);
1115
- }
1345
+ if (fs$c.existsSync(cmdPackageJson)) {
1346
+ const content = fs$c.readFileSync(cmdPackageJson, 'utf8');
1347
+ const json = JSON.parse(content);
1348
+ const deps = json.dependencies || {};
1349
+ const cmdConfigs = [];
1350
+ Object.keys(deps).forEach(name => {
1351
+ // 检索cmd的npm包
1352
+ if (!/^tmskit-cmd-|^@[^/]+\/tmskit-cmd-/.test(name)) return false;
1353
+ const cmdConfig = path$b.join(cmdNpmDir, name, 'tms.config.js');
1116
1354
 
1117
- return modulesArr;
1118
- };
1355
+ if (fs$c.existsSync(cmdConfig)) {
1356
+ cmdConfigs.push(cmdConfig);
1357
+ }
1358
+ });
1359
+ return cmdConfigs;
1360
+ }
1119
1361
 
1120
- module.exports = {
1121
- readTmsConfig,
1122
- readTmsPrivateCf,
1123
- getModulesConfig,
1124
- checkModules,
1125
- getSubPackages,
1126
- getModulesByMergeDepModules
1127
- };
1128
- })(tmsMpconfig);
1362
+ return [];
1363
+ }
1364
+
1365
+ var extendCmd = {
1366
+ installCmd,
1367
+ loadExtendCmd: loadExtendCmd$1
1368
+ };
1129
1369
 
1130
- const global$6 = {
1370
+ const global$7 = {
1131
1371
  data: {},
1132
1372
 
1133
1373
  setData(...args) {
@@ -1149,36 +1389,36 @@ const global$6 = {
1149
1389
 
1150
1390
  };
1151
1391
  var global_1 = {
1152
- global: global$6
1392
+ global: global$7
1153
1393
  };
1154
1394
 
1155
1395
  const {
1156
- fail: fail$8
1396
+ fail: fail$6
1157
1397
  } = log$1;
1158
1398
  const {
1159
- global: global$5
1399
+ global: global$6
1160
1400
  } = global_1;
1161
1401
 
1162
- function handleError$6(error, isQuit = false) {
1402
+ function handleError$5(error, isQuit = false) {
1163
1403
  const errMsg = typeof error === 'object' ? error.message : error;
1164
1404
 
1165
1405
  if (isQuit) {
1166
- fail$8(errMsg);
1406
+ fail$6(errMsg);
1167
1407
  process.exit(1);
1168
1408
  }
1169
1409
 
1170
- const isDev = global$5.getData('isDev');
1410
+ const isDev = global$6.getData('isDev');
1171
1411
 
1172
1412
  if (isDev) {
1173
- fail$8(errMsg);
1413
+ fail$6(errMsg);
1174
1414
  } else {
1175
- fail$8(errMsg);
1415
+ fail$6(errMsg);
1176
1416
  process.exit(1);
1177
1417
  }
1178
1418
  }
1179
1419
 
1180
1420
  var handleError_1 = {
1181
- handleError: handleError$6
1421
+ handleError: handleError$5
1182
1422
  };
1183
1423
 
1184
1424
  /**
@@ -1186,25 +1426,26 @@ var handleError_1 = {
1186
1426
  */
1187
1427
  /* eslint-disable no-param-reassign */
1188
1428
 
1189
- const fs$c = require$$0__default$2;
1429
+ const fs$b = require$$0__default$1;
1190
1430
  const {
1191
1431
  getSubPackages: getSubPackages$3,
1192
1432
  getModulesConfig
1193
1433
  } = tmsMpconfig.exports;
1194
1434
  const {
1195
- fail: fail$7,
1196
- info: info$9
1435
+ fail: fail$5,
1436
+ info: info$8
1197
1437
  } = log$1;
1198
1438
  const {
1199
- resolve: resolve$c,
1200
- filterField: filterField$3
1439
+ resolve: resolve$b,
1440
+ filterField: filterField$4
1201
1441
  } = widgets;
1202
1442
  const {
1203
- handleError: handleError$5
1443
+ handleError: handleError$4
1204
1444
  } = handleError_1;
1205
1445
  const {
1206
- global: global$4
1446
+ global: global$5
1207
1447
  } = global_1;
1448
+ const report$6 = report_1;
1208
1449
  /**
1209
1450
  * 更新appJson里面的主包配置
1210
1451
  * @param { object } appJson appJson信息
@@ -1212,7 +1453,7 @@ const {
1212
1453
  * @returns { object } appJson小程序主页配置信息
1213
1454
  */
1214
1455
 
1215
- function updateMainPackages(appJson, mainPackages = []) {
1456
+ function updateMainPackages(appJson, mainPackages) {
1216
1457
  let foundMainPackages = appJson.subpackages.filter(subpackage => mainPackages.includes(subpackage.name));
1217
1458
 
1218
1459
  if (foundMainPackages.length === 0) {
@@ -1223,7 +1464,7 @@ function updateMainPackages(appJson, mainPackages = []) {
1223
1464
 
1224
1465
  foundMainPackages.forEach(subpackage => {
1225
1466
  if (!subpackage.pages || !subpackage.pages.length) {
1226
- fail$7(`主包 ${subpackage} 不能没有 pages`);
1467
+ fail$5(`主包 ${subpackage} 不能没有 pages`);
1227
1468
  process.exit(-1);
1228
1469
  }
1229
1470
 
@@ -1248,12 +1489,12 @@ function updateMainPackages(appJson, mainPackages = []) {
1248
1489
 
1249
1490
 
1250
1491
  const getAppJsonContent = sourceAppJsonPath => {
1251
- if (!fs$c.existsSync(sourceAppJsonPath)) {
1252
- fail$7(`当前路径 ${sourceAppJsonPath} 没找到app.json`);
1492
+ if (!fs$b.existsSync(sourceAppJsonPath)) {
1493
+ fail$5(`当前路径 ${sourceAppJsonPath} 没找到app.json`);
1253
1494
  process.exit(1);
1254
1495
  }
1255
1496
 
1256
- const appJson = JSON.parse(fs$c.readFileSync(sourceAppJsonPath), 'utf-8'); // 加入默认值
1497
+ const appJson = JSON.parse(fs$b.readFileSync(sourceAppJsonPath), 'utf-8'); // 加入默认值
1257
1498
 
1258
1499
  appJson.subpackages = [];
1259
1500
  appJson.pages = [];
@@ -1298,7 +1539,7 @@ const fixAppJson = appJson => {
1298
1539
  appJson[key] = preloadRuleMap;
1299
1540
  }
1300
1541
  });
1301
- return filterField$3(subp, [...arrOfFileType, ...objOfFileType, 'dependencies', 'path']);
1542
+ return filterField$4(subp, [...arrOfFileType, ...objOfFileType, 'dependencies', 'path']);
1302
1543
  }); // 如果plugins重复,则错误提示
1303
1544
 
1304
1545
  const pluginsErrMsg = Object.keys(pluginsMap).map(pk => {
@@ -1332,7 +1573,7 @@ function buildOutputAppJson$2(tmsConfig, modules) {
1332
1573
 
1333
1574
  const subPackages = getSubPackages$3(modulesConfig); // 获取app.json的配置
1334
1575
 
1335
- const appJson = getAppJsonContent(resolve$c('./app.json')); // 更新app.json中的subpackages
1576
+ const appJson = getAppJsonContent(resolve$b('./app.json')); // 更新app.json中的subpackages
1336
1577
 
1337
1578
  appJson.subpackages = subPackages;
1338
1579
  appJson.subpackages.sort((item1, item2) => item1.name.localeCompare(item2.name)); // 处理appJson中重复||冲突的地方
@@ -1340,23 +1581,24 @@ function buildOutputAppJson$2(tmsConfig, modules) {
1340
1581
  fixAppJson(appJson); // 更新主包,需在subpackages处理完成后执行, pages/
1341
1582
 
1342
1583
  updateMainPackages(appJson, tmsConfig.mainPackages);
1343
- fs$c.writeFileSync(resolve$c(`${tmsConfig.outputDir}/app.json`), JSON.stringify(appJson, null, 2), 'utf8');
1584
+ fs$b.writeFileSync(resolve$b(`${tmsConfig.outputDir}/app.json`), JSON.stringify(appJson, null, 2), 'utf8');
1344
1585
 
1345
1586
  if (typeof (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks = tmsConfig.hooks) === null || _tmsConfig$hooks === void 0 ? void 0 : _tmsConfig$hooks.updateAppJson) === 'function') {
1346
1587
  var _tmsConfig$hooks2;
1347
1588
 
1348
1589
  tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks2 = tmsConfig.hooks) === null || _tmsConfig$hooks2 === void 0 ? void 0 : _tmsConfig$hooks2.updateAppJson({
1349
- tmsConfig: filterField$3(tmsConfig, ['gitAccount']),
1590
+ tmsConfig: filterField$4(tmsConfig, ['gitAccount']),
1350
1591
  modules,
1351
1592
  appJson,
1352
- isDev: global$4.getData('isDev')
1593
+ isDev: global$5.getData('isDev')
1353
1594
  });
1595
+ report$6('hooks:updateAppJson');
1354
1596
  }
1355
1597
 
1356
1598
  return appJson;
1357
1599
  } catch (e) {
1358
- handleError$5(`生成app.json出现错误: ${e}`);
1359
- info$9(e);
1600
+ handleError$4(`生成app.json出现错误: ${e}`);
1601
+ info$8(e);
1360
1602
  }
1361
1603
  }
1362
1604
 
@@ -1367,24 +1609,24 @@ var buildAppJson = {
1367
1609
  /**
1368
1610
  * 下载第三方代码
1369
1611
  */
1370
- const MetalSmith = require$$0__default$5;
1612
+ const MetalSmith = require$$0__default$4;
1371
1613
  const crypto$2 = require$$1__default$5;
1372
1614
  const {
1373
1615
  downloadRepoForGit,
1374
1616
  pullRepoForGit,
1375
- resolve: resolve$b
1617
+ resolve: resolve$a
1376
1618
  } = widgets;
1377
1619
  const {
1378
- fail: fail$6,
1379
- info: info$8
1620
+ fail: fail$4,
1621
+ info: info$7
1380
1622
  } = log$1;
1381
- const fs$b = require$$0__default$2;
1382
- const shelljs$5 = require$$0__default$3;
1623
+ const fs$a = require$$0__default$1;
1624
+ const shelljs$6 = require$$2__default;
1383
1625
  const {
1384
- handleError: handleError$4
1626
+ handleError: handleError$3
1385
1627
  } = handleError_1;
1386
1628
  const {
1387
- global: global$3
1629
+ global: global$4
1388
1630
  } = global_1;
1389
1631
  /**
1390
1632
  * 处理用户没有clone git仓库权限问题,拼接tms.private.config.js的账号信息
@@ -1397,7 +1639,7 @@ function replaceGitUrlAccount(httpRepoUrl, moduleName) {
1397
1639
  var _tmsConfig$gitAccount;
1398
1640
 
1399
1641
  // 用户本地的私有项目配置(用来配置环境\模块信息\账号信息)
1400
- const tmsConfig = global$3.getData('tmsConfig');
1642
+ const tmsConfig = global$4.getData('tmsConfig');
1401
1643
  let gitUrl = httpRepoUrl;
1402
1644
  const {
1403
1645
  username = '',
@@ -1420,12 +1662,16 @@ function replaceGitUrlAccount(httpRepoUrl, moduleName) {
1420
1662
  */
1421
1663
 
1422
1664
 
1423
- function moveFile(sourceDir, targetDir, ignore = []) {
1424
- // 删除不是文件夹的文件
1665
+ function moveFile(sourceDir, targetDir, ignore) {
1666
+ if (fs$a.existsSync(targetDir)) {
1667
+ shelljs$6.rm('-rf', targetDir);
1668
+ } // 删除不是文件夹的文件
1669
+
1670
+
1425
1671
  return new Promise((resolve, reject) => {
1426
1672
  MetalSmith(__dirname).ignore(ignore).source(sourceDir).destination(targetDir).build(e => {
1427
1673
  if (e) {
1428
- fail$6(`${sourceDir} moveFile ${targetDir}出现错误: ${e}`);
1674
+ fail$4(`${sourceDir} moveFile ${targetDir}出现错误: ${e}`);
1429
1675
  reject(e);
1430
1676
  }
1431
1677
 
@@ -1474,11 +1720,11 @@ async function cloneModules$1(sourceDir, targetDir, modules) {
1474
1720
  }) => fn(...Object.keys(cParams).map(key => cParams[key])));
1475
1721
  return Promise.all(callArr);
1476
1722
  }).catch(e => {
1477
- handleError$4(`下载代码${params.httpRepoUrl}出现错误:${e}`);
1723
+ handleError$3(`下载代码${params.httpRepoUrl}出现错误:${e}`);
1478
1724
  }));
1479
1725
  });
1480
1726
  await Promise.all(arrPromises);
1481
- shelljs$5.cd(cwd);
1727
+ shelljs$6.cd(cwd);
1482
1728
  }
1483
1729
  /**
1484
1730
  * 收集下载模块代码的任务
@@ -1519,9 +1765,9 @@ function collectDownLoadTasksMap(sourceDir, targetDir, modules) {
1519
1765
 
1520
1766
  const md5Key = md5ByGitUrlBranch(gitUrl, branch); // git源码临时存在的源目录
1521
1767
 
1522
- const sourcePath = resolve$b(sourceDir, md5Key); // 模块源码要放到目标目录
1768
+ const sourcePath = resolve$a(sourceDir, md5Key); // 模块源码要放到目标目录
1523
1769
 
1524
- const targetPath = resolve$b(targetDir, path); // 从git源码仓库中找到模块源码路径 (一个仓库存在存放多个模块的情况)
1770
+ const targetPath = resolve$a(targetDir, path); // 从git源码仓库中找到模块源码路径 (一个仓库存在存放多个模块的情况)
1525
1771
 
1526
1772
  const sourceModulePath = gitPath ? `${sourcePath}/${gitPath}` : sourcePath; // 下载完代码后,添加回调函数(主要将模块代码从临时目录移动代码到目标目录)
1527
1773
 
@@ -1531,8 +1777,8 @@ function collectDownLoadTasksMap(sourceDir, targetDir, modules) {
1531
1777
  targetPath
1532
1778
  },
1533
1779
  fn: async (sourceModulePath, targetPath) => {
1534
- if (fs$b.existsSync(targetPath)) {
1535
- shelljs$5.rm('-rf', `${targetPath}/*`);
1780
+ if (fs$a.existsSync(targetPath)) {
1781
+ shelljs$6.rm('-rf', `${targetPath}/*`);
1536
1782
  }
1537
1783
 
1538
1784
  await moveFile(`${sourceModulePath}`, targetPath, ['node_modules', '.git']);
@@ -1546,14 +1792,14 @@ function collectDownLoadTasksMap(sourceDir, targetDir, modules) {
1546
1792
  } else {
1547
1793
  let promiseTask;
1548
1794
 
1549
- if (fs$b.existsSync(sourcePath) && fs$b.existsSync(`${sourcePath}/.git`)) {
1795
+ if (fs$a.existsSync(sourcePath) && fs$a.existsSync(`${sourcePath}/.git`)) {
1550
1796
  promiseTask = (gitUrl, sourcePath, branch, httpRepoUrl) => {
1551
- info$8(`git pull:${httpRepoUrl}`);
1797
+ info$7(`git pull:${httpRepoUrl}`);
1552
1798
  return pullRepoForGit(sourcePath, branch);
1553
1799
  };
1554
1800
  } else {
1555
1801
  promiseTask = (gitUrl, sourcePath, branch, httpRepoUrl) => {
1556
- info$8(`git clone: ${httpRepoUrl}`);
1802
+ info$7(`git clone: ${httpRepoUrl}`);
1557
1803
  return downloadRepoForGit(gitUrl, sourcePath, branch);
1558
1804
  };
1559
1805
  }
@@ -1594,7 +1840,7 @@ function checkRemoteModGitUrlBranch(sourceDir, moduleInfo) {
1594
1840
  const gitUrl = replaceGitUrlAccount(httpRepoUrl, moduleName);
1595
1841
  const md5Key = md5ByGitUrlBranch(gitUrl, buildGitTag);
1596
1842
 
1597
- if (!fs$b.existsSync(`${sourceDir}/${md5Key}`)) {
1843
+ if (!fs$a.existsSync(`${sourceDir}/${md5Key}`)) {
1598
1844
  return true;
1599
1845
  }
1600
1846
  }
@@ -1607,8 +1853,8 @@ var cloneModules_1 = {
1607
1853
  checkRemoteModGitUrlBranch
1608
1854
  };
1609
1855
 
1610
- const ci = require$$0__default$7;
1611
- const path$a = require$$1__default$2;
1856
+ const ci = require$$0__default$6;
1857
+ const path$a = require$$1__default$1;
1612
1858
  /**
1613
1859
  * 获取小程序ci的Project对象
1614
1860
  * @returns {Object} 小程序ci对象
@@ -1688,22 +1934,21 @@ var mpCi = {
1688
1934
  buildMpNpm: buildMpNpm$1
1689
1935
  };
1690
1936
 
1691
- const fs$a = require$$0__default$2;
1692
- const path$9 = require$$1__default$2;
1937
+ const fs$9 = require$$0__default$1;
1938
+ const path$9 = require$$1__default$1;
1693
1939
  const {
1694
- CACHE_FILE,
1695
- CACHE_DIR: CACHE_DIR$2
1696
- } = require$$4;
1940
+ NPM_CACHE_FILE
1941
+ } = constant;
1697
1942
  const {
1698
- ensureDirExist: ensureDirExist$1
1943
+ ensureDirExist: ensureDirExist$2
1699
1944
  } = io$3;
1700
1945
 
1701
1946
  function getCache$1(projectDir, type) {
1702
1947
  var _content$projectDir;
1703
1948
 
1704
- const filePath = `${CACHE_DIR$2}/${CACHE_FILE}`;
1949
+ const filePath = NPM_CACHE_FILE;
1705
1950
 
1706
- if (!fs$a.existsSync(filePath)) {
1951
+ if (!fs$9.existsSync(filePath)) {
1707
1952
  return null;
1708
1953
  }
1709
1954
 
@@ -1713,12 +1958,12 @@ function getCache$1(projectDir, type) {
1713
1958
  }
1714
1959
 
1715
1960
  function setCache$1(projectDir, type = 'miniprogram_npm', data) {
1716
- const filePath = `${CACHE_DIR$2}/${CACHE_FILE}`;
1961
+ const filePath = NPM_CACHE_FILE;
1717
1962
 
1718
- if (!fs$a.existsSync(filePath)) {
1963
+ if (!fs$9.existsSync(filePath)) {
1719
1964
  const dir = path$9.dirname(filePath);
1720
- ensureDirExist$1(dir);
1721
- fs$a.writeFileSync(filePath, '{}');
1965
+ ensureDirExist$2(dir);
1966
+ fs$9.writeFileSync(filePath, '{}');
1722
1967
  }
1723
1968
 
1724
1969
  const content = require(filePath);
@@ -1730,7 +1975,7 @@ function setCache$1(projectDir, type = 'miniprogram_npm', data) {
1730
1975
  content[projectDir] = {
1731
1976
  [type]: data
1732
1977
  };
1733
- fs$a.writeFileSync(filePath, JSON.stringify(content, null, 2));
1978
+ fs$9.writeFileSync(filePath, JSON.stringify(content, null, 2));
1734
1979
  }
1735
1980
 
1736
1981
  var cache = {
@@ -1741,19 +1986,21 @@ var cache = {
1741
1986
  /**
1742
1987
  * 本文件主要负责项目或者分包依赖的npm的安装
1743
1988
  */
1744
- const fs$9 = require$$0__default$2;
1989
+ const fs$8 = require$$0__default$1;
1745
1990
  const fsExtra = require$$1__default$6;
1746
1991
  const crypto$1 = require$$1__default$5;
1747
- const path$8 = require$$1__default$2;
1748
- const shell = require$$0__default$3;
1749
- const glob = require$$6__default;
1992
+ const path$8 = require$$1__default$1;
1993
+ const shell = require$$2__default;
1750
1994
  const log = log$1;
1751
1995
  const {
1752
1996
  npmInstall: npmInstall$1
1753
1997
  } = widgets;
1754
1998
  const {
1755
- handleError: handleError$3
1999
+ handleError: handleError$2
1756
2000
  } = handleError_1;
2001
+ const {
2002
+ global: global$3
2003
+ } = global_1;
1757
2004
  const shellJsOption = {
1758
2005
  async: false,
1759
2006
  silent: true
@@ -1776,7 +2023,7 @@ const collectNpmTasksMap = (packageJsonFiles, cacheDir) => {
1776
2023
  const npmTasksMap = new Map();
1777
2024
 
1778
2025
  for (const packageJsonPath of packageJsonFiles) {
1779
- const packageContent = fs$9.readFileSync(packageJsonPath);
2026
+ const packageContent = fs$8.readFileSync(packageJsonPath);
1780
2027
  let packageJson;
1781
2028
 
1782
2029
  try {
@@ -1827,7 +2074,8 @@ const collectNpmTasksMap = (packageJsonFiles, cacheDir) => {
1827
2074
  fsExtra.emptydirSync(cacheNMPath);
1828
2075
  shell.cp('-f', packageJsonPath, cacheNMPath);
1829
2076
  log.info(`npm install: ${packageJsonPath}`);
1830
- return npmInstall$1(cacheNMPath).then(() => {
2077
+ const tmsConfig = global$3.getData('tmsConfig');
2078
+ return npmInstall$1(cacheNMPath, tmsConfig.npm).then(() => {
1831
2079
  const newShellJsOption = { ...shellJsOption,
1832
2080
  cwd: cacheNMPath
1833
2081
  };
@@ -1855,9 +2103,9 @@ const collectNpmTasksMap = (packageJsonFiles, cacheDir) => {
1855
2103
  }; // 遍历安装指定目录下所有项目的npm依赖
1856
2104
 
1857
2105
 
1858
- const npmInstallAll$1 = async (modules, contextDir, cacheDir) => {
2106
+ const npmInstallAll$1 = async (subPackages, contextDir, cacheDir) => {
1859
2107
  const cwd = process.cwd();
1860
- const packageJsonFiles = await findAllPackageJson(modules, contextDir); // 收集npm install的任务
2108
+ const packageJsonFiles = await findAllPackageJson(subPackages, contextDir); // 收集npm install的任务
1861
2109
 
1862
2110
  const npmTasksMap = collectNpmTasksMap(packageJsonFiles, cacheDir); // 开始执行npm install和回调(移动)的任务
1863
2111
 
@@ -1874,7 +2122,7 @@ const npmInstallAll$1 = async (modules, contextDir, cacheDir) => {
1874
2122
  }) => fn(...Object.keys(cParams).map(key => cParams[key])));
1875
2123
  return Promise.all(callArr);
1876
2124
  }).catch(e => {
1877
- handleError$3(`npm install ${params.packageJsonPath}出现错误:${e}`, true);
2125
+ handleError$2(`npm install ${params.packageJsonPath}出现错误:${e}`, true);
1878
2126
  }));
1879
2127
  });
1880
2128
  await Promise.all(arrPromises);
@@ -1900,7 +2148,7 @@ const findFilesByFilter = (startPath, filter) => {
1900
2148
 
1901
2149
  const find = (startPath, filter) => {
1902
2150
  // 目录不存在
1903
- if (!fs$9.existsSync(startPath)) {
2151
+ if (!fs$8.existsSync(startPath)) {
1904
2152
  log.fail(`${startPath}目录不存在`);
1905
2153
  process.exit(-1);
1906
2154
  return;
@@ -1913,10 +2161,10 @@ const findFilesByFilter = (startPath, filter) => {
1913
2161
  return;
1914
2162
  }
1915
2163
 
1916
- const files = fs$9.readdirSync(startPath);
2164
+ const files = fs$8.readdirSync(startPath);
1917
2165
  files.forEach(file => {
1918
2166
  const filename = path$8.join(startPath, file);
1919
- const stat = fs$9.lstatSync(filename); // 当前文件是文件夹类型,继续递归
2167
+ const stat = fs$8.lstatSync(filename); // 当前文件是文件夹类型,继续递归
1920
2168
 
1921
2169
  if (stat.isDirectory()) {
1922
2170
  find(filename, filter);
@@ -1945,11 +2193,6 @@ const findAllPackageJson = (subRoots = [], contextDir) => {
1945
2193
  const result = [path$8.join(cwd, packageJsonName)]; // 默认填充根目录下的package.json
1946
2194
 
1947
2195
  subRoots.forEach(subRoot => {
1948
- if (!subRoot.root) {
1949
- log.fail(`请检查${subRoot.name}的module.config.json是否有root字段`);
1950
- process.exit(1);
1951
- }
1952
-
1953
2196
  const toppath = path$8.join(cwd, subRoot.root); // 从该目录开始查找package.json文件
1954
2197
 
1955
2198
  const list = findFilesByFilter(toppath, packageJsonName);
@@ -1958,38 +2201,19 @@ const findAllPackageJson = (subRoots = [], contextDir) => {
1958
2201
  return result;
1959
2202
  };
1960
2203
 
1961
- function cloudNpmInstall(contextDir) {
1962
- return new Promise((resolve, reject) => {
1963
- glob(`${contextDir}/**/package.json`, ['node_modules', 'miniprogram_npm'], (err, files) => {
1964
- if (err) {
1965
- reject(err);
1966
- }
1967
-
1968
- files.forEach(file => {
1969
- const dir = path$8.dirname(file);
1970
- shell.cd(dir);
1971
- shell.exec('npx npm install --production --registry http://mirrors.tencent.com/npm/', {
1972
- silent: false
1973
- });
1974
- });
1975
- resolve();
1976
- });
1977
- });
1978
- }
1979
-
1980
2204
  var npm = {
1981
- cloudNpmInstall,
1982
2205
  npmInstallAll: npmInstallAll$1,
1983
- findAllPackageJson
2206
+ findAllPackageJson,
2207
+ findFilesByFilter
1984
2208
  };
1985
2209
 
1986
2210
  const crypto = require$$1__default$5;
1987
- const fs$8 = require$$0__default$2;
2211
+ const fs$7 = require$$0__default$1;
1988
2212
 
1989
2213
  function fileMd5$1(filePath) {
1990
2214
  return new Promise((resolve, reject) => {
1991
2215
  const md5sum = crypto.createHash('md5');
1992
- const stream = fs$8.ReadStream(filePath);
2216
+ const stream = fs$7.ReadStream(filePath);
1993
2217
  stream.on('data', d => {
1994
2218
  md5sum.update(d);
1995
2219
  });
@@ -2007,39 +2231,45 @@ var md5 = {
2007
2231
  fileMd5: fileMd5$1
2008
2232
  };
2009
2233
 
2010
- const fs$7 = require$$0__default$2;
2234
+ const fs$6 = require$$0__default$1;
2011
2235
  const semver$1 = require$$1__default$7;
2012
2236
  const {
2013
- resolve: resolve$a
2237
+ resolve: resolve$9,
2238
+ getAbsolutePath: getAbsolutePath$2
2014
2239
  } = widgets;
2015
- const path$7 = require$$1__default$2;
2016
- const shelljs$4 = require$$0__default$3;
2240
+ const path$7 = require$$1__default$1;
2241
+ const shelljs$5 = require$$2__default;
2017
2242
  const {
2018
- handleError: handleError$2
2243
+ handleError: handleError$1
2019
2244
  } = handleError_1;
2020
2245
 
2021
2246
  const getLatestVersion = npmName => {
2022
- const data = shelljs$4.exec(`npm view ${npmName} version`);
2023
- return data.stdout || '0.0.0';
2247
+ const data = shelljs$5.exec(`npm view ${npmName} version`);
2248
+
2249
+ if (data.code === 0) {
2250
+ return data.stdout;
2251
+ }
2252
+
2253
+ return '0.0.0';
2024
2254
  }; // 收集package.json
2025
2255
 
2026
2256
 
2027
- function collectHasPackageJson(modules, cwd, outputDir) {
2257
+ function collectPackageJson(subPackages, cwd, outputDir) {
2028
2258
  const packageJsonName = 'package.json'; // 查找文件名
2029
2259
  // 1.1根目录的package.json
2030
2260
 
2031
2261
  const packageArr = [{
2032
2262
  srcPackageDir: path$7.join(cwd, packageJsonName),
2033
- destNpmDir: resolve$a(outputDir, 'node_modules')
2263
+ destNpmDir: resolve$9(outputDir, 'node_modules')
2034
2264
  }]; // 1.2模块的package.json
2035
2265
 
2036
- modules.forEach(item => {
2037
- const srcPackageDir = path$7.join(cwd, item.path, 'package.json');
2266
+ subPackages.forEach(item => {
2267
+ const srcPackageDir = `${getAbsolutePath$2(item.path)}/package.json`;
2038
2268
 
2039
- if (fs$7.existsSync(srcPackageDir)) {
2269
+ if (fs$6.existsSync(srcPackageDir)) {
2040
2270
  packageArr.push({
2041
2271
  srcPackageDir,
2042
- destNpmDir: resolve$a(outputDir, item.root, 'node_modules')
2272
+ destNpmDir: resolve$9(outputDir, item.root, 'node_modules')
2043
2273
  });
2044
2274
  }
2045
2275
  });
@@ -2048,30 +2278,30 @@ function collectHasPackageJson(modules, cwd, outputDir) {
2048
2278
 
2049
2279
 
2050
2280
  function readPackageDependencies(srcPackageDir) {
2051
- const packageJson = fs$7.readFileSync(srcPackageDir, 'utf-8');
2281
+ const packageJson = fs$6.readFileSync(srcPackageDir, 'utf-8');
2052
2282
  let dependencies = {};
2053
2283
 
2054
2284
  try {
2055
2285
  const json = packageJson ? JSON.parse(packageJson) : {};
2056
2286
  dependencies = (json === null || json === void 0 ? void 0 : json.dependencies) || {};
2057
2287
  } catch (e) {
2058
- handleError$2(`解析${srcPackageDir}报错,请检查是否是正确的json配置项 ${e}`);
2288
+ handleError$1(`解析${srcPackageDir}报错,请检查是否是正确的json配置项 ${e}`);
2059
2289
  }
2060
2290
 
2061
2291
  return dependencies;
2062
2292
  }
2063
2293
  /**
2064
2294
  * 检查package.json的依赖大于node_module的版本,则返回true
2065
- * @param {*} modules 模块
2295
+ * @param {*} subPackages 模块
2066
2296
  * @param {*} cwd 待检查package.json所在的目录 (eg: 当前执行脚本的目录)
2067
2297
  * @param {*} outputDir 待检查node_modules存放的目录 (eg: dist/node_modules)
2068
2298
  * @returns
2069
2299
  */
2070
2300
 
2071
2301
 
2072
- const isDependenciesUpdate$1 = (modules, cwd, outputDir) => {
2302
+ const isDependenciesUpdate$1 = (subPackages, cwd, outputDir) => {
2073
2303
  // 步骤1. 收集package.json
2074
- const packageArr = collectHasPackageJson(modules, cwd, outputDir); // 步骤2. 比较package.json的依赖与node_modules依赖的版本号
2304
+ const packageArr = collectPackageJson(subPackages, cwd, outputDir); // 步骤2. 比较package.json的依赖与node_modules依赖的版本号
2075
2305
 
2076
2306
  return checkPackageVersion$1(packageArr);
2077
2307
  }; // 比较package.json的依赖与node_modules依赖的版本号
@@ -2085,13 +2315,13 @@ const checkPackageVersion$1 = packageArr => {
2085
2315
  for (const key of dependenciesKeys) {
2086
2316
  const depPath = path$7.join(item.destNpmDir, key);
2087
2317
 
2088
- if (!fs$7.existsSync(depPath)) {
2318
+ if (!fs$6.existsSync(depPath)) {
2089
2319
  return true;
2090
2320
  }
2091
2321
 
2092
2322
  const depPackagePath = path$7.join(depPath, 'package.json');
2093
2323
 
2094
- if (fs$7.existsSync(depPackagePath)) {
2324
+ if (fs$6.existsSync(depPackagePath)) {
2095
2325
  const packageData = require(depPackagePath);
2096
2326
 
2097
2327
  if (dependencies[key] === 'latest') {
@@ -2117,13 +2347,14 @@ var checkDependencies = {
2117
2347
  checkPackageVersion: checkPackageVersion$1
2118
2348
  };
2119
2349
 
2120
- const shelljs$3 = require$$0__default$3;
2121
- const fs$6 = require$$0__default$2;
2122
- const path$6 = require$$1__default$2;
2350
+ const shelljs$4 = require$$2__default;
2351
+ const fs$5 = require$$0__default$1;
2352
+ const path$6 = require$$1__default$1;
2123
2353
  const io$1 = io$3;
2124
2354
  const {
2125
2355
  createTask: createTask$1,
2126
- resolve: resolve$9
2356
+ resolve: resolve$8,
2357
+ getAbsolutePath: getAbsolutePath$1
2127
2358
  } = widgets;
2128
2359
  const {
2129
2360
  buildMpNpm
@@ -2133,14 +2364,13 @@ const {
2133
2364
  getCache
2134
2365
  } = cache;
2135
2366
  const {
2136
- CACHE_DIR: CACHE_DIR$1
2137
- } = require$$4;
2367
+ NODE_MODULES_DIR: NODE_MODULES_DIR$1
2368
+ } = constant;
2138
2369
  const {
2139
2370
  npmInstallAll
2140
2371
  } = npm;
2141
2372
  const {
2142
- fail: fail$5,
2143
- info: info$7
2373
+ info: info$6
2144
2374
  } = log$1;
2145
2375
  const {
2146
2376
  fileMd5
@@ -2149,62 +2379,56 @@ const {
2149
2379
  isDependenciesUpdate
2150
2380
  } = checkDependencies;
2151
2381
 
2152
- async function install$2(tmsConfig, modules, useCache = true) {
2382
+ async function install$2(tmsConfig, subPackages, useCache) {
2153
2383
  const cwd = process.cwd();
2154
- const npmInstallRes = await createTask$1(npmInstall, '小程序 开始npm install', '小程序npm install 完成')(tmsConfig, modules, useCache); // 如果npm install 没有命中缓存,则说明node_module有更新,此时必须构建miniprogram_npm
2384
+ const npmInstallRes = await createTask$1(npmInstall, '小程序 开始npm install', '小程序npm install 完成')(tmsConfig, subPackages, useCache); // 如果npm install 没有命中缓存,则说明node_module有更新,此时必须构建miniprogram_npm
2155
2385
 
2156
2386
  if (!npmInstallRes.isCache) {
2157
2387
  // 构建miniprogram_npm, 不使用缓存
2158
- await createTask$1(mpCiInstall, '开始构建miniprogram_npm', '构建miniprogram_npm 完成')(tmsConfig, modules, false);
2388
+ await createTask$1(mpCiInstall, '开始构建miniprogram_npm', '构建miniprogram_npm 完成')(tmsConfig, subPackages, false);
2159
2389
  } else {
2160
2390
  // 构建miniprogram_npm
2161
- await createTask$1(mpCiInstall, '开始构建miniprogram_npm', '构建miniprogram_npm 完成')(tmsConfig, modules, useCache);
2391
+ await createTask$1(mpCiInstall, '开始构建miniprogram_npm', '构建miniprogram_npm 完成')(tmsConfig, subPackages, useCache);
2162
2392
  }
2163
2393
 
2164
- shelljs$3.cd(cwd);
2394
+ shelljs$4.cd(cwd);
2165
2395
  }
2166
2396
 
2167
- async function npmInstall(tmsConfig, modules, useCache) {
2397
+ async function npmInstall(tmsConfig, subPackages, useCache) {
2168
2398
  // 如果依赖没有更新和使用缓存数据(则命中缓存)
2169
- if (!isDependenciesUpdate(modules, resolve$9('./'), tmsConfig.outputDir) && useCache) {
2170
- info$7('node_modules命中缓存');
2399
+ if (!isDependenciesUpdate(subPackages, resolve$8('./'), tmsConfig.outputDir) && useCache) {
2400
+ info$6('node_modules命中缓存');
2171
2401
  return {
2172
2402
  isCache: true
2173
2403
  };
2174
2404
  } // 拷贝模块的package.json到编译输出目录
2175
2405
 
2176
2406
 
2177
- modules.forEach(item => {
2178
- const outputModuleDir = resolve$9(`${tmsConfig.outputDir}/${item.root}`);
2179
-
2180
- if (!fs$6.existsSync(resolve$9(item.path))) {
2181
- fail$5(`${item.path}模块代码路径不存在, 请检查tms.config.js的${item.name}模块的path`);
2182
- process.exit(1);
2183
- }
2184
-
2407
+ subPackages.forEach(item => {
2408
+ const outputModuleDir = resolve$8(`${tmsConfig.outputDir}/${item.root}`);
2185
2409
  io$1.ensureDirExist(outputModuleDir);
2186
- const modulePackagePath = resolve$9(item.path, 'package.json');
2187
- if (fs$6.existsSync(modulePackagePath)) shelljs$3.cp('-Rf', modulePackagePath, outputModuleDir);
2410
+ const modulePackagePath = `${getAbsolutePath$1(item.path)}/package.json`;
2411
+ if (fs$5.existsSync(modulePackagePath)) shelljs$4.cp('-Rf', modulePackagePath, outputModuleDir);
2188
2412
  });
2189
- await npmInstallAll(modules, resolve$9(tmsConfig.outputDir), `${CACHE_DIR$1}/node_modules`);
2413
+ await npmInstallAll(subPackages, resolve$8(tmsConfig.outputDir), NODE_MODULES_DIR$1);
2190
2414
  return {
2191
2415
  isCache: false
2192
2416
  };
2193
2417
  } // 构建miniprogram_npm
2194
2418
 
2195
2419
 
2196
- async function mpCiInstall(tmsConfig, modules, useCache) {
2420
+ async function mpCiInstall(tmsConfig, subPackages, useCache) {
2197
2421
  const packageJsonFiles = [];
2198
- const rootPackFile = resolve$9(`${tmsConfig.outputDir}/package.json`);
2422
+ const rootPackFile = resolve$8(`${tmsConfig.outputDir}/package.json`);
2199
2423
 
2200
- if (fs$6.existsSync(rootPackFile)) {
2424
+ if (fs$5.existsSync(rootPackFile)) {
2201
2425
  packageJsonFiles.push(rootPackFile);
2202
2426
  }
2203
2427
 
2204
- modules.forEach(item => {
2205
- const packageJsonFile = resolve$9(`${tmsConfig.outputDir}/${item.root}/package.json`);
2428
+ subPackages.forEach(item => {
2429
+ const packageJsonFile = resolve$8(`${tmsConfig.outputDir}/${item.root}/package.json`);
2206
2430
 
2207
- if (fs$6.existsSync(packageJsonFile)) {
2431
+ if (fs$5.existsSync(packageJsonFile)) {
2208
2432
  packageJsonFiles.push(packageJsonFile);
2209
2433
  }
2210
2434
  });
@@ -2218,7 +2442,7 @@ async function mpCiInstall(tmsConfig, modules, useCache) {
2218
2442
  let flag = true;
2219
2443
  await Promise.all(packageJsonFiles.map(async item => {
2220
2444
  const packageDir = path$6.dirname(item);
2221
- const mpDir = resolve$9(`${packageDir}/miniprogram_npm`);
2445
+ const mpDir = resolve$8(`${packageDir}/miniprogram_npm`);
2222
2446
  const md5Value = await getMNPMd5(packageDir);
2223
2447
  const preCache = getCache(mpDir, 'miniprogram_npm'); // console.log('miniprogram_npm', preCache, md5Value);
2224
2448
  // 上一次构建成功 && 上次md5与当前本地的miniprogram_npm的md5 一致,才可以进入缓存
@@ -2231,14 +2455,14 @@ async function mpCiInstall(tmsConfig, modules, useCache) {
2231
2455
  }
2232
2456
 
2233
2457
  if (isCache) {
2234
- info$7('miniprogram_npm命中缓存');
2458
+ info$6('miniprogram_npm命中缓存');
2235
2459
  return;
2236
2460
  } // 即将构建,在cache中标记开始
2237
2461
 
2238
2462
 
2239
2463
  await Promise.all(packageJsonFiles.map(async item => {
2240
2464
  const packageDir = path$6.dirname(item);
2241
- const mpDir = resolve$9(`${packageDir}/miniprogram_npm`);
2465
+ const mpDir = resolve$8(`${packageDir}/miniprogram_npm`);
2242
2466
  setCache(mpDir, 'miniprogram_npm', {
2243
2467
  md5: '',
2244
2468
  status: statusMap.doing
@@ -2246,13 +2470,13 @@ async function mpCiInstall(tmsConfig, modules, useCache) {
2246
2470
  }));
2247
2471
  await buildMpNpm({
2248
2472
  appId: tmsConfig.appId,
2249
- projectPath: resolve$9('./'),
2473
+ projectPath: resolve$8('./'),
2250
2474
  privateKey: tmsConfig.privateKey
2251
2475
  }); // 构建成功后,计算md5写入cache
2252
2476
 
2253
2477
  await Promise.all(packageJsonFiles.map(async item => {
2254
2478
  const packageDir = path$6.dirname(item);
2255
- const mpDir = resolve$9(`${packageDir}/miniprogram_npm`);
2479
+ const mpDir = resolve$8(`${packageDir}/miniprogram_npm`);
2256
2480
  const md5Value = await getMNPMd5(packageDir);
2257
2481
  setCache(mpDir, 'miniprogram_npm', {
2258
2482
  md5: md5Value,
@@ -2267,16 +2491,16 @@ async function getMNPMd5(cwd) {
2267
2491
  async: false,
2268
2492
  silent: true
2269
2493
  };
2270
- shelljs$3.cd(cwd);
2494
+ shelljs$4.cd(cwd);
2271
2495
 
2272
- if (fs$6.existsSync('miniprogram_npm')) {
2273
- shelljs$3.exec('tar -cvf ./miniprogram_npm.tar.gz ./miniprogram_npm', {
2496
+ if (fs$5.existsSync('miniprogram_npm')) {
2497
+ shelljs$4.exec('tar -cvf ./miniprogram_npm.tar.gz ./miniprogram_npm', {
2274
2498
  cwd,
2275
2499
  ...shellJsOption
2276
2500
  });
2277
2501
  const tarDir = path$6.join(cwd, './miniprogram_npm.tar.gz');
2278
2502
  const md5Value = await fileMd5(tarDir);
2279
- shelljs$3.rm('-rf', tarDir);
2503
+ shelljs$4.rm('-rf', tarDir);
2280
2504
  return md5Value;
2281
2505
  }
2282
2506
 
@@ -2285,20 +2509,20 @@ async function getMNPMd5(cwd) {
2285
2509
 
2286
2510
  var install_1 = install$2;
2287
2511
 
2288
- const shelljs$2 = require$$0__default$3;
2289
- const fs$5 = require$$0__default$2;
2512
+ const shelljs$3 = require$$2__default;
2513
+ const fs$4 = require$$0__default$1;
2290
2514
  const io = io$3;
2291
2515
  const {
2292
- resolve: resolve$8,
2516
+ resolve: resolve$7,
2293
2517
  createTask
2294
2518
  } = widgets;
2295
2519
  const {
2296
2520
  buildOutputAppJson: buildOutputAppJson$1
2297
2521
  } = buildAppJson;
2298
2522
  const {
2299
- MODULE_CODE_DIR,
2523
+ MODULE_CODE_DIR: MODULE_CODE_DIR$1,
2300
2524
  DEFAULT_COPY_CONFIG: DEFAULT_COPY_CONFIG$1
2301
- } = require$$4;
2525
+ } = constant;
2302
2526
  const {
2303
2527
  cloneModules
2304
2528
  } = cloneModules_1;
@@ -2307,8 +2531,8 @@ const {
2307
2531
  getSubPackages: getSubPackages$2
2308
2532
  } = tmsMpconfig.exports;
2309
2533
  const {
2310
- fail: fail$4,
2311
- info: info$6
2534
+ fail: fail$3,
2535
+ info: info$5
2312
2536
  } = log$1;
2313
2537
  const install$1 = install_1;
2314
2538
  /**
@@ -2320,48 +2544,26 @@ const install$1 = install_1;
2320
2544
  */
2321
2545
 
2322
2546
  const cpFilesToOutput = function (tmsConfig, defaultFiles) {
2323
- const outputDir = resolve$8(tmsConfig.outputDir);
2547
+ const outputDir = resolve$7(tmsConfig.outputDir);
2324
2548
  io.ensureDirExist(outputDir);
2325
2549
  defaultFiles.forEach(item => {
2326
- if (fs$5.existsSync(resolve$8(item))) {
2327
- shelljs$2.cp('-rf', resolve$8(item), resolve$8(tmsConfig.outputDir, item));
2550
+ if (fs$4.existsSync(resolve$7(item))) {
2551
+ shelljs$3.cp('-rf', resolve$7(item), resolve$7(tmsConfig.outputDir, item));
2328
2552
  }
2329
2553
  });
2330
2554
  };
2331
- /**
2332
- * 校验相关配置项
2333
- * @param {*} targetModules
2334
- * @returns
2335
- */
2336
-
2337
-
2338
- function checkConfig(targetModules) {
2339
- for (const item of targetModules) {
2340
- if (!item.root) {
2341
- throw new Error(`检查${item.name} module.config.json的root字段`);
2342
- } // 判断源码目录是否有该模块
2343
-
2344
-
2345
- if (item.path && !fs$5.existsSync(resolve$8(item.path))) {
2346
- throw new Error(`${item.path}模块代码路径不存在, 请检查tms.config.js的${item.name}模块的path`);
2347
- }
2348
- }
2349
-
2350
- return true;
2351
- }
2352
2555
 
2353
2556
  async function task(tmsConfig, targetModules) {
2354
2557
  // 下载和移动代码
2355
- await createTask(cloneModules, '开始下载模块代码', '下载模块代码码完成')(MODULE_CODE_DIR, resolve$8('./'), targetModules); // 获取所有模块,合并模块依赖的模块
2558
+ await createTask(cloneModules, '开始下载模块代码', '下载模块代码码完成')(MODULE_CODE_DIR$1, resolve$7('./'), targetModules); // 获取所有模块,合并模块依赖的模块
2356
2559
 
2357
2560
  const newModules = getModulesByMergeDepModules$2(tmsConfig, targetModules, true); // 获取所有的分包
2358
2561
 
2359
- const newSubPackages = getSubPackages$2(newModules);
2360
- checkConfig(newSubPackages); // 拷贝相关配置文件到输出目录
2562
+ const newSubPackages = getSubPackages$2(newModules); // 拷贝相关配置文件到输出目录
2361
2563
 
2362
2564
  await createTask(cpFilesToOutput, '开始拷贝文件到编译输出目录', '拷贝文件到编译输出目录完成')(tmsConfig, DEFAULT_COPY_CONFIG$1); // install
2363
2565
 
2364
- await install$1(tmsConfig, newSubPackages); // 动态生成编译后的app.json;
2566
+ await install$1(tmsConfig, newSubPackages, true); // 动态生成编译后的app.json;
2365
2567
 
2366
2568
  await createTask(buildOutputAppJson$1, '开始生成编译后的app.json', '生成编译后的app.json完成')(tmsConfig, newModules);
2367
2569
  return {
@@ -2370,592 +2572,82 @@ async function task(tmsConfig, targetModules) {
2370
2572
  };
2371
2573
  }
2372
2574
 
2373
- async function init$5(tmsConfig, targetModules) {
2575
+ async function init$3(tmsConfig, targetModules) {
2374
2576
  try {
2375
2577
  const taskRes = await task(tmsConfig, targetModules);
2376
2578
  return taskRes;
2377
2579
  } catch (error) {
2378
2580
  const errMsg = typeof error === 'object' ? error.message : error;
2379
- fail$4(`初始化流程出现错误${errMsg}`);
2380
- info$6('详细的错误信息', error);
2381
- process.exit(1);
2382
- }
2383
- }
2384
-
2385
- var init_1 = init$5;
2386
-
2387
- /* eslint-disable no-param-reassign */
2388
- const strip = require$$0__default$8; // 匹配规则
2389
-
2390
- const MATCH_RULE = new RegExp(/@import *(?:url\(['"]?([^'")]+)['"]?\)|['"]([^'"]+)['"]);?/g);
2391
- /**
2392
- * 获取样式文件中的@import语句
2393
- * @param code 代码片段
2394
- * @returns 结果数组
2395
- */
2396
-
2397
- const findCssImports$1 = code => {
2398
- // 将buffer转成字符串
2399
- code = code.toString(); // 去除注释
2400
-
2401
- code = strip.block(code); // 定义最后返回的结果
2402
-
2403
- const result = [];
2404
- let matchList; // 循环遍历代码段,直至匹配结果为空
2405
-
2406
- while (matchList = MATCH_RULE.exec(code)) {
2407
- var _matchList, _matchList2;
2408
-
2409
- // 存入结果数组
2410
- result.push(((_matchList = matchList) === null || _matchList === void 0 ? void 0 : _matchList[1]) || ((_matchList2 = matchList) === null || _matchList2 === void 0 ? void 0 : _matchList2[2]));
2411
- } // 返回结果
2412
-
2413
-
2414
- return result;
2415
- };
2416
-
2417
- var findCssImport = {
2418
- findCssImports: findCssImports$1
2419
- };
2420
-
2421
- /* eslint-disable no-param-reassign */
2422
- const {
2423
- fail: fail$3
2424
- } = log$1;
2425
-
2426
- function pluginError$3(error, isWatch) {
2427
- const errMsg = error.message;
2428
-
2429
- if (isWatch) {
2430
- fail$3(errMsg);
2431
- } else {
2432
- fail$3(errMsg);
2581
+ fail$3(`初始化流程出现错误: ${errMsg}`);
2582
+ info$5('详细的错误信息', error);
2433
2583
  process.exit(1);
2434
2584
  }
2435
2585
  }
2436
2586
 
2437
- var pluginError_1 = {
2438
- pluginError: pluginError$3
2439
- };
2440
-
2441
- /* eslint-disable no-param-reassign */
2442
- const through$2 = require$$0__default$9;
2443
- const precinct = require$$1__default$8;
2444
- const path$5 = require$$1__default$2;
2445
- const {
2446
- findCssImports
2447
- } = findCssImport;
2448
- const {
2449
- ext: ext$2,
2450
- fileInDir: fileInDir$2,
2451
- diffContentCopyFile: diffContentCopyFile$2
2452
- } = io$3;
2453
- const {
2454
- resolve: resolve$7
2455
- } = widgets;
2456
- const fs$4 = require$$0__default$2;
2457
- const {
2458
- pluginError: pluginError$2
2459
- } = pluginError_1;
2460
- const cssFilter = ['.less', '.wxss'];
2461
-
2462
- const dfsFindCommonDep$2 = function (anaFileOriginFile, anaFileDestFile, extensions, isWatch = true) {
2463
- const resDep = new Map();
2464
-
2465
- function dfs(anaFileOriginFile, anaFileDestFile, extensions) {
2466
- let contents = '';
2467
-
2468
- try {
2469
- contents = fs$4.readFileSync(anaFileOriginFile, 'utf8');
2470
- } catch (e) {
2471
- pluginError$2(e, isWatch);
2472
- }
2473
-
2474
- const deps = cssFilter.indexOf(path$5.extname(anaFileOriginFile)) > -1 ? findCssImports(contents) : precinct(contents);
2475
- deps.forEach(depItem => {
2476
- if (depItem.startsWith('.')) {
2477
- // 被依赖文件的存在的绝对路径
2478
- const depOriginPath = path$5.join(path$5.dirname(anaFileOriginFile), depItem); // 被依赖文件加上后缀
2479
-
2480
- const {
2481
- ext: extAlias,
2482
- file: depOriginFile,
2483
- extPath
2484
- } = ext$2(depOriginPath, extensions);
2485
-
2486
- if (!fs$4.existsSync(depOriginFile)) {
2487
- pluginError$2(new Error(`${anaFileOriginFile}引用路径${depOriginFile}文件不存在, 请检查应用路径`), isWatch);
2488
- return;
2489
- }
2490
-
2491
- const depDestPath = resolve$7(path$5.dirname(anaFileDestFile), depItem);
2492
- const depDestFile = depDestPath.endsWith(extAlias) ? depDestPath : depDestPath + extPath;
2493
-
2494
- if (!resDep.has(depDestFile)) {
2495
- resDep.set(depDestFile, {
2496
- anaFileOriginFile,
2497
- anaFileDestFile,
2498
- depDestFile,
2499
- depOriginFile
2500
- });
2501
- dfs(depOriginFile, depDestFile, extensions);
2502
- }
2503
- }
2504
- });
2505
- }
2506
-
2507
- dfs(anaFileOriginFile, anaFileDestFile, extensions);
2508
- return resDep;
2509
- };
2510
-
2511
- function mpCommonDep$1(tmsConfig, module, extensions = [], isWatch = true) {
2512
- const stream = through$2.obj(function (file, enc, cb) {
2513
- // 依赖分析的文件
2514
- const anaFileOriginFile = file.history[0];
2515
- const anaFileRelativeModule = path$5.relative(resolve$7(module.from), anaFileOriginFile);
2516
- const anaFileDestFile = resolve$7(tmsConfig.outputDir, module.to, anaFileRelativeModule);
2517
-
2518
- if (file.isBuffer()) {
2519
- let contents = String(file.contents);
2520
- const deps = cssFilter.indexOf(path$5.extname(file.path)) > -1 ? findCssImports(contents) : precinct(contents);
2521
- const copyModules = new Map();
2522
- Object.keys(tmsConfig.dependencies).forEach(includeName => {
2523
- const includePath = tmsConfig.dependencies[includeName];
2524
- deps.forEach(depItem => {
2525
- if (depItem.indexOf(includeName) > -1) {
2526
- // 被依赖文件的存在的绝对路径 (eg: /User/thirdparty/loadsh)
2527
- const depOriginPath = path$5.join(path$5.dirname(anaFileOriginFile), depItem); // 被依赖文件加上后缀
2528
-
2529
- const {
2530
- ext: extAlias,
2531
- file: depOriginFile,
2532
- extPath
2533
- } = ext$2(depOriginPath, extensions);
2534
-
2535
- if (!fileInDir$2(includePath, depOriginFile)) {
2536
- pluginError$2(new Error(`${anaFileOriginFile}引用路径${depOriginFile}不在${includePath}不在文件夹内, 请检查应用路径`), isWatch);
2537
- return;
2538
- } // eslint-disable-next-line
2539
-
2540
-
2541
- const reg = new RegExp(`^(\./|\.\.\/)+.*\/${includeName}\/(.*)`);
2542
- const regRes = depItem.match(reg) || [];
2543
-
2544
- if (regRes[2]) {
2545
- const depDestPath = resolve$7(tmsConfig.outputDir, module.to, includeName, regRes[2]);
2546
- const depDestFile = depDestPath.endsWith(extAlias) ? depDestPath : depDestPath + extPath;
2547
-
2548
- if (!copyModules.has(depDestFile)) {
2549
- copyModules.set(depDestFile, {
2550
- depOriginFile,
2551
- depDestFile,
2552
- beforeDepPath: depItem,
2553
- afterDepPath: path$5.relative(path$5.dirname(anaFileDestFile), depDestPath).replace(/\\/g, '/')
2554
- });
2555
- }
2556
- }
2557
- }
2558
- });
2559
- }); // console.log('mpCommonDep copyModules', copyModules);
2560
-
2561
- copyModules.forEach(({
2562
- depOriginFile,
2563
- depDestFile,
2564
- beforeDepPath,
2565
- afterDepPath
2566
- }) => {
2567
- diffContentCopyFile$2(depOriginFile, depDestFile);
2568
- const reg = new RegExp(`['"]${beforeDepPath}["']`, 'g');
2569
- contents = contents.replace(reg, `"${afterDepPath}"`);
2570
- const defs = dfsFindCommonDep$2(depOriginFile, depDestFile, extensions, isWatch);
2571
- defs.forEach(item => {
2572
- diffContentCopyFile$2(item.depOriginFile, item.depDestFile);
2573
- }); // console.log('mpCommonDep defs', defs);
2574
- });
2575
- file.contents = Buffer.from(contents);
2576
- }
2577
-
2578
- this.push(file);
2579
- cb();
2580
- });
2581
- return stream;
2582
- }
2583
-
2584
- var mpCommonDep_1 = {
2585
- mpCommonDep: mpCommonDep$1,
2586
- dfsFindCommonDep: dfsFindCommonDep$2
2587
- };
2587
+ var init_1 = init$3;
2588
2588
 
2589
2589
  /* eslint-disable no-param-reassign */
2590
- const through$1 = require$$0__default$9;
2591
- const path$4 = require$$1__default$2;
2592
- const {
2593
- ext: ext$1,
2594
- fileInDir: fileInDir$1,
2595
- diffContentCopyFile: diffContentCopyFile$1
2596
- } = io$3;
2597
- const {
2598
- resolve: resolve$6
2599
- } = widgets;
2600
- const fs$3 = require$$0__default$2;
2601
- const {
2602
- pluginError: pluginError$1
2603
- } = pluginError_1;
2604
- const {
2605
- dfsFindCommonDep: dfsFindCommonDep$1
2606
- } = mpCommonDep_1;
2607
-
2608
- function mpJsonDep$1(tmsConfig, module, extensions = ['.json'], filesExt = ['.wxml', '.json', '.js', '.ts', '.wxss', '.less'], isWatch) {
2609
- const stream = through$1.obj(function (file, enc, cb) {
2610
- // 当前分析的文件的路径
2611
- const anaFileOriginFile = file.history[0];
2612
- const anaFileRelativeModule = path$4.relative(resolve$6(module.from), anaFileOriginFile);
2613
- const anaFileDestFile = resolve$6(tmsConfig.outputDir, module.to, anaFileRelativeModule);
2614
-
2615
- if (file.isBuffer()) {
2616
- let contents = String(file.contents);
2617
- const copyModules = new Map();
2618
2590
 
2619
- try {
2620
- try {
2621
- contents = contents ? JSON.parse(contents) : {};
2622
- } catch (e) {
2623
- throw new Error(`解析${file.path}出现错误,请检查配置信息: ${e}`);
2624
- }
2625
-
2626
- if (contents.usingComponents) {
2627
- Object.keys(tmsConfig.dependencies).forEach(includeName => {
2628
- const includePath = tmsConfig.dependencies[includeName];
2629
- Object.keys(contents.usingComponents).forEach(componentKey => {
2630
- const componentPath = contents.usingComponents[componentKey];
2631
-
2632
- if (componentPath.indexOf(includeName) > -1) {
2633
- const depOriginPath = path$4.join(path$4.dirname(anaFileOriginFile), componentPath); // 被依赖文件加上后缀
2634
-
2635
- const {
2636
- ext: extAlias,
2637
- file: depOriginFile,
2638
- extPath
2639
- } = ext$1(depOriginPath, extensions);
2640
- const isFileInDir = fileInDir$1(includePath, depOriginFile);
2641
-
2642
- if (!isFileInDir) {
2643
- pluginError$1(new Error(`${anaFileOriginFile}引用的路径${depOriginFile}不在${includePath}不在文件夹内, 请检查应用路径`), isWatch);
2644
- return;
2645
- } // eslint-disable-next-line
2646
-
2647
-
2648
- const reg = new RegExp(`^(\./|\.\.\/)+.*\/${includeName}\/(.*)`);
2649
- const regRes = componentPath.match(reg) || [];
2650
-
2651
- if (regRes[2]) {
2652
- const depDestPath = resolve$6(tmsConfig.outputDir, module.to, includeName, regRes[2]);
2653
- const depDestFile = depDestPath.endsWith(extAlias) ? depDestPath : depDestPath + extPath;
2654
-
2655
- if (!copyModules.has(depDestFile)) {
2656
- copyModules.set(depDestFile, {
2657
- depOriginFile,
2658
- depOriginExt: extAlias,
2659
- depDestFile,
2660
- beforeDepPath: componentPath,
2661
- afterDepPath: path$4.relative(path$4.dirname(anaFileDestFile), depDestPath).replace(/\\/g, '/')
2662
- });
2663
- }
2664
- }
2665
- }
2666
- });
2667
- });
2668
- }
2669
- } catch (e) {
2670
- pluginError$1(e, isWatch);
2671
- } // console.log('json copyModules', copyModules);
2672
-
2673
-
2674
- copyModules.forEach(({
2675
- depOriginFile,
2676
- depOriginExt,
2677
- depDestFile,
2678
- beforeDepPath,
2679
- afterDepPath
2680
- }) => {
2681
- // 拷贝当前依赖组件几个部分 wxml、wxss、wxs、json
2682
- filesExt.forEach(extKey => {
2683
- const originFile = depOriginFile.replace(depOriginExt, extKey);
2684
- const destFile = depDestFile.replace(depOriginExt, extKey);
2685
-
2686
- if (fs$3.existsSync(originFile)) {
2687
- diffContentCopyFile$1(originFile, destFile);
2688
- const extensionsFilter = ['.js', '.ts', '.wxss', '.less'];
2689
-
2690
- if (extensionsFilter.indexOf(extKey) > -1) {
2691
- const defs = dfsFindCommonDep$1(originFile, destFile, extensionsFilter); // console.log('json defs', defs);
2692
-
2693
- defs.forEach(item => {
2694
- diffContentCopyFile$1(item.depOriginFile, item.depDestFile);
2695
- });
2696
- }
2697
- }
2698
- });
2699
- contents = typeof contents === 'object' ? JSON.stringify(contents, null, 2) : contents;
2700
- const reg = new RegExp(`['"]${beforeDepPath}["']`, 'g');
2701
- contents = contents.replace(reg, `"${afterDepPath}"`);
2702
- });
2703
- contents = typeof contents === 'object' ? JSON.stringify(contents, null, 2) : contents;
2704
- file.contents = Buffer.from(contents);
2591
+ function mpProjectJson$1() {
2592
+ return function ({
2593
+ vinyl,
2594
+ next
2595
+ }) {
2596
+ if (vinyl.isBuffer()) {
2597
+ let contents = String(vinyl.contents);
2598
+ contents = contents.replace(/"miniprogramRoot"[^,]+,/g, '');
2599
+ vinyl.contents = Buffer.from(contents);
2705
2600
  }
2706
2601
 
2707
- this.push(file);
2708
- cb();
2709
- });
2710
- return stream;
2711
- }
2712
-
2713
- var mpJsonDep_1 = {
2714
- mpJsonDep: mpJsonDep$1
2715
- };
2716
-
2717
- /* eslint-disable no-param-reassign */
2718
- const through = require$$0__default$9;
2719
- const htmlparser2 = require$$1__default$9;
2720
- const fs$2 = require$$0__default$2;
2721
- const path$3 = require$$1__default$2;
2722
- const {
2723
- diffContentCopyFile,
2724
- ext,
2725
- fileInDir
2726
- } = io$3;
2727
- const {
2728
- resolve: resolve$5
2729
- } = widgets;
2730
- const {
2731
- dfsFindCommonDep
2732
- } = mpCommonDep_1;
2733
- const {
2734
- pluginError
2735
- } = pluginError_1; // 处理后缀(源码引入依赖时,不带后缀的情况)
2736
-
2737
- const extFile = function (name, file) {
2738
- const extMap = {
2739
- import: '.wxml',
2740
- include: '.wxml',
2741
- wxs: '.wxs'
2742
- };
2743
- let extObj = {};
2744
-
2745
- if (Object.keys(extMap).indexOf(name) > -1 && !file.endsWith(extMap[name])) {
2746
- extObj = ext(file, [extMap[name]]);
2747
- }
2748
-
2749
- return {
2750
- extPath: extObj.extPath || '',
2751
- ext: extObj.ext || '',
2752
- file: extObj.file || file
2753
- };
2754
- };
2755
-
2756
- const dfsFindWxmlDep = function (anaFileOriginFile, anaFileDestFile, isWatch = true) {
2757
- const resDep = {
2758
- image: new Map(),
2759
- wxml: new Map(),
2760
- wxs: new Map()
2602
+ next();
2761
2603
  };
2762
-
2763
- function dfs(anaFileOriginFile, anaFileDestFile) {
2764
- let contents = '';
2765
-
2766
- try {
2767
- contents = fs$2.readFileSync(anaFileOriginFile, 'utf8');
2768
- } catch (e) {
2769
- pluginError(e, isWatch);
2770
- }
2771
-
2772
- const parser = new htmlparser2.Parser({
2773
- onopentag(name, attributes) {
2774
- var _attributes$src;
2775
-
2776
- if (attributes !== null && attributes !== void 0 && (_attributes$src = attributes.src) !== null && _attributes$src !== void 0 && _attributes$src.startsWith('.')) {
2777
- const depOriginPath = path$3.join(path$3.dirname(anaFileOriginFile), attributes.src); // 被依赖文件加上后缀
2778
-
2779
- const {
2780
- ext,
2781
- file: depOriginFile,
2782
- extPath
2783
- } = extFile(name, depOriginPath);
2784
-
2785
- if (!fs$2.existsSync(depOriginFile)) {
2786
- pluginError(new Error(`${anaFileOriginFile}引用的路径${depOriginFile}找不到应用文件,请检查引用路径`), isWatch);
2787
- return;
2788
- }
2789
-
2790
- const depDestPath = path$3.join(path$3.dirname(anaFileDestFile), attributes.src);
2791
- const depDestFile = depDestPath.endsWith(ext) ? depDestPath : depDestPath + extPath; // 收集wxml依赖
2792
-
2793
- if (['import', 'include'].indexOf(name) > -1) {
2794
- resDep.wxml.set(depDestFile, {
2795
- anaFileOriginFile,
2796
- anaFileDestFile,
2797
- depDestFile,
2798
- depOriginFile
2799
- });
2800
- dfs(depOriginFile, depDestFile);
2801
- } // 收集image依赖
2802
- // if (name === 'image') {
2803
- // resDep.image.set(attributes.src, {
2804
- // anaFileOriginFile,
2805
- // anaFileDestFile,
2806
- // depDestFile,
2807
- // depOriginFile,
2808
- // });
2809
- // dfs(depOriginFile, depDestFile);
2810
- // }
2811
- // 收集wxs依赖
2812
-
2813
-
2814
- if (name === 'wxs') {
2815
- resDep.wxs.set(depDestFile, {
2816
- anaFileOriginFile,
2817
- anaFileDestFile,
2818
- depDestFile,
2819
- depOriginFile
2820
- });
2821
- const defs = dfsFindCommonDep(depOriginFile, depDestFile, ['.wxs']);
2822
- defs.forEach((item, key) => {
2823
- resDep.wxs.set(key, item);
2824
- });
2825
- }
2826
- }
2827
- }
2828
-
2829
- });
2830
- parser.write(contents);
2831
- parser.end();
2832
- }
2833
-
2834
- dfs(anaFileOriginFile, anaFileDestFile);
2835
- return resDep;
2836
- };
2837
-
2838
- function mpWxmlDep$1(tmsConfig, module, isWatch) {
2839
- const stream = through.obj(function (file, enc, cb) {
2840
- // 依赖分析的文件
2841
- const anaFileOriginFile = file.history[0];
2842
- const anaFileRelativeModule = path$3.relative(resolve$5(module.from), anaFileOriginFile);
2843
- const anaFileDestFile = resolve$5(tmsConfig.outputDir, module.to, anaFileRelativeModule);
2844
-
2845
- if (file.isBuffer()) {
2846
- let contents = String(file.contents);
2847
- const copyModules = new Map();
2848
- const parser = new htmlparser2.Parser({
2849
- onopentag(name, attributes) {
2850
- const nameFilter = ['import', 'include', 'wxs'];
2851
-
2852
- if (nameFilter.indexOf(name) > -1 && attributes.src) {
2853
- const depOriginPath = path$3.join(path$3.dirname(anaFileOriginFile), attributes.src); // 处理后缀(源码引入依赖时,后缀不全的情况)
2854
-
2855
- const {
2856
- ext,
2857
- file: depOriginFile,
2858
- extPath
2859
- } = extFile(name, depOriginPath);
2860
- Object.keys(tmsConfig.dependencies).forEach(includeName => {
2861
- if (attributes.src.indexOf(includeName) > -1) {
2862
- const includePath = tmsConfig.dependencies[includeName];
2863
-
2864
- if (!fileInDir(includePath, depOriginFile)) {
2865
- pluginError(new Error(`${anaFileOriginFile}引用路径${depOriginFile}不在${includePath}不在文件夹内, 请检查应用路径`), isWatch);
2866
- return;
2867
- } // eslint-disable-next-line
2868
-
2869
-
2870
- const reg = new RegExp(`^(\./\.\.\/)+.*\/${includeName}\/(.*)`);
2871
- const regRes = attributes.src.match(reg) || [];
2872
-
2873
- if (regRes[2]) {
2874
- const depDestPath = resolve$5(tmsConfig.outputDir, module.to, includeName, regRes[2]);
2875
- const depDestFile = depDestPath.endsWith(ext) ? depDestPath : depDestPath + extPath;
2876
-
2877
- if (!copyModules.has(depDestFile)) {
2878
- copyModules.set(depDestFile, {
2879
- depOriginFile,
2880
- depDestFile,
2881
- beforeDepPath: attributes.src,
2882
- afterDepPath: path$3.relative(path$3.dirname(anaFileDestFile), depDestFile).replace(/\\/g, '/')
2883
- });
2884
- }
2885
- }
2886
- }
2887
- });
2888
- }
2889
- }
2890
-
2891
- });
2892
- parser.write(contents);
2893
- parser.end(); // console.log('wxml copyModules', copyModules);
2894
-
2895
- copyModules.forEach(({
2896
- depOriginFile,
2897
- depDestFile,
2898
- beforeDepPath,
2899
- afterDepPath
2900
- }) => {
2901
- if (fs$2.existsSync(depOriginFile)) {
2902
- diffContentCopyFile(depOriginFile, depDestFile);
2903
- const reg = new RegExp(`['"]${beforeDepPath}["']`, 'g');
2904
- contents = contents.replace(reg, `"${afterDepPath}"`);
2905
- }
2906
-
2907
- if (depOriginFile.endsWith('.wxml')) {
2908
- const defs = dfsFindWxmlDep(depOriginFile, depDestFile, isWatch); // console.log('wxml defs', defs);
2909
-
2910
- [...defs.wxml, ...defs.wxs].forEach(([, item]) => {
2911
- diffContentCopyFile(item.depOriginFile, item.depDestFile);
2912
- });
2913
- }
2914
-
2915
- if (depOriginFile.endsWith('.wxs')) {
2916
- const defs = dfsFindCommonDep(depOriginFile, depDestFile, ['.wxs'], isWatch); // console.log('wxs defs', defs);
2917
-
2918
- defs.forEach(item => {
2919
- diffContentCopyFile(item.depOriginFile, item.depDestFile);
2920
- });
2921
- }
2922
- });
2923
- file.contents = Buffer.from(contents);
2924
- }
2925
-
2926
- this.push(file);
2927
- cb();
2928
- });
2929
- return stream;
2930
2604
  }
2931
2605
 
2932
- var mpWxmlDep_1 = {
2933
- mpWxmlDep: mpWxmlDep$1,
2934
- dfsFindWxmlDep
2935
- };
2606
+ var mpProjectJson_1 = mpProjectJson$1;
2936
2607
 
2937
2608
  const {
2938
2609
  src: src$1,
2939
2610
  dest
2940
- } = require$$0__default$a; // const px2rpx = require('gulp-px-to-rpx');
2941
- // const cache = require('gulp-cache');
2942
- // const image = require('gulp-image');
2943
- // const replaceEnv = require('./plugins/replaceEnv');
2944
-
2945
- const {
2946
- mpCommonDep
2947
- } = mpCommonDep_1;
2611
+ } = require$$0__default$7;
2612
+ const path$5 = require$$1__default$1;
2613
+ const minimatch = require$$2__default$1;
2614
+ const gulpif = require$$3__default$1;
2615
+ const mpProjectJson = mpProjectJson_1;
2948
2616
  const {
2949
- mpJsonDep
2950
- } = mpJsonDep_1;
2617
+ resolve: resolve$6
2618
+ } = widgets;
2619
+ const through = require$$6__default;
2951
2620
  const {
2952
- mpWxmlDep
2953
- } = mpWxmlDep_1; // const postcss = require('gulp-postcss');
2954
- // const base64 = require('./plugins/postcss-font-base64');
2621
+ fail: fail$2
2622
+ } = log$1;
2623
+
2624
+ const getTargetFile$1 = (sourceFile, module, outputDir) => {
2625
+ const sourceFileRelativeModule = path$5.relative(resolve$6(module.from), sourceFile);
2626
+ const targetFile = resolve$6(outputDir, module.to, sourceFileRelativeModule);
2627
+ return targetFile;
2628
+ };
2955
2629
 
2956
- const {
2957
- fail: fail$2
2958
- } = log$1; // const since = task => file => (lastRun(task) > file.stat.ctime ? lastRun(task) : 0);
2630
+ const addPlugins = function (tmsConfig, srcPipe, pluginParams) {
2631
+ const {
2632
+ plugins = []
2633
+ } = tmsConfig;
2634
+ const newPlugins = [{
2635
+ glob: '**/project.config.json',
2636
+ action: mpProjectJson()
2637
+ }, ...plugins];
2638
+ return newPlugins.reduce((srcPipe, pluginItem) => srcPipe.pipe(gulpif(vinyl => minimatch(vinyl.path, pluginItem.glob), through.obj(function (vinyl, enc, next) {
2639
+ const sourceFile = vinyl.history[0];
2640
+ pluginItem.action({
2641
+ tmsConfig,
2642
+ sourceFile,
2643
+ vinyl,
2644
+ targetFile: getTargetFile$1(sourceFile, pluginParams.module, tmsConfig.outputDir),
2645
+ isDev: pluginParams.isDev,
2646
+ next
2647
+ });
2648
+ this.push(vinyl);
2649
+ }))), srcPipe);
2650
+ };
2959
2651
 
2960
2652
  var compile$1 = function (tmsConfig, {
2961
2653
  glob,
@@ -2965,122 +2657,21 @@ var compile$1 = function (tmsConfig, {
2965
2657
  isDev
2966
2658
  }) {
2967
2659
  const compileTasksMap = new Map();
2968
- Object.keys(glob).forEach(globKey => {
2969
- const globValue = glob[globKey];
2970
-
2971
- switch (globKey) {
2972
- case 'js':
2973
- compileTasksMap.set(globValue, {
2974
- module,
2975
- taskFn: (sourceFile, targetPath) => {
2976
- const newGlobValue = Array.isArray(sourceFile) ? sourceFile : globValue;
2977
- const newDestPath = targetPath ? targetPath : destPath;
2978
- const srcPipe = src$1(newGlobValue, { ...srcOption
2979
- });
2980
- return srcPipe // .pipe(replaceEnv(/process\.env(\.(\w*))?/g, tmsConfig.envData))
2981
- .pipe(mpCommonDep(tmsConfig, module, ['.js', '.ts', '.wxs', '.json'], isDev)).on('error', err => {
2982
- fail$2(`mpCommonDep编译报错${err}`);
2983
- }).pipe(dest(newDestPath, {
2984
- overwrite: true
2985
- })).on('error', err => {
2986
- fail$2(`js编译报错${err}`);
2987
- });
2988
- }
2989
- });
2990
- break;
2991
-
2992
- case 'wxss':
2993
- compileTasksMap.set(globValue, {
2994
- module,
2995
- taskFn: (sourceFile, targetPath) => {
2996
- const newGlobValue = Array.isArray(sourceFile) ? sourceFile : globValue;
2997
- const newDestPath = targetPath ? targetPath : destPath;
2998
- const srcPipe = src$1(newGlobValue, { ...srcOption
2999
- });
3000
- return srcPipe.pipe(mpCommonDep(tmsConfig, module, ['.wxss', '.less'], isDev)).on('error', err => {
3001
- fail$2(`mpCommonDep编译报错${err}`);
3002
- }) // .pipe(postcss([base64()]))
3003
- // .on('error', (err) => {
3004
- // fail(`postcss编译报错${err}`);
3005
- // })
3006
- // .pipe(px2rpx({
3007
- // designWidth: 375, // 设计稿宽度,默认为750
3008
- // precision: 2, // 小数最大精度,默认为6
3009
- // }))
3010
- .pipe(dest(newDestPath)).on('error', err => {
3011
- fail$2(`wxss编译报错${err}`);
3012
- });
3013
- }
3014
- });
3015
- break;
3016
-
3017
- case 'json':
3018
- compileTasksMap.set(globValue, {
3019
- module,
3020
- taskFn: (sourceFile, targetPath) => {
3021
- const newGlobValue = Array.isArray(sourceFile) ? sourceFile : globValue;
3022
- const newDestPath = targetPath ? targetPath : destPath;
3023
- const srcPipe = src$1(newGlobValue, { ...srcOption
3024
- });
3025
- return srcPipe.pipe(mpJsonDep(tmsConfig, module, ['.json'], ['.wxml', '.json', '.js', '.ts', '.wxss', '.less'], isDev)).on('error', err => {
3026
- fail$2(`mpJsonDep编译报错${err}`);
3027
- }).pipe(dest(newDestPath)).on('error', err => {
3028
- fail$2(`json编译报错${err}`);
3029
- });
3030
- }
3031
- });
3032
- break;
3033
-
3034
- case 'wxml':
3035
- compileTasksMap.set(globValue, {
3036
- module,
3037
- taskFn: (sourceFile, targetPath) => {
3038
- const newGlobValue = Array.isArray(sourceFile) ? sourceFile : globValue;
3039
- const newDestPath = targetPath ? targetPath : destPath;
3040
- const srcPipe = src$1(newGlobValue, { ...srcOption
3041
- });
3042
- return srcPipe.pipe(mpWxmlDep(tmsConfig, module, isDev)).on('error', err => {
3043
- fail$2(`mpWxmlDep编译报错${err}`);
3044
- }).pipe(dest(newDestPath)).on('error', err => {
3045
- fail$2(`wxml编译报错${err}`);
3046
- });
3047
- }
3048
- });
3049
- break;
3050
-
3051
- case 'image':
3052
- compileTasksMap.set(globValue, {
3053
- module,
3054
- taskFn: (sourceFile, targetPath) => {
3055
- const newGlobValue = Array.isArray(sourceFile) ? sourceFile : globValue;
3056
- const newDestPath = targetPath ? targetPath : destPath;
3057
- const srcPipe = src$1(newGlobValue, { ...srcOption
3058
- });
3059
- return srcPipe // .pipe(cache(image()))
3060
- // .on('error', (err) => {
3061
- // fail(`image编译报错${err}`);
3062
- // })
3063
- .pipe(dest(newDestPath)).on('error', err => {
3064
- fail$2(`image编译报错${err}`);
3065
- });
3066
- }
3067
- });
3068
- break;
3069
-
3070
- case 'other':
3071
- compileTasksMap.set(globValue, {
3072
- module,
3073
- taskFn: (sourceFile, targetPath) => {
3074
- const newGlobValue = Array.isArray(sourceFile) ? sourceFile : globValue;
3075
- const newDestPath = targetPath ? targetPath : destPath;
3076
- const srcPipe = src$1(newGlobValue, { ...srcOption
3077
- });
3078
- return srcPipe.pipe(dest(newDestPath)).on('error', err => {
3079
- fail$2(`编译报错${err}`);
3080
- });
3081
- }
3082
- });
3083
- break;
2660
+ compileTasksMap.set(glob, {
2661
+ module,
2662
+ taskFn: (sourceFile, targetPath) => {
2663
+ const newGlobValue = Array.isArray(sourceFile) ? sourceFile : glob;
2664
+ const newDestPath = targetPath ? targetPath : destPath;
2665
+ let srcPipe = src$1(newGlobValue, { ...srcOption
2666
+ });
2667
+ const pluginParams = {
2668
+ module,
2669
+ isDev
2670
+ };
2671
+ srcPipe = addPlugins(tmsConfig, srcPipe, pluginParams);
2672
+ return srcPipe.pipe(dest(newDestPath)).on('error', err => {
2673
+ fail$2(`编译报错${err}`);
2674
+ });
3084
2675
  }
3085
2676
  });
3086
2677
  return compileTasksMap;
@@ -3089,18 +2680,18 @@ var compile$1 = function (tmsConfig, {
3089
2680
  /* eslint-disable */
3090
2681
  // 该文件源于npm包 gulp-watch 但内部有bug, 故源码进行单独修改
3091
2682
 
3092
- const assign = require$$0__default$b;
3093
- const path$2 = require$$1__default$2;
3094
- const PluginError = require$$2__default$1;
3095
- const fancyLog = require$$3__default;
3096
- const colors = require$$4__default;
2683
+ const assign = require$$0__default$8;
2684
+ const path$4 = require$$1__default$1;
2685
+ const PluginError = require$$2__default$2;
2686
+ const fancyLog = require$$3__default$2;
2687
+ const colors = require$$4__default$1;
3097
2688
  const chokidar = require$$5__default;
3098
2689
  const {
3099
2690
  Duplex
3100
2691
  } = require$$6__default$1;
3101
2692
  const vinyl = require$$7__default;
3102
2693
  const File = require$$8__default;
3103
- const anymatch = require$$9__default$1;
2694
+ const anymatch = require$$9__default;
3104
2695
  const pathIsAbsolute = require$$10__default$1;
3105
2696
  const globParent = require$$11__default;
3106
2697
  const slash = require$$12__default;
@@ -3135,10 +2726,10 @@ function watch$2(globs, opts, cb) {
3135
2726
 
3136
2727
  function resolveFilepath(filepath) {
3137
2728
  if (pathIsAbsolute(filepath)) {
3138
- return path$2.normalize(filepath);
2729
+ return path$4.normalize(filepath);
3139
2730
  }
3140
2731
 
3141
- return path$2.resolve(opts.cwd || process.cwd(), filepath);
2732
+ return path$4.resolve(opts.cwd || process.cwd(), filepath);
3142
2733
  }
3143
2734
 
3144
2735
  function resolveGlob(glob) {
@@ -3194,7 +2785,7 @@ function watch$2(globs, opts, cb) {
3194
2785
  let glob;
3195
2786
  let currentFilepath = filepath;
3196
2787
 
3197
- while (!(glob = globs[anymatch(globs, currentFilepath, true)]) && currentFilepath !== (currentFilepath = path$2.dirname(currentFilepath))) {} // eslint-disable-line no-empty-blocks/no-empty-blocks
2788
+ while (!(glob = globs[anymatch(globs, currentFilepath, true)]) && currentFilepath !== (currentFilepath = path$4.dirname(currentFilepath))) {} // eslint-disable-line no-empty-blocks/no-empty-blocks
3198
2789
 
3199
2790
 
3200
2791
  if (!glob) {
@@ -3203,7 +2794,7 @@ function watch$2(globs, opts, cb) {
3203
2794
  }
3204
2795
 
3205
2796
  if (!baseForced) {
3206
- fileOpts.base = path$2.normalize(globParent(glob));
2797
+ fileOpts.base = path$4.normalize(globParent(glob));
3207
2798
  } // Do not stat deleted files
3208
2799
 
3209
2800
 
@@ -3263,15 +2854,19 @@ var gulpWatch = watch$2;
3263
2854
 
3264
2855
  /* eslint-disable no-restricted-syntax */
3265
2856
  const watch$1 = gulpWatch;
3266
- const path$1 = require$$1__default$2;
3267
- const shellJs = require$$0__default$3;
2857
+ const path$3 = require$$1__default$1;
2858
+ const shellJs = require$$2__default;
2859
+ const {
2860
+ series: series$1
2861
+ } = require$$0__default$7;
3268
2862
  const {
3269
- info: info$5,
2863
+ info: info$4,
3270
2864
  warn: warn$1,
3271
2865
  fail: fail$1
3272
2866
  } = log$1;
3273
2867
  const {
3274
- resolve: resolve$4
2868
+ resolve: resolve$5,
2869
+ filterField: filterField$3
3275
2870
  } = widgets;
3276
2871
  const {
3277
2872
  global: global$2
@@ -3279,9 +2874,7 @@ const {
3279
2874
  const {
3280
2875
  checkPackageVersion
3281
2876
  } = checkDependencies;
3282
- const {
3283
- findAllFilesOfDir
3284
- } = io$3;
2877
+ const report$5 = report_1;
3285
2878
  const TIP_MAP = {
3286
2879
  'package.json': {
3287
2880
  tip: '依赖版本有变动,请重新执行tmskit run dev',
@@ -3310,15 +2903,15 @@ const logTip = (fileName, sourceFile, targetFile, tipMap) => {
3310
2903
  }
3311
2904
  }
3312
2905
 
3313
- info$5(`${fileName}有更新`);
2906
+ info$4(`${fileName}有更新`);
3314
2907
  } catch (e) {
3315
2908
  fail$1(`${sourceFile}文件更新提示出现错误: ${e.message}`);
3316
2909
  }
3317
2910
  };
3318
2911
 
3319
2912
  const getTargetFile = (sourceFile, module, outputDir) => {
3320
- const sourceFileRelativeModule = path$1.relative(resolve$4(module.from), sourceFile);
3321
- const targetFile = resolve$4(outputDir, module.to, sourceFileRelativeModule);
2913
+ const sourceFileRelativeModule = path$3.relative(resolve$5(module.from), sourceFile);
2914
+ const targetFile = resolve$5(outputDir, module.to, sourceFileRelativeModule);
3322
2915
  return targetFile;
3323
2916
  };
3324
2917
 
@@ -3330,181 +2923,166 @@ var watch_1 = function (globValue, watchOptions, callback, module) {
3330
2923
  const sourceFileDirArr = sourceFile.replace(/\\/g, '/').split('/');
3331
2924
  const sourceFileName = sourceFileDirArr.slice(sourceFileDirArr.length - 2).join('/');
3332
2925
  const tmsConfig = global$2.getData('tmsConfig');
3333
-
3334
- if (vinyl.event === 'addDir') {
3335
- info$5(`更新${sourceFileName}目录`);
3336
- const files = findAllFilesOfDir(sourceFile);
3337
-
3338
- for (const file of files) {
3339
- const fileDirArr = file.replace(/\\/g, '/').split('/');
3340
- const fileName = fileDirArr.slice(fileDirArr.length - 2).join('/');
3341
- const targetFile = getTargetFile(file, module, tmsConfig.outputDir);
3342
- logTip(fileName, sourceFile, targetFile, TIP_MAP);
3343
- callback([file], path$1.dirname(targetFile));
3344
- }
3345
-
3346
- return;
3347
- }
3348
-
3349
2926
  const targetFile = getTargetFile(sourceFile, module, tmsConfig.outputDir);
3350
2927
 
3351
2928
  if (vinyl.event === 'unlink' || vinyl.event === 'unlinkDir') {
3352
- info$5(`删除${sourceFileName}`);
2929
+ info$4(`删除${sourceFileName}`);
3353
2930
  shellJs.rm('-rf', targetFile);
2931
+ updateFileHook(tmsConfig, sourceFile, targetFile, vinyl.event);
3354
2932
  return;
3355
2933
  }
3356
2934
 
2935
+ runCallback({
2936
+ tmsConfig,
2937
+ sourceFile,
2938
+ targetFile,
2939
+ callback,
2940
+ type: vinyl.event
2941
+ });
3357
2942
  logTip(sourceFileName, sourceFile, targetFile, TIP_MAP);
3358
- return callback([sourceFile], path$1.dirname(targetFile));
3359
2943
  });
3360
- };
2944
+ }; // 开始执行watch 文件的 callback函数
2945
+
2946
+
2947
+ async function runCallback({
2948
+ tmsConfig,
2949
+ sourceFile,
2950
+ targetFile,
2951
+ callback,
2952
+ type
2953
+ }) {
2954
+ // callbacl.name === taskFn 代表进入gulp编译流程
2955
+ // series为gulp编译串行执行,callback执行完毕后,执行updateFileHooks钩子
2956
+ if (callback.name === 'taskFn') {
2957
+ series$1(callback.bind(null, [sourceFile], path$3.dirname(targetFile)), cb => {
2958
+ cb();
2959
+ updateFileHook(tmsConfig, sourceFile, targetFile, type);
2960
+ })();
2961
+ } else {
2962
+ // 普通的callback函数
2963
+ await callback([sourceFile], path$3.dirname(targetFile));
2964
+ await updateFileHook(tmsConfig, sourceFile, targetFile, type);
2965
+ }
2966
+ } // 执行源码文件更新的钩子
2967
+
2968
+
2969
+ async function updateFileHook(tmsConfig, sourceFile, targetFile, type) {
2970
+ var _tmsConfig$hooks;
2971
+
2972
+ if (typeof (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks = tmsConfig.hooks) === null || _tmsConfig$hooks === void 0 ? void 0 : _tmsConfig$hooks.updateFile) === 'function') {
2973
+ await tmsConfig.hooks.updateFile({
2974
+ tmsConfig: filterField$3(tmsConfig, ['gitAccount']),
2975
+ sourceFile,
2976
+ targetFile,
2977
+ type
2978
+ });
2979
+ report$5('hooks:updateFile');
2980
+ }
2981
+ }
3361
2982
 
3362
- const path = require$$1__default$2;
3363
- const fs$1 = require$$0__default$2;
3364
- const ora = require$$2__default;
3365
- const chalk$2 = require$$0__default;
2983
+ const path$2 = require$$1__default$1;
2984
+ const fs$3 = require$$0__default$1;
2985
+ const ora = require$$0__default;
2986
+ const chalk$3 = require$$3__default;
3366
2987
  const {
3367
2988
  parallel,
3368
2989
  series
3369
- } = require$$0__default$a;
2990
+ } = require$$0__default$7;
3370
2991
  const {
3371
- resolve: resolve$3,
2992
+ resolve: resolve$4,
3372
2993
  mergeMap,
3373
- filterField: filterField$2
2994
+ filterField: filterField$2,
2995
+ getAbsolutePath
3374
2996
  } = widgets;
3375
2997
  const {
3376
2998
  buildOutputAppJson
3377
2999
  } = buildAppJson;
3378
3000
  const {
3379
3001
  DEFAULT_COPY_CONFIG
3380
- } = require$$4;
3002
+ } = constant;
3381
3003
  const compile = compile$1;
3382
3004
  const watch = watch_1;
3383
3005
  const {
3384
- info: info$4
3006
+ info: info$3
3385
3007
  } = log$1;
3008
+ const report$4 = report_1;
3386
3009
  const watchEvents = ['add', 'change', 'unlink', 'addDir', 'unlinkDir'];
3387
3010
 
3388
- function excludeGlob(glob) {
3389
- const otherArr = new Set();
3390
- otherArr.add('!**/*.{ttf,otf,woff,eot}');
3391
- Object.keys(glob).forEach(globKey => {
3392
- if (typeof glob[globKey] === 'string') {
3393
- const data = glob[globKey].startsWith('!') ? glob[globKey] : `!${glob[globKey]}`;
3394
- otherArr.add(data);
3395
- }
3396
-
3397
- if (Array.isArray(glob[globKey])) {
3398
- glob[globKey].forEach(value => {
3399
- if (typeof value === 'string') {
3400
- const data = value.startsWith('!') ? value : `!${value}`;
3401
- otherArr.add(data);
3402
- }
3403
- });
3404
- }
3405
- });
3406
- return Array.from(otherArr);
3407
- }
3408
-
3409
- function adaptPath(pathDir, cwd = '') {
3410
- let newPath = pathDir;
3411
- newPath = newPath.startsWith('/') ? newPath : resolve$3(cwd, newPath);
3412
- newPath = newPath.endsWith('/') ? newPath.slice(0, newPath.length - 1) : newPath;
3413
- return newPath;
3414
- }
3415
-
3416
- var dev$3 = async (tmsConfig, modules, subPackages, isDev = true) => {
3011
+ var dev$3 = async (tmsConfig, modules, isDev = true) => {
3417
3012
  const compileTasksMap = new Map(); // 监听根目录的文件
3418
3013
 
3419
3014
  mergeMap(compileTasksMap, compile(tmsConfig, {
3420
- glob: {
3421
- json: DEFAULT_COPY_CONFIG.map(item => resolve$3(item))
3422
- },
3015
+ glob: DEFAULT_COPY_CONFIG.map(item => resolve$4(item)),
3423
3016
  module: {
3424
- from: resolve$3(),
3425
- to: resolve$3(tmsConfig.outputDir)
3017
+ from: resolve$4(),
3018
+ to: resolve$4(tmsConfig.outputDir)
3426
3019
  },
3427
- destPath: resolve$3(tmsConfig.outputDir),
3020
+ destPath: resolve$4(tmsConfig.outputDir),
3428
3021
  srcOption: {
3429
3022
  allowEmpty: true
3430
3023
  },
3431
3024
  isDev
3432
3025
  })); // 监听模块的文件
3433
3026
 
3434
- for (let pkg of subPackages) {
3027
+ for (let moduleItem of modules) {
3435
3028
  // 处理默认参数
3436
- pkg = { ...{
3029
+ moduleItem = { ...{
3437
3030
  exclude: []
3438
3031
  },
3439
- ...pkg
3032
+ ...moduleItem
3440
3033
  };
3441
- const packagePath = adaptPath(pkg.path);
3034
+ const srcModulePath = getAbsolutePath(moduleItem.path);
3035
+ const buildModulePath = resolve$4(tmsConfig.outputDir, moduleItem.modulePath);
3442
3036
 
3443
3037
  if (isDev) {
3444
3038
  // 监听模块配置文件
3445
- watch([`${packagePath}/**/module.config.json`], {
3039
+ watch([`${srcModulePath}/**/module.config.json`], {
3446
3040
  events: watchEvents
3447
3041
  }, () => buildOutputAppJson(tmsConfig, modules, isDev), {
3448
- from: packagePath,
3449
- to: packagePath
3042
+ from: srcModulePath,
3043
+ to: buildModulePath
3450
3044
  });
3451
3045
  }
3452
3046
 
3453
- const excludes = pkg.exclude.map(ePath => {
3454
- const newPath = adaptPath(ePath, packagePath);
3455
- const ext = path.extname(ePath).slice(1);
3047
+ const excludes = moduleItem.exclude.map(ePath => {
3048
+ const newPath = getAbsolutePath(ePath, srcModulePath);
3049
+ const ext = path$2.extname(ePath).slice(1);
3456
3050
 
3457
3051
  if (ext) {
3458
- return `!${resolve$3(packagePath, newPath)}`;
3052
+ return `!${resolve$4(srcModulePath, newPath)}`;
3459
3053
  }
3460
3054
 
3461
- return `!${resolve$3(packagePath, newPath)}/**/*`;
3055
+ return `!${resolve$4(srcModulePath, newPath)}/**/*`;
3462
3056
  });
3463
- const glob = {
3464
- js: [`${packagePath}/**/*.{js,ts,wxs}`, ...excludes],
3465
- json: [`${packagePath}/**/*.json`, `!${packagePath}/**/module.config.json`, ...excludes],
3466
- wxss: [`${packagePath}/**/*.{less,wxss,scss,sass,styl}`, ...excludes],
3467
- wxml: [`${packagePath}/**/*.wxml`, ...excludes],
3468
- image: [`${packagePath}/**/*.{png,jpg,jpeg,gif,svg}`, ...excludes]
3469
- };
3470
3057
  mergeMap(compileTasksMap, compile(tmsConfig, {
3471
- glob: { ...glob,
3472
- other: [`${packagePath}/**/*`, ...excludeGlob(glob)]
3473
- },
3474
- destPath: resolve$3(tmsConfig.outputDir, pkg.root),
3058
+ glob: [`${srcModulePath}/**/*`, `!${srcModulePath}/**/module.config.json`, ...excludes],
3059
+ destPath: buildModulePath,
3475
3060
  module: {
3476
- from: pkg.path,
3477
- to: pkg.root
3061
+ from: srcModulePath,
3062
+ to: buildModulePath
3478
3063
  },
3479
3064
  srcOption: {
3480
3065
  allowEmpty: true
3481
3066
  },
3482
3067
  isDev
3483
3068
  }));
3484
- } // 静态资源目录-拷贝
3069
+ } // static静态资源目录
3485
3070
 
3486
3071
 
3487
3072
  if (tmsConfig !== null && tmsConfig !== void 0 && tmsConfig.static && (tmsConfig === null || tmsConfig === void 0 ? void 0 : tmsConfig.static.length) > 0) {
3488
3073
  for (const item of tmsConfig.static) {
3489
- item.from = adaptPath(item.from);
3490
- item.to = adaptPath(item.to);
3074
+ item.from = getAbsolutePath(item.from);
3075
+ item.to = getAbsolutePath(item.to);
3491
3076
  let glob = {};
3492
- const ext = path.extname(item.from).slice(1);
3077
+ const ext = path$2.extname(item.from).slice(1);
3493
3078
 
3494
3079
  if (ext) {
3495
- glob[ext] = [item.from];
3080
+ glob = [item.from];
3496
3081
  } else {
3497
- glob = {
3498
- js: [`${item.from}/**/*.{js,ts,wxs}`],
3499
- json: [`${item.from}/**/*.json`],
3500
- wxss: [`${item.from}/**/*.{less,wxss,scss,sass,styl}`],
3501
- wxml: [`${item.from}/**/*.wxml`],
3502
- image: [`${item.from}/**/*.{png,jpg,jpeg,gif,svg}`]
3503
- };
3504
- glob.other = [`${item.from}/**/*`, ...excludeGlob(glob)];
3082
+ glob = [`${item.from}/**/*`];
3505
3083
  }
3506
3084
 
3507
- const from = fs$1.lstatSync(item.from).isFile() ? path.dirname(item.from) : item.from;
3085
+ const from = fs$3.lstatSync(item.from).isFile() ? path$2.dirname(item.from) : item.from;
3508
3086
  mergeMap(compileTasksMap, compile(tmsConfig, {
3509
3087
  glob,
3510
3088
  destPath: item.to,
@@ -3520,90 +3098,321 @@ var dev$3 = async (tmsConfig, modules, subPackages, isDev = true) => {
3520
3098
  }
3521
3099
  }
3522
3100
 
3523
- let sTime;
3524
- let eTime;
3525
- const spinner = ora();
3101
+ let sTime;
3102
+ let eTime;
3103
+ const spinner = ora();
3104
+
3105
+ function start(cb) {
3106
+ info$3('启动编译...');
3107
+ spinner.start();
3108
+ sTime = new Date().getTime();
3109
+ cb();
3110
+ }
3111
+
3112
+ async function end(cb) {
3113
+ var _tmsConfig$hooks;
3114
+
3115
+ if (isDev) {
3116
+ // 监听app.json
3117
+ watch([resolve$4('app.json')], {
3118
+ ignoreInitial: false,
3119
+ events: watchEvents
3120
+ }, () => buildOutputAppJson(tmsConfig, modules, isDev), {
3121
+ from: resolve$4(),
3122
+ to: resolve$4(tmsConfig.outputDir)
3123
+ }); // 监听其他文件
3124
+
3125
+ compileTasksMap.forEach(({
3126
+ taskFn,
3127
+ module
3128
+ }, globValue) => {
3129
+ watch(globValue, {
3130
+ ignoreInitial: true,
3131
+ events: watchEvents
3132
+ }, taskFn, module);
3133
+ });
3134
+ } else {
3135
+ buildOutputAppJson(tmsConfig, modules, isDev);
3136
+ }
3137
+
3138
+ eTime = new Date().getTime() - sTime;
3139
+
3140
+ if (typeof (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks = tmsConfig.hooks) === null || _tmsConfig$hooks === void 0 ? void 0 : _tmsConfig$hooks.afterCompile) === 'function') {
3141
+ var _tmsConfig$hooks2;
3142
+
3143
+ await (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks2 = tmsConfig.hooks) === null || _tmsConfig$hooks2 === void 0 ? void 0 : _tmsConfig$hooks2.afterCompile({
3144
+ isDev,
3145
+ tmsConfig: filterField$2(tmsConfig, ['gitAccount']),
3146
+ modules
3147
+ }));
3148
+ report$4('hooks:afterCompile');
3149
+ }
3150
+
3151
+ spinner.succeed(chalk$3.green(`首次编译完成, 耗时${eTime / 1000}s, 微信开发者工具打开项目即可预览。`));
3152
+ spinner.stop();
3153
+ cb();
3154
+ }
3155
+
3156
+ const compileTasks = [];
3157
+ compileTasksMap.forEach(({
3158
+ taskFn
3159
+ }) => {
3160
+ compileTasks.push(taskFn);
3161
+ }); // 一次性完成编译任务(编译完成后再添加watch任务-封装到end函数里面)
3162
+
3163
+ series(start, parallel(...compileTasks), end)();
3164
+ };
3165
+
3166
+ var require$$12 = {
3167
+ name: "@tmsfe/tmskit",
3168
+ version: "0.0.23",
3169
+ description: "tmskit",
3170
+ main: "dist/index.cjs",
3171
+ bin: {
3172
+ tmskit: "main.js"
3173
+ },
3174
+ files: [
3175
+ "build",
3176
+ "src",
3177
+ "dist",
3178
+ "main.js",
3179
+ "package.json"
3180
+ ],
3181
+ scripts: {
3182
+ dev: "rollup -wc --environment TARGET:tmskit",
3183
+ build: "rollup -c --environment TARGET:tmskit",
3184
+ "pub:patch": "sh build/publish.sh patch",
3185
+ "pub:minor": "sh build/publish.sh minor",
3186
+ "pub:major": "sh build/publish.sh major"
3187
+ },
3188
+ author: "tms·web",
3189
+ license: "ISC",
3190
+ buildOptions: {
3191
+ formats: [
3192
+ "cjs"
3193
+ ]
3194
+ },
3195
+ devDependencies: {
3196
+ "@rollup/plugin-babel": "^5.0.2",
3197
+ "@rollup/plugin-commonjs": "^19.0.0",
3198
+ "@rollup/plugin-json": "^4.0.3",
3199
+ rollup: "^2.6.1"
3200
+ },
3201
+ dependencies: {
3202
+ "ansi-colors": "1.1.0",
3203
+ anymatch: "^1.3.0",
3204
+ async: "^3.2.2",
3205
+ chalk: "^4.1.0",
3206
+ chokidar: "^3.5.3",
3207
+ commander: "^8.3.0",
3208
+ "copy-webpack-plugin": "^9.1.0",
3209
+ ejs: "^3.1.5",
3210
+ "fancy-log": "1.3.2",
3211
+ "fs-extra": "^10.0.1",
3212
+ "glob-ignore": "^1.0.2",
3213
+ "glob-parent": "^3.0.1",
3214
+ gulp: "^4.0.2",
3215
+ "gulp-if": "^3.0.0",
3216
+ "gulp-watch": "^5.0.1",
3217
+ htmlparser2: "^7.2.0",
3218
+ inquirer: "^7.3.3",
3219
+ leven: "3.1.0",
3220
+ lodash: "^4.17.21",
3221
+ metalsmith: "^2.3.0",
3222
+ minimatch: "^5.1.0",
3223
+ "miniprogram-ci": "1.4.13",
3224
+ moment: "^2.29.2",
3225
+ "object-assign": "^4.0.1",
3226
+ ora: "^5.1.0",
3227
+ "path-is-absolute": "^1.0.1",
3228
+ "plugin-error": "^1.0.0",
3229
+ postcss: "^8.4.6",
3230
+ precinct: "^8.3.1",
3231
+ "readable-stream": "^2.2.2",
3232
+ "replace-ext": "^2.0.0",
3233
+ request: "^2.88.2",
3234
+ shelljs: "^0.8.4",
3235
+ slash: "^1.0.0",
3236
+ "strip-comments": "^2.0.1",
3237
+ through2: "^4.0.2",
3238
+ unzipper: "^0.10.11",
3239
+ vinyl: "^2.1.0",
3240
+ "vinyl-file": "^2.0.0",
3241
+ "vinyl-sourcemaps-apply": "^0.2.0"
3242
+ },
3243
+ engines: {
3244
+ node: "^12.17.0 || >= 14.13.1"
3245
+ },
3246
+ jest: {
3247
+ testEnvironment: "jest-environment-node"
3248
+ }
3249
+ };
3250
+
3251
+ const fs$2 = require$$0__default$1;
3252
+ const path$1 = require$$1__default$1;
3253
+ const shelljs$2 = require$$2__default;
3254
+ const chalk$2 = require$$3__default;
3255
+ const request = require$$0__default$5;
3256
+ const inquirer = require$$1__default$4;
3257
+ const {
3258
+ infoNoTime: infoNoTime$1
3259
+ } = log$1;
3260
+ const packageJson$1 = require$$12;
3261
+ const {
3262
+ VERSION_CACHE_FILE,
3263
+ VERSION_URL
3264
+ } = constant;
3265
+ const {
3266
+ ensureDirExist: ensureDirExist$1
3267
+ } = io$3;
3268
+ const {
3269
+ versionCompare
3270
+ } = widgets; // 获取推荐的tmskit版本
3271
+
3272
+ function getRecommendVersion() {
3273
+ return new Promise((resolve, reject) => {
3274
+ request(`${VERSION_URL}?v=${new Date().getTime()}`, (error, response, body) => {
3275
+ if (!error && response && response.statusCode === 200) {
3276
+ resolve(JSON.parse(body));
3277
+ } else {
3278
+ reject(response.statusCode);
3279
+ }
3280
+ });
3281
+ });
3282
+ } // 获取当前用户tmskit的版本
3283
+
3284
+
3285
+ function getUserTmskitVersion() {
3286
+ const data = shelljs$2.exec('tmskit -v', {
3287
+ async: false,
3288
+ silent: true
3289
+ });
3290
+
3291
+ if (data.code === 0) {
3292
+ // tmskit 0.0.21 => 0.0.21
3293
+ return data.slice(7);
3294
+ }
3295
+
3296
+ return '0.0.0';
3297
+ } // 询问用户是否安装最新版本
3298
+
3299
+
3300
+ function isInstallLatestVersion() {
3301
+ return inquirer.prompt([{
3302
+ type: 'confirm',
3303
+ name: 'isInstall',
3304
+ message: '是否安装最新版本',
3305
+ choices: [{
3306
+ name: '否',
3307
+ value: false
3308
+ }, {
3309
+ name: '是',
3310
+ value: true
3311
+ }]
3312
+ }]);
3313
+ } // 获取tmskit的版本是否推荐过
3314
+
3315
+
3316
+ function getVersionIsRecommend(version) {
3317
+ const filePath = VERSION_CACHE_FILE;
3318
+
3319
+ if (!fs$2.existsSync(filePath)) {
3320
+ return false;
3321
+ }
3322
+
3323
+ const content = require(filePath);
3324
+
3325
+ return content === null || content === void 0 ? void 0 : content[version];
3326
+ } // 设置tmskit版本推荐过
3327
+
3328
+
3329
+ function setVersionRecommend(version, isRecommend) {
3330
+ const filePath = VERSION_CACHE_FILE;
3331
+
3332
+ if (!fs$2.existsSync(filePath)) {
3333
+ const dir = path$1.dirname(filePath);
3334
+ ensureDirExist$1(dir);
3335
+ fs$2.writeFileSync(filePath, '{}');
3336
+ }
3337
+
3338
+ const content = require(filePath);
3526
3339
 
3527
- function start(cb) {
3528
- info$4('启动编译...');
3529
- spinner.start();
3530
- sTime = new Date().getTime();
3531
- cb();
3532
- }
3340
+ content[version] = isRecommend;
3341
+ fs$2.writeFileSync(filePath, JSON.stringify(content, null, 2));
3342
+ } // 推荐理由
3533
3343
 
3534
- async function end(cb) {
3535
- var _tmsConfig$hooks;
3536
3344
 
3537
- if (isDev) {
3538
- // 监听app.json
3539
- watch([resolve$3('app.json')], {
3540
- ignoreInitial: false,
3541
- events: watchEvents
3542
- }, () => buildOutputAppJson(tmsConfig, modules, isDev), {
3543
- from: resolve$3(),
3544
- to: resolve$3(tmsConfig.outputDir)
3545
- }); // 监听其他文件
3345
+ function displayRecommends(arr) {
3346
+ infoNoTime$1(chalk$2.green('构建工具有新的版本~~:'));
3347
+ arr.forEach(item => {
3348
+ infoNoTime$1(chalk$2.green(item));
3349
+ });
3350
+ } // 推荐tmskit的安装版本
3546
3351
 
3547
- compileTasksMap.forEach(({
3548
- taskFn,
3549
- module
3550
- }, globValue) => {
3551
- watch(globValue, {
3552
- ignoreInitial: true,
3553
- events: watchEvents
3554
- }, taskFn, module);
3555
- });
3556
- } else {
3557
- buildOutputAppJson(tmsConfig, modules, isDev);
3558
- }
3559
3352
 
3560
- eTime = new Date().getTime() - sTime;
3353
+ async function recommendVersion$1() {
3354
+ try {
3355
+ // 获取当前用户安装的版本
3356
+ const tmskitVersion = getUserTmskitVersion(); // 获取官方推荐版本
3561
3357
 
3562
- if (typeof (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks = tmsConfig.hooks) === null || _tmsConfig$hooks === void 0 ? void 0 : _tmsConfig$hooks.afterCompile) === 'function') {
3563
- var _tmsConfig$hooks2;
3358
+ const recommendRes = await getRecommendVersion();
3359
+ const recommendVersion = recommendRes.version; // 当前用户安装版本小于官方推荐版本 && 该版本没有推荐过
3564
3360
 
3565
- await (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks2 = tmsConfig.hooks) === null || _tmsConfig$hooks2 === void 0 ? void 0 : _tmsConfig$hooks2.afterCompile({
3566
- isDev,
3567
- tmsConfig: filterField$2(tmsConfig, ['gitAccount']),
3568
- modules
3569
- }));
3570
- }
3361
+ if (versionCompare(tmskitVersion, recommendVersion) === -1 && !getVersionIsRecommend(recommendVersion)) {
3362
+ displayRecommends(recommendRes.version_detail); // 设置该版本推荐过
3571
3363
 
3572
- spinner.succeed(chalk$2.green(`首次编译完成, 耗时${eTime / 1000}s, 微信开发者工具打开项目即可预览。`));
3573
- spinner.stop();
3574
- cb();
3575
- }
3364
+ setVersionRecommend(recommendVersion, true); // 询问用户是否安装最新版本
3576
3365
 
3577
- const compileTasks = [];
3578
- compileTasksMap.forEach(({
3579
- taskFn
3580
- }) => {
3581
- compileTasks.push(taskFn);
3582
- }); // 一次性完成编译任务(编译完成后再添加watch任务-封装到end函数里面)
3366
+ const installRes = await isInstallLatestVersion(recommendRes);
3583
3367
 
3584
- series(start, parallel(...compileTasks), end)();
3368
+ if (installRes.isInstall) {
3369
+ // mac
3370
+ if (process.platform === 'darwin') {
3371
+ infoNoTime$1(`将执行以下命令: ${chalk$2.green(`sudo npm install -g ${packageJson$1.name}@${recommendVersion}`)}`);
3372
+ shelljs$2.exec(`sudo npm install -g ${packageJson$1.name}@${recommendVersion}`, {
3373
+ async: false,
3374
+ silent: false
3375
+ });
3376
+ process.exit(-1);
3377
+ } else {
3378
+ // window
3379
+ infoNoTime$1(`请使用超级管理员执行以下命令: ${chalk$2.green(`npm install -g ${packageJson$1.name}@${recommendVersion}`)}`);
3380
+ process.exit(-1);
3381
+ }
3382
+ }
3383
+ }
3384
+ } catch {}
3385
+ }
3386
+
3387
+ var recommendVersion_1 = {
3388
+ recommendVersion: recommendVersion$1
3585
3389
  };
3586
3390
 
3587
- const shelljs$1 = require$$0__default$3;
3391
+ const shelljs$1 = require$$2__default;
3588
3392
  const compileDev = dev$3;
3589
3393
  const {
3590
- resolve: resolve$2,
3394
+ resolve: resolve$3,
3591
3395
  filterField: filterField$1
3592
3396
  } = widgets;
3593
- const init$4 = init_1;
3397
+ const init$2 = init_1;
3594
3398
  const {
3595
3399
  getModulesByMergeDepModules: getModulesByMergeDepModules$1,
3596
3400
  getSubPackages: getSubPackages$1
3597
3401
  } = tmsMpconfig.exports;
3598
3402
  const {
3599
- info: info$3
3403
+ info: info$2
3600
3404
  } = log$1;
3601
3405
  const {
3602
3406
  global: global$1
3603
3407
  } = global_1;
3604
3408
  const {
3605
- CACHE_DIR
3606
- } = require$$4; // 用户编译分包时,需要将dist中其他分包(主包不能删除)的内容删除,否则其他分包的内容混入到主包(导致主包的体积超2M)
3409
+ MODULE_CODE_DIR,
3410
+ NODE_MODULES_DIR
3411
+ } = constant;
3412
+ const report$3 = report_1;
3413
+ const {
3414
+ recommendVersion
3415
+ } = recommendVersion_1; // 用户编译分包时,需要将dist中其他分包(主包不能删除)的内容删除,否则其他分包的内容混入到主包(导致主包的体积超2M)
3607
3416
 
3608
3417
  function delOtherPackages(tmsConfig, targetSubPackages) {
3609
3418
  // 获取所有模块,合并模块依赖的模块
@@ -3613,7 +3422,7 @@ function delOtherPackages(tmsConfig, targetSubPackages) {
3613
3422
  const targetSubPackagesName = targetSubPackages.map(item => item.name);
3614
3423
  allSubPackages.forEach(item => {
3615
3424
  if (item.root && targetSubPackagesName.indexOf(item.name) === -1) {
3616
- const moduleRootDir = resolve$2(`${tmsConfig.outputDir}/${item.root}`);
3425
+ const moduleRootDir = resolve$3(`${tmsConfig.outputDir}/${item.root}`);
3617
3426
  shelljs$1.rm('-rf', `${moduleRootDir}/*`, {
3618
3427
  silent: true
3619
3428
  }); // 解决微信开发者工具(dist/app.json: ["subpackages"][0]["root"] 字段需为 目录)错误 - 提前创建该目录
@@ -3630,16 +3439,19 @@ async function dev$2(tmsConfig, targetModules) {
3630
3439
  } = global$1.getData('cmd');
3631
3440
 
3632
3441
  if (noCache) {
3633
- shelljs$1.rm('-rf', resolve$2(tmsConfig.outputDir));
3634
- shelljs$1.rm('-rf', CACHE_DIR);
3635
- } // 初始化操作
3442
+ shelljs$1.rm('-rf', resolve$3(tmsConfig.outputDir));
3443
+ shelljs$1.rm('-rf', MODULE_CODE_DIR);
3444
+ shelljs$1.rm('-rf', NODE_MODULES_DIR);
3445
+ } // 推荐tmskit的版本
3446
+
3636
3447
 
3448
+ await recommendVersion(); // 初始化操作
3637
3449
 
3638
3450
  const {
3639
3451
  subPackages,
3640
3452
  modules: newModules
3641
- } = await init$4(tmsConfig, targetModules);
3642
- info$3('当前dev启动的有效模块', newModules.map(item => item.moduleName).sort());
3453
+ } = await init$2(tmsConfig, targetModules);
3454
+ info$2('当前dev启动的有效模块', newModules.map(item => item.moduleName).sort());
3643
3455
 
3644
3456
  if (typeof (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks = tmsConfig.hooks) === null || _tmsConfig$hooks === void 0 ? void 0 : _tmsConfig$hooks.beforeCompile) === 'function') {
3645
3457
  var _tmsConfig$hooks2;
@@ -3649,36 +3461,37 @@ async function dev$2(tmsConfig, targetModules) {
3649
3461
  tmsConfig: filterField$1(tmsConfig, ['gitAccount']),
3650
3462
  modules: newModules
3651
3463
  }));
3464
+ report$3('hooks:beforeCompile');
3652
3465
  }
3653
3466
  delOtherPackages(tmsConfig, subPackages);
3654
- compileDev(tmsConfig, newModules, subPackages, true);
3467
+ compileDev(tmsConfig, newModules, true);
3655
3468
  }
3656
3469
 
3657
3470
  var dev_1 = dev$2;
3658
3471
 
3659
3472
  const dev$1 = dev$3;
3660
3473
 
3661
- var build$2 = async (tmsConfig, newModules, subPackages, isDev) => {
3662
- dev$1(tmsConfig, newModules, subPackages, isDev);
3474
+ var build$2 = async (tmsConfig, newModules, isDev) => {
3475
+ dev$1(tmsConfig, newModules, isDev);
3663
3476
  };
3664
3477
 
3665
- const shelljs = require$$0__default$3;
3478
+ const shelljs = require$$2__default;
3666
3479
  const {
3667
- resolve: resolve$1,
3480
+ resolve: resolve$2,
3668
3481
  filterField
3669
3482
  } = widgets;
3670
- const init$3 = init_1;
3483
+ const init$1 = init_1;
3671
3484
  const compileBuild = build$2;
3485
+ const report$2 = report_1;
3672
3486
 
3673
3487
  async function build$1(tmsConfig, targetModules) {
3674
3488
  var _tmsConfig$hooks;
3675
3489
 
3676
3490
  // 开始构建前,清理输出目录
3677
- await shelljs.rm('-rf', resolve$1(tmsConfig.outputDir));
3491
+ await shelljs.rm('-rf', resolve$2(tmsConfig.outputDir));
3678
3492
  const {
3679
- modules: newModules,
3680
- subPackages
3681
- } = await init$3(tmsConfig, targetModules);
3493
+ modules: newModules
3494
+ } = await init$1(tmsConfig, targetModules);
3682
3495
  const isDev = false;
3683
3496
 
3684
3497
  if (typeof (tmsConfig === null || tmsConfig === void 0 ? void 0 : (_tmsConfig$hooks = tmsConfig.hooks) === null || _tmsConfig$hooks === void 0 ? void 0 : _tmsConfig$hooks.beforeCompile) === 'function') {
@@ -3689,24 +3502,23 @@ async function build$1(tmsConfig, targetModules) {
3689
3502
  tmsConfig: filterField(tmsConfig, ['gitAccount']),
3690
3503
  modules: newModules
3691
3504
  }));
3505
+ report$2('hooks:beforeCompile');
3692
3506
  }
3693
- compileBuild(tmsConfig, newModules, subPackages, isDev);
3507
+ compileBuild(tmsConfig, newModules, isDev);
3694
3508
  }
3695
3509
 
3696
3510
  var build_1 = build$1;
3697
3511
 
3698
- const fs = require$$0__default$2;
3512
+ const fs$1 = require$$0__default$1;
3699
3513
  const {
3700
- resolve
3514
+ resolve: resolve$1
3701
3515
  } = widgets;
3702
- const {
3703
- handleError: handleError$1
3704
- } = handleError_1;
3705
3516
  const {
3706
3517
  ensureDirExist
3707
3518
  } = io$3;
3708
3519
  const {
3709
- warn
3520
+ warn,
3521
+ succeed
3710
3522
  } = log$1;
3711
3523
  /**
3712
3524
  * 根据相关配置创建软链接
@@ -3714,26 +3526,25 @@ const {
3714
3526
  */
3715
3527
 
3716
3528
  const symLink$1 = tmsConfig => {
3717
- try {
3718
- ensureDirExist(resolve(tmsConfig.cloudDir));
3529
+ ensureDirExist(resolve$1(tmsConfig.cloudDir));
3719
3530
 
3720
- if (tmsConfig.cloudModules) {
3721
- tmsConfig.cloudModules.forEach(item => {
3722
- const sourcePath = resolve(item.path);
3723
- const targetPath = resolve(tmsConfig.cloudDir, item.name);
3531
+ if (tmsConfig.cloudModules) {
3532
+ tmsConfig.cloudModules.forEach(item => {
3533
+ const sourcePath = resolve$1(item.path);
3534
+ const targetPath = resolve$1(tmsConfig.cloudDir, item.name);
3724
3535
 
3725
- if (!fs.existsSync(sourcePath)) {
3726
- warn(`云函数${sourcePath}不存在`);
3727
- return;
3728
- }
3536
+ if (!fs$1.existsSync(sourcePath)) {
3537
+ warn(`云函数${sourcePath}不存在`);
3538
+ return;
3539
+ }
3729
3540
 
3730
- if (!fs.existsSync(targetPath)) {
3731
- fs.symlinkSync(sourcePath, targetPath);
3732
- }
3733
- });
3734
- }
3735
- } catch (e) {
3736
- handleError$1(`创建软链错误: ${e}`);
3541
+ if (!fs$1.existsSync(targetPath)) {
3542
+ fs$1.symlinkSync(sourcePath, targetPath);
3543
+ }
3544
+ });
3545
+ succeed('云函数创建软链成功');
3546
+ } else {
3547
+ warn('你没有在tms.config.js的cloudModules注册云函数');
3737
3548
  }
3738
3549
  };
3739
3550
 
@@ -3747,39 +3558,34 @@ const {
3747
3558
  const {
3748
3559
  handleError
3749
3560
  } = handleError_1;
3750
- const {
3751
- succeed
3752
- } = log$1;
3753
3561
 
3754
3562
  var cloud$1 = async tmsConfig => {
3755
3563
  try {
3756
3564
  await symLink(tmsConfig);
3757
- succeed('云函数创建软链成功');
3758
3565
  } catch (e) {
3759
3566
  handleError(`创建软链错误: ${e}`);
3760
3567
  }
3761
3568
  };
3762
3569
 
3763
3570
  /* eslint-disable no-param-reassign */
3764
- const loadash = require$$0__default$6;
3765
- const init$2 = init_1;
3571
+ const init = init_1;
3766
3572
  const dev = dev_1;
3767
3573
  const build = build_1;
3768
3574
  const install = install_1;
3769
3575
  const cloud = cloud$1;
3770
3576
  const {
3771
3577
  fail,
3772
- info: info$2
3578
+ info: info$1
3773
3579
  } = log$1;
3774
3580
  const {
3775
3581
  global
3776
3582
  } = global_1;
3583
+ const report$1 = report_1;
3777
3584
  const {
3778
- readTmsConfig,
3779
- readTmsPrivateCf,
3780
- checkModules,
3585
+ getTmsConfig: getTmsConfig$1,
3781
3586
  getModulesByMergeDepModules,
3782
- getSubPackages
3587
+ getSubPackages,
3588
+ getModulesByModuleNames
3783
3589
  } = tmsMpconfig.exports;
3784
3590
 
3785
3591
  const handleModuleArg = cmd => {
@@ -3798,7 +3604,7 @@ const handleModuleArg = cmd => {
3798
3604
  */
3799
3605
 
3800
3606
 
3801
- const getSpecificModules = (moduleArg, modules) => {
3607
+ const getSpecificModuleNames = (moduleArg, modules) => {
3802
3608
  if (moduleArg.length > 0) {
3803
3609
  return moduleArg;
3804
3610
  }
@@ -3824,85 +3630,83 @@ const getSpecificModules = (moduleArg, modules) => {
3824
3630
 
3825
3631
  return all.map(item => item.moduleName);
3826
3632
  };
3827
- /**
3828
- * 合并tms.config.js 与 tms.private.config.js的配置项
3829
- * @param {*} tmsConfig
3830
- * @param {*} tmsPrivateCf
3831
- * @returns
3832
- */
3833
-
3834
3633
 
3835
- const mergeConfig = (tmsConfig, tmsPrivateCf) => {
3836
- const modules = {};
3837
-
3838
- if (Array.isArray(tmsConfig.modules)) {
3839
- modules.all = tmsConfig.modules;
3840
- tmsConfig.modules = modules;
3841
- } // 合并默认值
3634
+ async function run(commandName, cmd) {
3635
+ // 用户本地的配置
3636
+ const tmsConfig = getTmsConfig$1();
3842
3637
 
3638
+ try {
3639
+ // 缓存数据
3640
+ global.setData({
3641
+ cmd,
3642
+ tmsConfig
3643
+ });
3843
3644
 
3844
- const res = loadash.mergeWith(tmsConfig, tmsPrivateCf, (objValue, srcValue) => {
3845
- if (loadash.isArray(objValue) && objValue[0] && loadash.isObject(objValue[0])) {
3846
- return objValue.concat(srcValue);
3645
+ if (commandName === 'cloud') {
3646
+ cloud(tmsConfig);
3647
+ report$1('run:cloud', {
3648
+ appName: tmsConfig === null || tmsConfig === void 0 ? void 0 : tmsConfig.appName
3649
+ });
3650
+ return;
3847
3651
  }
3848
- });
3849
- return res;
3850
- };
3851
-
3852
- async function run(commandName, cmd) {
3853
- try {
3854
- // 用户本地的私有项目配置
3855
- const tmsPrivateCf = readTmsPrivateCf();
3856
- const {
3857
- env = tmsPrivateCf === null || tmsPrivateCf === void 0 ? void 0 : tmsPrivateCf.env
3858
- } = cmd;
3859
- let tmsConfig = readTmsConfig(env);
3860
- tmsConfig = mergeConfig(tmsConfig, tmsPrivateCf); // 处理module参数
3861
3652
 
3862
- const specificModules = getSpecificModules(handleModuleArg(cmd), tmsConfig.modules);
3863
- const modules = checkModules(tmsConfig, [...new Set([...tmsConfig.mainPackages, ...specificModules])], true); // 获取所有模块,合并模块依赖的模块
3653
+ otherCommands(tmsConfig, commandName, cmd);
3654
+ } catch (error) {
3655
+ const errMsg = typeof error === 'object' ? error.message : error;
3656
+ report$1('run', {
3657
+ errMsg,
3658
+ appName: tmsConfig === null || tmsConfig === void 0 ? void 0 : tmsConfig.appName
3659
+ });
3660
+ fail(`构建出现错误: ${errMsg}`);
3661
+ info$1('详细错误信息', error);
3662
+ process.exit(1);
3663
+ }
3664
+ }
3864
3665
 
3865
- const newModules = getModulesByMergeDepModules(tmsConfig, modules); // 获取所有的分包
3666
+ function otherCommands(tmsConfig, commandName, cmd) {
3667
+ // 处理module参数
3668
+ const specificModuleNames = getSpecificModuleNames(handleModuleArg(cmd), tmsConfig.modules); // moduleNames => ['home', 'car']
3866
3669
 
3867
- const subPackages = getSubPackages(newModules); // 缓存数据
3670
+ const moduleNames = [...new Set([...specificModuleNames])];
3671
+ const modules = getModulesByModuleNames(tmsConfig, moduleNames, false); // 获取所有模块,合并模块依赖的模块
3868
3672
 
3869
- global.setData({
3870
- env,
3871
- cmd,
3872
- tmsConfig
3873
- });
3673
+ const newModules = getModulesByMergeDepModules(tmsConfig, modules, false); // 获取所有的分包
3874
3674
 
3875
- switch (commandName) {
3876
- case 'init':
3877
- init$2(tmsConfig, newModules);
3878
- return;
3675
+ const subPackages = getSubPackages(newModules);
3879
3676
 
3880
- case 'dev':
3881
- global.setData('isDev', true);
3882
- dev(tmsConfig, newModules);
3883
- return;
3677
+ switch (commandName) {
3678
+ case 'init':
3679
+ init(tmsConfig, newModules);
3680
+ report$1('run:init', {
3681
+ appName: tmsConfig === null || tmsConfig === void 0 ? void 0 : tmsConfig.appName
3682
+ });
3683
+ return;
3884
3684
 
3885
- case 'cloud':
3886
- cloud(tmsConfig);
3887
- return;
3685
+ case 'dev':
3686
+ global.setData('isDev', true);
3687
+ dev(tmsConfig, newModules);
3688
+ report$1('run:dev', {
3689
+ appName: tmsConfig === null || tmsConfig === void 0 ? void 0 : tmsConfig.appName
3690
+ });
3691
+ return;
3888
3692
 
3889
- case 'install':
3890
- install(tmsConfig, subPackages, false);
3891
- return;
3693
+ case 'install':
3694
+ install(tmsConfig, subPackages, false);
3695
+ report$1('run:install', {
3696
+ appName: tmsConfig === null || tmsConfig === void 0 ? void 0 : tmsConfig.appName
3697
+ });
3698
+ return;
3892
3699
 
3893
- case 'build':
3894
- global.setData('isDev', false);
3895
- build(tmsConfig, newModules);
3896
- return;
3700
+ case 'build':
3701
+ global.setData('isDev', false);
3702
+ build(tmsConfig, newModules);
3703
+ report$1('run:build', {
3704
+ appName: tmsConfig === null || tmsConfig === void 0 ? void 0 : tmsConfig.appName
3705
+ });
3706
+ return;
3897
3707
 
3898
- default:
3899
- return;
3900
- }
3901
- } catch (error) {
3902
- const errMsg = typeof error === 'object' ? error.message : error;
3903
- fail(`构建出现错误: ${errMsg}`);
3904
- info$2('详细错误信息', error);
3905
- process.exit(1);
3708
+ default:
3709
+ return;
3906
3710
  }
3907
3711
  }
3908
3712
 
@@ -3910,13 +3714,21 @@ var run_1 = run;
3910
3714
 
3911
3715
  var entry = [{
3912
3716
  command: 'create <project-name>',
3913
- description: '创建新的应用',
3717
+ description: '创建项目',
3914
3718
  action: projectName => {
3915
3719
  create_1(projectName);
3916
3720
  }
3721
+ }, {
3722
+ command: 'install-cmd <npm-name>',
3723
+ description: '安装扩展命令',
3724
+ options: [['--registry [registry]', 'npm源']],
3725
+ action: (npmName, cmd) => {
3726
+ const res = extendCmd;
3727
+ res.installCmd(npmName, cmd);
3728
+ }
3917
3729
  }, {
3918
3730
  name: 'run',
3919
- type: 'child',
3731
+ type: 'parent',
3920
3732
  description: '项目开发使用的命令',
3921
3733
  commands: [{
3922
3734
  command: 'install',
@@ -3946,114 +3758,14 @@ var entry = [{
3946
3758
  action: cmd => {
3947
3759
  run_1('build', cmd);
3948
3760
  }
3949
- } // 对外暂不暴露该命令
3950
- // {
3951
- // command: 'init',
3952
- // description: '模块配置初始化项目(eg: 下载第三方模块代码、安装依赖、生成app.json等)',
3953
- // options: [
3954
- // ['-m, --module [moduleName]', '模块名称'],
3955
- // ['-e, --env [env]', '环境变量'],
3956
- // ],
3957
- // action: (cmd) => {
3958
- // require('./scripts/run/index')('init', cmd);
3959
- // },
3960
- // },
3961
- ]
3761
+ }]
3962
3762
  }];
3963
3763
 
3964
- var require$$7 = {
3965
- name: "@tmsfe/tmskit",
3966
- version: "0.0.20",
3967
- description: "tmskit",
3968
- main: "dist/index.cjs",
3969
- bin: {
3970
- tmskit: "main.js"
3971
- },
3972
- files: [
3973
- "build",
3974
- "src",
3975
- "dist",
3976
- "main.js",
3977
- "package.json"
3978
- ],
3979
- scripts: {
3980
- dev: "rollup -wc --environment TARGET:tmskit",
3981
- build: "rollup -c --environment TARGET:tmskit",
3982
- "pub:patch": "sh build/publish.sh patch",
3983
- "pub:minor": "sh build/publish.sh minor",
3984
- "pub:major": "sh build/publish.sh major"
3985
- },
3986
- author: "tms·web",
3987
- license: "ISC",
3988
- buildOptions: {
3989
- formats: [
3990
- "cjs"
3991
- ]
3992
- },
3993
- devDependencies: {
3994
- "@rollup/plugin-babel": "^5.0.2",
3995
- "@rollup/plugin-commonjs": "^19.0.0",
3996
- "@rollup/plugin-dynamic-import-vars": "^1.1.1",
3997
- "@rollup/plugin-json": "^4.0.3",
3998
- rollup: "^2.6.1",
3999
- "rollup-plugin-node-resolve": "^5.2.0",
4000
- "rollup-plugin-replace": "^2.2.0",
4001
- "rollup-plugin-terser": "^6.1.0",
4002
- "rollup-plugin-typescript2": "0.27.0"
4003
- },
4004
- dependencies: {
4005
- "ansi-colors": "1.1.0",
4006
- anymatch: "^1.3.0",
4007
- async: "^3.2.2",
4008
- chalk: "^4.1.0",
4009
- chokidar: "^3.5.3",
4010
- commander: "^8.3.0",
4011
- "copy-webpack-plugin": "^9.1.0",
4012
- ejs: "^3.1.5",
4013
- "fancy-log": "1.3.2",
4014
- "fs-extra": "^10.0.1",
4015
- "glob-ignore": "^1.0.2",
4016
- "glob-parent": "^3.0.1",
4017
- gulp: "^4.0.2",
4018
- "gulp-watch": "^5.0.1",
4019
- htmlparser2: "^7.2.0",
4020
- inquirer: "^7.3.3",
4021
- leven: "3.1.0",
4022
- lodash: "^4.17.21",
4023
- metalsmith: "^2.3.0",
4024
- "miniprogram-ci": "1.4.13",
4025
- moment: "^2.29.2",
4026
- "object-assign": "^4.0.1",
4027
- ora: "^5.1.0",
4028
- "path-is-absolute": "^1.0.1",
4029
- "plugin-error": "^1.0.0",
4030
- postcss: "^8.4.6",
4031
- precinct: "^8.3.1",
4032
- "readable-stream": "^2.2.2",
4033
- "replace-ext": "^2.0.0",
4034
- request: "^2.88.2",
4035
- shelljs: "^0.8.4",
4036
- slash: "^1.0.0",
4037
- "strip-comments": "^2.0.1",
4038
- through2: "^4.0.2",
4039
- unzipper: "^0.10.11",
4040
- vinyl: "^2.1.0",
4041
- "vinyl-file": "^2.0.0",
4042
- "vinyl-sourcemaps-apply": "^0.2.0"
4043
- },
4044
- engines: {
4045
- node: "^12.17.0 || >= 14.13.1"
4046
- },
4047
- jest: {
4048
- testEnvironment: "jest-environment-node"
4049
- }
4050
- };
4051
-
4052
3764
  const semver = require$$1__default$7;
4053
- const packageJson = require$$7;
4054
- const chalk$1 = require$$0__default;
3765
+ const packageJson = require$$12;
3766
+ const chalk$1 = require$$3__default;
4055
3767
  const {
4056
- info: info$1
3768
+ info
4057
3769
  } = log$1;
4058
3770
  const requiredVersion = packageJson.engines.node;
4059
3771
  const packName = packageJson.name;
@@ -4068,44 +3780,53 @@ const checkNodeVersion = (wanted, id) => {
4068
3780
  if (!semver.satisfies(process.version, wanted, {
4069
3781
  includePrerelease: true
4070
3782
  })) {
4071
- info$1(chalk$1.red(`你正在使用的Node版本: ${process.version}, 但是此版本的 ${id} 需要的Node最小版本 ${wanted}.\n请先升级你的Node版本.`));
3783
+ info(chalk$1.red(`你正在使用的Node版本: ${process.version}, 但是此版本的 ${id} 需要的Node最小版本 ${wanted}.\n请先升级你的Node版本.`));
4072
3784
  process.exit(1);
4073
3785
  }
4074
3786
  };
4075
3787
  /**
4076
3788
  * 检查运行环境
4077
- * @returns {Undefined} 无需返回值
4078
3789
  */
4079
3790
 
4080
3791
 
4081
- function initCliContext() {
3792
+ function check$1() {
4082
3793
  // 执行操作前检查node版本
4083
3794
  // 旧版本node直接提示升级,退出脚本
4084
3795
  checkNodeVersion(requiredVersion, packName);
4085
3796
  }
4086
3797
 
4087
- var init$1 = initCliContext;
3798
+ var check_1 = check$1;
4088
3799
 
4089
- const chalk = require$$0__default;
4090
- const commander = require$$0__default$1;
3800
+ /* eslint-disable no-param-reassign */
3801
+ const chalk = require$$3__default;
3802
+ const commander = require$$1__default$8;
3803
+ const path = require$$1__default$1;
3804
+ const fs = require$$0__default$1;
4091
3805
  const {
4092
- suggestCommands
3806
+ resolve
4093
3807
  } = widgets;
4094
3808
  const {
4095
- info
3809
+ infoNoTime
4096
3810
  } = log$1;
3811
+ const {
3812
+ getTmsConfig
3813
+ } = tmsMpconfig.exports;
4097
3814
  const {
4098
3815
  TMS_NAME
4099
- } = require$$4;
3816
+ } = constant;
4100
3817
  const commands = entry;
4101
- const init = init$1;
4102
- init();
3818
+ const check = check_1;
3819
+ const {
3820
+ loadExtendCmd
3821
+ } = extendCmd;
3822
+ const report = report_1;
3823
+ check();
4103
3824
  const program = new commander.Command(TMS_NAME);
4104
- program.version(`${TMS_NAME} ${require$$7.version}`, '-v, -V, --version');
3825
+ program.version(`${TMS_NAME} ${require$$12.version}`, '-v, -V, --version'); // 注册命令底层实现
4105
3826
 
4106
3827
  function registerCommand(program, commands) {
4107
3828
  commands.forEach(cmd => {
4108
- if (cmd.type === 'child') {
3829
+ if (cmd.type === 'parent') {
4109
3830
  const childProgram = new commander.Command(cmd.name);
4110
3831
  cmd.usage && childProgram.usage(cmd.usage);
4111
3832
  cmd.description && childProgram.description(cmd.description);
@@ -4117,22 +3838,65 @@ function registerCommand(program, commands) {
4117
3838
  const command = program.command(cmd.command);
4118
3839
  cmd.usage && command.usage(cmd.usage);
4119
3840
  cmd.description && command.description(cmd.description);
4120
- (_cmd$options = cmd.options) === null || _cmd$options === void 0 ? void 0 : _cmd$options.forEach(opt => command.option(...opt));
3841
+ (_cmd$options = cmd.options) === null || _cmd$options === void 0 ? void 0 : _cmd$options.forEach(opt => command.option(...opt)); // 上报
3842
+
3843
+ command.hook('preAction', thisCommand => {
3844
+ report(`${thisCommand._name}-pre`);
3845
+ }); // 上报
3846
+
3847
+ command.hook('postAction', thisCommand => {
3848
+ report(`${thisCommand._name}-post`);
3849
+ });
4121
3850
  command.action(cmd.action);
4122
3851
  }
4123
3852
  });
3853
+ } // 注册扩展命令
3854
+
3855
+
3856
+ function registerExtendCommand(program, configPath) {
3857
+ const tmsConfig = getTmsConfig(configPath);
3858
+
3859
+ if (tmsConfig !== null && tmsConfig !== void 0 && tmsConfig.commands) {
3860
+ const commands = typeof tmsConfig.commands === 'function' ? tmsConfig.commands() : tmsConfig.commands;
3861
+
3862
+ if (Array.isArray(commands)) {
3863
+ registerCommand(program, commands);
3864
+ }
3865
+ }
3866
+ } // 注册所有的命令
3867
+
3868
+
3869
+ function registerAllCmds(program, commands) {
3870
+ // 注册脚手架内部命令
3871
+ registerCommand(program, commands); // 注册npm包扩展命令
3872
+
3873
+ const cmdConfigs = loadExtendCmd();
3874
+ cmdConfigs.forEach(cmdConfig => {
3875
+ registerExtendCommand(program, path.dirname(cmdConfig));
3876
+ }); // 注册当前目录扩展命令
3877
+
3878
+ const tmsConfigPath = resolve('./tms.config.js');
3879
+
3880
+ if (fs.existsSync(tmsConfigPath)) {
3881
+ registerExtendCommand(program, path.dirname(tmsConfigPath));
3882
+ }
4124
3883
  }
4125
3884
 
4126
- registerCommand(program, commands);
3885
+ registerAllCmds(program, commands); // 捕获未注册的命令
3886
+
3887
+ program.arguments('<command>').option('-c, --config <value>', '配置', value => {
3888
+ // 注册指定配置的扩展命令
3889
+ registerExtendCommand(program, path.dirname(resolve(value)));
3890
+ }).action(cmd => {
3891
+ infoNoTime(chalk.yellow(`
3892
+ 没有找到${cmd}命令
3893
+ 你可以通过${chalk.green('tmskit install-cmd <npm-name>')}安装扩展命令, ${chalk.green('扩展命令列表:https://www.npmjs.com/search?q=tmskit-cmd')}
3894
+ 你也可以通过 ${chalk.green('tmskit <command> --config=../tms.config.js')} 指定本地的扩展命令
3895
+ `));
3896
+ report(`${cmd}-not-find`);
3897
+ });
4127
3898
  program.on('--help', () => {
4128
- info(` Run ${chalk.cyan(`${TMS_NAME} <command> --help`)} for detailed usage of given command.`);
4129
- }); // 捕获未注册的命令
4130
-
4131
- program.arguments('<command>').action(cmd => {
4132
- program.outputHelp();
4133
- info(` ${chalk.red(`Unknown command ${chalk.yellow(cmd)}.`)}`);
4134
- suggestCommands(cmd);
4135
- process.exitCode = 1;
3899
+ infoNoTime(`Run ${chalk.cyan(`${TMS_NAME} <command> --help`)} for detailed usage of given command.`);
4136
3900
  });
4137
3901
 
4138
3902
  if (!process.argv.slice(2).length) {