@react-native-oh/react-native-harmony-cli 0.0.30 → 0.77.18-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.
Files changed (235) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +4 -4
  3. package/dist/assetResolver.js +105 -10
  4. package/dist/autolinking/Autolinking.js +21 -26
  5. package/dist/autolinking/index.js +0 -6
  6. package/dist/codegen/core/CodeGenerator.js +0 -6
  7. package/dist/codegen/core/CodegenError.js +0 -6
  8. package/dist/codegen/core/EventUtils.js +4 -13
  9. package/dist/codegen/core/TypeAnnotationToTS.js +3 -9
  10. package/dist/codegen/core/UberSchema.js +8 -21
  11. package/dist/codegen/core/index.js +0 -6
  12. package/dist/codegen/generators/AppBuildTimeGlueCodeGenerator.js +2 -7
  13. package/dist/codegen/generators/ArkTSComponentCodeGeneratorArkTS.js +3 -6
  14. package/dist/codegen/generators/ArkTSComponentCodeGeneratorCAPI.js +3 -6
  15. package/dist/codegen/generators/CppComponentCodeGenerator.js +3 -6
  16. package/dist/codegen/generators/LibGlueCodeGenerator.js +2 -8
  17. package/dist/codegen/generators/NativeModuleCodeGenerator.js +1 -7
  18. package/dist/codegen/generators/SharedComponentCodeGenerator.js +0 -6
  19. package/dist/codegen/generators/UberGeneratorV1.js +0 -6
  20. package/dist/codegen/generators/UberGeneratorV2.js +0 -6
  21. package/dist/codegen/generators/index.js +0 -6
  22. package/dist/codegen/index.js +0 -6
  23. package/dist/codegen/templates/BaseComponentInstanceHTemplate.js +0 -6
  24. package/dist/codegen/templates/BasePackageHTemplate.js +12 -7
  25. package/dist/codegen/templates/ComponentDescriptorHTemplate.js +1 -6
  26. package/dist/codegen/templates/ComponentJSIBinderHTemplate.js +15 -6
  27. package/dist/codegen/templates/ComponentUtilsTSTemplate.js +0 -6
  28. package/dist/codegen/templates/IndexTSTemplate.js +0 -6
  29. package/dist/codegen/templates/RNOHGeneratedPackageHTemplate.js +12 -7
  30. package/dist/codegen/templates/TurboModuleCppTemplate.js +0 -6
  31. package/dist/codegen/templates/TurboModuleHTemplate.js +0 -6
  32. package/dist/codegen/templates/TurboModuleSpecTSTemplate.js +0 -6
  33. package/dist/codegen/templates/index.js +0 -6
  34. package/dist/commands/bundle-harmony.js +133 -101
  35. package/dist/commands/clean-harmony.js +84 -0
  36. package/dist/commands/codegen-harmony.js +12 -22
  37. package/dist/commands/codegen-lib-harmony.js +15 -25
  38. package/dist/commands/index.js +3 -9
  39. package/dist/commands/init-harmony.js +226 -0
  40. package/dist/commands/init.js +703 -0
  41. package/dist/commands/link-harmony.js +12 -16
  42. package/dist/commands/run-harmony.js +438 -0
  43. package/dist/commands/types.js +2 -0
  44. package/dist/commands/verify-package-harmony.js +7 -11
  45. package/dist/core/AbsolutePath.js +3 -6
  46. package/dist/core/CodegenConfig.js +3 -11
  47. package/dist/core/DescriptiveError.js +7 -9
  48. package/dist/core/FileSystem.js +0 -6
  49. package/dist/core/OHPackageJSON5.js +0 -6
  50. package/dist/core/PackageJSON.js +4 -7
  51. package/dist/core/ProjectDependenciesManager.js +6 -14
  52. package/dist/core/ValidationError.js +0 -6
  53. package/dist/core/ValueObject.js +0 -6
  54. package/dist/core/fs.js +16 -10
  55. package/dist/core/index.js +0 -6
  56. package/dist/index.js +3 -9
  57. package/dist/init/templates/AppScopeAppJSON5Template.js +30 -0
  58. package/dist/init/templates/AppScopeStringVarTemplate.js +28 -0
  59. package/dist/init/templates/EntryIndexTemplate.js +65 -0
  60. package/dist/init/templates/EntryStringVarTemplate.js +38 -0
  61. package/dist/init/templates/HvigorConfigJson5Template.js +44 -0
  62. package/dist/init/templates/MetroConfigTemplate.js +47 -0
  63. package/dist/init/templates/OhPackageJson5Template.js +37 -0
  64. package/dist/init/templates/harmony/AppScope/app.json5 +10 -0
  65. package/dist/init/templates/harmony/AppScope/resources/base/element/string.json +8 -0
  66. package/dist/init/templates/harmony/AppScope/resources/base/media/app_icon.png +0 -0
  67. package/dist/init/templates/harmony/build-profile.json5 +36 -0
  68. package/dist/init/templates/harmony/codelinter.json +32 -0
  69. package/dist/init/templates/harmony/entry/build-profile.json5 +18 -0
  70. package/dist/init/templates/harmony/entry/gitignore +7 -0
  71. package/dist/init/templates/harmony/entry/hvigorfile.ts +13 -0
  72. package/dist/init/templates/harmony/entry/oh-package.json5 +9 -0
  73. package/dist/init/templates/harmony/entry/src/main/cpp/CMakeLists.txt +27 -0
  74. package/dist/init/templates/harmony/entry/src/main/cpp/PackageProvider.cpp +13 -0
  75. package/dist/init/templates/harmony/entry/src/main/cpp/gitignore +4 -0
  76. package/dist/init/templates/harmony/entry/src/main/ets/PackageProvider.ets +8 -0
  77. package/dist/init/templates/harmony/entry/src/main/ets/codegen/gitignore +2 -0
  78. package/dist/init/templates/harmony/entry/src/main/ets/entryability/EntryAbility.ets +11 -0
  79. package/dist/init/templates/harmony/entry/src/main/ets/gitignore +1 -0
  80. package/dist/init/templates/harmony/entry/src/main/ets/pages/.gitkeep +0 -0
  81. package/dist/init/templates/harmony/entry/src/main/ets/workers/RNOHWorker.ets +16 -0
  82. package/dist/init/templates/harmony/entry/src/main/module.json5 +58 -0
  83. package/dist/init/templates/harmony/entry/src/main/resources/base/element/color.json +8 -0
  84. package/dist/init/templates/harmony/entry/src/main/resources/base/element/string.json +16 -0
  85. package/dist/init/templates/harmony/entry/src/main/resources/base/media/background.png +0 -0
  86. package/dist/init/templates/harmony/entry/src/main/resources/base/media/foreground.png +0 -0
  87. package/dist/init/templates/harmony/entry/src/main/resources/base/media/layered_image.json +7 -0
  88. package/dist/init/templates/harmony/entry/src/main/resources/base/media/startIcon.png +0 -0
  89. package/dist/init/templates/harmony/entry/src/main/resources/base/profile/main_pages.json +5 -0
  90. package/dist/init/templates/harmony/entry/src/main/resources/gitignore +1 -0
  91. package/dist/init/templates/harmony/entry/src/ohosTest/ets/test/List.test.ets +2 -0
  92. package/dist/init/templates/harmony/entry/src/ohosTest/module.json5 +13 -0
  93. package/dist/init/templates/harmony/gitignore +16 -0
  94. package/dist/init/templates/harmony/hvigor/hvigor-config.json5 +22 -0
  95. package/dist/init/templates/harmony/hvigorfile.ts +7 -0
  96. package/dist/init/templates/index.js +21 -0
  97. package/dist/io/CliExecutor.js +56 -29
  98. package/dist/io/Logger.js +71 -47
  99. package/dist/io/RealFS.js +10 -6
  100. package/dist/io/TarGz.js +3 -10
  101. package/dist/io/__fixtures__.js +8 -8
  102. package/dist/io/fsUtils.js +1 -8
  103. package/dist/io/index.js +1 -6
  104. package/dist/package-verifier/checks/HarmonyDirContainsOnlyHarsCheck.js +1 -8
  105. package/dist/package-verifier/checks/HarmonyDirExistsCheck.js +1 -8
  106. package/dist/package-verifier/checks/NpmAnAndOhPackageVersionsAreEqual.js +1 -8
  107. package/dist/package-verifier/checks/OhPackageNameFollowsNamingConventionCheck.js +1 -8
  108. package/dist/package-verifier/checks/index.js +0 -6
  109. package/dist/package-verifier/index.js +0 -6
  110. package/dist/package-verifier/types.js +0 -6
  111. package/dist/package-verifier/verify-package.js +5 -14
  112. package/harmony/rnoh-hvigor-plugin-0.77.18.tgz +0 -0
  113. package/jest.config.js +0 -7
  114. package/package.json +20 -16
  115. package/react-native.config.js +0 -7
  116. package/scripts/copy-template.js +18 -0
  117. package/src/assetResolver.ts +117 -11
  118. package/src/autolinking/Autolinking.test.ts +54 -18
  119. package/src/autolinking/Autolinking.ts +32 -31
  120. package/src/autolinking/index.ts +1 -8
  121. package/src/codegen/core/CodeGenerator.ts +0 -7
  122. package/src/codegen/core/CodegenError.ts +0 -7
  123. package/src/codegen/core/EventUtils.ts +3 -12
  124. package/src/codegen/core/TypeAnnotationToTS.test.ts +0 -7
  125. package/src/codegen/core/TypeAnnotationToTS.ts +3 -8
  126. package/src/codegen/core/UberSchema.ts +9 -22
  127. package/src/codegen/core/index.ts +0 -7
  128. package/src/codegen/generators/AppBuildTimeGlueCodeGenerator.ts +5 -8
  129. package/src/codegen/generators/ArkTSComponentCodeGeneratorArkTS.ts +3 -7
  130. package/src/codegen/generators/ArkTSComponentCodeGeneratorCAPI.ts +3 -7
  131. package/src/codegen/generators/CppComponentCodeGenerator.ts +3 -7
  132. package/src/codegen/generators/LibGlueCodeGenerator.ts +2 -9
  133. package/src/codegen/generators/NativeModuleCodeGenerator.ts +1 -8
  134. package/src/codegen/generators/SharedComponentCodeGenerator.ts +0 -7
  135. package/src/codegen/generators/UberGeneratorV1.ts +0 -7
  136. package/src/codegen/generators/UberGeneratorV2.ts +0 -7
  137. package/src/codegen/generators/index.ts +0 -7
  138. package/src/codegen/index.ts +0 -7
  139. package/src/codegen/templates/BaseComponentInstanceHTemplate.ts +0 -7
  140. package/src/codegen/templates/BasePackageHTemplate.ts +13 -8
  141. package/src/codegen/templates/ComponentDescriptorHTemplate.ts +1 -7
  142. package/src/codegen/templates/ComponentJSIBinderHTemplate.ts +24 -8
  143. package/src/codegen/templates/ComponentUtilsTSTemplate.ts +0 -7
  144. package/src/codegen/templates/IndexTSTemplate.ts +0 -7
  145. package/src/codegen/templates/RNOHGeneratedPackageHTemplate.ts +13 -8
  146. package/src/codegen/templates/TurboModuleCppTemplate.ts +0 -7
  147. package/src/codegen/templates/TurboModuleHTemplate.ts +0 -7
  148. package/src/codegen/templates/TurboModuleSpecTSTemplate.ts +0 -7
  149. package/src/codegen/templates/index.ts +0 -7
  150. package/src/commands/bundle-harmony.ts +178 -118
  151. package/src/commands/clean-harmony.ts +54 -0
  152. package/src/commands/codegen-harmony.ts +13 -25
  153. package/src/commands/codegen-lib-harmony.ts +16 -28
  154. package/src/commands/index.ts +3 -10
  155. package/src/commands/init-harmony.ts +299 -0
  156. package/src/commands/init.ts +755 -0
  157. package/src/commands/link-harmony.ts +14 -19
  158. package/src/commands/run-harmony.ts +478 -0
  159. package/src/commands/types.ts +14 -0
  160. package/src/commands/verify-package-harmony.ts +9 -12
  161. package/src/core/AbsolutePath.ts +4 -7
  162. package/src/core/CodegenConfig.ts +3 -12
  163. package/src/core/DescriptiveError.ts +8 -15
  164. package/src/core/FileSystem.ts +5 -8
  165. package/src/core/OHPackageJSON5.ts +0 -7
  166. package/src/core/PackageJSON.ts +4 -13
  167. package/src/core/ProjectDependenciesManager.ts +14 -22
  168. package/src/core/ValidationError.ts +0 -7
  169. package/src/core/ValueObject.ts +0 -7
  170. package/src/core/fs.ts +14 -8
  171. package/src/core/index.ts +0 -7
  172. package/src/index.ts +8 -15
  173. package/src/init/templates/AppScopeAppJSON5Template.ts +24 -0
  174. package/src/init/templates/AppScopeStringVarTemplate.ts +22 -0
  175. package/src/init/templates/EntryIndexTemplate.ts +59 -0
  176. package/src/init/templates/EntryStringVarTemplate.ts +31 -0
  177. package/src/init/templates/HvigorConfigJson5Template.ts +40 -0
  178. package/src/init/templates/MetroConfigTemplate.ts +41 -0
  179. package/src/init/templates/OhPackageJson5Template.ts +31 -0
  180. package/src/init/templates/harmony/AppScope/app.json5 +10 -0
  181. package/src/init/templates/harmony/AppScope/resources/base/element/string.json +8 -0
  182. package/src/init/templates/harmony/AppScope/resources/base/media/app_icon.png +0 -0
  183. package/src/init/templates/harmony/build-profile.json5 +36 -0
  184. package/src/init/templates/harmony/codelinter.json +32 -0
  185. package/src/init/templates/harmony/entry/build-profile.json5 +18 -0
  186. package/src/init/templates/harmony/entry/gitignore +7 -0
  187. package/src/init/templates/harmony/entry/hvigorfile.ts +13 -0
  188. package/src/init/templates/harmony/entry/oh-package.json5 +9 -0
  189. package/src/init/templates/harmony/entry/src/main/cpp/CMakeLists.txt +27 -0
  190. package/src/init/templates/harmony/entry/src/main/cpp/PackageProvider.cpp +13 -0
  191. package/src/init/templates/harmony/entry/src/main/cpp/gitignore +4 -0
  192. package/src/init/templates/harmony/entry/src/main/ets/PackageProvider.ets +8 -0
  193. package/src/init/templates/harmony/entry/src/main/ets/codegen/gitignore +2 -0
  194. package/src/init/templates/harmony/entry/src/main/ets/entryability/EntryAbility.ets +11 -0
  195. package/src/init/templates/harmony/entry/src/main/ets/gitignore +1 -0
  196. package/src/init/templates/harmony/entry/src/main/ets/pages/.gitkeep +0 -0
  197. package/src/init/templates/harmony/entry/src/main/ets/workers/RNOHWorker.ets +16 -0
  198. package/src/init/templates/harmony/entry/src/main/module.json5 +58 -0
  199. package/src/init/templates/harmony/entry/src/main/resources/base/element/color.json +8 -0
  200. package/src/init/templates/harmony/entry/src/main/resources/base/element/string.json +16 -0
  201. package/src/init/templates/harmony/entry/src/main/resources/base/media/background.png +0 -0
  202. package/src/init/templates/harmony/entry/src/main/resources/base/media/foreground.png +0 -0
  203. package/src/init/templates/harmony/entry/src/main/resources/base/media/layered_image.json +7 -0
  204. package/src/init/templates/harmony/entry/src/main/resources/base/media/startIcon.png +0 -0
  205. package/src/init/templates/harmony/entry/src/main/resources/base/profile/main_pages.json +5 -0
  206. package/src/init/templates/harmony/entry/src/main/resources/gitignore +1 -0
  207. package/src/init/templates/harmony/entry/src/ohosTest/ets/test/List.test.ets +2 -0
  208. package/src/init/templates/harmony/entry/src/ohosTest/module.json5 +13 -0
  209. package/src/init/templates/harmony/gitignore +16 -0
  210. package/src/init/templates/harmony/hvigor/hvigor-config.json5 +22 -0
  211. package/src/init/templates/harmony/hvigorfile.ts +7 -0
  212. package/src/init/templates/index.ts +5 -0
  213. package/src/io/CliExecutor.ts +55 -40
  214. package/src/io/Logger.ts +77 -51
  215. package/src/io/RealFS.ts +15 -8
  216. package/src/io/TarGz.ts +1 -8
  217. package/src/io/__fixtures__.ts +15 -18
  218. package/src/io/fsUtils.ts +1 -7
  219. package/src/io/index.ts +1 -7
  220. package/src/package-verifier/checks/HarmonyDirContainsOnlyHarsCheck.ts +0 -7
  221. package/src/package-verifier/checks/HarmonyDirExistsCheck.ts +0 -7
  222. package/src/package-verifier/checks/NpmAnAndOhPackageVersionsAreEqual.ts +0 -7
  223. package/src/package-verifier/checks/OhPackageNameFollowsNamingConventionCheck.ts +0 -7
  224. package/src/package-verifier/checks/index.ts +0 -7
  225. package/src/package-verifier/index.ts +0 -7
  226. package/src/package-verifier/types.ts +0 -7
  227. package/src/package-verifier/verify-package.ts +4 -13
  228. package/tsconfig.build.json +2 -5
  229. package/tsconfig.json +4 -0
  230. package/dist/commands/create-metro-host-constants.js +0 -67
  231. package/dist/commands/pack-harmony.js +0 -106
  232. package/dist/commands/unpack-harmony.js +0 -191
  233. package/src/commands/create-metro-host-constants.ts +0 -55
  234. package/src/commands/pack-harmony.ts +0 -128
  235. package/src/commands/unpack-harmony.ts +0 -240
