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