@hadss/hmrouter-plugin 1.1.1-alpha.0 → 1.2.0-beta.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 (55) hide show
  1. package/README.md +126 -56
  2. package/dist/HMRouterPluginManager.d.ts +3 -1
  3. package/dist/HMRouterPluginManager.js +26 -8
  4. package/dist/Index.d.ts +5 -0
  5. package/dist/Index.js +29 -1
  6. package/dist/framework/core/PluginExecutionController.d.ts +11 -0
  7. package/dist/framework/core/PluginExecutionController.js +129 -22
  8. package/dist/framework/core/TaskManager.js +6 -5
  9. package/dist/framework/utils/FileUtil.d.ts +4 -0
  10. package/dist/framework/utils/FileUtil.js +11 -0
  11. package/dist/hmrouter_extension/HMRouterExtension.d.ts +1 -0
  12. package/dist/hmrouter_extension/HMRouterExtension.js +55 -0
  13. package/dist/hmrouter_extension/analyzer/ComponentAnalyzer.js +0 -1
  14. package/dist/hmrouter_extension/analyzer/RouterAnalyzer.d.ts +1 -0
  15. package/dist/hmrouter_extension/analyzer/RouterAnalyzer.js +16 -8
  16. package/dist/hmrouter_extension/config/HMRouterPluginConfig.js +3 -4
  17. package/dist/hmrouter_extension/constants/PluginConstants.d.ts +1 -0
  18. package/dist/hmrouter_extension/constants/PluginConstants.js +1 -0
  19. package/dist/hmrouter_extension/processor/CodeGenerationProcessor.js +2 -1
  20. package/dist/hmrouter_extension/processor/InitializerProcessor.d.ts +1 -0
  21. package/dist/hmrouter_extension/processor/InitializerProcessor.js +30 -5
  22. package/dist/hmrouter_extension/processor/ObfuscationProcessor.d.ts +0 -1
  23. package/dist/hmrouter_extension/processor/ObfuscationProcessor.js +6 -9
  24. package/dist/hmrouter_extension/processor/ResourceProcessor.js +14 -0
  25. package/dist/hmrouter_extension/processor/RouterMapBuildingProcessor.js +2 -6
  26. package/package.json +2 -1
  27. package/template/viewBuilder.ejs +1 -1
  28. package/dist/HMRouterAnalyzer.d.ts +0 -31
  29. package/dist/HMRouterAnalyzer.js +0 -343
  30. package/dist/HMRouterHvigorPlugin.d.ts +0 -15
  31. package/dist/HMRouterHvigorPlugin.js +0 -153
  32. package/dist/HMRouterPluginConfig.d.ts +0 -39
  33. package/dist/HMRouterPluginConfig.js +0 -74
  34. package/dist/HMRouterPluginHandle.d.ts +0 -23
  35. package/dist/HMRouterPluginHandle.js +0 -222
  36. package/dist/common/Logger.d.ts +0 -13
  37. package/dist/common/Logger.js +0 -55
  38. package/dist/common/PluginModel.d.ts +0 -51
  39. package/dist/common/PluginModel.js +0 -23
  40. package/dist/constants/CommonConstants.d.ts +0 -39
  41. package/dist/constants/CommonConstants.js +0 -46
  42. package/dist/constants/ConfigConstants.d.ts +0 -12
  43. package/dist/constants/ConfigConstants.js +0 -16
  44. package/dist/constants/TaskConstants.d.ts +0 -9
  45. package/dist/constants/TaskConstants.js +0 -13
  46. package/dist/store/PluginStore.d.ts +0 -14
  47. package/dist/store/PluginStore.js +0 -20
  48. package/dist/utils/FileUtil.d.ts +0 -13
  49. package/dist/utils/FileUtil.js +0 -20
  50. package/dist/utils/ObfuscationUtil.d.ts +0 -4
  51. package/dist/utils/ObfuscationUtil.js +0 -34
  52. package/dist/utils/StringUtil.d.ts +0 -3
  53. package/dist/utils/StringUtil.js +0 -18
  54. package/dist/utils/TsAstUtil.d.ts +0 -9
  55. package/dist/utils/TsAstUtil.js +0 -97
package/README.md CHANGED
@@ -8,9 +8,9 @@ HMRouter编译插件是一个基于hvigor的编译插件,用于:
8
8
 
9
9
  1. 扫描代码中的`@HMRouter`、`@HMInterceptor`、`@HMLifecycle`、`@HMAnimator`、`@HMService`等注解
10
10
  2. 生成路由表和NavDestination页面代码