@@ -1,11 +1,4 @@
1
- /**
2
- * Copyright (c) 2024 Huawei Technologies Co., Ltd.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE-MIT file in the root directory of this source tree.
6
- */
7
-
8
- import { Command } from '@react-native-community/cli-types';
1
+ import { Command } from './types';
9
2
  import { AbsolutePath, DescriptiveError } from '../core';
10
3
  import { Logger, RealFS } from '../io';
11
4
  import { Autolinking } from '../autolinking';
@@ -53,14 +46,16 @@ export const commandLinkHarmony: Command = {
53
46
  default: './oh-package.json5',
54
47
  },
55
48
  {
56
- name: '--exclude-npm-packages [string]',
49
+ name: '--exclude-npm-packages [string...]',
57
50
  description:
58
- "Lists npm package names to be excluded from the autolinking process, separated by semicolons. By default every library is included. Can't be used with --included-npm-packages.",
51
+ "Lists npm package names to be excluded from the autolinking process. By default every library is included. Can't be used with --included-npm-packages.",
52
+ parse: (val, prev) => (prev ? [...prev, val] : [val]),
59
53
  },
60
54
  {
61
- name: '--include-npm-packages [string]',
55
+ name: '--include-npm-packages [string...]',
62
56
  description:
63
- "Lists npm package names to be included from the autolinking process, separated by semicolons. By default every library is included. Can't be used with --excluded-npm-packages.",
57
+ "Lists npm package names to be included from the autolinking process. By default every library is included. Can't be used with --excluded-npm-packages.",
58
+ parse: (val, prev) => (prev ? [...prev, val] : [val]),
64
59
  },
