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

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 (66) hide show
  1. package/dist/assetResolver.js +105 -10
  2. package/dist/autolinking/Autolinking.js +9 -11
  3. package/dist/codegen/core/EventUtils.js +5 -8
  4. package/dist/codegen/core/TypeAnnotationToTS.js +3 -3
  5. package/dist/codegen/core/UberSchema.js +7 -11
  6. package/dist/codegen/generators/ArkTSComponentCodeGeneratorArkTS.js +3 -0
  7. package/dist/codegen/generators/ArkTSComponentCodeGeneratorCAPI.js +3 -0
  8. package/dist/codegen/generators/CppComponentCodeGenerator.js +3 -0
  9. package/dist/codegen/templates/ComponentJSIBinderHTemplate.js +15 -0
  10. package/dist/commands/bundle-harmony.js +4 -67
  11. package/dist/commands/codegen-harmony.js +13 -17
  12. package/dist/commands/codegen-lib-harmony.js +10 -14
  13. package/dist/commands/create-metro-host-constants.js +1 -1
  14. package/dist/commands/index.js +2 -1
  15. package/dist/commands/init.js +703 -0
  16. package/dist/commands/link-harmony.js +1 -1
  17. package/dist/commands/pack-harmony.js +1 -1
  18. package/dist/commands/run-harmony.js +438 -0
  19. package/dist/commands/types.js +8 -0
  20. package/dist/commands/unpack-harmony.js +2 -4
  21. package/dist/commands/verify-package-harmony.js +2 -2
  22. package/dist/core/CodegenConfig.js +4 -6
  23. package/dist/core/DescriptiveError.js +8 -4
  24. package/dist/core/PackageJSON.js +4 -7
  25. package/dist/core/fs.js +4 -5
  26. package/dist/index.js +2 -1
  27. package/dist/io/CliExecutor.js +57 -24
  28. package/dist/io/Logger.js +72 -42
  29. package/dist/io/TarGz.js +1 -2
  30. package/dist/io/__fixtures__.js +9 -3
  31. package/dist/io/fsUtils.js +1 -2
  32. package/dist/package-verifier/checks/HarmonyDirContainsOnlyHarsCheck.js +1 -2
  33. package/dist/package-verifier/checks/HarmonyDirExistsCheck.js +1 -2
  34. package/dist/package-verifier/checks/NpmAnAndOhPackageVersionsAreEqual.js +1 -2
  35. package/dist/package-verifier/checks/OhPackageNameFollowsNamingConventionCheck.js +1 -2
  36. package/dist/package-verifier/verify-package.js +7 -10
  37. package/package.json +10 -3
  38. package/src/assetResolver.ts +117 -11
  39. package/src/autolinking/Autolinking.ts +10 -12
  40. package/src/codegen/core/EventUtils.ts +4 -6
  41. package/src/codegen/core/UberSchema.ts +7 -11
  42. package/src/codegen/generators/ArkTSComponentCodeGeneratorArkTS.ts +3 -0
  43. package/src/codegen/generators/ArkTSComponentCodeGeneratorCAPI.ts +3 -0
  44. package/src/codegen/generators/CppComponentCodeGenerator.ts +3 -0
  45. package/src/codegen/templates/ComponentJSIBinderHTemplate.ts +24 -1
  46. package/src/commands/bundle-harmony.ts +6 -81
  47. package/src/commands/codegen-harmony.ts +14 -19
  48. package/src/commands/codegen-lib-harmony.ts +11 -16
  49. package/src/commands/create-metro-host-constants.ts +2 -2
  50. package/src/commands/index.ts +2 -1
  51. package/src/commands/init.ts +755 -0
  52. package/src/commands/link-harmony.ts +2 -2
  53. package/src/commands/pack-harmony.ts +2 -2
  54. package/src/commands/run-harmony.ts +478 -0
  55. package/src/commands/types.ts +21 -0
  56. package/src/commands/unpack-harmony.ts +3 -5
  57. package/src/commands/verify-package-harmony.ts +3 -3
  58. package/src/core/CodegenConfig.ts +4 -6
  59. package/src/core/DescriptiveError.ts +9 -9
  60. package/src/core/PackageJSON.ts +5 -8
  61. package/src/core/fs.ts +2 -2
  62. package/src/index.ts +5 -3
  63. package/src/io/CliExecutor.ts +56 -34
  64. package/src/io/Logger.ts +78 -45
  65. package/src/io/__fixtures__.ts +15 -11
  66. package/src/package-verifier/verify-package.ts +5 -7