11
- 3. 生成混淆规则
12
- 4. 支持自定义模板
13
- 5. 编译时自定义扩展
11
+ 3. **自动生成混淆规则**
12
+ 4. **支持自定义模板**,开发者可以自定义特殊页面的生成
13
+ 5. **支持插件扩展**,开发者可以在HMRouterPlugin的编译中进行自定义解析
14
14
 
15
15
  ## 插件安装与配置
16
16
 
@@ -21,50 +21,40 @@ HMRouter编译插件是一个基于hvigor的编译插件,用于:
21
21
  ```json5
22
22
  {
23
23
  "dependencies": {
24
- "@hadss/hmrouter-plugin": "^1.1.0-beta.0" // 使用最新版本
24
+ "@hadss/hmrouter-plugin": "^1.2.0-beta.0" // 使用最新版本
25
25
  },
26
26
  // ...其余配置
27
27
  }
28
28
  ```
29
29
 
30
- ### 模块级配置
31
-
32
- 在使用HMRouter的模块中引入路由编译插件,修改`hvigorfile.ts`:
30
+ 修改工程根目录下的`hvigorfile.ts`,使用路由编译插件
33
31
 
34
- ```extendtypescript
35
- // entry/hvigorfile.ts entry模块的hvigorfile.ts
36
- import { hapTasks } from '@ohos/hvigor-ohos-plugin';
37
- import { hapPlugin } from '@hadss/hmrouter-plugin';
32
+ ```typescript
33
+ // 工程根目录/hvigorfile.ts
34
+ import { appTasks } from '@ohos/hvigor-ohos-plugin';
35
+ import { appPlugin } from "@hadss/hmrouter-plugin";
38
36
 
39
37
  export default {
40
- system: hapTasks,
41
- plugins: [hapPlugin()] // 使用HMRouter标签的模块均需要配置,与模块类型保持一致
42
- }
38
+ system: appTasks,
39
+ plugins: [appPlugin({ ignoreModuleNames: [ /** 不需要扫描的模块 **/ ] })]
40
+ };
41
+ ```
43
42
 
44
- // libHar/hvigorfile.ts libHar模块的hvigorfile.ts
45
- import { harTasks } from '@ohos/hvigor-ohos-plugin';
46
- import { harPlugin } from '@hadss/hmrouter-plugin';
43
+ ### 模块级配置
47
44
 
48
- export default {
49
- system: harTasks,
50
- plugins:[harPlugin()] // 使用HMRouter标签的模块均需要配置,与模块类型保持一致
51
- }
45
+ 在使用HMRouter的模块中单独配置路由编译插件,修改模块目录下的`hvigorfile.ts`:
52
46
 
53
- // libHsp/hvigorfile.ts libHsp模块的hvigorfile.ts
54
- import { hspTasks } from '@ohos/hvigor-ohos-plugin';
55
- import { hspPlugin } from '@hadss/hmrouter-plugin';
47
+ ```typescript
48
+ // entry/hvigorfile.ts entry模块的hvigorfile.ts
49
+ import { hapTasks } from '@ohos/hvigor-ohos-plugin';
50
+ import { modulePlugin } from '@hadss/hmrouter-plugin';
56
51
 
57
52
  export default {
58
- system: hspTasks,
59
- plugins: [hspPlugin()] // 使用HMRouter标签的模块均需要配置,与模块类型保持一致
53
+ system: hapTasks,
54
+ plugins: [modulePlugin()] // 使用HMRouter标签的模块均需要配置,与模块类型保持一致
60
55
  }
