@appthen/cli 1.2.1 → 1.2.2

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.
Files changed (2) hide show
  1. package/dist/index.js +555 -261
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -329,49 +329,127 @@ var svgToBase64 = function (svgString) {
329
329
  var alphabet = '0123456789abcdefghijklmnopqrstuvwxyz';
330
330
  var nanoid = customAlphabet(alphabet, 6);
331
331
  /**
332
- * 清理文件名,移除无效字符
332
+ * 文件名管理器,确保全局唯一性
333
+ */
334
+ var FileNameManager = /** @class */ (function () {
335
+ function FileNameManager() {
336
+ this.usedNames = new Set();
337
+ this.usedIdentifiers = new Set();
338
+ this.nameCounters = new Map();
339
+ this.identifierCounters = new Map();
340
+ }
341
+ /**
342
+ * 生成唯一的文件名
343
+ * @param baseName 基础文件名
344
+ * @param extension 文件扩展名(包含点号,如 '.png')
345
+ * @returns 唯一的文件名
346
+ */
347
+ FileNameManager.prototype.generateUniqueFileName = function (baseName, extension) {
348
+ var cleanBaseName = this.sanitizeFileName(baseName);
349
+ var finalName = "".concat(cleanBaseName).concat(extension);
350
+ // 如果名称已存在,使用计数器生成唯一名称
351
+ if (this.usedNames.has(finalName.toLowerCase())) {
352
+ var counter = (this.nameCounters.get(cleanBaseName) || 0) + 1;
353
+ this.nameCounters.set(cleanBaseName, counter);
354
+ finalName = "".concat(cleanBaseName, "_").concat(counter).concat(extension);
355
+ // 如果计数器名称仍然存在,使用 nanoid 确保唯一性
356
+ while (this.usedNames.has(finalName.toLowerCase())) {
357
+ finalName = "".concat(cleanBaseName, "_").concat(counter, "_").concat(nanoid(4)).concat(extension);
358
+ }
359
+ }
360
+ this.usedNames.add(finalName.toLowerCase());
361
+ return finalName;
362
+ };
363
+ /**
364
+ * 生成唯一的 JavaScript 标识符名称
365
+ * @param baseName 基础标识符名
366
+ * @returns 唯一的标识符名称
367
+ */
368
+ FileNameManager.prototype.generateUniqueIdentifier = function (baseName) {
369
+ var cleanBaseName = this.sanitizeIdentifier(baseName);
370
+ var finalName = cleanBaseName;
371
+ // 如果标识符已存在,使用计数器生成唯一名称
372
+ if (this.usedIdentifiers.has(finalName.toLowerCase())) {
373
+ var counter = (this.identifierCounters.get(cleanBaseName) || 0) + 1;
374
+ this.identifierCounters.set(cleanBaseName, counter);
375
+ finalName = "".concat(cleanBaseName, "_").concat(counter);
376
+ // 如果计数器名称仍然存在,使用 nanoid 确保唯一性
377
+ while (this.usedIdentifiers.has(finalName.toLowerCase())) {
378
+ finalName = "".concat(cleanBaseName, "_").concat(counter, "_").concat(nanoid(4));
379
+ }
380
+ }
381
+ this.usedIdentifiers.add(finalName.toLowerCase());
382
+ return finalName;
383
+ };
384
+ /**
385
+ * 清理文件名,移除无效字符
386
+ * @param rawName 原始文件名
387
+ * @returns 清理后的文件名
388
+ */
389
+ FileNameManager.prototype.sanitizeFileName = function (rawName) {
390
+ if (!rawName)
391
+ return "file_".concat(nanoid(6));
392
+ var cleaned = rawName
393
+ // 移除或替换无效的文件名字符
394
+ .replace(/[<>:"/\\|?*]/g, '') // 移除文件系统不允许的字符
395
+ .replace(/\s+/g, '_') // 空格替换为下划线
396
+ .replace(/[^\w\-_.]/g, '') // 只保留字母、数字、下划线、连字符和点
397
+ .replace(/_{2,}/g, '_') // 多个连续下划线替换为单个
398
+ .replace(/^[_-]+|[_-]+$/g, '') // 移除开头和结尾的下划线和连字符
399
+ .substring(0, 30); // 限制长度
400
+ return cleaned || "file_".concat(nanoid(6));
401
+ };
402
+ /**
403
+ * 清理JavaScript标识符,确保符合变量命名规范
404
+ * @param rawName 原始标识符名
405
+ * @returns 清理后的标识符名
406
+ */
407
+ FileNameManager.prototype.sanitizeIdentifier = function (rawName) {
408
+ if (!rawName)
409
+ return "id_".concat(nanoid(6));
410
+ var cleaned = rawName
411
+ // 移除或替换无效的标识符字符
412
+ .replace(/[^\w]/g, '_') // 只保留字母、数字、下划线
413
+ .replace(/_{2,}/g, '_') // 多个连续下划线替换为单个
414
+ .replace(/^[_\d]+|[_]+$/g, '') // 移除开头的数字和下划线,结尾的下划线
415
+ .substring(0, 30); // 限制长度
416
+ return cleaned || "id_".concat(nanoid(6));
417
+ };
418
+ /**
419
+ * 重置管理器状态
420
+ */
421
+ FileNameManager.prototype.reset = function () {
422
+ this.usedNames.clear();
423
+ this.usedIdentifiers.clear();
424
+ this.nameCounters.clear();
425
+ this.identifierCounters.clear();
426
+ };
427
+ return FileNameManager;
428
+ }());
429
+ // 全局文件名管理器实例
430
+ var fileNameManager = new FileNameManager();
431
+ /**
432
+ * 清理文件名,移除无效字符(保持向后兼容)
333
433
  * @param rawName 原始文件名
334
434
  * @returns 清理后的文件名
335
435
  */
336
436
  function sanitizeFileName(rawName) {
337
- if (!rawName)
338
- return '';
339
- return rawName
340
- // 移除或替换无效的文件名字符
341
- .replace(/[<>:"/\\|?*]/g, '') // 移除文件系统不允许的字符
342
- .replace(/\s+/g, '_') // 空格替换为下划线
343
- .replace(/[^\w\-_.]/g, '') // 只保留字母、数字、下划线、连字符和点
344
- .replace(/_{2,}/g, '_') // 多个连续下划线替换为单个
345
- .replace(/^[_-]+|[_-]+$/g, '') // 移除开头和结尾的下划线和连字符
346
- .substring(0, 50) // 限制长度
347
- || "fallback_".concat(nanoid(6)); // 如果清理后为空,使用fallback名称
348
- }
349
- /**
350
- * 清理JavaScript标识符,确保符合变量命名规范
351
- * @param rawName 原始标识符名
352
- * @returns 清理后的标识符名
353
- */
354
- function sanitizeIdentifier(rawName) {
355
- if (!rawName)
356
- return "id_".concat(nanoid(6));
357
- return rawName
358
- // 移除或替换无效的标识符字符
359
- .replace(/[^\w]/g, '_') // 只保留字母、数字、下划线
360
- .replace(/_{2,}/g, '_') // 多个连续下划线替换为单个
361
- .replace(/^[_\d]+|[_]+$/g, '') // 移除开头的数字和下划线,结尾的下划线
362
- .substring(0, 30) // 限制长度
363
- || "id_".concat(nanoid(6)); // 如果清理后为空,使用fallback名称
437
+ return fileNameManager['sanitizeFileName'](rawName);
364
438
  }
365
439
  var transformJsx = function (file, solution, outputPath) {
366
440
  // const componentsDeps: string[] = [];
367
441
  var images = [];
368
442
  var svgs = [];
443
+ // 重置文件名管理器,确保每次转换都从干净状态开始
444
+ fileNameManager.reset();
369
445
  // 全局数据相关状态追踪
370
446
  var hasGlobalDataDecorator = false;
371
447
  var usesGlobalData = false;
372
448
  var classDeclarationPath = null;
373
449
  // 简单判断组件还是页面
374
- var componentType = file.path.includes('/src/components/') ? 'Component' : 'Page';
450
+ var componentType = file.path.includes('/src/components/')
451
+ ? 'Component'
452
+ : 'Page';
375
453
  var source = fs__namespace.readFileSync(file.path + '/' + file.fileName, 'utf-8');
376
454
  // 检测源码中是否使用了 this.globalData
377
455
  if (source.includes('this.globalData')) {
@@ -401,7 +479,8 @@ var transformJsx = function (file, solution, outputPath) {
401
479
  var decorators = path.node.decorators;
402
480
  if (decorators) {
403
481
  var hasGlobalDataDec = decorators.some(function (decorator) {
404
- if (t__namespace.isDecorator(decorator) && t__namespace.isIdentifier(decorator.expression)) {
482
+ if (t__namespace.isDecorator(decorator) &&
483
+ t__namespace.isIdentifier(decorator.expression)) {
405
484
  return decorator.expression.name === 'GlobalDataDecorator';
406
485
  }
407
486
  return false;
@@ -462,12 +541,18 @@ var transformJsx = function (file, solution, outputPath) {
462
541
  body.splice(lastImportIndex + 2, 0, importDeclaration);
463
542
  }
464
543
  if (componentType === 'Page' && solution === 'vite') {
465
- var importDeclaration = t__namespace.importDeclaration([t__namespace.importSpecifier(t__namespace.identifier('withRouter'), t__namespace.identifier('withRouter'))], t__namespace.stringLiteral('@/utils/router'));
544
+ var importDeclaration = t__namespace.importDeclaration([
545
+ t__namespace.importSpecifier(t__namespace.identifier('withRouter'), t__namespace.identifier('withRouter')),
546
+ ], t__namespace.stringLiteral('@/utils/router'));
466
547
  body.splice(lastImportIndex + (haveChildren ? 3 : 2), 0, importDeclaration);
467
548
  }
468
549
  if (usesGlobalData && !hasGlobalDataDecorator) {
469
- var globalDataImport = t__namespace.importDeclaration([t__namespace.importSpecifier(t__namespace.identifier('GlobalDataDecorator'), t__namespace.identifier('GlobalDataDecorator'))], t__namespace.stringLiteral('@/utils'));
470
- body.splice(lastImportIndex + (haveChildren ? 3 : 2) + (componentType === 'Page' && solution === 'vite' ? 1 : 0), 0, globalDataImport);
550
+ var globalDataImport = t__namespace.importDeclaration([
551
+ t__namespace.importSpecifier(t__namespace.identifier('GlobalDataDecorator'), t__namespace.identifier('GlobalDataDecorator')),
552
+ ], t__namespace.stringLiteral('@/utils'));
553
+ body.splice(lastImportIndex +
554
+ (haveChildren ? 3 : 2) +
555
+ (componentType === 'Page' && solution === 'vite' ? 1 : 0), 0, globalDataImport);
471
556
  }
472
557
  },
473
558
  ImportDeclaration: function (path) {
@@ -540,7 +625,7 @@ var transformJsx = function (file, solution, outputPath) {
540
625
  if (nodePath.parent.name.name === 'AtIcon' &&
541
626
  nodePath.node.name.name === 'svg' &&
542
627
  ((_a = nodePath.node) === null || _a === void 0 ? void 0 : _a.value.type) === 'StringLiteral') {
543
- var fileName_1 = '';
628
+ var fileName = '';
544
629
  var color = '';
545
630
  if (Array.isArray(nodePath.container)) {
546
631
  var valueNode = nodePath.container.find(function (item) { return item.name.name === 'value'; });
@@ -549,25 +634,18 @@ var transformJsx = function (file, solution, outputPath) {
549
634
  // @ts-ignore
550
635
  )) === null || _b === void 0 ? void 0 : _b.value) === null || _c === void 0 ? void 0 : _c.value) || '';
551
636
  if (valueNode) {
552
- fileName_1 = "svg_".concat(((_d = valueNode === null || valueNode === void 0 ? void 0 : valueNode.value) === null || _d === void 0 ? void 0 : _d.value) || nanoid(6));
553
- // const classNameArr = fileName.split('__');
554
- // fileName =
555
- // (classNameArr.length > 0
556
- // ? classNameArr[classNameArr.length - 1]
557
- // : fileName) + '.png';
637
+ var baseName = "svg_".concat(((_d = valueNode === null || valueNode === void 0 ? void 0 : valueNode.value) === null || _d === void 0 ? void 0 : _d.value) || nanoid(6));
638
+ fileName = fileNameManager.generateUniqueFileName(baseName, '');
558
639
  }
559
640
  }
560
- if (!fileName_1) {
561
- fileName_1 = "svg_".concat(nanoid(6));
562
- }
563
- // 文件名去重
564
- if (svgs.findIndex(function (item) { return item.fileName === fileName_1; }) > -1) {
565
- fileName_1 = "".concat(fileName_1, "_").concat(nanoid(6));
641
+ if (!fileName) {
642
+ var baseName = "svg_".concat(nanoid(6));
643
+ fileName = fileNameManager.generateUniqueFileName(baseName, '');
566
644
  }
567
645
  // 替换
568
646
  var node = nodePath.node;
569
647
  var svgStr = node.value.value;
570
- if (fileName_1 && svgStr) {
648
+ if (fileName && svgStr) {
571
649
  // 替换颜色
572
650
  if (svgStr && color) {
573
651
  svgStr = svgStr.replace(/currentColor/g, color);
@@ -577,54 +655,50 @@ var transformJsx = function (file, solution, outputPath) {
577
655
  svgStr = svgStr.replace(/width="100%"/g, '');
578
656
  svgStr = svgStr.replace(/height="100%"/g, '');
579
657
  }
580
- nodePath.replaceWith(t__namespace.jsxAttribute(t__namespace.jsxIdentifier('svg'), t__namespace.jsxExpressionContainer(t__namespace.memberExpression(t__namespace.identifier('ICONS'), t__namespace.stringLiteral(fileName_1), true))));
658
+ nodePath.replaceWith(t__namespace.jsxAttribute(t__namespace.jsxIdentifier('svg'), t__namespace.jsxExpressionContainer(t__namespace.memberExpression(t__namespace.identifier('ICONS'), t__namespace.stringLiteral(fileName), true))));
581
659
  svgs.push({
582
660
  svgStr: svgStr,
583
- fileName: fileName_1,
661
+ fileName: fileName,
584
662
  });
585
663
  }
586
664
  }
587
665
  if (nodePath.parent.name.name === 'Image' &&
588
666
  nodePath.node.name.name === 'src' &&
589
667
  ((_e = nodePath.node) === null || _e === void 0 ? void 0 : _e.value.type) === 'StringLiteral') {
590
- var fileName_2 = '';
668
+ var fileName = '';
591
669
  if (Array.isArray(nodePath.container)) {
592
670
  var classNameNode = nodePath.container.find(function (item) { return item.name.name === 'className'; });
593
671
  if (classNameNode) {
594
672
  var rawClassName = (_f = classNameNode === null || classNameNode === void 0 ? void 0 : classNameNode.value) === null || _f === void 0 ? void 0 : _f.value;
595
673
  if (rawClassName) {
596
674
  // 处理 Tailwind CSS 类名和其他复杂类名
597
- fileName_2 = sanitizeFileName(rawClassName);
598
- var classNameArr = fileName_2.split('__');
599
- fileName_2 =
600
- (classNameArr.length > 0
601
- ? classNameArr[classNameArr.length - 1]
602
- : fileName_2) + '.png';
675
+ var cleanedName = sanitizeFileName(rawClassName);
676
+ var classNameArr = cleanedName.split('__');
677
+ var baseName = classNameArr.length > 0
678
+ ? classNameArr[classNameArr.length - 1]
679
+ : cleanedName;
680
+ fileName = fileNameManager.generateUniqueFileName(baseName, '.png');
603
681
  }
604
682
  }
605
683
  }
606
684
  // 如果没有从className获取到有效文件名,使用随机名称
607
- if (!fileName_2) {
608
- fileName_2 = "image_".concat(nanoid(6), ".png");
609
- }
610
- // 文件名去重
611
- if (images.findIndex(function (item) { return item.fileName === fileName_2.toLowerCase(); }) >
612
- -1) {
613
- fileName_2 = "r".concat(images.length, "_").concat(fileName_2.toLowerCase());
685
+ if (!fileName) {
686
+ var baseName = "image_".concat(nanoid(6));
687
+ fileName = fileNameManager.generateUniqueFileName(baseName, '.png');
614
688
  }
615
689
  // 替换
616
690
  var node = nodePath.node;
617
691
  var imageSrc = node.value.value;
618
- var staticFileName = fileName_2.toLowerCase();
619
- var staticInentifierName = "static_".concat(sanitizeIdentifier(staticFileName.split('.')[0]));
620
- if (fileName_2 && imageSrc) {
692
+ var staticFileName = fileName.toLowerCase();
693
+ var staticInentifierName = fileNameManager.generateUniqueIdentifier("static_".concat(staticFileName.split('.')[0]));
694
+ if (fileName && imageSrc) {
621
695
  var func = t__namespace.jSXExpressionContainer(t__namespace.identifier(staticInentifierName));
622
696
  // const func = t.jSXExpressionContainer(
623
697
  // t.callExpression(t.identifier('require'), [
624
698
  // t.stringLiteral(`./images/${staticFileName}`),
625
699
  // ])
626
700
  // );
627
- nodePath.node.value = fileName_2 ? func : null;
701
+ nodePath.node.value = fileName ? func : null;
628
702
  images.push({
629
703
  url: imageSrc,
630
704
  fileName: staticFileName,
@@ -674,10 +748,12 @@ var transformJsx = function (file, solution, outputPath) {
674
748
  if (componentType === 'Page' && solution === 'vite') {
675
749
  var declaration = path.node.declaration;
676
750
  // @ts-ignore
677
- var withRouterCall = t__namespace.callExpression(t__namespace.identifier('withRouter'), [declaration]);
751
+ var withRouterCall = t__namespace.callExpression(t__namespace.identifier('withRouter'), [
752
+ declaration,
753
+ ]);
678
754
  path.node.declaration = withRouterCall;
679
755
  }
680
- }
756
+ },
681
757
  });
682
758
  // 处理装饰器自动添加
683
759
  if (usesGlobalData && !hasGlobalDataDecorator && classDeclarationPath) {
@@ -730,7 +806,7 @@ var transformJsx = function (file, solution, outputPath) {
730
806
  var base64String = svgToBase64(node.value);
731
807
  path.replaceWith(t__namespace.stringLiteral(base64String));
732
808
  }
733
- }
809
+ },
734
810
  });
735
811
  if (isHaveSvg_1)
736
812
  code = generate__default["default"](astTree).code;
@@ -19537,7 +19613,7 @@ var createDataSourceCode = function (dataSourceConfig) {
19537
19613
  },
19538
19614
  }), ";\n");
19539
19615
  }
19540
- var code = "\n// \u517C\u5BB9\u6027\uFF1A\u4FDD\u7559\u65E7\u7684\u5168\u5C40\u6570\u636E API\uFF0C\u4F46\u4F7F\u7528\u65B0\u7684\u5168\u5C40\u6570\u636E\u5B58\u50A8\nimport { globalDataStore } from './globalData';\n".concat(dataSourceConfigCode, "\n// \u517C\u5BB9\u65E7\u7248\u672C\u7684 API\nexport const setGlobalData = (key, value) => globalDataStore.set(key, value);\nexport const getGlobalData = (key) => globalDataStore.get(key);\nexport const reloadGlobalData = (key, options) => globalDataStore.load(key, options);\nexport const globalDataSourceMap = globalDataStore.dataSourceMap;\n ");
19616
+ var code = "\n// \u517C\u5BB9\u6027\uFF1A\u4FDD\u7559\u65E7\u7684\u5168\u5C40\u6570\u636E API\uFF0C\u4F46\u4F7F\u7528\u65B0\u7684\u5168\u5C40\u6570\u636E\u5B58\u50A8\nimport { globalDataStore } from './globalData';\n".concat(dataSourceConfigCode, "\n// \u517C\u5BB9\u65E7\u7248\u672C\u7684 API\nexport const setGlobalData = (key, value) => globalDataStore.set(key, value);\nexport const getGlobalData = (key) => globalDataStore.get(key);\nexport const reloadGlobalData = (key, options) => globalDataStore.loadDataSource(key, options);\nexport const globalDataSourceMap = globalDataStore.dataSourceMap;\n ");
19541
19617
  return code;
19542
19618
  };
19543
19619
  function wrapAsFunction$1(value, scope) {
@@ -19702,7 +19778,10 @@ var transformUtils = function (file, schema, project, solution, outputPath) {
19702
19778
  globalFunctionNames.add('getGlobalData');
19703
19779
  globalFunctionNames.add('reloadGlobalData');
19704
19780
  globalFunctionNames.add('globalDataSourceMap');
19705
- utilsFunctionNames.add('dataSource');
19781
+ globalFunctionNames.add('renderComponent');
19782
+ globalFunctionNames.add('showComponentModal');
19783
+ globalFunctionNames.add('dataSource');
19784
+ globalFunctionNames.add('_');
19706
19785
  body.splice(1, 0, t__namespace.importDeclaration(Array.from(utilsFunctionNames)
19707
19786
  .filter(function (name) {
19708
19787
  return !globalFunctionNames.has(name) &&
@@ -19711,9 +19790,7 @@ var transformUtils = function (file, schema, project, solution, outputPath) {
19711
19790
  })
19712
19791
  .map(function (name) {
19713
19792
  return t__namespace.importSpecifier(t__namespace.identifier(name), t__namespace.identifier(name));
19714
- }), t__namespace.stringLiteral(solution === 'vite'
19715
- ? '@appthen/utils'
19716
- : 'cross-ui/utils')));
19793
+ }), t__namespace.stringLiteral(solution === 'vite' ? '@appthen/utils' : 'cross-ui/utils')));
19717
19794
  body.splice(2, 0, t__namespace.importDeclaration(['requestHandle'].map(function (name) {
19718
19795
  return t__namespace.importSpecifier(t__namespace.identifier(name), t__namespace.identifier(name));
19719
19796
  }), t__namespace.stringLiteral('./dataSource')));
@@ -19739,7 +19816,9 @@ var transformUtils = function (file, schema, project, solution, outputPath) {
19739
19816
  // 创建 VariableDeclarator 节点,表示 const Fuck = constants.Fuck
19740
19817
  var variableDeclarator = t__namespace.variableDeclarator(t__namespace.identifier(util.name), memberExpression);
19741
19818
  // 创建 VariableDeclaration 节点,表示 const Fuck 的声明
19742
- var variableDeclaration = t__namespace.variableDeclaration('const', [variableDeclarator]);
19819
+ var variableDeclaration = t__namespace.variableDeclaration('const', [
19820
+ variableDeclarator,
19821
+ ]);
19743
19822
  // 创建 ExportNamedDeclaration 节点,表示 export const Fuck
19744
19823
  var exportNamedDeclaration = t__namespace.exportNamedDeclaration(variableDeclaration);
19745
19824
  body.splice(4 + index, 0, exportNamedDeclaration);
@@ -19794,7 +19873,8 @@ var transformUtils = function (file, schema, project, solution, outputPath) {
19794
19873
  if (extendsCodes.length > 0) {
19795
19874
  code = extendsCodes.join('\n') + '\n' + code;
19796
19875
  }
19797
- code = code + "\n\nexport {\n addPortal,\n removePortal,\n registerPartalComponent,\n showComponentModal,\n renderComponentPortal,\n renderComponent,\n} from '@appthen/react';\n";
19876
+ code =
19877
+ "import {\n addPortal,\n removePortal,\n registerPartalComponent,\n showComponentModal,\n renderComponentPortal,\n renderComponent\n} from '@appthen/react';\n\nexport {\n addPortal,\n removePortal,\n registerPartalComponent,\n showComponentModal,\n renderComponentPortal,\n renderComponent,\n} from '@appthen/react';\n" + code;
19798
19878
  fs__namespace.writeFileSync(file.path + '/' + file.fileName, code);
19799
19879
  return { code: code };
19800
19880
  };
@@ -32909,30 +32989,21 @@ var createRouter = function (project) {
32909
32989
  if (!router || ((_a = router.routes) === null || _a === void 0 ? void 0 : _a.length) === 0) {
32910
32990
  return;
32911
32991
  }
32912
- // const router = {
32913
- // routes: [
32914
- // {
32915
- // path: '/',
32916
- // page: 'antdBackgroundManagementSystem',
32917
- // children: [
32918
- // {
32919
- // path: '/dashboard',
32920
- // page: 'dashboard',
32921
- // },
32922
- // ],
32923
- // },
32924
- // {
32925
- // path: '/admin',
32926
- // redirect: '/admin/fuck',
32927
- // },
32928
- // {
32929
- // path: '/antdBackgroundManagementSystem',
32930
- // page: 'antdBackgroundManagementSystem',
32931
- // },
32932
- // ],
32933
- // };
32992
+ console.log('router: ', router.routes[0]);
32993
+ console.log('🔍 原始路由数据:', JSON.stringify(router.routes, null, 2));
32994
+ // 保存调试数据到文件
32995
+ var fs = require('fs');
32996
+ try {
32997
+ fs.writeFileSync('./router-debug.json', JSON.stringify({
32998
+ routes: router.routes,
32999
+ timestamp: new Date().toISOString(),
33000
+ }, null, 2));
33001
+ console.log('📝 路由调试数据已保存到 router-debug.json');
33002
+ }
33003
+ catch (error) {
33004
+ console.log('⚠️ 无法保存调试数据:', error.message);
33005
+ }
32934
33006
  var allPages = [];
32935
- // const routeElements: any[] = [];
32936
33007
  // 遍历router.routes,生成路由
32937
33008
  var checkRoutes = function (routes) {
32938
33009
  routes.forEach(function (route) {
@@ -32945,7 +33016,8 @@ var createRouter = function (project) {
32945
33016
  });
32946
33017
  };
32947
33018
  checkRoutes(router.routes);
32948
- var routeElements = router.routes.map(function (route) { return createNestedRoutes(route); });
33019
+ // 处理路由结构,正确处理布局和嵌套路由
33020
+ var routeElements = processRoutesWithLayout(router.routes);
32949
33021
  var fileLazyImports = allPages.map(function (_) {
32950
33022
  return createLazyImport(_, "./pages/".concat(_));
32951
33023
  });
@@ -32954,6 +33026,68 @@ var createRouter = function (project) {
32954
33026
  routeElements: routeElements,
32955
33027
  };
32956
33028
  };
33029
+ // 处理路由结构,正确处理布局和嵌套路由
33030
+ function processRoutesWithLayout(routes) {
33031
+ var e_1, _a, e_2, _b;
33032
+ var result = [];
33033
+ console.log('🔧 开始处理路由结构...');
33034
+ try {
33035
+ for (var routes_1 = __values(routes), routes_1_1 = routes_1.next(); !routes_1_1.done; routes_1_1 = routes_1.next()) {
33036
+ var route = routes_1_1.value;
33037
+ console.log("\uD83D\uDCCD \u5904\u7406\u8DEF\u7531: ".concat(route.path, ", page: ").concat(route.page));
33038
+ // 检查是否为独立路由
33039
+ if (route.noLayout) {
33040
+ console.log(" \uD83D\uDEAA \u72EC\u7ACB\u8DEF\u7531");
33041
+ var routeElement = createNestedRoutesWithLayout(route);
33042
+ result.push(routeElement);
33043
+ continue;
33044
+ }
33045
+ // 检查是否为布局组件(有 children)
33046
+ var isLayoutRoute = route.children && route.children.length > 0;
33047
+ if (isLayoutRoute) {
33048
+ console.log(" \uD83C\uDFE0 \u8BC6\u522B\u4E3A\u5E03\u5C40\u8DEF\u7531\uFF0C\u5B50\u8DEF\u7531\u6570\u91CF: ".concat(route.children.length));
33049
+ // 创建布局路由,包含子路由
33050
+ var layoutChildren = route.children
33051
+ .filter(function (child) { return !child.noLayout; }) // 过滤掉 noLayout 的子路由
33052
+ .map(function (child) { return createNestedRoutesWithLayout(child); });
33053
+ var layoutElement = createNestedRoutesWithLayout(route, layoutChildren);
33054
+ result.push(layoutElement);
33055
+ // 处理 noLayout 的子路由,作为独立路由
33056
+ var independentChildren = route.children.filter(function (child) { return child.noLayout; });
33057
+ try {
33058
+ for (var independentChildren_1 = (e_2 = void 0, __values(independentChildren)), independentChildren_1_1 = independentChildren_1.next(); !independentChildren_1_1.done; independentChildren_1_1 = independentChildren_1.next()) {
33059
+ var independentChild = independentChildren_1_1.value;
33060
+ console.log(" \uD83D\uDEAA \u5904\u7406\u72EC\u7ACB\u5B50\u8DEF\u7531: ".concat(independentChild.path));
33061
+ var childElement = createNestedRoutesWithLayout(independentChild);
33062
+ result.push(childElement);
33063
+ }
33064
+ }
33065
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
33066
+ finally {
33067
+ try {
33068
+ if (independentChildren_1_1 && !independentChildren_1_1.done && (_b = independentChildren_1.return)) _b.call(independentChildren_1);
33069
+ }
33070
+ finally { if (e_2) throw e_2.error; }
33071
+ }
33072
+ }
33073
+ else {
33074
+ // 普通路由
33075
+ console.log(" \uD83D\uDCC4 \u5904\u7406\u666E\u901A\u8DEF\u7531");
33076
+ var routeElement = createNestedRoutesWithLayout(route);
33077
+ result.push(routeElement);
33078
+ }
33079
+ }
33080
+ }
33081
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
33082
+ finally {
33083
+ try {
33084
+ if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
33085
+ }
33086
+ finally { if (e_1) throw e_1.error; }
33087
+ }
33088
+ console.log("\u2705 \u8DEF\u7531\u5904\u7406\u5B8C\u6210\uFF0C\u751F\u6210 ".concat(result.length, " \u4E2A\u8DEF\u7531\u5143\u7D20"));
33089
+ return result;
33090
+ }
32957
33091
  // Create a component with lazy loading
32958
33092
  function createLazyImport(varName, source) {
32959
33093
  var _varName = varName.slice(0, 1).toUpperCase() + varName.slice(1);
@@ -32965,17 +33099,18 @@ function createLazyImport(varName, source) {
32965
33099
  }
32966
33100
  // const indexLazyImport = createLazyImport('index', './pages/index');
32967
33101
  // 助手函数,用于创建<Route> JSX元素
32968
- function createRoute(path, componentName, exact, children) {
33102
+ function createRoute(path, componentName, exact, children, isLayout) {
32969
33103
  if (exact === void 0) { exact = false; }
32970
33104
  if (children === void 0) { children = null; }
33105
+ if (isLayout === void 0) { isLayout = false; }
32971
33106
  var props = [
32972
33107
  t__namespace.jsxAttribute(t__namespace.jsxIdentifier('path'), t__namespace.stringLiteral(path)),
32973
33108
  ];
32974
33109
  if (exact) {
32975
33110
  props.push(t__namespace.jsxAttribute(t__namespace.jsxIdentifier('exact')));
32976
33111
  }
32977
- var openingElement = t__namespace.jsxOpeningElement(t__namespace.jsxIdentifier('Route'), props, !children);
32978
- if (!componentName && !children) {
33112
+ var openingElement = t__namespace.jsxOpeningElement(t__namespace.jsxIdentifier('Route'), props, !children && !isLayout);
33113
+ if (!componentName && !children && !isLayout) {
32979
33114
  return t__namespace.jsxElement(openingElement, t__namespace.jsxClosingElement(t__namespace.jsxIdentifier('Route')), [], false);
32980
33115
  }
32981
33116
  // 添加component属性如果存在
@@ -33001,21 +33136,61 @@ function codeToAST(code) {
33001
33136
  return null;
33002
33137
  }
33003
33138
  }
33004
- // 递归函数,为每个路由创建JSX节点,包括嵌套的子路由
33005
- function createNestedRoutes(route) {
33006
- var children = [];
33007
- if (route.children) {
33008
- children = route.children.map(function (childRoute) {
33009
- return createNestedRoutes(childRoute);
33010
- });
33011
- }
33139
+ // 新的路由创建函数,处理实际的数据格式
33140
+ function createNestedRoutesWithLayout(route, children) {
33141
+ console.log(" \uD83D\uDD27 \u521B\u5EFA\u8DEF\u7531\u5143\u7D20: ".concat(route.path, ", page: ").concat(route.page));
33142
+ // 处理重定向路由
33012
33143
  if (route.redirect) {
33144
+ console.log(" \u21AA\uFE0F \u91CD\u5B9A\u5411\u8DEF\u7531: ".concat(route.path, " -> ").concat(route.redirect));
33013
33145
  return codeToAST("<Route path=\"".concat(route.path, "\" element={<Navigate to=\"").concat(route.redirect, "\"/>}></Route>"));
33014
- // return createRedirect(route.redirect);
33015
33146
  }
33016
- return createRoute(route.path, route.page, route.exact, children);
33147
+ // 如果传入了 children,说明这是一个布局路由
33148
+ if (children && children.length > 0) {
33149
+ console.log(" \uD83C\uDFE0 \u5E03\u5C40\u8DEF\u7531\uFF0C\u5305\u542B ".concat(children.length, " \u4E2A\u5B50\u8DEF\u7531"));
33150
+ return createRoute(route.path, route.page || '', route.exact, children, true // isLayout = true
33151
+ );
33152
+ }
33153
+ // 普通页面路由
33154
+ console.log(" \uD83D\uDCC4 \u666E\u901A\u9875\u9762\u8DEF\u7531");
33155
+ return createRoute(route.path, route.page || '', route.exact, null, false);
33017
33156
  }
33018
33157
 
33158
+ /**
33159
+ * 创建详细的错误信息,包含代码片段和位置信息
33160
+ */
33161
+ function createDetailedError(error, context) {
33162
+ var operation = context.operation, _a = context.filePath, filePath = _a === void 0 ? './src/App.jsx' : _a, code = context.code, suggestion = context.suggestion;
33163
+ var errorMessage = "".concat(operation, "\u5931\u8D25: ").concat(error.message);
33164
+ if (error.loc) {
33165
+ errorMessage += " (\u7B2C".concat(error.loc.line, "\u884C\u7B2C").concat(error.loc.column, "\u5217)");
33166
+ }
33167
+ console.error("\u274C ".concat(operation, "\u5931\u8D25:"), {
33168
+ filePath: filePath,
33169
+ error: error.message,
33170
+ type: error.name || 'Error',
33171
+ position: error.loc
33172
+ ? "\u7B2C".concat(error.loc.line, "\u884C\u7B2C").concat(error.loc.column, "\u5217")
33173
+ : '未知位置',
33174
+ snippet: error.loc && code
33175
+ ? (function () {
33176
+ var lines = code.split('\n');
33177
+ var errorLine = error.loc.line - 1;
33178
+ var start = Math.max(0, errorLine - 2);
33179
+ var end = Math.min(lines.length, errorLine + 3);
33180
+ return lines
33181
+ .slice(start, end)
33182
+ .map(function (line, index) {
33183
+ var lineNum = start + index + 1;
33184
+ var marker = lineNum === error.loc.line ? '>>> ' : ' ';
33185
+ return "".concat(marker).concat(lineNum.toString().padStart(3), ": ").concat(line);
33186
+ })
33187
+ .join('\n');
33188
+ })()
33189
+ : '无法获取代码片段',
33190
+ suggestion: suggestion || '请检查代码语法和结构是否正确',
33191
+ });
33192
+ return new Error(errorMessage);
33193
+ }
33019
33194
  function manageImports(ast, imports) {
33020
33195
  // 记录需要处理的导入名称和包
33021
33196
  var targetImports = new Map(imports.map(function (imp) { return [imp.name, imp]; }));
@@ -33049,14 +33224,16 @@ function manageImports(ast, imports) {
33049
33224
  }
33050
33225
  // 移除原有的目标包导入声明
33051
33226
  path.remove();
33052
- }
33227
+ },
33053
33228
  });
33054
33229
  // 添加新的导入到对应的包
33055
33230
  imports.forEach(function (imp) {
33056
33231
  if (!packageImports.has(imp.from)) {
33057
33232
  packageImports.set(imp.from, new Set());
33058
33233
  }
33059
- packageImports.get(imp.from).add(t__namespace.importSpecifier(t__namespace.identifier(imp.as || imp.name), t__namespace.identifier(imp.name)));
33234
+ packageImports
33235
+ .get(imp.from)
33236
+ .add(t__namespace.importSpecifier(t__namespace.identifier(imp.as || imp.name), t__namespace.identifier(imp.name)));
33060
33237
  });
33061
33238
  // 第二遍:添加新的导入
33062
33239
  traverse__default["default"](ast, {
@@ -33066,21 +33243,49 @@ function manageImports(ast, imports) {
33066
33243
  var _b = __read(_a, 2), source = _b[0], specifiers = _b[1];
33067
33244
  if (specifiers.size > 0) {
33068
33245
  // 找到第一个导入声明
33069
- var firstImport = path.node.body.find(function (node) { return t__namespace.isImportDeclaration(node); });
33070
- var insertIndex = firstImport ? path.node.body.indexOf(firstImport) : 0;
33246
+ var firstImport = path.node.body.find(function (node) {
33247
+ return t__namespace.isImportDeclaration(node);
33248
+ });
33249
+ var insertIndex = firstImport
33250
+ ? path.node.body.indexOf(firstImport)
33251
+ : 0;
33071
33252
  path.node.body.splice(insertIndex, 0, t__namespace.importDeclaration(Array.from(specifiers), t__namespace.stringLiteral(source)));
33072
33253
  }
33073
33254
  });
33074
- }
33255
+ },
33075
33256
  });
33076
33257
  }
33077
33258
  var createAppFile = function (project, solution, outputPath) {
33078
- var _a, _b, _c, _d;
33079
- var appFile = fs__namespace.readFileSync('./src/App.jsx', 'utf8');
33080
- var astTree = parser__namespace.parse("".concat(appFile), {
33081
- sourceType: 'module',
33082
- plugins: ['jsx', 'typescript', 'decorators-legacy'],
33083
- });
33259
+ var _a, _b, _c, _d, _e;
33260
+ var appFile;
33261
+ var astTree;
33262
+ try {
33263
+ appFile = fs__namespace.readFileSync('./src/App.jsx', 'utf8');
33264
+ }
33265
+ catch (error) {
33266
+ console.error('❌ 读取 App.jsx 文件失败:', {
33267
+ filePath: './src/App.jsx',
33268
+ error: error.message,
33269
+ suggestion: '请确保 src/App.jsx 文件存在且可读',
33270
+ });
33271
+ throw new Error("\u65E0\u6CD5\u8BFB\u53D6 App.jsx \u6587\u4EF6: ".concat(error.message));
33272
+ }
33273
+ try {
33274
+ astTree = parser__namespace.parse("".concat(appFile), {
33275
+ sourceType: 'module',
33276
+ plugins: ['jsx', 'typescript', 'decorators-legacy'],
33277
+ });
33278
+ }
33279
+ catch (error) {
33280
+ throw createDetailedError(error, {
33281
+ operation: 'App.jsx 文件解析',
33282
+ code: appFile,
33283
+ suggestion: '请检查 App.jsx 文件的语法是否正确,特别注意:\n' +
33284
+ '- 是否有未闭合的标签或括号\n' +
33285
+ '- 是否有未完成的变量声明(const/let/var)\n' +
33286
+ '- 是否有语法错误的 JSX 表达式',
33287
+ });
33288
+ }
33084
33289
  astTree.program.body = astTree.program.body.filter(function (item) {
33085
33290
  var _a, _b, _c, _d;
33086
33291
  var isPageFile = item.type === 'VariableDeclaration' &&
@@ -33089,110 +33294,167 @@ var createAppFile = function (project, solution, outputPath) {
33089
33294
  return !isPageFile;
33090
33295
  });
33091
33296
  // 添加路由
33092
- var router = createRouter(project);
33093
- if (router) {
33094
- var fileLazyImports_1 = router.fileLazyImports, routeElements_1 = router.routeElements;
33095
- traverse__default["default"](astTree, {
33096
- Program: function (nodePath) {
33097
- var body = nodePath.node.body;
33098
- var componentIndex = body.findIndex(function (item) { return item.type === 'ExportDefaultDeclaration'; });
33099
- body.splice.apply(body, __spreadArray([componentIndex, 0], __read(fileLazyImports_1), false));
33100
- },
33101
- JSXElement: function (nodePath) {
33102
- var _a, _b;
33103
- var node = nodePath.node;
33104
- // @ts-ignore
33105
- if (((_b = (_a = node.openingElement) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.name) === 'Routes') {
33106
- node.children = routeElements_1;
33107
- }
33108
- },
33297
+ try {
33298
+ var router = createRouter(project);
33299
+ if (router) {
33300
+ var fileLazyImports_1 = router.fileLazyImports, routeElements_1 = router.routeElements;
33301
+ traverse__default["default"](astTree, {
33302
+ Program: function (nodePath) {
33303
+ var body = nodePath.node.body;
33304
+ var componentIndex = body.findIndex(function (item) { return item.type === 'ExportDefaultDeclaration'; });
33305
+ body.splice.apply(body, __spreadArray([componentIndex, 0], __read(fileLazyImports_1), false));
33306
+ },
33307
+ JSXElement: function (nodePath) {
33308
+ var _a, _b;
33309
+ var node = nodePath.node;
33310
+ // @ts-ignore
33311
+ if (((_b = (_a = node.openingElement) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.name) === 'Routes') {
33312
+ node.children = routeElements_1;
33313
+ }
33314
+ },
33315
+ });
33316
+ console.log('✅ 路由配置已添加');
33317
+ }
33318
+ }
33319
+ catch (error) {
33320
+ console.error('❌ 路由处理失败:', {
33321
+ error: error.message,
33322
+ type: error.name || 'RouterError',
33323
+ suggestion: '请检查项目配置中的路由信息是否正确',
33109
33324
  });
33325
+ throw new Error("\u8DEF\u7531\u5904\u7406\u5931\u8D25: ".concat(error.message));
33110
33326
  }
33111
33327
  // 增加全局配置
33112
33328
  var schema = project.schema;
33113
33329
  var config = schema.config;
33114
33330
  if ((_a = config === null || config === void 0 ? void 0 : config.layout) === null || _a === void 0 ? void 0 : _a.componentName) {
33115
- var _e = config.layout, componentName = _e.componentName, props_1 = _e.props;
33116
- var code_1 = "\n <".concat(componentName, "\n ").concat(Object.keys(props_1 || {})
33117
- .map(function (k) {
33118
- var valueStr = '';
33119
- if (typeof props_1[k] === 'string') {
33120
- valueStr = "'".concat(props_1[k], "'");
33121
- }
33122
- else if (typeof props_1[k] === 'number') {
33123
- valueStr = "".concat(props_1[k]);
33124
- }
33125
- else if (typeof props_1[k] === 'object') {
33126
- valueStr = "{".concat(JSON.stringify(props_1[k]), "}");
33127
- }
33128
- return "".concat(k, "=").concat(valueStr);
33129
- })
33130
- .join('\n'), "\n ><AntdApp></AntdApp></").concat(componentName, ">\n ");
33131
- var layoutAstNode = codeToAST(code_1);
33132
- var elNode_1 = layoutAstNode.expression;
33133
- /**
33134
- * 找到 AntdApp 下的 HashRouter 节点
33135
- */
33136
- var routerNode_1;
33137
- traverse__default["default"](astTree, {
33138
- JSXElement: function (nodePath) {
33139
- var _a, _b;
33140
- var node = nodePath.node;
33141
- // @ts-ignore
33142
- if (((_b = (_a = node.openingElement) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.name) === 'HashRouter') {
33143
- routerNode_1 = nodePath;
33331
+ try {
33332
+ var _f = config.layout, componentName = _f.componentName, props_1 = _f.props;
33333
+ var code = "\n <".concat(componentName, "\n ").concat(Object.keys(props_1 || {})
33334
+ .map(function (k) {
33335
+ var valueStr = '';
33336
+ if (typeof props_1[k] === 'string') {
33337
+ valueStr = "'".concat(props_1[k], "'");
33144
33338
  }
33145
- },
33146
- });
33147
- var once_1 = false;
33148
- traverse__default["default"](astTree, {
33149
- JSXElement: function (nodePath) {
33150
- var _a, _b, _c, _d;
33151
- var node = nodePath.node;
33152
- // @ts-ignore
33153
- if (((_b = (_a = node.openingElement) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.name) === 'ConfigProvider' && !once_1) {
33154
- if (appFile.includes('<AntdApp>') && routerNode_1) {
33155
- // @ts-ignore
33156
- elNode_1.children[0].children = routerNode_1.parent.children;
33339
+ else if (typeof props_1[k] === 'number') {
33340
+ valueStr = "".concat(props_1[k]);
33341
+ }
33342
+ else if (typeof props_1[k] === 'object') {
33343
+ valueStr = "{".concat(JSON.stringify(props_1[k]), "}");
33344
+ }
33345
+ return "".concat(k, "=").concat(valueStr);
33346
+ })
33347
+ .join('\n'), "\n ><AntdApp></AntdApp></").concat(componentName, ">\n ");
33348
+ var layoutAstNode = codeToAST(code);
33349
+ var elNode_1 = layoutAstNode.expression;
33350
+ /**
33351
+ * 找到 AntdApp 下的 HashRouter 节点
33352
+ */
33353
+ var routerNode_1;
33354
+ traverse__default["default"](astTree, {
33355
+ JSXElement: function (nodePath) {
33356
+ var _a, _b;
33357
+ var node = nodePath.node;
33358
+ // @ts-ignore
33359
+ if (((_b = (_a = node.openingElement) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.name) === 'HashRouter') {
33360
+ routerNode_1 = nodePath;
33157
33361
  }
33158
- else {
33159
- // @ts-ignore
33160
- elNode_1.children[0].children = node.children;
33362
+ },
33363
+ });
33364
+ var once_1 = false;
33365
+ traverse__default["default"](astTree, {
33366
+ JSXElement: function (nodePath) {
33367
+ var _a, _b, _c, _d;
33368
+ var node = nodePath.node;
33369
+ // @ts-ignore
33370
+ if (((_b = (_a = node.openingElement) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.name) === 'ConfigProvider' && !once_1) {
33371
+ if (appFile.includes('<AntdApp>') && routerNode_1) {
33372
+ // @ts-ignore
33373
+ elNode_1.children[0].children = routerNode_1.parent.children;
33374
+ }
33375
+ else {
33376
+ // @ts-ignore
33377
+ elNode_1.children[0].children = node.children;
33378
+ }
33379
+ nodePath.replaceWith(elNode_1);
33380
+ once_1 = true;
33161
33381
  }
33162
- nodePath.replaceWith(elNode_1);
33163
- once_1 = true;
33164
- }
33165
- // @ts-ignore
33166
- if (((_d = (_c = node.openingElement) === null || _c === void 0 ? void 0 : _c.name) === null || _d === void 0 ? void 0 : _d.name) === 'HashRouter' && !once_1) {
33167
33382
  // @ts-ignore
33168
- elNode_1.children[0].children = [node];
33169
- nodePath.replaceWith(elNode_1);
33170
- once_1 = true;
33171
- }
33172
- },
33173
- });
33383
+ if (((_d = (_c = node.openingElement) === null || _c === void 0 ? void 0 : _c.name) === null || _d === void 0 ? void 0 : _d.name) === 'HashRouter' && !once_1) {
33384
+ // @ts-ignore
33385
+ elNode_1.children[0].children = [node];
33386
+ nodePath.replaceWith(elNode_1);
33387
+ once_1 = true;
33388
+ }
33389
+ },
33390
+ });
33391
+ console.log('✅ 布局配置已添加');
33392
+ }
33393
+ catch (error) {
33394
+ console.error('❌ 布局配置处理失败:', {
33395
+ error: error.message,
33396
+ type: error.name || 'LayoutError',
33397
+ componentName: (_b = config === null || config === void 0 ? void 0 : config.layout) === null || _b === void 0 ? void 0 : _b.componentName,
33398
+ suggestion: '请检查布局组件配置是否正确,包括组件名称和属性',
33399
+ });
33400
+ throw new Error("\u5E03\u5C40\u914D\u7F6E\u5904\u7406\u5931\u8D25: ".concat(error.message));
33401
+ }
33174
33402
  }
33175
33403
  // 处理导入语句
33176
- if ((_d = (_c = (_b = project.schema) === null || _b === void 0 ? void 0 : _b.config) === null || _c === void 0 ? void 0 : _c.layout) === null || _d === void 0 ? void 0 : _d.componentName) {
33177
- var requiredImports = [
33178
- {
33179
- name: 'App',
33180
- as: 'AntdApp',
33181
- from: 'antd',
33182
- priority: 2,
33183
- protected: true // App 必须从 antd 导入
33184
- },
33185
- {
33186
- name: 'ConfigProvider',
33187
- from: '@appthen/antd',
33188
- priority: 1
33189
- }
33190
- ];
33191
- manageImports(astTree, requiredImports);
33404
+ if ((_e = (_d = (_c = project.schema) === null || _c === void 0 ? void 0 : _c.config) === null || _d === void 0 ? void 0 : _d.layout) === null || _e === void 0 ? void 0 : _e.componentName) {
33405
+ try {
33406
+ var requiredImports = [
33407
+ {
33408
+ name: 'App',
33409
+ as: 'AntdApp',
33410
+ from: 'antd',
33411
+ priority: 2,
33412
+ protected: true, // App 必须从 antd 导入
33413
+ },
33414
+ {
33415
+ name: 'ConfigProvider',
33416
+ from: '@appthen/antd',
33417
+ priority: 1,
33418
+ },
33419
+ ];
33420
+ manageImports(astTree, requiredImports);
33421
+ console.log('✅ 导入语句已处理');
33422
+ }
33423
+ catch (error) {
33424
+ console.error('❌ 导入语句处理失败:', {
33425
+ error: error.message,
33426
+ type: error.name || 'ImportError',
33427
+ suggestion: '请检查导入配置是否正确,确保相关包已安装',
33428
+ });
33429
+ throw new Error("\u5BFC\u5165\u8BED\u53E5\u5904\u7406\u5931\u8D25: ".concat(error.message));
33430
+ }
33431
+ }
33432
+ var generatedCode;
33433
+ try {
33434
+ var result = generate__default["default"](astTree);
33435
+ generatedCode = result.code;
33436
+ }
33437
+ catch (error) {
33438
+ console.error('❌ 代码生成失败:', {
33439
+ error: error.message,
33440
+ type: error.name || 'GenerateError',
33441
+ suggestion: '请检查 AST 结构是否正确,可能是在处理过程中产生了无效的 AST 节点',
33442
+ });
33443
+ throw new Error("\u4EE3\u7801\u751F\u6210\u5931\u8D25: ".concat(error.message));
33444
+ }
33445
+ try {
33446
+ // 删除之前的字符串处理逻辑
33447
+ fs__namespace.writeFileSync('./src/App.jsx', generatedCode, 'utf8');
33448
+ console.log('✅ App.jsx 文件已成功更新');
33449
+ }
33450
+ catch (error) {
33451
+ console.error('❌ 写入 App.jsx 文件失败:', {
33452
+ filePath: './src/App.jsx',
33453
+ error: error.message,
33454
+ suggestion: '请确保有写入权限,且磁盘空间充足',
33455
+ });
33456
+ throw new Error("\u5199\u5165 App.jsx \u6587\u4EF6\u5931\u8D25: ".concat(error.message));
33192
33457
  }
33193
- var code = generate__default["default"](astTree).code;
33194
- // 删除之前的字符串处理逻辑
33195
- fs__namespace.writeFileSync('./src/App.jsx', code, 'utf8');
33196
33458
  };
33197
33459
 
33198
33460
  var writePackageJSON = function (packageJSON) {
@@ -36715,11 +36977,11 @@ var lastTimeKey$1 = '$__cacheTime';
36715
36977
  * @returns {Promise<number>} 错误码
36716
36978
  */
36717
36979
  function run(args, options) {
36718
- var _a, _b, _c, _d;
36980
+ var _a, _b, _c, _d, _e, _f;
36719
36981
  return __awaiter(this, void 0, void 0, function () {
36720
- var cacheDirPath, keyCacheDirPath, currentLastTimeKey, cacheTime, afterTime, result, schema, project, documents, componentDocs, packageJSON, projectDocuments, projectDocumentNames_1, subPageDocumentNames_1, clientType, isWeb, solution, outputPath_1, builder, envInfoItem, generatedSourceCodes, publisher, subPageRoot_1, subPagePath, subPagePathIsExist, getPageUrl_1, transformFilePath, existFiles, existSubFiles, _e, files, syncMap, _loop_1, i, indexPage_1, indexPageUrl_1, globalStyle, globalStyleWithoutFirstLine, globalStyle, globalStyleWithoutFirstLine, appContent, appContentWithImport, portalImportCode, haveUpdate, installCmd, e_1;
36721
- return __generator(this, function (_f) {
36722
- switch (_f.label) {
36982
+ var cacheDirPath, keyCacheDirPath, currentLastTimeKey, cacheTime, afterTime, result, schema, project, documents, componentDocs, packageJSON, projectDocuments, projectDocumentNames_1, subPageDocumentNames_1, clientType, isWeb, solution, outputPath_1, builder, envInfoItem, schemaStr, generatedSourceCodes, publisher, subPageRoot_1, subPagePath, subPagePathIsExist, getPageUrl_1, transformFilePath, existFiles, existSubFiles, _g, files, syncMap, _loop_1, i, indexPage_1, indexPageUrl_1, globalStyle, globalStyleWithoutFirstLine, globalStyle, globalStyleWithoutFirstLine, appContent, appContentWithImport, utilsFilePath, portalImportCode, haveUpdate, installCmd, e_1;
36983
+ return __generator(this, function (_h) {
36984
+ switch (_h.label) {
36723
36985
  case 0:
36724
36986
  cacheDirPath = path__default["default"].join(os__default["default"].homedir(), '.cache', 'mengti_temp');
36725
36987
  keyCacheDirPath = path__default["default"].join(os__default["default"].homedir(), '.cache', 'mengti_translate');
@@ -36728,9 +36990,9 @@ function run(args, options) {
36728
36990
  removeDir(keyCacheDirPath);
36729
36991
  }
36730
36992
  currentLastTimeKey = path__default["default"].join(process.cwd() + '/' + (options.output || '')) + lastTimeKey$1;
36731
- _f.label = 1;
36993
+ _h.label = 1;
36732
36994
  case 1:
36733
- _f.trys.push([1, 15, , 16]);
36995
+ _h.trys.push([1, 15, , 16]);
36734
36996
  cacheTime = cache$1.getKey(currentLastTimeKey);
36735
36997
  console.log('[最后同步时间] ', cacheTime ? new Date(Number(cacheTime)).toLocaleString() : '无');
36736
36998
  afterTime = cacheTime && !options.clear ? Number(cacheTime) : 0;
@@ -36746,13 +37008,16 @@ function run(args, options) {
36746
37008
  afterTime: afterTime,
36747
37009
  })];
36748
37010
  case 2:
36749
- result = _f.sent();
37011
+ result = _h.sent();
36750
37012
  console.log('[INFO] 项目下载完成... ');
36751
37013
  schema = result.schema;
37014
+ console.log('🔍 原始路由数据:',
37015
+ // @ts-ignore
37016
+ JSON.stringify((_a = schema.router) === null || _a === void 0 ? void 0 : _a.routes, null, 2));
36752
37017
  project = result.project, documents = result.documents, componentDocs = result.componentDocs, packageJSON = result.packageJSON;
36753
37018
  projectDocuments = project.documents || [];
36754
37019
  projectDocumentNames_1 = projectDocuments.map(function (_) { return _.fileName; });
36755
- subPageDocumentNames_1 = ((_a = project.appConfig) === null || _a === void 0 ? void 0 : _a.subPages) || [];
37020
+ subPageDocumentNames_1 = ((_b = project.appConfig) === null || _b === void 0 ? void 0 : _b.subPages) || [];
36756
37021
  clientType = options.frame || (project === null || project === void 0 ? void 0 : project.type);
36757
37022
  isWeb = clientType === 'web';
36758
37023
  solution = isWeb ? 'vite' : 'taro';
@@ -36761,7 +37026,7 @@ function run(args, options) {
36761
37026
  return [4 /*yield*/, updateProjectTemplate(solution)];
36762
37027
  case 3:
36763
37028
  // 更新项目模板
36764
- _f.sent();
37029
+ _h.sent();
36765
37030
  console.log('[INFO] 项目模板更新完成... ');
36766
37031
  // 检查是否有文件需要更新
36767
37032
  if (!project || documents.length === 0) {
@@ -36777,20 +37042,21 @@ function run(args, options) {
36777
37042
  console.log('[INFO] 创建项目构建器... ');
36778
37043
  // 处理环境配置
36779
37044
  if (options.env) {
36780
- envInfoItem = (_c = (_b = project.envInfo) === null || _b === void 0 ? void 0 : _b.list) === null || _c === void 0 ? void 0 : _c.find(function (_) { return _.alias === options.env; });
37045
+ envInfoItem = (_d = (_c = project.envInfo) === null || _c === void 0 ? void 0 : _c.list) === null || _d === void 0 ? void 0 : _d.find(function (_) { return _.alias === options.env; });
36781
37046
  if (envInfoItem) {
36782
37047
  schema.constants = __assign(__assign({}, schema.constants), getPureValue(envInfoItem.data));
36783
37048
  }
36784
37049
  }
36785
37050
  console.log('[INFO] 处理环境配置... ');
36786
- // const schemaStr = JSON.stringify(schema);
37051
+ schemaStr = JSON.stringify((_e = schema.componentsTree) === null || _e === void 0 ? void 0 : _e.slice(0, 20).map(function (item) { return item.fileName; }));
37052
+ console.log('schemaStr: ', schemaStr);
36787
37053
  // const isHaveCheckicon = schemaStr.indexOf('icon.style');
36788
37054
  // console.log('isHaveCheck', schemaStr.slice(isHaveCheckicon - 20000, isHaveCheckicon + 20000));
36789
37055
  // 生成代码
36790
37056
  console.log('[INFO] 开始生成代码... ');
36791
- return [4 /*yield*/, builder.generateProject(schema)];
37057
+ return [4 /*yield*/, builder.generateProject(JSON.parse(JSON.stringify(schema)))];
36792
37058
  case 4:
36793
- generatedSourceCodes = _f.sent();
37059
+ generatedSourceCodes = _h.sent();
36794
37060
  console.log('[INFO] 代码生成完成... ');
36795
37061
  generatedSourceCodes.files = generatedSourceCodes.files.filter(function (item) { return item.ext === 'css' || item.ext === 'jsx'; });
36796
37062
  console.log('[INFO] 过滤代码... ');
@@ -36807,7 +37073,7 @@ function run(args, options) {
36807
37073
  createProjectFolder: false,
36808
37074
  })];
36809
37075
  case 5:
36810
- _f.sent();
37076
+ _h.sent();
36811
37077
  console.log('[INFO] 代码生成完成... ');
36812
37078
  if (!fs.existsSync("./".concat(outputPath_1, "/"))) {
36813
37079
  fs.mkdirSync("./".concat(outputPath_1, "/"), {
@@ -36833,27 +37099,29 @@ function run(args, options) {
36833
37099
  return "".concat(pagesPath, "/").concat(file.name, "/index");
36834
37100
  };
36835
37101
  transformFilePath = function (file) {
36836
- if (subPageRoot_1 && file.path.includes('pages') && subPageDocumentNames_1.includes(file.name)) {
37102
+ if (subPageRoot_1 &&
37103
+ file.path.includes('pages') &&
37104
+ subPageDocumentNames_1.includes(file.name)) {
36837
37105
  return file.path.replace('pages', subPageRoot_1);
36838
37106
  }
36839
37107
  return file.path;
36840
37108
  };
36841
37109
  return [4 /*yield*/, getAllFile("./".concat(outputPath_1, "/"))];
36842
37110
  case 6:
36843
- existFiles = _f.sent();
37111
+ existFiles = _h.sent();
36844
37112
  if (!subPagePathIsExist) return [3 /*break*/, 8];
36845
37113
  return [4 /*yield*/, getAllFile(subPagePath)];
36846
37114
  case 7:
36847
- _e = _f.sent();
37115
+ _g = _h.sent();
36848
37116
  return [3 /*break*/, 9];
36849
37117
  case 8:
36850
- _e = [];
36851
- _f.label = 9;
37118
+ _g = [];
37119
+ _h.label = 9;
36852
37120
  case 9:
36853
- existSubFiles = _e;
37121
+ existSubFiles = _g;
36854
37122
  return [4 /*yield*/, getAllFile(cacheDirPath + '/')];
36855
37123
  case 10:
36856
- files = _f.sent();
37124
+ files = _h.sent();
36857
37125
  syncMap = {
36858
37126
  components: existFiles
36859
37127
  .filter(function (_) { return ['tsx', 'jsx'].includes(_.ext) && _.path.includes('components'); })
@@ -36905,12 +37173,17 @@ function run(args, options) {
36905
37173
  .map(function (_) { return getPageUrl_1(_, subPageRoot_1); }),
36906
37174
  };
36907
37175
  _loop_1 = function (i) {
36908
- var file, fileName_1, extName, cssFilePath, cssStr, doc, _g, code, images, svgs, configJsCode, iconsFile, iconsConsts, index, svg, index, image, e_2, realFilePath;
36909
- return __generator(this, function (_h) {
36910
- switch (_h.label) {
37176
+ var file, fileName_1, extName, cssFilePath, cssStr, doc, _j, code, images, svgs, configJsCode, iconsFile, iconsConsts, index, svg, index, image, e_2, realFilePath;
37177
+ return __generator(this, function (_k) {
37178
+ switch (_k.label) {
36911
37179
  case 0:
36912
37180
  file = files[i];
36913
- console.log('[BUILD FILE]', file.name);
37181
+ if (process.env.DEV) {
37182
+ console.log('[BUILD FILE]', file);
37183
+ }
37184
+ else {
37185
+ console.log('[BUILD FILE]', file.name);
37186
+ }
36914
37187
  if (!!file.path.includes('/BasicLayout/')) return [3 /*break*/, 10];
36915
37188
  fileName_1 = file.name;
36916
37189
  extName = file.ext;
@@ -36919,8 +37192,8 @@ function run(args, options) {
36919
37192
  if (!(file.fileName === 'utils.js')) return [3 /*break*/, 2];
36920
37193
  return [4 /*yield*/, transformUtils(file, schema, project, solution)];
36921
37194
  case 1:
36922
- _h.sent();
36923
- _h.label = 2;
37195
+ _k.sent();
37196
+ _k.label = 2;
36924
37197
  case 2:
36925
37198
  if (extName === 'css' || extName === 'scss') {
36926
37199
  cssFilePath = file.path + '/' + file.fileName;
@@ -36945,15 +37218,18 @@ function run(args, options) {
36945
37218
  }
36946
37219
  if (!(extName === 'jsx' || extName === 'tsx')) return [3 /*break*/, 10];
36947
37220
  doc = documents.concat(componentDocs).find(function (_) {
37221
+ console.log('fileName: ', fileName_1, _.fileName);
36948
37222
  return _.fileName.toLowerCase() === fileName_1.toLowerCase();
36949
37223
  });
36950
37224
  // 判断是否是页面
36951
37225
  if ((doc === null || doc === void 0 ? void 0 : doc.type) === 'Page') {
36952
- if (!syncMap.pages.includes(fileName_1) && !subPageDocumentNames_1.includes(fileName_1)) {
37226
+ if (!syncMap.pages.includes(fileName_1) &&
37227
+ !subPageDocumentNames_1.includes(fileName_1)) {
36953
37228
  syncMap.pages.push(fileName_1);
36954
37229
  syncMap.pageUrls.push(getPageUrl_1(file));
36955
37230
  }
36956
- if (!syncMap.subPages.includes(fileName_1) && subPageDocumentNames_1.includes(fileName_1)) {
37231
+ if (!syncMap.subPages.includes(fileName_1) &&
37232
+ subPageDocumentNames_1.includes(fileName_1)) {
36957
37233
  syncMap.subPages.push(fileName_1);
36958
37234
  syncMap.subPageUrls.push(getPageUrl_1(file, subPageRoot_1));
36959
37235
  }
@@ -36966,7 +37242,7 @@ function run(args, options) {
36966
37242
  }
36967
37243
  return [4 /*yield*/, transformJsx(file, solution, outputPath_1)];
36968
37244
  case 3:
36969
- _g = _h.sent(), code = _g.code, images = _g.images, svgs = _g.svgs;
37245
+ _j = _k.sent(), code = _j.code, images = _j.images, svgs = _j.svgs;
36970
37246
  console.log('[BUILD SUCCESS]', file.name);
36971
37247
  // 写入暂存文件夹
36972
37248
  fs.writeFileSync(file.path + '/' + file.fileName, code);
@@ -37012,30 +37288,32 @@ function run(args, options) {
37012
37288
  .join('\n'));
37013
37289
  }
37014
37290
  index = 0;
37015
- _h.label = 4;
37291
+ _k.label = 4;
37016
37292
  case 4:
37017
37293
  if (!(index < images.length)) return [3 /*break*/, 9];
37018
37294
  image = images[index];
37019
37295
  if (!(image.url && image.fileName)) return [3 /*break*/, 8];
37020
- _h.label = 5;
37296
+ _k.label = 5;
37021
37297
  case 5:
37022
- _h.trys.push([5, 7, , 8]);
37298
+ _k.trys.push([5, 7, , 8]);
37023
37299
  if (!fs.existsSync(file.path + '/images')) {
37024
37300
  fs.mkdirSync(file.path + '/images');
37025
37301
  }
37026
37302
  return [4 /*yield*/, downloadFile(image.url, file.path + '/images/' + image.fileName)];
37027
37303
  case 6:
37028
- _h.sent();
37304
+ _k.sent();
37029
37305
  return [3 /*break*/, 8];
37030
37306
  case 7:
37031
- e_2 = _h.sent();
37307
+ e_2 = _k.sent();
37032
37308
  console.log('[downloadFile Error] ', e_2);
37033
37309
  return [3 /*break*/, 8];
37034
37310
  case 8:
37035
37311
  index++;
37036
37312
  return [3 /*break*/, 4];
37037
37313
  case 9:
37038
- realFilePath = "./".concat(subPageDocumentNames_1.includes(file.name) ? outputPath_1 === null || outputPath_1 === void 0 ? void 0 : outputPath_1.replace('pages', subPageRoot_1) : outputPath_1, "/").concat(file.name);
37314
+ realFilePath = "./".concat(subPageDocumentNames_1.includes(file.name)
37315
+ ? outputPath_1 === null || outputPath_1 === void 0 ? void 0 : outputPath_1.replace('pages', subPageRoot_1)
37316
+ : outputPath_1, "/").concat(file.name);
37039
37317
  if ((doc === null || doc === void 0 ? void 0 : doc.type) === 'Component') {
37040
37318
  realFilePath = "./".concat(outputPath_1, "/components/").concat(file.name);
37041
37319
  }
@@ -37043,32 +37321,35 @@ function run(args, options) {
37043
37321
  if (fs.existsSync(realFilePath)) {
37044
37322
  removeDir(realFilePath);
37045
37323
  }
37324
+ console.log('realFilePath: ', realFilePath, doc === null || doc === void 0 ? void 0 : doc.fileName, doc === null || doc === void 0 ? void 0 : doc.type);
37046
37325
  if ((doc === null || doc === void 0 ? void 0 : doc.type) === 'Page') {
37047
- fs.copySync("".concat(cacheDirPath, "/src/pages/").concat(file.name), realFilePath);
37326
+ console.log('realFilePath: ', realFilePath);
37327
+ fs.copySync("".concat(cacheDirPath, "/src/pages/").concat(file.name), realFilePath.replace(file.name, doc.fileName));
37048
37328
  }
37049
37329
  if ((doc === null || doc === void 0 ? void 0 : doc.type) === 'Component') {
37050
- fs.copySync("".concat(cacheDirPath, "/src/components/").concat(file.name), realFilePath);
37330
+ console.log('realFilePath1: ', realFilePath);
37331
+ fs.copySync("".concat(cacheDirPath, "/src/components/").concat(file.name), realFilePath.replace(file.name, doc.fileName));
37051
37332
  }
37052
- _h.label = 10;
37333
+ _k.label = 10;
37053
37334
  case 10: return [2 /*return*/];
37054
37335
  }
37055
37336
  });
37056
37337
  };
37057
37338
  i = 0;
37058
- _f.label = 11;
37339
+ _h.label = 11;
37059
37340
  case 11:
37060
37341
  if (!(i < files.length)) return [3 /*break*/, 14];
37061
37342
  return [5 /*yield**/, _loop_1(i)];
37062
37343
  case 12:
37063
- _f.sent();
37064
- _f.label = 13;
37344
+ _h.sent();
37345
+ _h.label = 13;
37065
37346
  case 13:
37066
37347
  i++;
37067
37348
  return [3 /*break*/, 11];
37068
37349
  case 14:
37069
37350
  // 更新同步时间
37070
37351
  cache$1.setKey(currentLastTimeKey, String(Date.now()));
37071
- indexPage_1 = (_d = project.appConfig) === null || _d === void 0 ? void 0 : _d.indexPage;
37352
+ indexPage_1 = (_f = project.appConfig) === null || _f === void 0 ? void 0 : _f.indexPage;
37072
37353
  if (indexPage_1) {
37073
37354
  // 首页排序
37074
37355
  syncMap.pages = syncMap.pages.sort(function (a, b) {
@@ -37120,11 +37401,21 @@ function run(args, options) {
37120
37401
  fs.writeFileSync('./src/app.tsx', appContentWithImport);
37121
37402
  }
37122
37403
  }
37404
+ utilsFilePath = "".concat(cacheDirPath, "/src/utils.js");
37405
+ if (process.env.DEV) {
37406
+ console.log('[utilsFilePath]', utilsFilePath);
37407
+ }
37123
37408
  // 生成 utils & constants
37124
- fs.copyFileSync("".concat(cacheDirPath, "/src/utils.js"), './src/utils/utils.js');
37409
+ fs.copyFileSync(utilsFilePath, './src/utils/utils.js');
37125
37410
  fs.copyFileSync("".concat(cacheDirPath, "/src/constants.js"), './src/utils/constants.js');
37411
+ if (process.env.DEV) {
37412
+ console.log('[Start CreatePartalImport]');
37413
+ }
37126
37414
  portalImportCode = createPartalImport(project, outputPath_1, solution);
37127
37415
  fs.writeFileSync('./src/utils/portal.js', portalImportCode);
37416
+ if (process.env.DEV) {
37417
+ console.log('[End CreatePartalImport]');
37418
+ }
37128
37419
  if (!isWeb) {
37129
37420
  // 小程序配置
37130
37421
  genAppConfig(options.frame || project.type, project, syncMap);
@@ -37132,6 +37423,9 @@ function run(args, options) {
37132
37423
  else {
37133
37424
  createAppFile(project);
37134
37425
  }
37426
+ if (process.env.DEV) {
37427
+ console.log('[End GenAppConfig]');
37428
+ }
37135
37429
  haveUpdate = writePackageJSON(packageJSON);
37136
37430
  if (haveUpdate) {
37137
37431
  console.log('[INFO] package.json 文件已更新,将重新安装依赖');
@@ -37146,7 +37440,7 @@ function run(args, options) {
37146
37440
  console.log("[INFO ".concat(new Date().toLocaleString(), "] \u4EE3\u7801\u589E\u91CF\u540C\u6B65\u5B8C\u6210"));
37147
37441
  return [2 /*return*/, 0];
37148
37442
  case 15:
37149
- e_1 = _f.sent();
37443
+ e_1 = _h.sent();
37150
37444
  console.log(chalk__default["default"].red(getErrorMessage(e_1) || "Unexpected error: ".concat(e_1)));
37151
37445
  // 保存缓存
37152
37446
  cache$1.removeKey(currentLastTimeKey);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@appthen/cli",
3
- "version": "1.2.1",
3
+ "version": "1.2.2",
4
4
  "description": "Appthen Cli Tool",
5
5
  "files": [
6
6
  "dist",