@react-native-oh/react-native-harmony-cli 0.0.36 → 0.0.40

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 (137) hide show
  1. package/README.md +11 -11
  2. package/dist/assetResolver.js +74 -43
  3. package/dist/autolinking/Autolinking.js +183 -179
  4. package/dist/codegen/core/CodegenError.js +23 -3
  5. package/dist/codegen/core/EventUtils.js +3 -3
  6. package/dist/codegen/core/TypeAnnotationToTS.js +28 -24
  7. package/dist/codegen/core/UberSchema.js +96 -57
  8. package/dist/codegen/generators/AppBuildTimeGlueCodeGenerator.js +42 -28
  9. package/dist/codegen/generators/ArkTSComponentCodeGeneratorArkTS.js +34 -27
  10. package/dist/codegen/generators/ArkTSComponentCodeGeneratorCAPI.js +33 -25
  11. package/dist/codegen/generators/CppComponentCodeGenerator.js +28 -23
  12. package/dist/codegen/generators/LibGlueCodeGenerator.js +29 -26
  13. package/dist/codegen/generators/NativeModuleCodeGenerator.js +30 -25
  14. package/dist/codegen/generators/SharedComponentCodeGenerator.js +15 -15
  15. package/dist/codegen/generators/UberGeneratorV1.js +24 -18
  16. package/dist/codegen/generators/UberGeneratorV2.js +36 -28
  17. package/dist/codegen/templates/BaseComponentInstanceHTemplate.js +24 -50
  18. package/dist/codegen/templates/BasePackageHTemplate.js +21 -109
  19. package/dist/codegen/templates/ComponentDescriptorHTemplate.js +8 -53
  20. package/dist/codegen/templates/ComponentJSIBinderHTemplate.js +27 -75
  21. package/dist/codegen/templates/ComponentUtilsTSTemplate.js +29 -162
  22. package/dist/codegen/templates/IndexTSTemplate.js +17 -37
  23. package/dist/codegen/templates/RNOHGeneratedPackageHTemplate.js +24 -108
  24. package/dist/codegen/templates/TurboModuleCppTemplate.js +15 -38
  25. package/dist/codegen/templates/TurboModuleHTemplate.js +11 -32
  26. package/dist/codegen/templates/TurboModuleSpecTSTemplate.js +19 -52
  27. package/dist/commands/bundle-harmony.js +138 -53
  28. package/dist/commands/codegen-harmony.js +175 -104
  29. package/dist/commands/codegen-lib-harmony.js +116 -76
  30. package/dist/commands/create-metro-host-constants.js +47 -18
  31. package/dist/commands/init.js +961 -537
  32. package/dist/commands/link-harmony.js +71 -33
  33. package/dist/commands/pack-harmony.js +108 -47
  34. package/dist/commands/run-harmony.js +520 -352
  35. package/dist/commands/unpack-harmony.js +198 -105
  36. package/dist/commands/verify-package-harmony.js +108 -54
  37. package/dist/core/AbsolutePath.js +47 -31
  38. package/dist/core/CodegenConfig.js +22 -24
  39. package/dist/core/DescriptiveError.js +37 -18
  40. package/dist/core/FileSystem.js +18 -14
  41. package/dist/core/OHPackageJSON5.js +23 -17
  42. package/dist/core/PackageJSON.js +42 -26
  43. package/dist/core/ProjectDependenciesManager.js +96 -46
  44. package/dist/core/ValidationError.js +22 -2
  45. package/dist/core/fs.js +6 -9
  46. package/dist/index.js +1 -1
  47. package/dist/io/CliExecutor.js +98 -46
  48. package/dist/io/Logger.js +46 -40
  49. package/dist/io/RealFS.js +88 -35
  50. package/dist/io/TarGz.js +8 -11
  51. package/dist/io/__fixtures__.js +141 -79
  52. package/dist/io/fsUtils.js +12 -13
  53. package/dist/package-verifier/checks/HarmonyDirContainsOnlyHarsCheck.js +47 -19
  54. package/dist/package-verifier/checks/HarmonyDirExistsCheck.js +41 -13
  55. package/dist/package-verifier/checks/NpmAnAndOhPackageVersionsAreEqual.js +38 -8
  56. package/dist/package-verifier/checks/OhPackageNameFollowsNamingConventionCheck.js +54 -22
  57. package/dist/package-verifier/verify-package.js +132 -55
  58. package/dist/simulator/LaunchSimulator.js +395 -0
  59. package/dist/simulator/index.js +23 -0
  60. package/jest.config.js +12 -12
  61. package/package.json +78 -70
  62. package/react-native.config.js +17 -17
  63. package/tsconfig.build.json +6 -6
  64. package/tsconfig.json +2 -2
  65. package/.prettierrc +0 -6
  66. package/src/assetResolver.ts +0 -134
  67. package/src/autolinking/Autolinking.test.ts +0 -483
  68. package/src/autolinking/Autolinking.ts +0 -382
  69. package/src/autolinking/index.ts +0 -8
  70. package/src/codegen/core/CodeGenerator.ts +0 -16
  71. package/src/codegen/core/CodegenError.ts +0 -10
  72. package/src/codegen/core/EventUtils.ts +0 -23
  73. package/src/codegen/core/TypeAnnotationToTS.test.ts +0 -82
  74. package/src/codegen/core/TypeAnnotationToTS.ts +0 -195
  75. package/src/codegen/core/UberSchema.ts +0 -152
  76. package/src/codegen/core/index.ts +0 -12
  77. package/src/codegen/generators/AppBuildTimeGlueCodeGenerator.ts +0 -120
  78. package/src/codegen/generators/ArkTSComponentCodeGeneratorArkTS.ts +0 -128
  79. package/src/codegen/generators/ArkTSComponentCodeGeneratorCAPI.ts +0 -122
  80. package/src/codegen/generators/CppComponentCodeGenerator.ts +0 -95
  81. package/src/codegen/generators/LibGlueCodeGenerator.ts +0 -98
  82. package/src/codegen/generators/NativeModuleCodeGenerator.ts +0 -124
  83. package/src/codegen/generators/SharedComponentCodeGenerator.ts +0 -57
  84. package/src/codegen/generators/UberGeneratorV1.ts +0 -75
  85. package/src/codegen/generators/UberGeneratorV2.ts +0 -114
  86. package/src/codegen/generators/index.ts +0 -15
  87. package/src/codegen/index.ts +0 -9
  88. package/src/codegen/templates/BaseComponentInstanceHTemplate.ts +0 -128
  89. package/src/codegen/templates/BasePackageHTemplate.ts +0 -147
  90. package/src/codegen/templates/ComponentDescriptorHTemplate.ts +0 -63
  91. package/src/codegen/templates/ComponentJSIBinderHTemplate.ts +0 -121
  92. package/src/codegen/templates/ComponentUtilsTSTemplate.ts +0 -222
  93. package/src/codegen/templates/IndexTSTemplate.ts +0 -62
  94. package/src/codegen/templates/RNOHGeneratedPackageHTemplate.ts +0 -138
  95. package/src/codegen/templates/TurboModuleCppTemplate.ts +0 -61
  96. package/src/codegen/templates/TurboModuleHTemplate.ts +0 -42
  97. package/src/codegen/templates/TurboModuleSpecTSTemplate.ts +0 -101
  98. package/src/codegen/templates/index.ts +0 -16
  99. package/src/commands/bundle-harmony.ts +0 -134
  100. package/src/commands/codegen-harmony.ts +0 -297
  101. package/src/commands/codegen-lib-harmony.ts +0 -389
  102. package/src/commands/create-metro-host-constants.ts +0 -55
  103. package/src/commands/index.ts +0 -16
  104. package/src/commands/init.ts +0 -755
  105. package/src/commands/link-harmony.ts +0 -102
  106. package/src/commands/pack-harmony.ts +0 -128
  107. package/src/commands/run-harmony.ts +0 -478
  108. package/src/commands/types.ts +0 -21
  109. package/src/commands/unpack-harmony.ts +0 -238
  110. package/src/commands/verify-package-harmony.ts +0 -113
  111. package/src/core/AbsolutePath.ts +0 -66
  112. package/src/core/CodegenConfig.ts +0 -67
  113. package/src/core/DescriptiveError.ts +0 -68
  114. package/src/core/FileSystem.ts +0 -57
  115. package/src/core/OHPackageJSON5.ts +0 -30
  116. package/src/core/PackageJSON.ts +0 -104
  117. package/src/core/ProjectDependenciesManager.ts +0 -103
  118. package/src/core/ValidationError.ts +0 -8
  119. package/src/core/ValueObject.ts +0 -9
  120. package/src/core/fs.ts +0 -38
  121. package/src/core/index.ts +0 -17
  122. package/src/index.ts +0 -33
  123. package/src/io/CliExecutor.ts +0 -69
  124. package/src/io/Logger.ts +0 -112
  125. package/src/io/RealFS.ts +0 -62
  126. package/src/io/TarGz.ts +0 -33
  127. package/src/io/__fixtures__.ts +0 -139
  128. package/src/io/fsUtils.ts +0 -44
  129. package/src/io/index.ts +0 -11
  130. package/src/package-verifier/checks/HarmonyDirContainsOnlyHarsCheck.ts +0 -35
  131. package/src/package-verifier/checks/HarmonyDirExistsCheck.ts +0 -31
  132. package/src/package-verifier/checks/NpmAnAndOhPackageVersionsAreEqual.ts +0 -25
  133. package/src/package-verifier/checks/OhPackageNameFollowsNamingConventionCheck.ts +0 -54
  134. package/src/package-verifier/checks/index.ts +0 -11
  135. package/src/package-verifier/index.ts +0 -9
  136. package/src/package-verifier/types.ts +0 -19
  137. package/src/package-verifier/verify-package.ts +0 -123