61
56
  ```
62
57
 
63
- > 注意:模块类型与插件类型必须匹配:
64
- > - Har模块使用`harPlugin()`
65
- > - Hsp模块使用`hspPlugin()`
66
- > - Hap模块使用`hapPlugin()`
67
-
68
58
  ## 配置文件详解
69
59
 
70
60
  在项目根目录或模块目录创建`hmrouter_config.json`文件,配置插件行为:
@@ -106,17 +96,17 @@ export default {
106
96
 
107
97
  ### 配置选项说明
108
98
 
109
- | 配置项 | 类型 | 是否必填 | 说明 |
110
- |---------------------|---------|------|----------------------------------------------------------------------------------------------------------------------------------------|
111
- | scanDir | array | 否 | 指定扫描当前模块路径,默认值为`src/main/ets` |
112
- | saveGeneratedFile | boolean | 否 | 默认为 false,不保留插件自动生成的代码,如果需要保留,需要设置为 true |
99
+ | 配置项 | 类型 | 是否必填 | 说明 |
100
+ |---------------------|---------|------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
101
+ | scanDir | array | 否 | 指定扫描当前模块路径,默认值为`src/main/ets` |
102
+ | saveGeneratedFile | boolean | 否 | 默认为 false,不保留插件自动生成的代码,如果需要保留,需要设置为 true |
113
103
  | autoObfuscation | boolean | 否 | 默认为 false,不自动配置混淆规则,只会生成`hmrouter_obfuscation_rules.txt`文件帮助开发者配置混淆规则;如果设置为 true,会自动配置混淆规则,并在编译完成后删除`hmrouter_obfuscation_rules.txt`文件,详细说明请参考[混淆配置](Obfuscation.md)文档。 |
114
- | defaultPageTemplate | string | 否 | 默认模版路径,相对于hmrouter_config.json文件,例如:`./templates/defaultTemplate.ejs` |
115
- | customPageTemplate | object | 否 | srcPath为匹配的代码文件路径,支持通配符,templatePath为模版路径,可以实现不同的代码使用不同的模版来生成 |
104
+ | defaultPageTemplate | string | 否 | 默认模版路径,相对于hmrouter_config.json文件,例如:`./templates/defaultTemplate.ejs` |
105
+ | customPageTemplate | object | 否 | srcPath为匹配的代码文件路径,支持通配符,templatePath为模版路径,可以实现不同的代码使用不同的模版来生成 |
116
106
 
117
107
  ### 配置文件读取规则
118
108
 
119
- > 配置文件读取规则为 模块 > 工程 > 默认
109
+ > 配置文件会自动合并,读取优先级为 模块 > 工程 > 默认
120
110
  >
121
111
  > 优先使用本模块内的配置,如果没有配置,则使用工程根目录配置,若都找不到则使用默认配置
122
112
 
@@ -124,22 +114,6 @@ export default {
124
114
  >
125
115
  > 1.0.0-rc.9 版本开始,支持自定义模版配置`customPageTemplate`
126
116
 
127
- ## 多模块配置
128
-
129
- 在多模块项目中,每个使用HMRouter的模块都需要配置插件。
130
-
131
- ### 方式一:每个模块单独配置
132
-
133
- 在每个模块的根目录下创建`hmrouter_config.json`文件,分别配置。
134
-
135
- ### 方式二:共享配置
136
-
137
- 在项目根目录创建`hmrouter_config.json`文件,所有模块共享配置。
138
-
139
- 如果需要为不同模块指定不同的配置,可以在模块根目录创建`hmrouter_config.json`文件,覆盖共享配置。
140
-
141
- > 注意:当前多模块配置时不会做字段合并,即模块配置会直接覆盖工程配置
142
-
143
117
  ## 自定义模板使用
144
118
 
145
119
  在 `HMRouterPlugin` 中,EJS模板用于生成动态页面或组件,可以在模板文件中使用 EJS 的语法
@@ -356,9 +330,78 @@ export struct <%= componentName %>Generated {
356
330
  - customPageTemplate > defaultPageTemplate > 库中携带的模板
357
331
  - 如遇到customPageTemplate中的多个srcPath都能匹配上,优先取前面的模板文件
358
332
 
359
- ## 插件自定义扩展
333
+ ## 插件扩展
334
+
335
+ HMRouterPlugin提供了完善的扩展机制,允许开发者在插件执行的不同阶段注入自定义逻辑。通过继承`PluginExtension`抽象类并实现特定方法来扩展功能。
336
+
337
+ ### 编写扩展类
338
+
339
+ 创建一个继承自`PluginExtension`的类,并实现需要的生命周期方法:
340
+
341
+ ```typescript
342
+ // MyCustomExtension.ts
343
+ import { PluginExtension, ExtensionContext } from '@hadss/hmrouter-plugin';
344
+ import { SourceFile } from 'ts-morph';
345
+
346
+ export class MyCustomExtension extends PluginExtension {
347
+ // 可选:扩展名称,主要用于调试日志
348
+ get name(): string {
349
+ return 'MyCustomExtension';
350
+ }
351
+
352
+ // hmrouter_extension初始化阶段后执行
353
+ afterInitialize(context: ExtensionContext): void {
354
+ console.log('Extension initialization');
355
+ // 初始化设置逻辑
356
+ }
357
+
358
+ // 注解分析阶段后执行
359
+ afterAnnotationAnalysis(sourceFile: SourceFile, filePath: string, context: ExtensionContext): void {
360
+ // 在源文件上执行分析逻辑
361
+ console.log(`Analyzing file: ${filePath}`);
362
+ // 可以提取信息并添加到上下文
363
+ const results = [
364
+ // 分析结果...
365
+ ];
366
+
367
+ // 将结果添加到上下文
368
+ context.addAnalyzeResults(results);
369
+ }
370
+
371
+ // 代码生成阶段后执行
372
+ afterCodeGeneration(context: ExtensionContext): void {
373
+ // 自定义代码生成逻辑
374
+ console.log('Custom code generation');
375
+ }
376
+
377
+ // 其它阶段方法...
378
+ // afterRouterMapBuilding
379
+ // afterConfigUpdate
380
+ // afterObfuscationProcess
381
+ // afterResourceProcess
382
+ // afterCompletion
383
+ }
384
+ ```
385
+
386
+ > 如需要进行自定义解析,请将`ts-morph`加入到`hvigor-config.json`依赖中
360
387
 
361
- 见[插件扩展指南](https://gitcode.com/openharmony-sig/ohrouter/blob/master/docs/PluginExtension.md)
388
+ ### 注册扩展
389
+ ```typescript
390
+ import { appTasks } from '@ohos/hvigor-ohos-plugin';
391
+ import { registerPluginExtension } from '@hadss/hmrouter-plugin';
392
+ import { MyCustomExtension } from './MyCustomExtension';
393
+ import { appPlugin } from "@hadss/hmrouter-plugin";
394
+
395
+ // 注册扩展实例
396
+ registerPluginExtension(new MyCustomExtension());
397
+
398
+ export default {
399
+ system: appTasks,
400
+ plugins: [appPlugin({ ignoreModuleNames: [] })]
401
+ };
402
+ ```
403
+
404
+ > 更多使用介绍请访问[插件扩展](https://gitcode.com/openharmony-sig/ohrouter/blob/master/docs/PluginExtension.md)
362
405
 
363
406
  ## 编译产物
364
407
 
@@ -393,6 +436,33 @@ hvigor 5.7.3及以上
393
436
  > [HMRouterPlugin] Your DevEco Studio version less than 5.0.3.800, may cause remote hsp dependencies get failed
394
437
  > ```
