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