@tarojs/cli-convertor 3.8.0-canary.0 → 3.8.0-canary.1

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.
@@ -1,8 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.incrementId = exports.analyzeImportUrl = exports.getPkgVersion = exports.getRootPath = void 0;
3
+ exports.DEFAULT_Component_SET = exports.IReportError = exports.createErrorCodeMsg = exports.parseError = exports.paseGlobalErrMsgs = exports.computeProjectFileNums = exports.parseProjectName = exports.astToCode = exports.replacePluginComponentUrl = exports.printToLogFile = exports.updateLogFileContent = exports.getLineBreak = exports.generateDir = exports.generateReportFile = exports.getWxssImports = exports.transRelToAbsPath = exports.handleUnconvertDir = exports.getMatchUnconvertDir = exports.handleThirdPartyLib = exports.incrementId = exports.analyzeImportUrl = exports.copyFileToTaro = exports.getPkgVersion = exports.getRootPath = void 0;
4
+ const generator_1 = require("@babel/generator");
4
5
  const helper_1 = require("@tarojs/helper");
5
6
  const path = require("path");
7
+ const prettier = require("prettier");
8
+ const global_1 = require("./global");
9
+ const NODE_MODULES = 'node_modules';
10
+ /* 代码格式化参数 */
11
+ const prettierJSConfig = {
12
+ semi: false,
13
+ singleQuote: true,
14
+ parser: 'babel',
15
+ };
6
16
  function getRootPath() {
7
17
  return path.resolve(__dirname, '../../');
8
18
  }
@@ -11,37 +21,116 @@ function getPkgVersion() {
11
21
  return require(path.join(getRootPath(), 'package.json')).version;
12
22
  }
13
23
  exports.getPkgVersion = getPkgVersion;