65
60
  ],
66
61
  func: async (_argv, _config, rawArgs: any) => {
@@ -79,14 +74,14 @@ export const commandLinkHarmony: Command = {
79
74
  rawArgs.etsRnohPackagesFactoryPathRelativeToHarmony,
80
75
  ohPackagePathRelativeToHarmony: rawArgs.ohPackagePathRelativeToHarmony,
81
76
  excludedNpmPackageNames: new Set(
82
- rawArgs.excludeNpmPackages
83
- ? (rawArgs.excludeNpmPackages ?? '').split(';')
84
- : undefined
77
+ rawArgs.excludeNpmPackages?.length === 1
78
+ ? rawArgs.excludeNpmPackages[0].split(';')
79
+ : rawArgs.excludeNpmPackages
85
80
  ),
86
81
  includedNpmPackageNames: new Set(
87
- rawArgs.includeNpmPackages
88
- ? (rawArgs.includeNpmPackages ?? '').split(';')
89
- : undefined
82
+ rawArgs.includeNpmPackages?.length === 1
83
+ ? rawArgs.includeNpmPackages[0].split(';')
84
+ : rawArgs.includeNpmPackages
90
85
  ),
91
86
  });
92
87
  const result = autolinking.evaluate(config);
@@ -99,4 +94,4 @@ export const commandLinkHarmony: Command = {
99
94
  throw err;
100
95
  }