395
438
 
439
+ ## 更新日志
440
+
441
+ ### 1.2.0-beta.1 (2025.07.29)
442
+
443
+ - 修复相同组件名称冲突的问题
444
+ - 修复默认模版的问题
445
+ - 修复ohosTest编译错误
446
+ - 修复oh-package.json5含注解的编译错误
447
+ - 修复自动混淆问题
448
+
449
+ ### 1.2.0-beta.0 (2025.06.17)
450
+
451
+ - 新增插件扩展能力
452
+ - 修复了路由表生成与hvigor编译流程冲突的问题
453
+
454
+ ### 1.1.0-beta.0 (2025.04.11)
455
+
456
+ - 更新了自定义模版,支持原生组件接入
457
+
458
+ ### 1.0.0-rc.9 (2024.10.09)
459
+
460
+ - 支持自定义页面模版配置`customPageTemplate`
461
+
462
+ ### 1.0.0-rc.6 (2024.09.27)
463
+
464
+ - 新增自动混淆配置参数`autoObfuscation`,开启可以自动配置HMRouter混淆白名单
465
+
396
466
  ## 常见问题
397
467
 
398
468
  ### 编译失败,提示重复的routerMap对象名称
@@ -2,8 +2,10 @@ import { HvigorNode } from '@ohos/hvigor';
2
2
  import { PluginParam } from './Index';
3
3
  export declare class HMRouterPluginManager {
4
4
  private static instance;
5
- private controllerSet;
5
+ private controllerMap;
6
+ private moduleNodes;
6
7
  private constructor();
7
8
  static getInstance(): HMRouterPluginManager;
8
9
  registerPlugin(node: HvigorNode, pluginId: string, options: PluginParam): void;
10
+ addModuleNode(node: HvigorNode): void;
9
11
  }
@@ -7,22 +7,30 @@ const HMRouterExtension_1 = require("./hmrouter_extension/HMRouterExtension");
7
7
  const framework_1 = require("./framework");