@@ -1,102 +0,0 @@
1
- /**
2
- * Copyright (c) 2024-2025 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 './types';
9
- import { AbsolutePath, DescriptiveError } from '../core';
10
- import { Logger, RealFS } from '../io';
11
- import { Autolinking } from '../autolinking';
12
-
13
- const COMMAND_NAME = 'link-harmony';
14
-
15
- export const commandLinkHarmony: Command = {
16
- name: COMMAND_NAME,
17
- description:
18
- 'Handles the automatic linking of RNOH libraries. This command is meant to be used by the RNOH HvigorPlugin.',
19
- options: [
20
- {
21
- name: '--harmony-project-path <path>',
22
- description: 'Specifies the root of your OpenHarmony project.',
23
- default: './harmony',
24
- },
25
- {
26
- name: '--node-modules-path <path>',
27
- description:
28
- 'Defines the path to the node_modules directory which holds npm packages.',
29
- default: './node_modules',
30
- },
31
- {
32
- name: '--cmake-autolink-path-relative-to-harmony <path>',
33
- description:
34
- 'Path relative to the root of your OpenHarmony project for the generated CMake file involved in autolinking.',
35
- default: './entry/src/main/cpp/autolinking.cmake',
36
- },
37
- {
38
- name: '--cpp-rnoh-packages-factory-path-relative-to-harmony <path>',
39
- description:
40
- 'Path relative to the root of your OpenHarmony project, for the generated file used to link packages on C++ side.',
41
- default: './entry/src/main/cpp/RNOHPackagesFactory.h',
42
- },
43
- {
44
- name: '--ets-rnoh-packages-factory-path-relative-to-harmony <path>',
45
- description:
46
- 'Path relative to the root of your OpenHarmony project, for the generated file used to link packages on ETS side.',
47
- default: './entry/src/main/ets/RNOHPackagesFactory.ets',
48
- },
49
- {
50
- name: '--oh-package-path-relative-to-harmony <path>',
51
- description:
52
- 'Path to the oh-package.json5 relative to the root of your OpenHarmony project.',
53
- default: './oh-package.json5',
54
- },
55
- {
56
- name: '--exclude-npm-packages [string]',
57
- 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.",
59
- },
60
- {
61
- name: '--include-npm-packages [string]',
62
- 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.",
64
- },
65
- ],
66
- func: async (_argv, _config, rawArgs: any) => {
67
- const logger = new Logger();
68
- const fs = new RealFS();
69
- const autolinking = new Autolinking(fs, logger);
70
- try {
71
- const config = await autolinking.prepareInput({
72
- harmonyProjectPath: new AbsolutePath(rawArgs.harmonyProjectPath),
73
- nodeModulesPath: new AbsolutePath(rawArgs.nodeModulesPath),
74
- cmakeAutolinkPathRelativeToHarmony:
75
- rawArgs.cmakeAutolinkPathRelativeToHarmony,
76
- cppRNOHPackagesFactoryPathRelativeToHarmony:
77
- rawArgs.cppRnohPackagesFactoryPathRelativeToHarmony,
78
- etsRNOHPackagesFactoryPathRelativeToHarmony:
79
- rawArgs.etsRnohPackagesFactoryPathRelativeToHarmony,
80
- ohPackagePathRelativeToHarmony: rawArgs.ohPackagePathRelativeToHarmony,
81
- excludedNpmPackageNames: new Set(
82
- rawArgs.excludeNpmPackages
83
- ? (rawArgs.excludeNpmPackages ?? '').split(';')
84
- : undefined
85
- ),
86
- includedNpmPackageNames: new Set(
87
- rawArgs.includeNpmPackages
88
- ? (rawArgs.includeNpmPackages ?? '').split(';')
89
- : undefined
90
- ),
91
- });
92
- const result = autolinking.evaluate(config);
93
- autolinking.saveAndLogOutput(result);
94
- } catch (err) {
95
- if (err instanceof DescriptiveError && !err.isUnexpected()) {
96
- logger.descriptiveError(err);
97
- return;
98
- }
99
- throw err;
100
- }
101
- },
102
- };
@@ -1,128 +0,0 @@
1
- /**
2
- * Copyright (c) 2024-2025 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 './types';
9
- import { globSync } from 'glob';
10
- import pathUtils from 'path';
11
- import tar from 'tar';
12
- import fs from 'fs';
13
- import { ValidationError } from '../core';
14
- import ignore, { Ignore } from 'ignore';
15
- import JSON5 from 'json5';
16
-
17
- export const commandPackHarmony: Command = {
18
- name: 'pack-harmony',
19
- description: 'Pack native code. Used for package development.',
20
- options: [
21
- {
22
- name: '--oh-module-path <string>',
23
- description: 'Path to the OH module',
24
- },
25
- {
26
- name: '--harmony-dir-path <string>',
27
- description: 'Path to the harmony dir',
28
- },
29
- {
30
- name: '--package-json-path <string>',
31
- description: 'Path to the package.json',
32
- },
33
- ],
34
- func: async (argv, config, args: any) => {
35
- try {
36
- await pack(
37
- pathUtils.resolve(args.harmonyDirPath),
38
- pathUtils.resolve(args.ohModulePath),
39
- pathUtils.resolve(args.packageJsonPath)
40
- );
41
- } catch (err) {
42
- if (err instanceof ValidationError) {
43
- console.error('[ERROR]', err.message);
44
- process.exit(1);
45
- } else {
46
- throw err;
47
- }
48
- }
49
- },
50
- };
51
-
52
- async function pack(
53
- harmonyDirPath: string,
54
- ohModuleDirPath: string,
55
- packageJSONPath: string
56
- ) {
57
- syncVersions(
58
- packageJSONPath,
59
- pathUtils.join(ohModuleDirPath, 'oh-package.json5')
60
- );
61
- if (!fs.existsSync(harmonyDirPath)) {
62
- fs.mkdirSync(harmonyDirPath, { recursive: true });
63
- }
64
- await createTGZFromDir(
65
- ohModuleDirPath,
66
- pathUtils.join(
67
- harmonyDirPath,
68
- `${pathUtils.parse(ohModuleDirPath).name}.tar.gz`
69
- )
70
- );
71
- await createTGZFromDir(
72
- harmonyDirPath,
73
- pathUtils.join(pathUtils.dirname(harmonyDirPath), 'harmony.tar.gz')
74
- );
75
- }
76
-
77
- function syncVersions(
78
- packageJSONFilePath: string,
79
- ohPackageJSONFilePath: string
80
- ) {
81
- const packageJSONFileContent = JSON.parse(
82
- fs.readFileSync(packageJSONFilePath, { encoding: 'utf-8' })
83
- );
84
- if (fs.existsSync(ohPackageJSONFilePath)) {
85
- const ohPackageJSONFileContent = JSON5.parse(
86
- fs.readFileSync(ohPackageJSONFilePath, { encoding: 'utf-8' })
87
- );
88
- ohPackageJSONFileContent['version'] = packageJSONFileContent['version'];
89
- fs.writeFileSync(
90
- ohPackageJSONFilePath,
91
- JSON5.stringify(ohPackageJSONFileContent, null, 2)
92
- );
93
- }
94
- }
95
-
96
- async function createTGZFromDir(dirPath: string, outputFilePath: string) {
97
- const ig = getIgnoreUtil(pathUtils.join(dirPath, '.tarignore'));
98
- const filesToInclude = globSync('**', {
99
- cwd: dirPath,
100
- nodir: true,
101
- }).filter((path) => !ig.ignores(path));
102
- await createArchive(outputFilePath, dirPath, filesToInclude);
103
- }
104
-
105
- function getIgnoreUtil(tarignorePath: string): Ignore {
106
- if (!fs.existsSync(tarignorePath)) {
107
- return ignore();
108
- }
109
- return ignore().add(fs.readFileSync(tarignorePath).toString());
110
- }
111
-
112
- async function createArchive(
113
- outputFilePath: string,
114
- packageDirPath: string,
115
- filesToInclude: string[]
116
- ) {
117
- if (filesToInclude.length === 0) {
118
- throw new ValidationError('Nothing to pack');
119
- }
120
- await tar.c(
121
- {
122
- gzip: true,
123
- file: outputFilePath,
124
- cwd: packageDirPath,
125
- },
126
- filesToInclude
127
- );
128
- }
@@ -1,478 +0,0 @@
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
- }