101
96
  },
102
- };
97
+ };
@@ -0,0 +1,478 @@
1
+ /**
2
+ * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import { AbsolutePath, DescriptiveError } from '../core';
9
+ import { Logger, RealFS } from '../io';
10
+ import { RealCliExecutor } from '../io/CliExecutor';
11
+ import { Command } from './types';
12
+ import fs from 'fs-extra';
13
+ import crypto from 'node:crypto';
14
+ import JSON5 from 'json5';
15
+ import inquirer from 'inquirer';
16
+ import path from 'path';
17
+ import {
18
+ getDefaultUserTerminal,
19
+ startServerInNewWindow,
20
+ findDevServerPort,
21
+ } from '@react-native-community/cli-tools';
22
+
23
+ const COMMAND_NAME = 'run-harmony';
24
+
25
+ export const commandRunHarmony: Command = {
26
+ name: COMMAND_NAME,
27
+ description: 'Builds your app and starts it on your phone.',
28
+ options: [
29
+ {
30
+ name: '--harmony-project-path <path>',
31
+ description: 'Specifies the root of your OpenHarmony project.',
32
+ default: './harmony',
33
+ },
34
+ {
35
+ name: '--module <string>',
36
+ description: 'Name of the OH module to run.',
37
+ default: 'entry',
38
+ },
39
+ {
40
+ name: '--build-mode <string>',
41
+ description: 'Debug or Release.',
42
+ default: 'debug',
43
+ },
44
+ {
45
+ name: '--product <string>',
46
+ description: 'OpenHarmony product defined in build-profile.json5.',
47
+ default: 'default',
48
+ },
49
+ {
50
+ name: '--ability <string>',
51
+ description: 'Name of the ability to start.',
52
+ default: 'EntryAbility',
53
+ },
54
+ {
55
+ name: '--simulator <string>',
56
+ description: 'The name of the simulator that are currently connected.',
57
+ default: 'undefined',
58
+ },
59
+ {
60
+ name: '--port <number>',
61
+ description: 'The port to use for the device.',
62
+ default: process.env.RCT_METRO_PORT || 8081,
63
+ },
64
+ {
65
+ name: '--no-packager',
66
+ description: 'Do not launch packager while running the app.',
67
+ },
68
+ ],
69
+ func: async (_argv, _config, rawArgs: any) => {
70
+ const logger = new Logger();
71
+ try {
72
+ const DEVECO_SDK_HOME = process.env.DEVECO_SDK_HOME;
73
+ if (!DEVECO_SDK_HOME) {
74
+ throw new DescriptiveError({
75
+ whatHappened: 'DEVECO_SDK_HOME environment variable is not set',
76
+ whatCanUserDo: [
77
+ process.platform === 'darwin'
78
+ ? 'On MacOS, the contents directory is typically located at: /Applications/DevEco-Studio.app/Contents/sdk. Set this path as the value of DEVECO_SDK_HOME'
79
+ : "Locate the installation directory of DevEco Studio, and set its 'sdk' subdirectory as the value of DEVECO_SDK_HOME environment variable.",
80
+ ],
81
+ });
82
+ }
83
+ const fs = new RealFS();
84
+ const sdkPath = new AbsolutePath(DEVECO_SDK_HOME);
85
+ const sdkDirectoryNames = fs
86
+ .readDirentsSync(sdkPath)
87
+ .flatMap((dirent) => {
88
+ if (dirent.isDirectory()) {
89
+ return [dirent.name];
90
+ } else {
91
+ return [];
92
+ }
93
+ });
94
+ if (sdkDirectoryNames.length === 0) {
95
+ throw new DescriptiveError({
96
+ whatHappened: `${sdkPath.toString()} has no directories`,
97
+ unexpected: true,
98
+ });
99
+ }
100
+ const sdkToolchainsPath = sdkPath.copyWithNewSegment(
101
+ sdkDirectoryNames[0],
102
+ 'openharmony',
103
+ 'toolchains'
104
+ );
105
+ const cli = new RealCliExecutor();
106
+ const harmonyProjectPath = new AbsolutePath(rawArgs.harmonyProjectPath);
107
+ const productName: string = rawArgs.product;
108
+ const buildMode: string = rawArgs.buildMode;
109
+ const moduleName: string = rawArgs.module;
110
+ const abilityName: string = rawArgs.ability;
111
+ const simulatorName: string = rawArgs.simulator;
112
+ const defaultPort: number = rawArgs.port;
113
+ const packager: boolean = rawArgs.packager;
114
+ const devEcoStudioToolsPath = new AbsolutePath(
115
+ DEVECO_SDK_HOME
116
+ ).copyWithNewSegment('..', 'tools');
117
+ if (!fs.existsSync(devEcoStudioToolsPath)) {
118
+ throw new DescriptiveError({
119
+ whatHappened: `${devEcoStudioToolsPath.toString()} doesn't exist`,
120
+ });
121
+ }
122
+ const bundleName = JSON5.parse(
123
+ fs.readTextSync(
124
+ harmonyProjectPath.copyWithNewSegment('AppScope', 'app.json5')
125
+ )
126
+ ).app.bundleName;
127
+
128
+ const selectDevice = async (deviceAndSimulatorInfos: string) => {
129
+ const lines = deviceAndSimulatorInfos.trim().split('\n');
130
+ const availableDevices = lines.map((line) => {
131
+ const parts = line.split(/\s+/);
132
+ return {
133
+ name: parts[0],
134
+ method: parts[1],
135
+ state: parts[2],
136
+ locate: parts[3],
137
+ connectTool: parts[4]
138
+ };
139
+ });
140
+ if (simulatorName !== 'undefined') {
141
+ const isRequestedDeviceAvailable = availableDevices.some((deviceOrSimulator) => deviceOrSimulator.name === simulatorName);
142
+ if (!isRequestedDeviceAvailable) {
143
+ throw new DescriptiveError({
144
+ whatHappened: `Simulator with name "${simulatorName}" not found.`,
145
+ whatCanUserDo: [
146
+ 'Please confirm whether the entered simulator name has been activated.',
147
+ ]
148
+ });
149
+ }
150
+ return simulatorName;
151
+ }
152
+ const connectedDevices = availableDevices.filter((deviceOrSimulator) => deviceOrSimulator.state === 'Connected');
153
+ if (connectedDevices.length > 1) {
154
+ const answers = await inquirer.prompt([
155
+ {
156
+ type: 'list',
157
+ name: 'selectedDeviceIndex',
158
+ message: 'Please select a device:',
159
+ choices: connectedDevices.map((deviceOrSimulator, index) => `${index + 1}. ${deviceOrSimulator.name}`)
160
+ }
161
+ ])
162
+ return connectedDevices[parseInt(answers.selectedDeviceIndex) - 1].name;
163
+ } else if (connectedDevices.length === 1) {
164
+ return connectedDevices[0].name;
165
+ } else {
166
+ throw new DescriptiveError({
167
+ whatHappened: `No devices are connected in the current environment.`,
168
+ whatCanUserDo: [
169
+ 'Please connect your HarmonyOS device or open the simulator.',
170
+ ]
171
+ });
172
+ }
173
+ };
174
+
175
+ const deviceAndSimulatorInfo: string = await cli.run(
176
+ sdkToolchainsPath.copyWithNewSegment('hdc').toString(),
177
+ {
178
+ args: ['list', 'targets', '-v'],
179
+ cwd: harmonyProjectPath,
180
+ }
181
+ );
182
+
183
+ const deviceOrSimulatorName = await selectDevice(deviceAndSimulatorInfo)
184
+
185
+ let currentPort: number = defaultPort;
186
+ if (packager) {
187
+ const root: string = _config.root || '.';
188
+ const reactNativePath: string = _config.reactNativePath || path.dirname(
189
+ require.resolve('react-native', { paths: [root] }),
190
+ );
191
+ const { port: newPort, startPackager } = await findDevServerPort(
192
+ defaultPort,
193
+ root,
194
+ );
195
+
196
+ if (newPort !== 8081) {
197
+ await trySetMetroPort(harmonyProjectPath.copyWithNewSegment(
198
+ 'entry', 'src', 'main', 'ets', 'pages', 'Index.ets').toString(), newPort);
199
+ }
200
+ if (startPackager) {
201
+ startServerInNewWindow(
202
+ newPort,
203
+ root,
204
+ reactNativePath,
205
+ getDefaultUserTerminal(),
206
+ );
207
+ }
208
+ currentPort = newPort;
209
+ }
210
+
211
+ const runJob = async (name: string, job: () => Promise<void>) => {
212
+ const stop = logger.start((s) => s.bold(name));
213
+ logger.info((s) => s.bold(`${name} started`));
214
+ try {
215
+ await job();
216
+ logger.succeed((s) => s.bold(`${name} finished`));
217
+ } catch (err) {
218
+ if (err instanceof DescriptiveError) {
219
+ throw err;
220
+ }
221
+ throw new DescriptiveError({
222
+ whatHappened: `${name} failed`,
223
+ extraData: err,
224
+ });
225
+ } finally {
226
+ stop();
227
+ }
228
+ };
229
+
230
+ await runJob('[1/3] installing dependencies', async () => {
231
+ let ohpmPath = devEcoStudioToolsPath
232
+ .copyWithNewSegment('ohpm', 'bin', 'ohpm');
233
+ if (process.platform === 'win32') {
234
+ ohpmPath = devEcoStudioToolsPath
235
+ .copyWithNewSegment('ohpm', 'bin', 'ohpm.bat');
236
+ }
237
+ await cli.run(
238
+ process.platform === 'win32' ? `"${ohpmPath.toString()}"` :
239
+ ohpmPath.toString(),
240
+ {
241
+ args: [
242
+ 'install',
243
+ '--all',
244
+ '--strict_ssl',
245
+ 'true',
246
+ ],
247
+ cwd: harmonyProjectPath,
248
+ shell: true,
249
+ onArgsStringified: (commandWithArgs) => {
250
+ logger.debug((s) => s.bold(s.gray(commandWithArgs)));
251
+ },
252
+ onStdout: (msg) => {
253
+ logger.debug((s) => s.gray(msg.trimEnd()));
254
+ },
255
+ onStderr(msg) {
256
+ logger.debug(() => msg.trimEnd());
257
+ },
258
+ }
259
+ );
260
+ });
261
+ await runJob('[2/3] building app', async () => {
262
+ let nodePath = devEcoStudioToolsPath
263
+ .copyWithNewSegment('node', 'bin', 'node');
264
+ if (!fs.existsSync(nodePath)) {
265
+ nodePath = devEcoStudioToolsPath.copyWithNewSegment('node', 'node');
266
+ }
267
+ let hvigorPathRaw = devEcoStudioToolsPath.copyWithNewSegment('hvigor', 'bin', 'hvigorw.js').toString();
268
+ const hvigorPath = process.platform === 'win32' ? `"${hvigorPathRaw}"` : hvigorPathRaw;
269
+ await cli.run(
270
+ process.platform === 'win32' ? `"${nodePath.toString()}"` :
271
+ nodePath.toString(),
272
+ {
273
+ args: [
274
+ hvigorPath,
275
+ `-p`,
276
+ `module=${moduleName}@default`,
277
+ `-p`,
278
+ `product=${productName}`,
279
+ `-p`,
280
+ `buildMode=${buildMode}`,
281
+ `-p`,
282
+ `requiredDeviceType=phone`,
283
+ `assembleHap`,
284
+ ],
285
+ cwd: harmonyProjectPath,
286
+ shell: true,
287
+ onArgsStringified: (commandWithArgs) => {
288
+ logger.debug((s) => s.bold(s.gray(commandWithArgs)));
289
+ },
290
+ onStdout: (msg) => {
291
+ logger.debug((s) => s.gray(msg.trimEnd()));
292
+ },
293
+ onStderr(msg) {
294
+ logger.debug(() => msg.trimEnd());
295
+ },
296
+ }
297
+ );
298
+ });
299
+ await runJob('[3/3] installing and opening app', async () => {
300
+ const tmpDirName = generateRandomString();
301
+ const ohosTmpDirPath = `data/local/tmp/${tmpDirName}`;
302
+
303
+ const exec = async (command: string, args: string[]) => {
304
+ const result = await cli.run(command, {
305
+ args: args,
306
+ shell: true,
307
+ onArgsStringified: (commandWithArgs) =>
308
+ logger.debug((s) => s.bold(s.gray(commandWithArgs))),
309
+ });
310
+ if (result.startsWith('[Fail]')) {
311
+ throw new DescriptiveError({ whatHappened: result });
312
+ }
313
+ if (result) {
314
+ logger.debug((s) => s.gray(result.trimEnd() + '\n'));
315
+ } else {
316
+ logger.debug(() => '');
317
+ }
318
+ return result;
319
+ };
320
+
321
+ const hdcPathStrRaw = sdkToolchainsPath
322
+ .copyWithNewSegment('hdc')
323
+ .toString();
324
+ const hdcPathStr = process.platform === 'win32' ? `"${hdcPathStrRaw.toString()}"` : hdcPathStrRaw;
325
+
326
+ const tryRemoveForwardPorting = async () => {
327
+ let fportInfo: string = '';
328
+ await cli.run(
329
+ hdcPathStrRaw,
330
+ {
331
+ args: ['fport', 'ls'],
332
+ cwd: harmonyProjectPath,
333
+ onStdout: (msg) => {
334
+ fportInfo += msg;
335
+ },
336
+ onStderr: (msg) => {
337
+ logger.debug((s) => s.gray(msg.trimEnd()));
338
+ },
339
+ });
340
+ if (fportInfo.includes(`tcp:${currentPort} tcp:${currentPort}`)) {
341
+ await exec(hdcPathStr, [
342
+ 'fport',
343
+ 'rm',
344
+ `tcp:${currentPort}`,
345
+ `tcp:${currentPort}`
346
+ ]);
347
+ }
348
+ };
349
+
350
+ await exec(hdcPathStr, ['-t', deviceOrSimulatorName, 'shell', 'aa', 'force-stop', bundleName]);
351
+ try {
352
+ await exec(hdcPathStr, ['-t', deviceOrSimulatorName, 'shell', 'mkdir', ohosTmpDirPath]);
353
+ let hapName = `${moduleName}-default-signed.hap`;
354
+ if (simulatorName !== 'undefined') {
355
+ hapName = `${moduleName}-default-unsigned.hap`;
356
+ }
357
+ await exec(hdcPathStr, [
358
+ '-t',
359
+ deviceOrSimulatorName,
360
+ 'file',
361
+ 'send',
362
+ harmonyProjectPath
363
+ .copyWithNewSegment(
364
+ moduleName,
365
+ 'build',
366
+ 'default',
367
+ 'outputs',
368
+ 'default',
369
+ hapName
370
+ )
371
+ .toString(),
372
+ ohosTmpDirPath,
373
+ ]);
374
+ const installationResult = await exec(hdcPathStr, [
375
+ '-t',
376
+ deviceOrSimulatorName,
377
+ 'shell',
378
+ 'bm',
379
+ 'install',
380
+ '-p',
381
+ ohosTmpDirPath,
382
+ ]);
383
+ if (installationResult.includes('failed to install')) {
384
+ throw new DescriptiveError({
385
+ whatHappened: 'Installation failed.',
386
+ whatCanUserDo: [
387
+ `If an application with the same bundle name is already installed, try uninstalling it:\n${hdcPathStr} shell bm uninstall -n ${bundleName}`,
388
+ ],
389
+ });
390
+ }
391
+ } finally {
392
+ await exec(hdcPathStr, ['-t', deviceOrSimulatorName, 'shell', 'rm', '-rf', ohosTmpDirPath]);
393
+ }
394
+ await exec(hdcPathStr, [
395
+ '-t',
396
+ deviceOrSimulatorName,
397
+ 'shell',
398
+ 'aa',
399
+ 'start',
400
+ '-a',
401
+ abilityName,
402
+ '-b',
403
+ bundleName,
404
+ ]);
405
+ await tryRemoveForwardPorting();
406
+ await exec(hdcPathStr, [
407
+ '-t',
408
+ deviceOrSimulatorName,
409
+ 'rport',
410
+ `tcp:${currentPort}`,
411
+ `tcp:${currentPort}`
412
+ ]);
413
+ });
414
+ } catch (err) {
415
+ if (err instanceof DescriptiveError) {
416
+ logger.descriptiveError(
417
+ new DescriptiveError({
418
+ whatHappened: err.getMessage(),
419
+ whatCanUserDo: [
420
+ ...err.getSuggestions(),
421
+ 'Try building and running the app from DevEco studio.',
422
+ ],
423
+ extraData: err.getRawData().extraData,
424
+ })
425
+ );
426
+ } else {
427
+ throw err;
428
+ }
429
+ }
430
+ },
431
+ };
432
+
433
+ function generateRandomString(length: number = 32): string {
434
+ const chars: string = '0123456789abcdefghijklmnopqrstuvwxyz';
435
+ let result: string = '';
436
+ const randomValues = new Uint8Array(length);
437
+ crypto.getRandomValues(randomValues);
438
+ for (let i = 0; i < length; i++) {
439
+ const randomIndex = randomValues[i] % chars.length;
440
+ result += chars[randomIndex];
441
+ }
442
+ return result;
443
+ }
444
+
445
+ async function trySetMetroPort(filePath: string, port: number): Promise<void> {
446
+ let content = await fs.readFile(filePath, 'utf-8');
447
+
448
+ const reFromServerIp = /MetroJSBundleProvider\.fromServerIp\(\s*"([^"]+)"\s*,\s*(\d+)\s*\)/;
449
+ if (reFromServerIp.test(content)) {
450
+ content = content.replace(reFromServerIp, (_match: any, host: any) => {
451
+ return `MetroJSBundleProvider.fromServerIp("${host}", ${port})`;
452
+ });
453
+ await fs.writeFile(filePath, content, 'utf-8');
454
+ return;
455
+ }
456
+
457
+ const reNewProvider = /new\s+MetroJSBundleProvider\s*\(\s*\)/;
458
+ if (reNewProvider.test(content)) {
459
+ content = content.replace(reNewProvider, () => {
460
+ return `MetroJSBundleProvider.fromServerIp("localhost", ${port}),\n new MetroJSBundleProvider()`;
461
+ });
462
+ await fs.writeFile(filePath, content, 'utf-8');
463
+ return;
464
+ }
465
+
466
+ throw new DescriptiveError({
467
+ whatHappened: `Unable to set the specified port [${port}] for the Metro server automatically.`,
468
+ whatCanUserDo: [
469
+ `Please manually add "MetroJSBundleProvider.fromServerIp("localhost", ${port})" in the "new AnyJSBundleProvider" section of your ${filePath} file.
470
+ e.g:
471
+ new AnyJSBundleProvider([
472
+ MetroJSBundleProvider.fromServerIp("localhost", ${port}),
473
+ new MetroJSBundleProvider(),
474
+ new ResourceJSBundleProvider(this.rnohCoreContext.uiAbilityContext.resourceManager, 'hermes_bundle.hbc'),
475
+ ])`
476
+ ],
477
+ });
478
+ }
@@ -0,0 +1,14 @@
1
+ import { Command as CLICommand } from '@react-native-community/cli-types';
2
+
3
+ // RNOH patch: The parse function in the Command.options type is missing an extra argument in @react-native-community/cli-types.
4
+ // @react-native-community/cli parses options with Commander.js, which allows defining a custom parse function. This function
5
+ // receives two arguments: the value to parse and the previous values. The default parse function in the CLI is defined as (val) => val,
6
+ // which makes parsing multiple values impossible because this function will always return the last value.
7
+ export type Command = Omit<CLICommand, 'options'> & {
8
+ options: Array<{
9
+ name: string;
10
+ description: string;
11
+ default?: any;
12
+ parse?: (val: string, prev: any) => any;
13
+ }>;
14
+ };
@@ -1,11 +1,4 @@
1
- /**
2
- * Copyright (c) 2024 Huawei Technologies Co., Ltd.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE-MIT file in the root directory of this source tree.
6
- */
7
-
8
- import { Command } from '@react-native-community/cli-types';
1
+ import { Command } from './types';
9
2
  import { getLoader, Loader } from '@react-native-community/cli-tools';