8
8
  class HMRouterPluginManager {
9
9
  constructor() {
10
- this.controllerSet = new Set();
10
+ this.controllerMap = new Map();
11
+ this.moduleNodes = [];
11
12
  framework_1.Logger.info('', 'HMRouterPlugin starting...');
12
13
  (0, framework_1.registerPluginExtension)(new HMRouterExtension_1.HMRouterDefaultExtension());
13
14
  hvigor_1.hvigor.nodesEvaluated(() => {
14
- this.controllerSet.forEach((controller) => {
15
- controller.start();
15
+ this.moduleNodes.forEach((node) => {
16
+ if (this.controllerMap.has(node.getNodeName()))
17
+ return;
18
+ node.getAllPluginIds().forEach((pluginId) => {
19
+ this.registerPlugin(node, pluginId, {});
20
+ });
16
21
  });
22
+ for (const [_key, controller] of this.controllerMap) {
23
+ controller.start();
24
+ }
17
25
  });
18
26
  hvigor_1.hvigor.buildFinished(() => {
19
- this.controllerSet.forEach((controller) => {
27
+ this.controllerMap.forEach((controller) => {
20
28
  controller.complete();
21
29
  });
22
30
  HMRouterPluginManager.instance = null;
23
31
  framework_1.PluginStore.destroy();
24
32
  framework_1.ExtensionManager.destroy();
25
- this.controllerSet.clear();
33
+ this.controllerMap.clear();
26
34
  framework_1.TsAstUtil.clearProject();
27
35
  });
28
36
  }
@@ -38,18 +46,28 @@ class HMRouterPluginManager {
38
46
  throw PluginError_1.PluginError.create(PluginError_1.ErrorCode.ERROR_CONFIG, node.getNodeName(), node.getNodePath());
39
47
  }
40
48
  const controller = new framework_1.PluginExecutionController(node, moduleContext, options.extensions);
41
- this.controllerSet.add(controller);
49
+ this.controllerMap.set(node.getNodeName(), controller);
42
50
  if ((0, framework_1.isHspModule)(node)) {
43
51
  let packageJsonPath = framework_1.PluginFileUtil.pathResolve(node.getNodePath(), 'oh-package.json5');
44
- let packageJsonContent = framework_1.PluginFileUtil.readFileSync(packageJsonPath);
45
- let packageJson = JSON.parse(packageJsonContent.toString());
52
+ let packageJson = framework_1.PluginFileUtil.readJson5(packageJsonPath);
46
53
  let hspNameArr = framework_1.PluginStore.getInstance().get('hspModuleNames');
47
54
  if (!hspNameArr) {
48
55
  framework_1.PluginStore.getInstance().set('hspModuleNames', []);
49
56
  }
57
+ let hspModulesInfo = framework_1.PluginStore.getInstance().get('hspModulesInfo');
58
+ if (!hspModulesInfo) {
59
+ framework_1.PluginStore.getInstance().set('hspModulesInfo', []);
60
+ }
50
61
  framework_1.PluginStore.getInstance().get('hspModuleNames')?.push(packageJson.name);
62
+ framework_1.PluginStore.getInstance().get('hspModulesInfo')?.push({
63
+ moduleName: node.getNodeName(),
64
+ packageName: packageJson.name
65
+ });
51
66
  }
52
67
  }
68
+ addModuleNode(node) {
69
+ this.moduleNodes.push(node);
70
+ }
53
71
  }
54
72
  exports.HMRouterPluginManager = HMRouterPluginManager;
55
73
  HMRouterPluginManager.instance = null;
package/dist/Index.d.ts CHANGED
@@ -5,6 +5,11 @@ export * from './framework/extension';
5
5
  export interface PluginParam {
6
6
  extensions?: PluginExtension[];
7
7
  }
8
+ export interface AppPluginParam {
9
+ ignoreModuleNames: string[];
10
+ }
8
11
  export declare function hapPlugin(options?: PluginParam): HvigorPlugin;
9
12
  export declare function hspPlugin(options?: PluginParam): HvigorPlugin;
10
13
  export declare function harPlugin(options?: PluginParam): HvigorPlugin;
14
+ export declare function modulePlugin(options?: PluginParam): HvigorPlugin;
15
+ export declare function appPlugin(options: AppPluginParam): HvigorPlugin;
package/dist/Index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.harPlugin = exports.hspPlugin = exports.hapPlugin = void 0;
17
+ exports.appPlugin = exports.modulePlugin = exports.harPlugin = exports.hspPlugin = exports.hapPlugin = void 0;
18
18
  const hvigor_ohos_plugin_1 = require("@ohos/hvigor-ohos-plugin");
19
19
  const constants_1 = require("./hmrouter_extension/constants");
20
20
  const HMRouterPluginManager_1 = require("./HMRouterPluginManager");
@@ -47,3 +47,31 @@ function harPlugin(options = {}) {
47
47
  };
48
48
  }
49
49
  exports.harPlugin = harPlugin;
50
+ function modulePlugin(options = {}) {
51
+ return {
52
+ pluginId: constants_1.PluginConstants.HAP_PLUGIN_ID,
53
+ apply(node) {
54
+ node.getAllPluginIds().forEach((pluginId) => {
55
+ HMRouterPluginManager_1.HMRouterPluginManager.getInstance().registerPlugin(node, pluginId, options);
56
+ });
57
+ },
58
+ };
59
+ }
60
+ exports.modulePlugin = modulePlugin;
61
+ function appPlugin(options) {
62
+ return {
63
+ pluginId: constants_1.PluginConstants.HAP_PLUGIN_ID,
64
+ apply(node) {
65
+ if (!options) {
66
+ throw new Error('No options provided');
67
+ }
68
+ node.subNodes(subNode => {
69
+ if (options.ignoreModuleNames.includes(subNode.getNodeName())) {
70
+ return;
71
+ }
72
+ HMRouterPluginManager_1.HMRouterPluginManager.getInstance().addModuleNode(subNode);
73
+ });
74
+ },
75
+ };
76
+ }
77
+ exports.appPlugin = appPlugin;
@@ -7,9 +7,20 @@ export declare class PluginExecutionController {
7
7
  private readonly taskManager;
8
8
  private readonly baseContext;
9
9
  private extensionContextCache;
10
+ private originalBuilderDir?;
10
11
  constructor(node: HvigorNode, moduleContext: OhosModuleContext, moduleExtensions?: PluginExtension[]);
11
12
  start(): void;
12
13
  complete(): void;
13
14
  private initializeContext;
14
15
  private registerHvigorTasks;
16
+ private filterScanFilesForTarget;
17
+ private backupScanFiles;
18
+ private restoreScanFiles;
19
+ private backupConfig;
20
+ private restoreConfig;
21
+ private adjustConfigForTarget;
22
+ private registerMainPluginTask;
23
+ private registerObfuscationTask;
24
+ private registerCopyRouterMapTask;
25
+ private getTaskName;
15
26
  }
@@ -5,6 +5,7 @@ const TaskManager_1 = require("./TaskManager");
5
5
  const TaskStage_1 = require("./TaskStage");
6
6
  const constants_1 = require("../constants");
7
7
  const extension_1 = require("../extension");
8
+ const utils_1 = require("../utils");
8
9
  class PluginExecutionController {
9
10
  constructor(node, moduleContext, moduleExtensions) {
10
11
  this.extensionContextCache = new Map();
@@ -28,35 +29,141 @@ class PluginExecutionController {
28
29
  registerHvigorTasks() {
29
30
  this.moduleContext.targets((target) => {
30
31
  const targetName = target.getTargetName();
31
- this.node.registerTask({
32
- name: targetName + constants_1.TaskConstants.PLUGIN_TASK,
33
- run: () => {
32
+ this.taskManager.context.currentTarget = target;
33
+ this.registerMainPluginTask(targetName);
34
+ this.registerObfuscationTask(targetName);
35
+ if ((0, utils_1.isHapModule)(this.node) || (0, utils_1.isHspModule)(this.node)) {
36
+ this.registerCopyRouterMapTask(targetName);
37
+ }
38
+ });
39
+ }
40
+ filterScanFilesForTarget() {
41
+ const currentTargetName = this.taskManager.context.currentTarget?.getTargetName();
42
+ if (!currentTargetName) {
43
+ return;
44
+ }
45
+ const buildProfileTargets = this.moduleContext.getBuildProfileOpt().targets || [];
46
+ const targetOpt = buildProfileTargets.find((target) => target.name === currentTargetName);
47
+ if (!targetOpt?.source?.sourceRoots || targetOpt.source.sourceRoots.length === 0) {
48
+ return;
49
+ }
50
+ const moduleRoot = this.moduleContext.getModulePath();
51
+ const absoluteSourceRoots = targetOpt.source.sourceRoots.map((sourceRoot) => {
52
+ const absolutePath = utils_1.PluginFileUtil.resolve(moduleRoot, sourceRoot);
53
+ const normalizedPath = utils_1.PluginFileUtil.normalize(absolutePath);
54
+ return normalizedPath.endsWith(utils_1.PluginFileUtil.sep) ? normalizedPath : normalizedPath + utils_1.PluginFileUtil.sep;
55
+ });
56
+ this.baseContext.scanFiles = this.baseContext.scanFiles.filter((filePath) => {
57
+ const normalizedFilePath = utils_1.PluginFileUtil.normalize(filePath);
58
+ return absoluteSourceRoots.some((sourceRootPath) => {
59
+ return normalizedFilePath.startsWith(sourceRootPath);
60
+ });
61
+ });
62
+ }
63
+ backupScanFiles() {
64
+ return [...this.baseContext.scanFiles];
65
+ }
66
+ restoreScanFiles(backup) {
67
+ this.baseContext.scanFiles = backup;
68
+ }
69
+ backupConfig() {
70
+ const hmrouterContext = this.taskManager.context;
71
+ if (hmrouterContext.config && hmrouterContext.config.builderDir) {
72
+ this.originalBuilderDir = hmrouterContext.config.builderDir;
73
+ }
74
+ }
75
+ restoreConfig() {
76
+ if (this.originalBuilderDir) {
77
+ const hmrouterContext = this.taskManager.context;
78
+ if (hmrouterContext.config) {
79
+ hmrouterContext.config.builderDir = this.originalBuilderDir;
80
+ }
81
+ this.originalBuilderDir = undefined;
82
+ }
83
+ }
84
+ adjustConfigForTarget() {
85
+ const currentTargetName = this.taskManager.context.currentTarget?.getTargetName();
86
+ if (!currentTargetName) {
87
+ return;
88
+ }
89
+ const buildProfileTargets = this.moduleContext.getBuildProfileOpt().targets || [];
90
+ const targetOpt = buildProfileTargets.find((target) => target.name === currentTargetName);
91
+ if (!targetOpt?.source?.sourceRoots || targetOpt.source.sourceRoots.length === 0) {
92
+ return;
93
+ }
94
+ const hmrouterContext = this.taskManager.context;
95
+ if (!hmrouterContext.config || !hmrouterContext.config.builderDir) {
96
+ return;
97
+ }
98
+ const firstSourceRoot = targetOpt.source.sourceRoots[0];
99
+ const cleanSourceRoot = firstSourceRoot.replace(/^\.\//, '');
100
+ hmrouterContext.config.builderDir = `${cleanSourceRoot}/ets/generated`;
101
+ }
102
+ registerMainPluginTask(targetName) {
103
+ this.node.registerTask({
104
+ name: this.getTaskName(targetName, constants_1.TaskConstants.PLUGIN_TASK),
105
+ run: () => {
106
+ const scanFilesBackup = this.backupScanFiles();
107
+ try {
108
+ this.backupConfig();
109
+ this.filterScanFilesForTarget();
110
+ this.adjustConfigForTarget();
34
111
  this.taskManager.executeStage(TaskStage_1.TaskStage.AFTER_ANNOTATION_ANALYSIS);
35
112
  this.taskManager.executeStage(TaskStage_1.TaskStage.AFTER_CODE_GENERATION);
36
113
  this.taskManager.executeStage(TaskStage_1.TaskStage.AFTER_ROUTER_MAP_BUILDING);
37
114
  this.taskManager.executeStage(TaskStage_1.TaskStage.AFTER_CONFIG_UPDATE);
38
- },
39
- dependencies: [],
40
- postDependencies: [targetName + constants_1.TaskConstants.PRE_BUILD],
41
- });
42
- this.node.registerTask({
43
- name: targetName + constants_1.TaskConstants.GENERATE_OBFUSCATION_TASK,
44
- run: () => {
115
+ }
116
+ finally {
117
+ this.restoreConfig();
118
+ this.restoreScanFiles(scanFilesBackup);
119
+ }
120
+ },
121
+ dependencies: [],
122
+ postDependencies: [this.getTaskName(targetName, constants_1.TaskConstants.PRE_BUILD)],
123
+ });
124
+ }
125
+ registerObfuscationTask(targetName) {
126
+ this.node.registerTask({
127
+ name: this.getTaskName(targetName, constants_1.TaskConstants.GENERATE_OBFUSCATION_TASK),
128
+ run: () => {
129
+ const scanFilesBackup = this.backupScanFiles();
130
+ try {
131
+ this.backupConfig();
132
+ this.filterScanFilesForTarget();
133
+ this.adjustConfigForTarget();
45
134
  this.taskManager.executeStage(TaskStage_1.TaskStage.AFTER_OBFUSCATION_PROCESS);
46
- },
47
- dependencies: [targetName + constants_1.TaskConstants.PLUGIN_TASK],
48
- postDependencies: [targetName + constants_1.TaskConstants.PRE_BUILD],
49
- });
50
- this.node.registerTask({
51
- name: targetName + constants_1.TaskConstants.COPY_ROUTER_MAP_TASK,
52
- run: () => {
53
- this.taskManager.context.currentTarget = target;
135
+ }
136
+ finally {
137
+ this.restoreConfig();
138
+ this.restoreScanFiles(scanFilesBackup);
139
+ }
140
+ },
141
+ dependencies: [this.getTaskName(targetName, constants_1.TaskConstants.PLUGIN_TASK)],
142
+ postDependencies: [this.getTaskName(targetName, constants_1.TaskConstants.PRE_BUILD)],
143
+ });
144
+ }
145
+ registerCopyRouterMapTask(targetName) {
146
+ this.node.registerTask({
147
+ name: this.getTaskName(targetName, constants_1.TaskConstants.COPY_ROUTER_MAP_TASK),
148
+ run: () => {
149
+ const scanFilesBackup = this.backupScanFiles();
150
+ try {
151
+ this.backupConfig();
152
+ this.filterScanFilesForTarget();
153
+ this.adjustConfigForTarget();
54
154
  this.taskManager.executeStage(TaskStage_1.TaskStage.AFTER_RESOURCE_PROCESS);
55
- },
56
- dependencies: [targetName + constants_1.TaskConstants.PROCESS_ROUTER_MAP],
57
- postDependencies: [targetName + constants_1.TaskConstants.PROCESS_RESOURCE],
58
- });
155
+ }
156
+ finally {
157
+ this.restoreConfig();
158
+ this.restoreScanFiles(scanFilesBackup);
159
+ }
160
+ },
161
+ dependencies: [this.getTaskName(targetName, constants_1.TaskConstants.PROCESS_ROUTER_MAP)],
162
+ postDependencies: [this.getTaskName(targetName, constants_1.TaskConstants.PROCESS_RESOURCE)],
59
163
  });
60
164
  }
165
+ getTaskName(targetName, taskConstant) {
166
+ return targetName + taskConstant;
167
+ }
61
168
  }
62
169
  exports.PluginExecutionController = PluginExecutionController;
@@ -24,14 +24,15 @@ class TaskManager {
24
24
  }
25
25
  }
26
26
  executeAnnotationAnalysis() {
27
- const analyzers = this.getExtensions()
28
- .map((extension) => extension.afterAnnotationAnalysis || null);
27
+ const extensions = this.getExtensions();
29
28
  this.context.scanFiles.forEach((file) => {
30
29
  this.context.setCurrentFilePath(file);
31
30
  const sourceFile = utils_1.TsAstUtil.getSourceFile(file);
32
- for (const analyzer of analyzers) {
33
- analyzer?.(sourceFile, file, this.context);
34
- }
31
+ extensions.forEach((extension) => {
32
+ if (extension.afterAnnotationAnalysis) {
33
+ extension.afterAnnotationAnalysis(sourceFile, file, this.context);
34
+ }
35
+ });
35
36
  });
36
37
  this.context.setCurrentFilePath('');
37
38
  this.validateTemplateData();
@@ -3,6 +3,7 @@
3
3
  import { FileUtil } from '@ohos/hvigor';
4
4
  import fs from 'fs';
5
5
  export declare class PluginFileUtil extends FileUtil {
6
+ static readonly sep: "\\" | "/";
6
7
  static rmSync(path: fs.PathLike, options?: fs.RmOptions): void;
7
8
  static unlinkSync(path: fs.PathLike): void;
8
9
  static readdirSync(path: fs.PathLike, options?: {
@@ -10,4 +11,7 @@ export declare class PluginFileUtil extends FileUtil {
10
11
  withFileTypes?: false | undefined;
11
12
  recursive?: boolean | undefined;
12
13
  }): string[];
14
+ static normalize(filePath: string): string;
15
+ static resolve(...paths: string[]): string;
16
+ static join(...paths: string[]): string;
13
17
  }
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.PluginFileUtil = void 0;
7
7
  const hvigor_1 = require("@ohos/hvigor");
8
8
  const fs_1 = __importDefault(require("fs"));
9
+ const path_1 = __importDefault(require("path"));
9
10
  class PluginFileUtil extends hvigor_1.FileUtil {
10
11
  static rmSync(path, options) {
11
12
  return fs_1.default.rmSync(path, options);
@@ -16,5 +17,15 @@ class PluginFileUtil extends hvigor_1.FileUtil {
16
17
  static readdirSync(path, options) {
17
18
  return fs_1.default.readdirSync(path, options);
18
19
  }
20
+ static normalize(filePath) {
21
+ return path_1.default.normalize(filePath);
22
+ }
23
+ static resolve(...paths) {
24
+ return path_1.default.resolve(...paths);
25
+ }
26
+ static join(...paths) {
27
+ return path_1.default.join(...paths);
28
+ }
19
29
  }
20
30
  exports.PluginFileUtil = PluginFileUtil;
31
+ PluginFileUtil.sep = path_1.default.sep;
@@ -5,6 +5,7 @@ export declare class HMRouterDefaultExtension extends PluginExtension<HMRouterEx
5
5
  get name(): string;
6
6
  afterInitialize(context: HMRouterExtensionContext): void;
7
7
  afterAnnotationAnalysis(sourceFile: SourceFile, filePath: string, context: HMRouterExtensionContext): void;
8
+ private executeConstantParsing;
8
9
  afterCodeGeneration(context: HMRouterExtensionContext): void;
9
10
  afterRouterMapBuilding(context: HMRouterExtensionContext): void;
10
11
  afterConfigUpdate(context: HMRouterExtensionContext): void;