@@ -0,0 +1,755 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Copyright (c) 2025 Huawei Technologies Co., Ltd.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ import path from 'node:path';
10
+ import os from 'node:os';
11
+ import { Command } from 'commander';
12
+ import inquirer from 'inquirer';
13
+ import chalk from 'chalk';
14
+ import fs from 'fs-extra';
15
+ import JSON5 from 'json5';
16
+ import { getLoader, logger } from '@react-native-community/cli-tools';
17
+ import { RealCliExecutor } from '../io/CliExecutor';
18
+ import { AbsolutePath } from '../core/AbsolutePath';
19
+ import { DescriptiveError } from '../core/DescriptiveError';
20
+
21
+ const VALID_APP_NAME_REG = /^[A-Za-z][A-Za-z0-9_]*[A-Za-z0-9]$/;
22
+ const DEFAULT_PACKAGE_PREFIX = 'com.example.';
23
+ const HARMONY_DIR = 'harmony';
24
+ const JSON5_EXT = '.json5';
25
+ const DEFAULT_ENCODING = 'utf8';
26
+ const MODULE_DESC = 'module_desc';
27
+ const ENTRY_ABILITY_DESC = 'EntryAbility_desc';
28
+ const ENTRY_ABILITY_LABEL = 'EntryAbility_label';
29
+ const REACT_NATIVE = 'react-native';
30
+ const NODE_MODULES = 'node_modules';
31
+ const STRING_TYPE = 'string';
32
+ const PROJECT_NAME_INDEX = 0;
33
+ const JSON_INDENTATION_LENGTH = 2;
34
+ const GIT_EXE = 'git';
35
+ const NODE_EXE = 'node';
36
+ const NPM_EXE = 'npm';
37
+ const APP_JSON = 'app.json';
38
+ const APP_JSON5 = 'app.json5';
39
+ const STRING_JSON = 'string.json';
40
+ const PACKAGE_JSON = 'package.json';
41
+ const TEMPLATE_CONFIG_JS = 'template.config.js';
42
+ const METRO_CONFIG_JS = 'metro.config.js';
43
+ const DEFAULT_TEMPLATE_PKG = '@react-native-oh/template';
44
+ const REACT_NATIVE_OH_REACT_NATIVE_HARMONY = '@react-native-oh/react-native-harmony';
45
+ const REACT_NATIVE_OH_REACT_NATIVE_HARMONY_CLI = '@react-native-oh/react-native-harmony-cli';
46
+
47
+ interface CliOptions {
48
+ version?: string;
49
+ template?: string;
50
+ }
51
+
52
+ interface TemplateConfig {
53
+ placeholderName: string;
54
+ templateDir: string;
55
+ postInitScript?: string;
56
+ titlePlaceholder?: string;
57
+ }
58
+
59
+ interface UpdateConfig {
60
+ destDir: string;
61
+ templateRoot: string;
62
+ templateConfig: TemplateConfig;
63
+ projectName: string;
64
+ packageName: string;
65
+ isHarmonyTemplate: boolean;
66
+ rnohVersion: string | undefined;
67
+ rnohCliVersion: string | undefined,
68
+ rnohTemplateConfig: TemplateConfig | undefined;
69
+ }
70
+
71
+ /**
72
+ * Helper class for file operations (JSON and text file updates).
73
+ */
74
+ class FileOperationHelper {
75
+ static async updateJsonFile(filePath: string, updateFn: (data: any) => any, errorMessage: string): Promise<void> {
76
+ if (!await fs.pathExists(filePath)) {
77
+ return;
78
+ }
79
+
80
+ try {
81
+ const content = await fs.readFile(filePath, DEFAULT_ENCODING);
82
+ const data = JSON5.parse(content);
83
+ const updatedData = updateFn(data);
84
+
85
+ const outputContent = filePath.endsWith(JSON5_EXT)
86
+ ? JSON5.stringify(updatedData, null, JSON_INDENTATION_LENGTH)
87
+ : JSON.stringify(updatedData, null, JSON_INDENTATION_LENGTH);
88
+
89
+ await fs.writeFile(filePath, outputContent);
90
+ } catch (e: any) {
91
+ throw new DescriptiveError({
92
+ whatHappened: errorMessage,
93
+ whatCanUserDo: ['Please check if the file format is correct.'],
94
+ extraData: e,
95
+ });
96
+ }
97
+ }
98
+
99
+ static async updateTextFile(filePath: string, placeholder: string, replacement: string): Promise<void> {
100
+ if (!await fs.pathExists(filePath)) {
101
+ return;
102
+ }
103
+
104
+ try {
105
+ let content = await fs.readFile(filePath, DEFAULT_ENCODING);
106
+ if (content.includes(placeholder)) {
107
+ content = content.replace(new RegExp(placeholder, 'g'), replacement);
108
+ await fs.writeFile(filePath, content, DEFAULT_ENCODING);
109
+ }
110
+ } catch (e: any) {
111
+ throw new DescriptiveError({
112
+ whatHappened: `Failed to update ${path.basename(filePath)}.`,
113
+ whatCanUserDo: ['Please check if the file is readable and writable.'],
114
+ extraData: e,
115
+ });
116
+ }
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Helper class for validation operations.
122
+ */
123
+ class ValidationHelper {
124
+ static validateProjectName(projectName: string): string | true {
125
+ if (!projectName.trim()) {
126
+ return 'Project name cannot be empty.';
127
+ }
128
+ if (!VALID_APP_NAME_REG.test(projectName.trim())) {
129
+ return 'Project name must start with a letter and can only contain letters, numbers, _.';
130
+ }
131
+ return true;
132
+ }
133
+
134
+ static validateOptions(options: CliOptions): void {
135
+ if (options.version && options.template) {
136
+ throw new DescriptiveError({
137
+ whatHappened: 'Cannot specify both --version and --template.',
138
+ whatCanUserDo: ['Please specify only one of --version or --template.'],
139
+ });
140
+ }
141
+ }
142
+
143
+ static async validateReactNativeVersion(destDir: string): Promise<string> {
144
+ const packageJsonPath = path.join(destDir, PACKAGE_JSON);
145
+ if (await fs.pathExists(packageJsonPath)) {
146
+ const packageJson = JSON.parse(await fs.readFile(packageJsonPath, DEFAULT_ENCODING));
147
+ const reactNativeVersion = packageJson.dependencies?.[REACT_NATIVE];
148
+ if (!reactNativeVersion || !/^\^?0\.(72)|(77)\./.test(reactNativeVersion)) {
149
+ throw new DescriptiveError({
150
+ whatHappened: `Unsupported RN community template. Please ensure react-native version starts with "0.77.".`,
151
+ whatCanUserDo: ['Please use a template with react-native version 0.77.x.'],
152
+ });
153
+ }
154
+ return reactNativeVersion;
155
+ }
156
+ return "0.77";
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Main entry point for the RNOH init command.
162
+ * Initializes a new RNOH project with proper template and configuration.
163
+ */
164
+ export async function rnohInit() {
165
+ const program = new Command();
166
+ program
167
+ .command('init [projectName]')
168
+ .description('Initialize a new RNOH project')
169
+ .option('-v, --version <version>', 'Harmonized RN version')
170
+ .option('-t, --template <template>', 'Template npm package')
171
+ .action(async (projectName: string | undefined, options: CliOptions) => {
172
+ try {
173
+ await runInit(projectName, options);
174
+ } catch (err) {
175
+ handleError(err);
176
+ process.exit(1);
177
+ }
178
+ });
179
+
180
+ await program.parseAsync(process.argv);
181
+ }
182
+
183
+ function showWelcomeMessage(version: string) {
184
+ const rnohLogoArray = [
185
+ ' ',
186
+ ' ____ _ ______ __ __ ',
187
+ ' / __ \\/ | / / __ \\/ / / / ',
188
+ ' / /_/ / |/ / / / / /_/ / ',
189
+ ' / _, _/ /| / /_/ / __ / ',
190
+ ' /_/ |_/_/ |_/\\____/_/ /_/ ',
191
+ ' ',
192
+ ];
193
+ const versionInfo = version && version !== 'undefined'
194
+ ? ` Welcome to RNOH ${version}!`
195
+ : ' Welcome to RNOH!';
196
+ logger.log(`${chalk.cyan(rnohLogoArray.join('\n'))}\n${chalk.cyanBright.bold(versionInfo)}\n`);
197
+ }
198
+
199
+ async function runInit(projectName: string | undefined, options: CliOptions) {
200
+ projectName = await getValidatedProjectName(projectName);
201
+
202
+ ValidationHelper.validateOptions(options);
203
+
204
+ const packageName = `${DEFAULT_PACKAGE_PREFIX}${projectName}`;
205
+
206
+ const destDir = path.resolve(process.cwd(), projectName);
207
+ await checkDestinationDirectory(destDir, projectName);
208
+
209
+ showWelcomeMessage(options.version as string);
210
+ const tempDir = await createTempDir();
211
+
212
+ try {
213
+ await executeInitializationSteps(tempDir, destDir, projectName, packageName, options);
214
+ } catch (error) {
215
+ await cleanupOnError(destDir);
216
+ throw error;
217
+ } finally {
218
+ await cleanupTempDir(tempDir);
219
+ }
220
+ }
221
+
222
+ async function getValidatedProjectName(projectName: string | undefined): Promise<string> {
223
+ if (!projectName) {
224
+ const { name } = await inquirer.prompt([
225
+ {
226
+ type: 'input',
227
+ name: 'name',
228
+ message: 'Please input your project name:',
229
+ validate: ValidationHelper.validateProjectName,
230
+ },
231
+ ]);
232
+ return name.trim();
233
+ }
234
+
235
+ const validationResult = ValidationHelper.validateProjectName(projectName);
236
+ if (validationResult !== true) {
237
+ throw new DescriptiveError({
238
+ whatHappened: 'Invalid project name.',
239
+ whatCanUserDo: [validationResult],
240
+ });
241
+ }
242
+
243
+ return projectName;
244
+ }
245
+
246
+ async function checkDestinationDirectory(destDir: string, projectName: string): Promise<void> {
247
+ if (await fs.pathExists(destDir)) {
248
+ const { overwrite } = await inquirer.prompt([
249
+ {
250
+ type: 'confirm',
251
+ name: 'overwrite',
252
+ message: `Directory '${projectName}' already exists. Do you want to overwrite it?`,
253
+ default: false,
254
+ },
255
+ ]);
256
+
257
+ if (!overwrite) {
258
+ process.exit(0);
259
+ }
260
+
261
+ try {
262
+ await fs.remove(destDir);
263
+ } catch (err) {
264
+ throw new DescriptiveError({
265
+ whatHappened: `Failed to remove existing directory ${destDir}`,
266
+ whatCanUserDo: ['Check permissions for the directory.', 'Ensure the directory is not in use.'],
267
+ });
268
+ }
269
+ }
270
+ }
271
+
272
+ async function executeInitializationSteps(
273
+ tempDir: string,
274
+ destDir: string,
275
+ projectName: string,
276
+ packageName: string,
277
+ options: CliOptions
278
+ ): Promise<void> {
279
+ const loader = getLoader();
280
+
281
+ loader.start(`${chalk.bold('Downloading template...')}`);
282
+ try {
283
+ await npmInitAndInstall(tempDir, options.template, options.version);
284
+ loader.succeed('Template downloaded successfully!');
285
+ } catch (err) {
286
+ loader.fail('Failed to download template');
287
+ if (err instanceof DescriptiveError) {
288
+ throw err;
289
+ }
290
+ throw new DescriptiveError({
291
+ whatHappened: 'Template download failed',
292
+ whatCanUserDo: ['Check your internet connection.', 'Ensure the template package exists.'],
293
+ });
294
+ }
295
+
296
+ loader.start(`${chalk.bold('Copying template...')}`);
297
+ const { templateConfig, templateRoot } = await getTemplateConfigFromPkg(tempDir);
298
+ let isHarmonyTemplate = true;
299
+ let rnohTemplateConfig: TemplateConfig | undefined = undefined;
300
+ let rnohVersion: string | undefined = undefined;
301
+ let rnohCliVersion: string | undefined = undefined;
302
+ try {
303
+ await copyAndReplaceTemplate(templateConfig, templateRoot, destDir);
304
+
305
+ const rnVersion = await ValidationHelper.validateReactNativeVersion(destDir);
306
+
307
+ if (!(await fs.pathExists(path.join(destDir, HARMONY_DIR)))) {
308
+ isHarmonyTemplate = false;
309
+ ({ rnohTemplateConfig, rnohVersion, rnohCliVersion } = await handleMissingHarmonyDir(destDir, rnVersion));
310
+ }
311
+ loader.succeed('Template copied successfully!');
312
+ } catch (err) {
313
+ loader.fail('Failed to copy template');
314
+ if (err instanceof DescriptiveError) {
315
+ throw err;
316
+ }
317
+ throw new DescriptiveError({
318
+ whatHappened: 'Template copy failed',
319
+ whatCanUserDo: ['Ensure you have write permissions for the destination directory.'],
320
+ });
321
+ }
322
+
323
+ loader.start(`${chalk.bold('Processing template...')}`);
324
+ try {
325
+ const updateConfig: UpdateConfig = {
326
+ destDir,
327
+ templateRoot,
328
+ templateConfig,
329
+ projectName,
330
+ packageName,
331
+ isHarmonyTemplate,
332
+ rnohVersion,
333
+ rnohCliVersion,
334
+ rnohTemplateConfig,
335
+ };
336
+ await processTemplate(updateConfig);
337
+ loader.succeed('Template processed successfully!');
338
+ } catch (err) {
339
+ loader.fail('Failed to process template');
340
+ if (err instanceof DescriptiveError) {
341
+ throw err;
342
+ }
343
+ throw new DescriptiveError({
344
+ whatHappened: 'Template processing failed',
345
+ whatCanUserDo: ['Check if the template files are corrupted.'],
346
+ });
347
+ }
348
+
349
+ loader.start(`${chalk.bold('Installing dependencies...')}`);
350
+ try {
351
+ await runCliCommand(NPM_EXE, ['install', '--legacy-peer-deps'], destDir);
352
+ loader.succeed('Dependencies installed successfully!');
353
+ } catch (err) {
354
+ loader.fail('Failed to install dependencies');
355
+ if (err instanceof DescriptiveError) {
356
+ throw err;
357
+ }
358
+ throw new DescriptiveError({
359
+ whatHappened: 'Dependency installation failed',
360
+ whatCanUserDo: ['Check your internet connection.'],
361
+ });
362
+ }
363
+
364
+ loader.start(`${chalk.bold('Initializing git repository...')}`);
365
+ const isSuccess = await initGitRepo(destDir);
366
+ if (isSuccess) {
367
+ loader.succeed('Git repository initialized successfully!');
368
+ } else {
369
+ loader.fail('Failed to initialize git repository.');
370
+ }
371
+ }
372
+
373
+ async function createTempDir(): Promise<string> {
374
+ const tempDir = path.join(os.tmpdir(), `rnoh-init-${Date.now()}-${Math.random().toString(36).slice(2)}`);
375
+ await fs.ensureDir(tempDir);
376
+ return tempDir;
377
+ }
378
+
379
+ async function npmInitAndInstall(tempDir: string, customTemplate: string | undefined, version?: string): Promise<void> {
380
+ await runCliCommand(NPM_EXE, ['init', '-y'], tempDir);
381
+ const installTarget = customTemplate ? customTemplate : version ? `${DEFAULT_TEMPLATE_PKG}@${version}` : DEFAULT_TEMPLATE_PKG;
382
+ await runCliCommand(NPM_EXE, ['install', installTarget], tempDir);
383
+ }
384
+
385
+ async function getTemplateConfigFromPkg(tempDir: string): Promise<{ templateConfig: TemplateConfig; templateRoot: string }> {
386
+ const pkgJsonPath = path.join(tempDir, PACKAGE_JSON);
387
+ const packageJson = JSON.parse(await fs.readFile(pkgJsonPath, DEFAULT_ENCODING));
388
+ const dependencies = packageJson.dependencies;
389
+ const templateName = Object.keys(dependencies)[0];
390
+ const templateRoot = path.join(tempDir, NODE_MODULES, ...templateName.split('/'));
391
+ if (!await fs.pathExists(templateRoot)) {
392
+ throw new DescriptiveError({
393
+ whatHappened: 'Cannot find installed template package.',
394
+ whatCanUserDo: ['Check npm install output.'],
395
+ });
396
+ }
397
+
398
+ const configPath = path.join(templateRoot, TEMPLATE_CONFIG_JS);
399
+
400
+ if (!await fs.pathExists(configPath)) {
401
+ throw new DescriptiveError({
402
+ whatHappened: `${TEMPLATE_CONFIG_JS} not found in template package.`,
403
+ whatCanUserDo: ['Check the template package.'],
404
+ });
405
+ }
406
+ const templateConfig: TemplateConfig = require(configPath);
407
+
408
+ validateTemplateConfig(templateConfig);
409
+
410
+ return { templateConfig, templateRoot };
411
+ }
412
+
413
+ function validateTemplateConfig(templateConfig: TemplateConfig): void {
414
+ if (!templateConfig.placeholderName || !templateConfig.templateDir) {
415
+ throw new DescriptiveError({
416
+ whatHappened: `${TEMPLATE_CONFIG_JS} missing required fields (placeholderName, templateDir).`,
417
+ whatCanUserDo: [`Check ${TEMPLATE_CONFIG_JS} format.`],
418
+ });
419
+ }
420
+
421
+ if (typeof templateConfig.placeholderName !== STRING_TYPE || typeof templateConfig.templateDir !== STRING_TYPE) {
422
+ throw new DescriptiveError({
423
+ whatHappened: `${TEMPLATE_CONFIG_JS} fields must be strings.`,
424
+ whatCanUserDo: [`Check ${TEMPLATE_CONFIG_JS} format.`],
425
+ });
426
+ }
427
+ }
428
+
429
+ async function copyAndReplaceTemplate(templateConfig: TemplateConfig, templateRoot: string, destDir: string): Promise<void> {
430
+ const srcDir = path.join(templateRoot, templateConfig.templateDir);
431
+
432
+ if (!await fs.pathExists(srcDir)) {
433
+ throw new DescriptiveError({
434
+ whatHappened: 'Template directory not found.',
435
+ whatCanUserDo: [`Check templateDir in ${TEMPLATE_CONFIG_JS}.`],
436
+ });
437
+ }
438
+
439
+ await fs.copy(srcDir, destDir);
440
+ }
441
+
442
+ async function updateRNConfigFiles(updateConfig: UpdateConfig): Promise<void> {
443
+ const updates = [
444
+ FileOperationHelper.updateJsonFile(
445
+ path.join(updateConfig.destDir, APP_JSON),
446
+ (data) => ({ ...data, name: updateConfig.projectName, displayName: updateConfig.projectName }),
447
+ `Failed to update ${APP_JSON}.`
448
+ ),
449
+ FileOperationHelper.updateJsonFile(
450
+ path.join(updateConfig.destDir, PACKAGE_JSON),
451
+ (data) => {
452
+ if (!updateConfig.isHarmonyTemplate) {
453
+ data.dependencies = { ...data.dependencies, [REACT_NATIVE_OH_REACT_NATIVE_HARMONY]: updateConfig.rnohVersion };
454
+ data.devDependencies = { ...data.devDependencies, [REACT_NATIVE_OH_REACT_NATIVE_HARMONY_CLI]: updateConfig.rnohCliVersion };
455
+ }
456
+ return { ...data, name: updateConfig.packageName };
457
+ },
458
+ `Failed to update ${PACKAGE_JSON}.`
459
+ ),
460
+ ];
461
+
462
+ await Promise.all(updates);
463
+ }
464
+
465
+ async function renameDotFiles(destDir: string): Promise<void> {
466
+ const dotMap: Record<string, string> = {
467
+ '_bundle': '.bundle',
468
+ '_eslintrc.js': '.eslintrc.js',
469
+ '_gitignore': '.gitignore',
470
+ '_prettierrc.js': '.prettierrc.js',
471
+ '_watchmanconfig': '.watchmanconfig',
472
+ '_buckconfig': '.buckconfig',
473
+ '_flowconfig': '.flowconfig',
474
+ '_gitattributes': '.gitattributes',
475
+ '_editorconfig': '.editorconfig',
476
+ '_ruby-version': '.ruby-version',
477
+ '_node-version': '.node-version',
478
+ '_xcode.env': '.xcode.env',
479
+ };
480
+
481
+ const renameOperations = Object.entries(dotMap).map(async ([src, dest]) => {
482
+ const srcPath = path.join(destDir, src);
483
+ if (await fs.pathExists(srcPath)) {
484
+ await fs.move(srcPath, path.join(destDir, dest), { overwrite: true });
485
+ }
486
+ });
487
+
488
+ await Promise.all(renameOperations);
489
+ }
490
+
491
+ async function runPostInitScript(scriptPath: string, templateRoot: string, cwd: string, isHarmonyTemplate: boolean): Promise<void> {
492
+ const absScriptPath = path.join(templateRoot, scriptPath);
493
+
494
+ if (!await fs.pathExists(absScriptPath)) {
495
+ throw new DescriptiveError({
496
+ whatHappened: 'postInitScript not found.',
497
+ whatCanUserDo: [`Check postInitScript path in ${TEMPLATE_CONFIG_JS}.`],
498
+ });
499
+ }
500
+
501
+ if (!isHarmonyTemplate) {
502
+ try {
503
+ await runCliCommand(NODE_EXE, [absScriptPath], cwd);
504
+ } catch (err) {
505
+ logger.error(`Failed to execute postInitScript in RN community template, please execute manually.`);
506
+ }
507
+ } else {
508
+ await runCliCommand(NODE_EXE, [absScriptPath], cwd);
509
+ }
510
+ }
511
+
512
+ async function runCliCommand(cmd: string, args: string[], cwd: string, silent = true, stdOutFunc?: (data: any) => any): Promise<void> {
513
+ const cli = new RealCliExecutor();
514
+ try {
515
+ await cli.run(cmd, {
516
+ args,
517
+ cwd: new AbsolutePath(cwd),
518
+ shell: true,
519
+ onStdout: silent ? undefined : stdOutFunc ? (data) => stdOutFunc(data) : (data) => logger.info(data),
520
+ onStderr: silent ? undefined : (data) => logger.error(data),
521
+ });
522
+ } catch (err) {
523
+ throw new DescriptiveError({
524
+ whatHappened: `Failed to run command: ${cmd} ${args.join(' ')}`,
525
+ extraData: err,
526
+ });
527
+ }
528
+ }
529
+
530
+ async function initGitRepo(destDir: string): Promise<boolean> {
531
+ const gitDir = path.join(destDir, '.git');
532
+ if (await fs.pathExists(gitDir)) {
533
+ logger.warn('Git repository already exists, skipping git init.');
534
+ return false;
535
+ }
536
+
537
+ try {
538
+ await runCliCommand(GIT_EXE, ['init'], destDir);
539
+ await runCliCommand(GIT_EXE, ['add', '.'], destDir);
540
+ await runCliCommand(GIT_EXE, ['commit', '-m', `"Initial RNOH by ${REACT_NATIVE_OH_REACT_NATIVE_HARMONY_CLI}"`], destDir);
541
+ } catch (error) {
542
+ logger.warn('Failed to initialize git repository. You can initialize it manually later.');
543
+ if (await fs.pathExists(gitDir)) {
544
+ await fs.remove(gitDir);
545
+ }
546
+ return false;
547
+ }
548
+ return true;
549
+ }
550
+
551
+ function handleError(err: unknown): void {
552
+ if (err instanceof DescriptiveError) {
553
+ logger.error(chalk.red(err.getMessage()));
554
+ for (const suggestion of err.getSuggestions()) {
555
+ logger.info(chalk.yellow('Tip: ' + suggestion));
556
+ }
557
+ if (err.getDetails()) {
558
+ logger.info(chalk.gray(err.getDetails()));
559
+ }
560
+ } else {
561
+ const message = err instanceof Error ? err.message : String(err);
562
+ logger.error(chalk.red('Unexpected error: ' + message));
563
+ }
564
+ }
565
+
566
+ async function cleanupOnError(destDir: string): Promise<void> {
567
+ if (await fs.pathExists(destDir)) {
568
+ await fs.remove(destDir);
569
+ }
570
+ }
571
+
572
+ async function cleanupTempDir(tempDir: string): Promise<void> {
573
+ try {
574
+ await fs.remove(tempDir);
575
+ } catch (cleanupError) {
576
+ logger.warn('Failed to clean up temporary directory:', tempDir);
577
+ }
578
+ }
579
+
580
+ async function getRNOHVersion(rnVersion: string): Promise<string> {
581
+ const versionParts = rnVersion.split('.');
582
+ const majorMinorVersion = `${versionParts[0]}.${versionParts[1]}`;
583
+ let versionInfos = "";
584
+ await runCliCommand(NPM_EXE, ['view', DEFAULT_TEMPLATE_PKG, 'versions', '--json'], process.cwd(), false,
585
+ (data) => {
586
+ versionInfos += data.toString();
587
+ }
588
+ );
589
+ const versions = JSON.parse(versionInfos);
590
+ const matchingVersions = versions.filter((v: string) => v.startsWith(majorMinorVersion));
591
+ if (matchingVersions.length === 0) {
592
+ throw new DescriptiveError({
593
+ whatHappened: `No matching versions found for ${DEFAULT_TEMPLATE_PKG} with major version ${majorMinorVersion}.`,
594
+ whatCanUserDo: ['Please check the available versions of the template package.'],
595
+ });
596
+ }
597
+ return matchingVersions.pop();
598
+ }
599
+
600
+ async function handleMissingHarmonyDir(destDir: string, rnVersion: string): Promise<{ rnohTemplateConfig: TemplateConfig, rnohVersion: string, rnohCliVersion: string }> {
601
+ const lastestVersion = await getRNOHVersion(rnVersion);
602
+ const defaultTempDir = await createTempDir();
603
+ try {
604
+ await npmInitAndInstall(defaultTempDir, `${DEFAULT_TEMPLATE_PKG}@${lastestVersion}`);
605
+ const defaultTemplateConfig = await getTemplateConfigFromPkg(defaultTempDir);
606
+
607
+ const sourceHarmonyDir = path.join(defaultTemplateConfig.templateRoot, defaultTemplateConfig.templateConfig.templateDir, HARMONY_DIR);
608
+ const targetHarmonyDir = path.join(destDir, HARMONY_DIR);
609
+
610
+ if (!await fs.pathExists(sourceHarmonyDir)) {
611
+ throw new DescriptiveError({
612
+ whatHappened: `Default template does not contain harmony directory at ${sourceHarmonyDir}`,
613
+ whatCanUserDo: ['Please use a template that contains harmony directory.', 'Check if the default template package is correct.'],
614
+ });
615
+ }
616
+
617
+ await fs.copy(sourceHarmonyDir, targetHarmonyDir);
618
+
619
+ const sourceMetroConfigPath = path.join(defaultTemplateConfig.templateRoot, defaultTemplateConfig.templateConfig.templateDir, METRO_CONFIG_JS);
620
+ const targetMetroConfigPath = path.join(destDir, METRO_CONFIG_JS);
621
+ if (await fs.pathExists(sourceMetroConfigPath)) {
622
+ await fs.copyFile(sourceMetroConfigPath, targetMetroConfigPath);
623
+ } else {
624
+ throw new DescriptiveError({
625
+ whatHappened: `Default template does not contain ${METRO_CONFIG_JS} at ${sourceMetroConfigPath}`,
626
+ whatCanUserDo: [`Please use a template that contains ${METRO_CONFIG_JS}.`, 'Check if the default template package is correct.'],
627
+ });
628
+ }
629
+
630
+ const pkgJsonPath = path.join(defaultTemplateConfig.templateRoot, defaultTemplateConfig.templateConfig.templateDir, PACKAGE_JSON);
631
+ const pkgContent = JSON.parse(await fs.readFile(pkgJsonPath, DEFAULT_ENCODING));
632
+ const rnohVersion = pkgContent.dependencies?.[REACT_NATIVE_OH_REACT_NATIVE_HARMONY];
633
+ const rnohCliVersion = pkgContent.devDependencies?.[REACT_NATIVE_OH_REACT_NATIVE_HARMONY_CLI];
634
+
635
+ const androidDir = path.join(destDir, 'android');
636
+ const iosDir = path.join(destDir, 'ios');
637
+
638
+ if (await fs.pathExists(androidDir)) {
639
+ await fs.remove(androidDir);
640
+ }
641
+ if (await fs.pathExists(iosDir)) {
642
+ await fs.remove(iosDir);
643
+ }
644
+ return { rnohTemplateConfig: defaultTemplateConfig.templateConfig, rnohVersion, rnohCliVersion };
645
+ } catch (error) {
646
+ if (error instanceof DescriptiveError) {
647
+ throw error;
648
+ }
649
+ throw new DescriptiveError({
650
+ whatHappened: 'Failed to handle missing harmony directory from default template.',
651
+ whatCanUserDo: [
652
+ 'Check your internet connection.',
653
+ 'Ensure you have write permissions for the destination directory.',
654
+ 'Verify that the default template package exists and is accessible.',
655
+ ],
656
+ extraData: error,
657
+ });
658
+ } finally {
659
+ await cleanupTempDir(defaultTempDir);
660
+ }
661
+ }
662
+
663
+ async function updateHarmonyFiles(updateConfig: UpdateConfig): Promise<void> {
664
+ const harmonyDir = path.join(updateConfig.destDir, HARMONY_DIR);
665
+ const appScopeDir = path.join(harmonyDir, 'AppScope');
666
+ const entryDir = path.join(harmonyDir, 'entry');
667
+
668
+ const updateOperations = [
669
+ updateAppScopeStringJson(appScopeDir, updateConfig.projectName),
670
+ updateEntryIndexEts(entryDir, updateConfig),
671
+ updateAppScopeAppJson5(appScopeDir, updateConfig.packageName),
672
+ updateEntryStringJson(entryDir, updateConfig.projectName),
673
+ ];
674
+
675
+ await Promise.all(updateOperations);
676
+ }
677
+
678
+ async function updateAppScopeStringJson(appScopeDir: string, projectName: string): Promise<void> {
679
+ const appScopeStringJson = path.join(appScopeDir, 'resources', 'base', 'element', STRING_JSON);
680
+
681
+ await FileOperationHelper.updateJsonFile(
682
+ appScopeStringJson,
683
+ (data) => {
684
+ if (Array.isArray(data.string) && data.string.length > 0) {
685
+ data.string[PROJECT_NAME_INDEX].value = projectName;
686
+ }
687
+ return data;
688
+ },
689
+ `Failed to update AppScope ${STRING_JSON}.`
690
+ );
691
+ }
692
+
693
+ async function updateEntryIndexEts(entryDir: string, updateConfig: UpdateConfig): Promise<void> {
694
+ const entryIndexEts = path.join(entryDir, 'src', 'main', 'ets', 'pages', 'Index.ets');
695
+ let replacedText = updateConfig.templateConfig.placeholderName;
696
+ if (!updateConfig.isHarmonyTemplate && updateConfig.rnohTemplateConfig) {
697
+ replacedText = updateConfig.rnohTemplateConfig.placeholderName;
698
+ }
699
+ await FileOperationHelper.updateTextFile(entryIndexEts, replacedText, updateConfig.projectName);
700
+ }
701
+
702
+ async function updateAppScopeAppJson5(appScopeDir: string, packageName: string): Promise<void> {
703
+ const appScopeAppJson5 = path.join(appScopeDir, APP_JSON5);
704
+
705
+ await FileOperationHelper.updateJsonFile(
706
+ appScopeAppJson5,
707
+ (data) => ({
708
+ ...data,
709
+ app: { ...data.app, bundleName: packageName },
710
+ }),
711
+ `Failed to update AppScope ${APP_JSON5}.`
712
+ );
713
+ }
714
+
715
+ async function updateEntryStringJson(entryDir: string, projectName: string): Promise<void> {
716
+ const entryStringJson = path.join(entryDir, 'src', 'main', 'resources', 'base', 'element', STRING_JSON);
717
+
718
+ await FileOperationHelper.updateJsonFile(
719
+ entryStringJson,
720
+ (data) => {
721
+ if (Array.isArray(data.string)) {
722
+ data.string.forEach((item: any) => {
723
+ if (item.name === MODULE_DESC || item.name === ENTRY_ABILITY_DESC) {
724
+ item.value = '';
725
+ }
726
+ if (item.name === ENTRY_ABILITY_LABEL) {
727
+ item.value = projectName;
728
+ }
729
+ });
730
+ }
731
+ return data;
732
+ },
733
+ `Failed to update entry ${STRING_JSON}.`
734
+ );
735
+ }
736
+
737
+ async function processTemplate(
738
+ updateConfig: UpdateConfig
739
+ ): Promise<void> {
740
+ await Promise.all([
741
+ updateRNConfigFiles(updateConfig),
742
+ updateHarmonyFiles(updateConfig),
743
+ renameDotFiles(updateConfig.destDir),
744
+ ]);
745
+
746
+ if (updateConfig.templateConfig.postInitScript) {
747
+ await runPostInitScript(
748
+ updateConfig.templateConfig.postInitScript,
749
+ updateConfig.templateRoot,
750
+ updateConfig.destDir,
751
+ updateConfig.isHarmonyTemplate);
752
+ }
753
+ }
754
+
755
+ rnohInit();