10
3
  import chalk from 'chalk';
11
4
  import { DescriptiveError, AbsolutePath } from '../core';
@@ -25,8 +18,9 @@ export const commandVerifyPackageHarmony: Command = {
25
18
  description: 'Disable har verification',
26
19
  },
27
20
  {
28
- name: '--skip-checks <string>',
29
- description: 'Disable certain checks by their names separated by ";"',
21
+ name: '--skip-checks <string...>',
22
+ description: 'Disable certain checks by their names',
23
+ parse: (val, prev) => (prev ? [...prev, val] : [val]),
30
24
  },
31
25
  ],
32
26
  func: async (argv, config, rawArgs: any) => {
@@ -82,13 +76,16 @@ function validateArgs(args: any): Args {
82
76
  if (!args.packagePath) {
83
77
  throw new DescriptiveError({
84
78
  whatHappened: 'package-path is undefined',
85
- whatCanUserDo: { default: ['Please provide --package-path'] },
79
+ whatCanUserDo: ['Please provide --package-path'],
86
80
  });
87
81
  }
88
82
  return {
89
83
  packagePath: new AbsolutePath(args.packagePath),
90
84
  hasHarmonyCode: args.harmonyCode,
91
- checkNamesToSkip: ((args.skipChecks ?? '') as string).split(';'),
85
+ checkNamesToSkip:
86
+ args.skipChecks.length === 1
87
+ ? args.skipChecks[0].split(';')
88
+ : args.skipChecks,
92
89
  };
93
90
  }
94
91
 
@@ -1,10 +1,3 @@
1
- /**
2
- * Copyright (c) 2024 Huawei Technologies Co., Ltd.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE-MIT file in the root directory of this source tree.
6
- */
7
-
8
1
  import pathUtils from 'node:path';
9
2
  import { ValueObject } from './ValueObject';
10
3
 
@@ -39,6 +32,10 @@ export class AbsolutePath implements ValueObject {
39
32
  return null;
40
33
  }
41
34
 
35
+ getBasename(): string {
36
+ return pathUtils.basename(this.value);
37
+ }
38
+
42
39
  getDirectoryPath(): AbsolutePath {
43
40
  const dirPath = pathUtils.extname(this.value)
44
41
  ? pathUtils.dirname(this.value)
@@ -1,10 +1,3 @@
1
- /**
2
- * Copyright (c) 2024 Huawei Technologies Co., Ltd.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE-MIT file in the root directory of this source tree.
6
- */
7
-
8
1
  import fs from 'node:fs';
9
2
  import { AbsolutePath } from './AbsolutePath';
10
3
  import { findFilePathsWithExtensions } from '../io';
@@ -34,11 +27,9 @@ export class CodegenConfig {
34
27
  if (!fs.existsSync(specPath.getValue())) {
35
28
  throw new DescriptiveError({
36
29
  whatHappened: `No such file or directory: ${specPath.getValue()}`,
37
- whatCanUserDo: {
38
- default: [
39
- `Please verify "${packageName}/package.json::harmony::codegenConfig". If you are not the maintainer of this package, please report this problem to the package maintainer.`,
40
- ],
41
- },
30
+ whatCanUserDo: [
31
+ `Please verify "${packageName}/package.json::harmony::codegenConfig". If you are not the maintainer of this package, please report this problem to the package maintainer.`,
32
+ ],
42
33
  });
43
34
  }
44
35
  if (fs.lstatSync(specPath.getValue()).isDirectory()) {
@@ -1,20 +1,9 @@
1
- /**
2
- * Copyright (c) 2024 Huawei Technologies Co., Ltd.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE-MIT file in the root directory of this source tree.
6
- */
7
-
8
1
  export class DescriptiveError extends Error {
9
2
  constructor(
10
3
  private data:
11
4
  | {
12
5
  whatHappened: string;
13
- whatCanUserDo: {
14
- default?: string[];
15
- rnAppDeveloper?: string[];
16
- rnPackageDeveloper?: string[];
17
- };
6
+ whatCanUserDo?: string[];
18
7
  extraData?: any;
19
8
  }
20
9
  | {
@@ -34,14 +23,18 @@ export class DescriptiveError extends Error {
34
23
  return this.data.whatHappened;
35
24
  }
36
25
 
37
- getSuggestionsByRole() {
26
+ getSuggestions() {
38
27
  if ('whatCanUserDo' in this.data) {
39
- return this.data.whatCanUserDo;
28
+ return this.data.whatCanUserDo ?? [];
40
29
  } else {
41
- return null;
30
+ return [];
42
31
  }
43
32
  }
44
33
 
34
+ getRawData() {
35
+ return this.data;
36
+ }
37
+
45
38
  getDetails(): string {
46
39
  if (!this.data.extraData) {
47
40
  return '';