14
- function getRelativePath(rootPath, sourceFilePath, oriPath) {
24
+ // 文件存在或添加后缀.js、.jsx、.ts、.tsx存在则返回文件路径,否则返回null
25
+ function revertScriptPath(absolutePath, SCRIPT_EXT) {
26
+ for (const item of SCRIPT_EXT) {
27
+ if (helper_1.fs.existsSync(absolutePath)) {
28
+ return absolutePath;
29
+ }
30
+ else if (helper_1.fs.existsSync(`${absolutePath}${item}`)) {
31
+ return `${absolutePath}${item}`;
32
+ }
33
+ }
34
+ return null;
35
+ }
36
+ function getRelativePath(_rootPath, sourceFilePath, oriPath, alias) {
15
37
  // 处理以/开头的绝对路径,比如 /a/b
16
38
  if (path.isAbsolute(oriPath)) {
17
39
  if (oriPath.indexOf('/') !== 0) {
18
40
  return '';
19
41
  }
20
- const vpath = path.resolve(rootPath, oriPath.substr(1));
21
- if (!helper_1.fs.existsSync(vpath)) {
42
+ const absolutePath = revertScriptPath(path.join(sourceFilePath, '..' + oriPath), helper_1.SCRIPT_EXT);
43
+ if (absolutePath == null) {
22
44
  return '';
23
45
  }
24
- let relativePath = path.relative(path.dirname(sourceFilePath), vpath);
46
+ let relativePath = path.relative(path.dirname(sourceFilePath), absolutePath);
25
47
  relativePath = (0, helper_1.promoteRelativePath)(relativePath);
26
48
  if (relativePath.indexOf('.') !== 0) {
27
- return './' + relativePath;
49
+ return `./${relativePath}`;
28
50
  }
29
51
  return relativePath;
30
52
  }
31
53
  // 处理非正常路径,比如 a/b
32
54
  if (oriPath.indexOf('.') !== 0) {
33
- const vpath = path.resolve(sourceFilePath, '..', oriPath);
34
- if (helper_1.fs.existsSync(vpath)) {
35
- return './' + oriPath;
55
+ let absolutePath;
56
+ // 根据app.json中是否有resolveAlias 配置项自定义模块路径的映射规则来获取引用文件的绝对路径
57
+ if (alias) {
58
+ // 预防用户定义了模块路径的映射规则但没有使用的情况
59
+ absolutePath = revertScriptPath(path.join(sourceFilePath, '..', oriPath), helper_1.SCRIPT_EXT);
60
+ Object.keys(alias).forEach((key) => {
61
+ const newKey = key.replace(/\/\*$/, '');
62
+ if (oriPath.startsWith(newKey)) {
63
+ const realPath = path.join(_rootPath, alias[key].replace(/\/\*$/, ''));
64
+ absolutePath = revertScriptPath(oriPath.replace(newKey, realPath), helper_1.SCRIPT_EXT);
65
+ }
66
+ });
36
67
  }
68
+ else {
69
+ absolutePath = revertScriptPath(path.join(sourceFilePath, '..', oriPath), helper_1.SCRIPT_EXT);
70
+ }
71
+ // 可能为三方库
72
+ if (absolutePath == null) {
73
+ return oriPath;
74
+ }
75
+ let relativePath = path.relative(path.dirname(sourceFilePath), absolutePath);
76
+ relativePath = normalizePath(relativePath);
77
+ if (relativePath.indexOf('.') !== 0) {
78
+ return `./${relativePath}`;
79
+ }
80
+ return relativePath;
37
81
  }
38
82
  return oriPath;
39
83
  }
40
- function analyzeImportUrl(rootPath, sourceFilePath, scriptFiles, source, value) {
84
+ function copyFileToTaro(from, to, options) {
85
+ const filename = path.basename(from);
86
+ if (helper_1.fs.statSync(from).isFile() && !path.extname(to)) {
87
+ helper_1.fs.ensureDir(to);
88
+ return helper_1.fs.copySync(from, path.join(to, filename), options);
89
+ }
90
+ helper_1.fs.ensureDir(path.dirname(to));
91
+ return helper_1.fs.copySync(from, to, options);
92
+ }
93
+ exports.copyFileToTaro = copyFileToTaro;
94
+ // 递归复制文件夹
95
+ function copyFolderToTaro(source, destination) {
96
+ // 创建目标文件夹
97
+ if (!helper_1.fs.existsSync(destination)) {
98
+ helper_1.fs.mkdirSync(destination, { recursive: true });
99
+ }
100
+ // 获取源文件夹中的所有项
101
+ const items = helper_1.fs.readdirSync(source);
102
+ for (const item of items) {
103
+ const sourcePath = path.join(source, item);
104
+ const destinationPath = path.join(destination, item);
105
+ const stat = helper_1.fs.lstatSync(sourcePath);
106
+ if (stat.isSymbolicLink()) {
107
+ // 如果是符号链接,获取链接的目标路径并进行复制
108
+ const target = helper_1.fs.readlinkSync(sourcePath);
109
+ copyFolderToTaro(target, destinationPath);
110
+ }
111
+ else if (stat.isDirectory()) {
112
+ // 如果是子文件夹,则递归复制
113
+ copyFolderToTaro(sourcePath, destinationPath);
114
+ }
115
+ else {
116
+ // 如果是普通文件,则直接复制
117
+ helper_1.fs.copyFileSync(sourcePath, destinationPath);
118
+ }
119
+ }
120
+ }
121
+ function analyzeImportUrl(rootPath, sourceFilePath, scriptFiles, source, value, isTsProject, pluginName, alias) {
122
+ // 将参数记录到log文件
123
+ updateLogFileContent(`INFO [taro-cli-convertor] analyzeImportUrl - 入参 ${getLineBreak()}sourceFilePath: ${sourceFilePath} ${getLineBreak()}value: ${value} ${getLineBreak()}`);
124
+ if (isPluginMainJs(value, pluginName)) {
125
+ // 插件的入口文件单独转换
126
+ return;
127
+ }
41
128
  const valueExtname = path.extname(value);
42
- const rpath = getRelativePath(rootPath, sourceFilePath, value);
129
+ const rpath = getRelativePath(rootPath, sourceFilePath, value, alias);
43
130
  if (!rpath) {
131
+ createErrorCodeMsg('ReferenceFileNotFound', `文件 ${sourceFilePath} 中引用 ${value} 不存在!`, `${value}`, sourceFilePath);
44
132
  (0, helper_1.printLog)("error" /* processTypeEnum.ERROR */, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 不存在!`);
133
+ updateLogFileContent(`WARN [taro-cli-convertor] analyzeImportUrl - 文件 ${sourceFilePath} 中引用 ${value} 不存在 ${getLineBreak()}`);
45
134
  return;
46
135
  }
47
136
  if (rpath !== value) {
@@ -50,21 +139,25 @@ function analyzeImportUrl(rootPath, sourceFilePath, scriptFiles, source, value)
50
139
  }
51
140
  if (value.indexOf('.') === 0) {
52
141
  if (helper_1.REG_SCRIPT.test(valueExtname) || helper_1.REG_TYPESCRIPT.test(valueExtname)) {
53
- const vpath = path.resolve(sourceFilePath, '..', value);
142
+ const vpath = path.join(sourceFilePath, '..', value);
54
143
  let fPath = value;
55
144
  if (helper_1.fs.existsSync(vpath)) {
56
145
  fPath = vpath;
57
146
  }
58
147
  else {
148
+ createErrorCodeMsg('ReferenceFileNotFound', `文件 ${sourceFilePath} 中引用 ${value} 不存在!`, `${value}`, sourceFilePath);
59
149
  (0, helper_1.printLog)("error" /* processTypeEnum.ERROR */, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 不存在!`);
150
+ updateLogFileContent(`WARN [taro-cli-convertor] analyzeImportUrl - 文件 ${sourceFilePath} 中引用 ${value} 不存在 ${getLineBreak()}`);
60
151
  }
61
152
  scriptFiles.add(fPath);
62
153
  }
63
154
  else {
64
- let vpath = (0, helper_1.resolveScriptPath)(path.resolve(sourceFilePath, '..', value));
155
+ let vpath = (0, helper_1.resolveScriptPath)(path.join(sourceFilePath, '..', value));
65
156
  if (vpath) {
66
157
  if (!helper_1.fs.existsSync(vpath)) {
158
+ createErrorCodeMsg('ReferenceFileNotFound', `文件 ${sourceFilePath} 中引用 ${value} 不存在!`, `${value}`, sourceFilePath);
67
159
  (0, helper_1.printLog)("error" /* processTypeEnum.ERROR */, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 不存在!`);
160
+ updateLogFileContent(`WARN [taro-cli-convertor] analyzeImportUrl - 文件 ${sourceFilePath} 中引用 ${value} 不存在! ${getLineBreak()}`);
68
161
  }
69
162
  else {
70
163
  if (helper_1.fs.lstatSync(vpath).isDirectory()) {
@@ -72,7 +165,9 @@ function analyzeImportUrl(rootPath, sourceFilePath, scriptFiles, source, value)
72
165
  vpath = path.join(vpath, 'index.js');
73
166
  }
74
167
  else {
168
+ createErrorCodeMsg('ReferenceDirNotFound', `文件 ${sourceFilePath} 中引用了目录 ${value}!`, `${value}`, sourceFilePath);
75
169
  (0, helper_1.printLog)("error" /* processTypeEnum.ERROR */, '引用目录', `文件 ${sourceFilePath} 中引用了目录 ${value}!`);
170
+ updateLogFileContent(`WARN [taro-cli-convertor] analyzeImportUrl - 文件 ${sourceFilePath} 中引用了目录 ${value}! ${getLineBreak()}`);
76
171
  return;
77
172
  }
78
173
  }
@@ -83,7 +178,7 @@ function analyzeImportUrl(rootPath, sourceFilePath, scriptFiles, source, value)
83
178
  if (/\.wxs/.test(relativePathExtname)) {
84
179
  relativePath += '.js';
85
180
  }
86
- else {
181
+ else if (!isTsProject) {
87
182
  relativePath = relativePath.replace(relativePathExtname, '.js');
88
183
  }
89
184
  source.value = relativePath;
@@ -91,11 +186,505 @@ function analyzeImportUrl(rootPath, sourceFilePath, scriptFiles, source, value)
91
186
  }
92
187
  }
93
188
  }
189
+ else {
190
+ if (value.startsWith('/') || value.startsWith('@tarojs') || value.startsWith('react')) {
191
+ return;
192
+ }
193
+ scriptFiles.add(value);
194
+ }
94
195
  }
95
196
  exports.analyzeImportUrl = analyzeImportUrl;
197
+ /**
198
+ * 判断导入模块的路径是否是plugin的module
199
+ *
200
+ * @param modulePath
201
+ * @param pluginName
202
+ * @returns
203
+ */
204
+ function isPluginMainJs(modulePath, pluginName) {
205
+ if (pluginName === undefined) {
206
+ return false;
207
+ }
208
+ const regex = new RegExp(`/${pluginName}/`);
209
+ return regex.test(modulePath);
210
+ }
96
211
  const incrementId = () => {
97
212
  let n = 0;
98
213
  return () => (n++).toString();
99
214
  };
100
215
  exports.incrementId = incrementId;
216
+ // 处理三方库引用
217
+ function handleThirdPartyLib(filePath, nodePath, root, convertRoot) {
218
+ // 默认使用node_modules中的三方库
219
+ if (typeof nodePath === 'undefined') {
220
+ nodePath = [NODE_MODULES];
221
+ }
222
+ try {
223
+ let isThirdPartyLibExist = false;
224
+ for (const modulePath of nodePath) {
225
+ const parts = filePath.split('/');
226
+ const npmModulePath = path.join(root, modulePath, parts[0]);
227
+ if (helper_1.fs.existsSync(npmModulePath)) {
228
+ isThirdPartyLibExist = true;
229
+ // 转换后的三方库放在node_modules中
230
+ const moduleConvertPath = path.join(convertRoot, NODE_MODULES, parts[0]);
231
+ if (!helper_1.fs.existsSync(moduleConvertPath)) {
232
+ copyFolderToTaro(npmModulePath, moduleConvertPath);
233
+ (0, helper_1.printLog)("copy" /* processTypeEnum.COPY */, '三方库', normalizePath(npmModulePath.replace(path.join(root, '/'), '')));
234
+ }
235
+ break;
236
+ }
237
+ }
238
+ if (!isThirdPartyLibExist) {
239
+ createErrorCodeMsg('dependencyNotFound', `在[${nodePath.toString()}]中没有找到依赖的三方库${filePath},请安装依赖后运行`, filePath, global_1.globals.currentParseFile);
240
+ console.log(helper_1.chalk.red(`在[${nodePath.toString()}]中没有找到依赖的三方库${filePath},请安装依赖后运行`));
241
+ updateLogFileContent(`WARN [taro-cli-convertor] handleThirdPartyLib - 在 [${nodePath.toString()}] 中没有找到依赖的三方库 ${filePath},请安装依赖后运行 ${getLineBreak()}`);
242
+ }
243
+ }
244
+ catch (error) {
245
+ createErrorCodeMsg('ConvertThirdPartyLibError', `转换三方库${filePath}异常,请手动处理, error message:${error}`, filePath, global_1.globals.currentParseFile);
246
+ console.log(helper_1.chalk.red(`转换三方库${filePath}异常,请手动处理, error message:${error}`));
247
+ updateLogFileContent(`WARN [taro-cli-convertor] handleThirdPartyLib - 转换三方库 ${filePath} 异常 ${getLineBreak()}${error} ${getLineBreak()}`);
248
+ }
249
+ }
250
+ exports.handleThirdPartyLib = handleThirdPartyLib;
251
+ function getMatchUnconvertDir(importPath, externalPaths) {
252
+ if (importPath === undefined || externalPaths === undefined) {
253
+ return null;
254
+ }
255
+ // 支持用户在convert.config.json中配置不转换的目录
256
+ for (let externalPath of externalPaths) {
257
+ externalPath = normalizePath(externalPath).replace('*', '.*');
258
+ const reg = new RegExp(externalPath);
259
+ const match = reg.exec(normalizePath(importPath));
260
+ // external字段配置如 1:../demo 2:../demo/* 3:../demo/*/demo
261
+ if (match) {
262
+ // 处理../demo/*
263
+ if (externalPath.length >= 2 && externalPath.endsWith('*')) {
264
+ // 去掉结尾的".*"
265
+ return externalPath.slice(0, externalPath.length - 3);
266
+ }
267
+ return match[0];
268
+ }
269
+ }
270
+ return null;
271
+ }
272
+ exports.getMatchUnconvertDir = getMatchUnconvertDir;
273
+ function handleUnconvertDir(matchUnconvertDir, rootPath, convertRoot) {
274
+ if (matchUnconvertDir == null) {
275
+ return;
276
+ }
277
+ // 支持用户在convert.config.json中配置不转换的目录
278
+ const outputFilePath = matchUnconvertDir.replace(normalizePath(rootPath), normalizePath(convertRoot));
279
+ if (!helper_1.fs.existsSync(outputFilePath)) {
280
+ copyFileToTaro(matchUnconvertDir, outputFilePath);
281
+ (0, helper_1.printLog)("copy" /* processTypeEnum.COPY */, '不转换目录', matchUnconvertDir.replace(normalizePath(path.join(rootPath, '/')), ''));
282
+ }
283
+ }
284
+ exports.handleUnconvertDir = handleUnconvertDir;
285
+ // export function getMatchDirPath (filePath: string, matchStr: string) {
286
+ // const reg = new RegExp(matchStr)
287
+ // const match = reg.exec(filePath)
288
+ // if (match) {
289
+ // if (matchStr.length >= 2 && matchStr.endsWith('*')) {
290
+ // return matchStr.slice(0, matchStr.length - 2)
291
+ // }
292
+ // return match[0]
293
+ // }
294
+ // }
295
+ // 路径标准化
296
+ function normalizePath(path) {
297
+ if (typeof path === 'undefined') {
298
+ return '';
299
+ }
300
+ return path.replace(/\\/g, '/');
301
+ }
302
+ // 将数组中的相对路径转换为绝对路径
303
+ function transRelToAbsPath(baseFilePath, fileRelativePaths) {
304
+ if (typeof fileRelativePaths === 'undefined') {
305
+ return [];
306
+ }
307
+ const absolutePath = [];
308
+ for (const fileRelativePath of fileRelativePaths) {
309
+ // 相对路径转为绝对路径
310
+ absolutePath.push(path.join(baseFilePath, '..', fileRelativePath));
311
+ }
312
+ return absolutePath;
313
+ }
314
+ exports.transRelToAbsPath = transRelToAbsPath;
315
+ // 获取wxss中引用文件的相对路径集合
316
+ function getWxssImports(content) {
317
+ if (content == null) {
318
+ return [];
319
+ }
320
+ // 匹配 /* ... */ 形式的注释
321
+ const regex = /\/\*([\s\S]*?)\*\//g;
322
+ // 去掉css中的注释
323
+ const contentWithoutComment = content.replace(regex, '');
324
+ let match;
325
+ const imports = [];
326
+ const cssImportReg = new RegExp(helper_1.CSS_IMPORT_REG);
327
+ while ((match = cssImportReg.exec(contentWithoutComment)) !== null) {
328
+ imports.push(match[2]);
329
+ }
330
+ return imports;
331
+ }
332
+ exports.getWxssImports = getWxssImports;
333
+ /**
334
+ * copyFileTo: 将报告模版文件复制到转换后 taroConvert 目录中
335
+ *
336
+ * @param { string } sourceFilePath 源文件路径
337
+ * @param { string } targeFileDir 转换后文件所在目录
338
+ * @param { string } targeFileName 转换后文件名
339
+ * @param { IReportData } reportErroMsg 报错信息
340
+ */
341
+ function generateReportFile(sourceFilePath, targeFileDir, targeFileName, reportErroMsg) {
342
+ try {
343
+ if (!helper_1.fs.existsSync(targeFileDir)) {
344
+ helper_1.fs.mkdirSync(targeFileDir, { recursive: true });
345
+ }
346
+ const fileType = ['.js', '.css', '.html'];
347
+ if (fileType.some((type) => sourceFilePath.endsWith(type))) {
348
+ let data = helper_1.fs.readFileSync(sourceFilePath, 'utf-8');
349
+ if (reportErroMsg) {
350
+ data = data.replace('__errorMsgReport__', JSON.stringify(reportErroMsg));
351
+ }
352
+ helper_1.fs.writeFileSync(path.join(targeFileDir, targeFileName), data);
353
+ }
354
+ else {
355
+ // 处理二进制文件
356
+ const data = helper_1.fs.readFileSync(sourceFilePath);
357
+ helper_1.fs.writeFileSync(path.join(targeFileDir, targeFileName), data);
358
+ }
359
+ }
360
+ catch (error) {
361
+ updateLogFileContent(`WARN [taro-cli-convertor] generateReportFile - 文件 ${sourceFilePath} 写入异常 ${getLineBreak()}${error} ${getLineBreak()}`);
362
+ console.log(`文件${sourceFilePath}写入失败,errorMsg:${error}`);
363
+ }
364
+ }
365
+ exports.generateReportFile = generateReportFile;
366
+ /**
367
+ * 创建文件夹
368
+ *
369
+ * @param dirPath 文件夹路径
370
+ */
371
+ function generateDir(dirPath) {
372
+ try {
373
+ if (!helper_1.fs.existsSync(dirPath)) {
374
+ helper_1.fs.mkdirSync(dirPath);
375
+ }
376
+ }
377
+ catch (error) {
378
+ createErrorCodeMsg('CreateFolderError', `创建文件夹${dirPath}失败`, '', dirPath);
379
+ console.log(`创建文件夹${dirPath}失败`);
380
+ }
381
+ }
382
+ exports.generateDir = generateDir;
383
+ /**
384
+ * 获取不同操作系统下的换行符
385
+ *
386
+ * @returns { string } 换行符
387
+ */
388
+ function getLineBreak() {
389
+ if (process.platform === 'win32') {
390
+ return '\r\n';
391
+ }
392
+ return '\n';
393
+ }
394
+ exports.getLineBreak = getLineBreak;
395
+ /**
396
+ * 记录数据到logFileContent中
397
+ *
398
+ * @param data 日志数据
399
+ */
400
+ function updateLogFileContent(data) {
401
+ try {
402
+ global_1.globals.logFileContent += data;
403
+ // 日志分段写入log文件
404
+ if (global_1.globals.logCount === 2000) {
405
+ printToLogFile();
406
+ global_1.globals.logCount = 0;
407
+ }
408
+ else {
409
+ global_1.globals.logCount++;
410
+ }
411
+ }
412
+ catch (error) {
413
+ console.error(`记录日志数据异常 ${error.message}}`);
414
+ }
415
+ }
416
+ exports.updateLogFileContent = updateLogFileContent;
417
+ /**
418
+ * 写入数据到日志文件中
419
+ *
420
+ */
421
+ function printToLogFile() {
422
+ try {
423
+ helper_1.fs.appendFile(global_1.globals.logFilePath, global_1.globals.logFileContent);
424
+ global_1.globals.logFileContent = '';
425
+ }
426
+ catch (error) {
427
+ console.error(`写入日志文件异常 ${error.message}}`);
428
+ throw new IReportError('写日志文件异常', 'WriteLogException', global_1.globals.logFilePath, '');
429
+ }
430
+ }
431
+ exports.printToLogFile = printToLogFile;
432
+ /**
433
+ * 将引用插件的路径替换为引用子包插件的路径
434
+ *
435
+ * @param pluginComponentPath 小程序中引用的插件路径
436
+ * @param pluginInfo 插件信息
437
+ * @returns
438
+ */
439
+ function replacePluginComponentUrl(pluginComponentPath, pluginInfo) {
440
+ // 捕获跳转路径中的插件名和页面名,替换为子包路径
441
+ const regexPluginUrl = /plugin:\/\/([^/]+)\/([^/?]+)/;
442
+ const matchPluginUrl = pluginComponentPath.match(regexPluginUrl);
443
+ if (!matchPluginUrl) {
444
+ createErrorCodeMsg('ImportSrcPathFormatError', `引用插件路径格式异常,插件路径:${pluginComponentPath}`, pluginComponentPath, global_1.globals.currentParseFile);
445
+ console.log(`引用插件路径格式异常,插件路径:${pluginComponentPath}`);
446
+ }
447
+ // 捕获页面名
448
+ const componentName = matchPluginUrl[2];
449
+ // 通过引用的插件组件名在注册的插件组件信息中查找组件路径
450
+ let componentPath = null;
451
+ pluginInfo.publicComponents.forEach((publicComponent) => {
452
+ if (publicComponent.name === componentName) {
453
+ componentPath = publicComponent.path;
454
+ }
455
+ });
456
+ if (!componentPath) {
457
+ createErrorCodeMsg('UnregisteredPluginComponentError', `引用了未注册的插件组件,插件路径: ${pluginComponentPath}`, pluginComponentPath, global_1.globals.currentParseFile);
458
+ console.log(`引用了未注册的插件组件,插件路径: ${pluginComponentPath}`);
459
+ }
460
+ return componentPath;
461
+ }
462
+ exports.replacePluginComponentUrl = replacePluginComponentUrl;
463
+ /**
464
+ * 将部分 ast 节点转为代码片段
465
+ * @param ast astNode 节点
466
+ * @returns
467
+ */
468
+ function astToCode(ast) {
469
+ if (!ast)
470
+ return '';
471
+ try {
472
+ // 格式化生成的代码
473
+ let formatCode = prettier.format((0, generator_1.default)(ast).code, prettierJSConfig);
474
+ if (formatCode.startsWith(';')) {
475
+ formatCode = formatCode.slice(1);
476
+ }
477
+ return formatCode;
478
+ }
479
+ catch (err) {
480
+ //
481
+ }
482
+ }
483
+ exports.astToCode = astToCode;
484
+ /**
485
+ * 解析项目名称
486
+ * @param projectPath 项目路径
487
+ * @returns { string } 项目名称
488
+ */
489
+ function parseProjectName(projectPath) {
490
+ if (!projectPath)
491
+ return '';
492
+ const projectPathInfo = path.parse(projectPath);
493
+ if (projectPathInfo.name === 'miniprogram') {
494
+ return path.parse(projectPathInfo.dir).name;
495
+ }
496
+ else {
497
+ return projectPathInfo.name;
498
+ }
499
+ }
500
+ exports.parseProjectName = parseProjectName;
501
+ /**
502
+ * 统计工程目录下文件数量
503
+ * @param projectPath
504
+ * @returns
505
+ */
506
+ function computeProjectFileNums(projectPath) {
507
+ let count = 0;
508
+ if (!projectPath)
509
+ return count;
510
+ const files = helper_1.fs.readdirSync(projectPath);
511
+ files.forEach((file) => {
512
+ if (file !== 'taroConvert') {
513
+ const filePath = path.join(projectPath, file);
514
+ const stats = helper_1.fs.statSync(filePath);
515
+ if (stats.isFile()) {
516
+ // 如果是文件,则增加计数
517
+ count++;
518
+ }
519
+ else if (stats.isDirectory()) {
520
+ // 如果是目录,则递归统计子目录中的文件
521
+ count += computeProjectFileNums(filePath);
522
+ }
523
+ }
524
+ });
525
+ return count;
526
+ }
527
+ exports.computeProjectFileNums = computeProjectFileNums;
528
+ /**
529
+ * 通过错误代码信息的 msgType、filePath 在 errMsgs 中寻找对应 errMsg
530
+ * @param msgType
531
+ * @param filePath
532
+ * @param errMsgList
533
+ */
534
+ function findErrMsg(msgType, filePath, errMsgList) {
535
+ return errMsgList.find((errMsg) => {
536
+ return errMsg.msgType === msgType && errMsg.filePath === filePath;
537
+ });
538
+ }
539
+ /**
540
+ * 判断 errCodeMsg 是否包含 code 代码
541
+ * @param errCodeMsg 错误信息代码
542
+ * @returns
543
+ */
544
+ function hasCode(errCodeMsg) {
545
+ var _a;
546
+ return !!((_a = errCodeMsg.codeBeforeConvert) === null || _a === void 0 ? void 0 : _a.code);
547
+ }
548
+ /**
549
+ * 将 errCodeMsgs 分类,生成 errMsgs 列表
550
+ * @param errCodeMsgs 错误代码信息
551
+ */
552
+ function paseGlobalErrMsgs(errCodeMsgs) {
553
+ const errMsgList = [];
554
+ errCodeMsgs.forEach((errCodeMsg) => {
555
+ var _a;
556
+ const msgType = errCodeMsg.msgType;
557
+ const filePath = (_a = errCodeMsg.codeBeforeConvert) === null || _a === void 0 ? void 0 : _a.filePath;
558
+ if (msgType && filePath) {
559
+ const errMsgs = findErrMsg(msgType, filePath, errMsgList);
560
+ if (errMsgs) {
561
+ if (hasCode(errCodeMsg)) {
562
+ errMsgs.errCodeList.push(errCodeMsg);
563
+ }
564
+ }
565
+ else {
566
+ errMsgList.push({
567
+ filePath,
568
+ msgType,
569
+ errCodeList: [errCodeMsg],
570
+ mesDescribe: hasCode(errCodeMsg) ? '' : errCodeMsg.describe,
571
+ });
572
+ }
573
+ }
574
+ });
575
+ return errMsgList;
576
+ }
577
+ exports.paseGlobalErrMsgs = paseGlobalErrMsgs;
578
+ /**
579
+ * 解析 catch 捕获的错误信息
580
+ * @param { IReportError } errMsg 捕获的错误对象
581
+ * @param { string } jsPath js文件路径
582
+ * @param { string } wxmlPath wxml文件路径
583
+ */
584
+ function parseError(errMsg, jsPath, wxmlPath) {
585
+ const filePathMap = new Map([
586
+ ['WXML_FILE', wxmlPath],
587
+ ['JS_FILE', jsPath],
588
+ ]);
589
+ if (errMsg.msgType) {
590
+ const currentFilePath = filePathMap.get(errMsg.filePath) || errMsg.filePath;
591
+ const errCodeMsg = {
592
+ msgType: errMsg.msgType,
593
+ describe: errMsg.message,
594
+ codeBeforeConvert: {
595
+ filePath: currentFilePath,
596
+ code: errMsg.code,
597
+ location: { start: errMsg.location },
598
+ },
599
+ };
600
+ global_1.globals.errCodeMsgs.push(errCodeMsg);
601
+ }
602
+ }
603
+ exports.parseError = parseError;
604
+ /**
605
+ * 存储错误信息,放到转换报告中
606
+ * @param msgType 错误类型
607
+ * @param describe 错误描述
608
+ * @param code 错误代码
609
+ * @param filePath 错误信息所在文件路径
610
+ * @returns
611
+ */
612
+ function createErrorCodeMsg(msgType, describe, code, filePath, position) {
613
+ const errorCodeMst = {
614
+ msgType,
615
+ describe,
616
+ codeBeforeConvert: {
617
+ filePath,
618
+ code,
619
+ location: { start: position || { col: 0, row: 0 } },
620
+ },
621
+ };
622
+ global_1.globals.errCodeMsgs.push(errorCodeMst);
623
+ }
624
+ exports.createErrorCodeMsg = createErrorCodeMsg;
625
+ /**
626
+ * 拓展原生 Error 属性
627
+ */
628
+ class IReportError extends Error {
629
+ constructor(message, msgType, filePath, code, location) {
630
+ super(message);
631
+ this.msgType = msgType || '';
632
+ this.filePath = filePath || '';
633
+ this.code = code || '';
634
+ this.location = location || { col: 0, row: 0 };
635
+ }
636
+ }
637
+ exports.IReportError = IReportError;
638
+ // eslint-disable-next-line camelcase
639
+ exports.DEFAULT_Component_SET = new Set([
640
+ 'View',
641
+ 'Icon',
642
+ 'Progress',
643
+ 'RichText',
644
+ 'Text',
645
+ 'Button',
646
+ 'Checkbox',
647
+ 'CheckboxGroup',
648
+ 'Form',
649
+ 'Input',
650
+ 'Label',
651
+ 'Picker',
652
+ 'PickerView',
653
+ 'PickerViewColumn',
654
+ 'Radio',
655
+ 'RadioGroup',
656
+ 'Slider',
657
+ 'Switch',
658
+ 'CoverImage',
659
+ 'Textarea',
660
+ 'CoverView',
661
+ 'MovableArea',
662
+ 'MovableView',
663
+ 'ScrollView',
664
+ 'Swiper',
665
+ 'SwiperItem',
666
+ 'Navigator',
667
+ 'Audio',
668
+ 'Camera',
669
+ 'Image',
670
+ 'LivePlayer',
671
+ 'Video',
672
+ 'Canvas',
673
+ 'Ad',
674
+ 'WebView',
675
+ 'Block',
676
+ 'Map',
677
+ 'Slot',
678
+ 'SlotView',
679
+ 'Editor',
680
+ 'MatchMedia',
681
+ 'FunctionalPageNavigator',
682
+ 'LivePusher',
683
+ 'OfficialAccount',
684
+ 'OpenData',
685
+ 'NavigationBar',
686
+ 'PageMeta',
687
+ 'VoipRoom',
688
+ 'AdCustom',
689
+ ]);
101
690
  //# sourceMappingURL=index.js.map