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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/README.md +11 -11
  2. package/dist/assetResolver.js +74 -43
  3. package/dist/autolinking/Autolinking.js +183 -179
  4. package/dist/codegen/core/CodegenError.js +23 -3
  5. package/dist/codegen/core/EventUtils.js +3 -3
  6. package/dist/codegen/core/TypeAnnotationToTS.js +28 -24
  7. package/dist/codegen/core/UberSchema.js +96 -57
  8. package/dist/codegen/generators/AppBuildTimeGlueCodeGenerator.js +42 -28
  9. package/dist/codegen/generators/ArkTSComponentCodeGeneratorArkTS.js +34 -27
  10. package/dist/codegen/generators/ArkTSComponentCodeGeneratorCAPI.js +33 -25
  11. package/dist/codegen/generators/CppComponentCodeGenerator.js +28 -23
  12. package/dist/codegen/generators/LibGlueCodeGenerator.js +29 -26
  13. package/dist/codegen/generators/NativeModuleCodeGenerator.js +30 -25
  14. package/dist/codegen/generators/SharedComponentCodeGenerator.js +15 -15
  15. package/dist/codegen/generators/UberGeneratorV1.js +24 -18
  16. package/dist/codegen/generators/UberGeneratorV2.js +36 -28
  17. package/dist/codegen/templates/BaseComponentInstanceHTemplate.js +24 -50
  18. package/dist/codegen/templates/BasePackageHTemplate.js +21 -109
  19. package/dist/codegen/templates/ComponentDescriptorHTemplate.js +8 -53
  20. package/dist/codegen/templates/ComponentJSIBinderHTemplate.js +27 -75
  21. package/dist/codegen/templates/ComponentUtilsTSTemplate.js +29 -162
  22. package/dist/codegen/templates/IndexTSTemplate.js +17 -37
  23. package/dist/codegen/templates/RNOHGeneratedPackageHTemplate.js +24 -108
  24. package/dist/codegen/templates/TurboModuleCppTemplate.js +15 -38
  25. package/dist/codegen/templates/TurboModuleHTemplate.js +11 -32
  26. package/dist/codegen/templates/TurboModuleSpecTSTemplate.js +19 -52
  27. package/dist/commands/bundle-harmony.js +138 -53
  28. package/dist/commands/codegen-harmony.js +175 -104
  29. package/dist/commands/codegen-lib-harmony.js +116 -76
  30. package/dist/commands/create-metro-host-constants.js +47 -18
  31. package/dist/commands/init.js +961 -537
  32. package/dist/commands/link-harmony.js +71 -33
  33. package/dist/commands/pack-harmony.js +108 -47
  34. package/dist/commands/run-harmony.js +520 -352
  35. package/dist/commands/unpack-harmony.js +198 -105
  36. package/dist/commands/verify-package-harmony.js +108 -54
  37. package/dist/core/AbsolutePath.js +47 -31
  38. package/dist/core/CodegenConfig.js +22 -24
  39. package/dist/core/DescriptiveError.js +37 -18
  40. package/dist/core/FileSystem.js +18 -14
  41. package/dist/core/OHPackageJSON5.js +23 -17
  42. package/dist/core/PackageJSON.js +42 -26
  43. package/dist/core/ProjectDependenciesManager.js +96 -46
  44. package/dist/core/ValidationError.js +22 -2
  45. package/dist/core/fs.js +6 -9
  46. package/dist/index.js +1 -1
  47. package/dist/io/CliExecutor.js +98 -46
  48. package/dist/io/Logger.js +46 -40
  49. package/dist/io/RealFS.js +88 -35
  50. package/dist/io/TarGz.js +8 -11
  51. package/dist/io/__fixtures__.js +141 -79
  52. package/dist/io/fsUtils.js +12 -13
  53. package/dist/package-verifier/checks/HarmonyDirContainsOnlyHarsCheck.js +47 -19
  54. package/dist/package-verifier/checks/HarmonyDirExistsCheck.js +41 -13
  55. package/dist/package-verifier/checks/NpmAnAndOhPackageVersionsAreEqual.js +38 -8
  56. package/dist/package-verifier/checks/OhPackageNameFollowsNamingConventionCheck.js +54 -22
  57. package/dist/package-verifier/verify-package.js +132 -55
  58. package/dist/simulator/LaunchSimulator.js +395 -0
  59. package/dist/simulator/index.js +23 -0
  60. package/jest.config.js +12 -12
  61. package/package.json +78 -70
  62. package/react-native.config.js +17 -17
  63. package/tsconfig.build.json +6 -6
  64. package/tsconfig.json +2 -2
  65. package/.prettierrc +0 -6
  66. package/src/assetResolver.ts +0 -134
  67. package/src/autolinking/Autolinking.test.ts +0 -483
  68. package/src/autolinking/Autolinking.ts +0 -382
  69. package/src/autolinking/index.ts +0 -8
  70. package/src/codegen/core/CodeGenerator.ts +0 -16
  71. package/src/codegen/core/CodegenError.ts +0 -10
  72. package/src/codegen/core/EventUtils.ts +0 -23
  73. package/src/codegen/core/TypeAnnotationToTS.test.ts +0 -82
  74. package/src/codegen/core/TypeAnnotationToTS.ts +0 -195
  75. package/src/codegen/core/UberSchema.ts +0 -152
  76. package/src/codegen/core/index.ts +0 -12
  77. package/src/codegen/generators/AppBuildTimeGlueCodeGenerator.ts +0 -120
  78. package/src/codegen/generators/ArkTSComponentCodeGeneratorArkTS.ts +0 -128
  79. package/src/codegen/generators/ArkTSComponentCodeGeneratorCAPI.ts +0 -122
  80. package/src/codegen/generators/CppComponentCodeGenerator.ts +0 -95
  81. package/src/codegen/generators/LibGlueCodeGenerator.ts +0 -98
  82. package/src/codegen/generators/NativeModuleCodeGenerator.ts +0 -124
  83. package/src/codegen/generators/SharedComponentCodeGenerator.ts +0 -57
  84. package/src/codegen/generators/UberGeneratorV1.ts +0 -75
  85. package/src/codegen/generators/UberGeneratorV2.ts +0 -114
  86. package/src/codegen/generators/index.ts +0 -15
  87. package/src/codegen/index.ts +0 -9
  88. package/src/codegen/templates/BaseComponentInstanceHTemplate.ts +0 -128
  89. package/src/codegen/templates/BasePackageHTemplate.ts +0 -147
  90. package/src/codegen/templates/ComponentDescriptorHTemplate.ts +0 -63
  91. package/src/codegen/templates/ComponentJSIBinderHTemplate.ts +0 -121
  92. package/src/codegen/templates/ComponentUtilsTSTemplate.ts +0 -222
  93. package/src/codegen/templates/IndexTSTemplate.ts +0 -62
  94. package/src/codegen/templates/RNOHGeneratedPackageHTemplate.ts +0 -138
  95. package/src/codegen/templates/TurboModuleCppTemplate.ts +0 -61
  96. package/src/codegen/templates/TurboModuleHTemplate.ts +0 -42
  97. package/src/codegen/templates/TurboModuleSpecTSTemplate.ts +0 -101
  98. package/src/codegen/templates/index.ts +0 -16
  99. package/src/commands/bundle-harmony.ts +0 -134
  100. package/src/commands/codegen-harmony.ts +0 -297
  101. package/src/commands/codegen-lib-harmony.ts +0 -389
  102. package/src/commands/create-metro-host-constants.ts +0 -55
  103. package/src/commands/index.ts +0 -16
  104. package/src/commands/init.ts +0 -755
  105. package/src/commands/link-harmony.ts +0 -102
  106. package/src/commands/pack-harmony.ts +0 -128
  107. package/src/commands/run-harmony.ts +0 -478
  108. package/src/commands/types.ts +0 -21
  109. package/src/commands/unpack-harmony.ts +0 -238
  110. package/src/commands/verify-package-harmony.ts +0 -113
  111. package/src/core/AbsolutePath.ts +0 -66
  112. package/src/core/CodegenConfig.ts +0 -67
  113. package/src/core/DescriptiveError.ts +0 -68
  114. package/src/core/FileSystem.ts +0 -57
  115. package/src/core/OHPackageJSON5.ts +0 -30
  116. package/src/core/PackageJSON.ts +0 -104
  117. package/src/core/ProjectDependenciesManager.ts +0 -103
  118. package/src/core/ValidationError.ts +0 -8
  119. package/src/core/ValueObject.ts +0 -9
  120. package/src/core/fs.ts +0 -38
  121. package/src/core/index.ts +0 -17
  122. package/src/index.ts +0 -33
  123. package/src/io/CliExecutor.ts +0 -69
  124. package/src/io/Logger.ts +0 -112
  125. package/src/io/RealFS.ts +0 -62
  126. package/src/io/TarGz.ts +0 -33
  127. package/src/io/__fixtures__.ts +0 -139
  128. package/src/io/fsUtils.ts +0 -44
  129. package/src/io/index.ts +0 -11
  130. package/src/package-verifier/checks/HarmonyDirContainsOnlyHarsCheck.ts +0 -35
  131. package/src/package-verifier/checks/HarmonyDirExistsCheck.ts +0 -31
  132. package/src/package-verifier/checks/NpmAnAndOhPackageVersionsAreEqual.ts +0 -25
  133. package/src/package-verifier/checks/OhPackageNameFollowsNamingConventionCheck.ts +0 -54
  134. package/src/package-verifier/checks/index.ts +0 -11
  135. package/src/package-verifier/index.ts +0 -9
  136. package/src/package-verifier/types.ts +0 -19
  137. package/src/package-verifier/verify-package.ts +0 -123
@@ -1,297 +0,0 @@
1
- /**
2
- * Copyright (c) 2024-2025 Huawei Technologies Co., Ltd.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE-MIT file in the root directory of this source tree.
6
- */
7
-
8
- import pathUtils from 'node:path';
9
- import Case from 'case';
10
- import { Command } from './types';
11
- import {
12
- AbsolutePath,
13
- DescriptiveError,
14
- FS,
15
- PackageJSON,
16
- ProjectDependenciesManager,
17
- maybeMakeDirectories,
18
- maybeRemoveFilesInDirectory,
19
- } from '../core';
20
- import {
21
- UberSchema,
22
- LibraryData,
23
- UberGeneratorV1,
24
- UberGeneratorV2,
25
- AppBuildTimeGlueCodeGenerator,
26
- CodegenError,
27
- } from '../codegen';
28
- import { Logger, RealFS } from '../io';
29
-
30
- export const commandCodegenHarmony: Command = {
31
- name: 'codegen-harmony',
32
- description:
33
- 'Generates boilerplate, types, and utilities from Turbo Module and Fabric Component specifications. This command is meant to be executed during the application build process.',
34
- options: [
35
- {
36
- name: '--rnoh-module-path <path>',
37
- description: 'Specifies the relative path to the rnoh OHOS module',
38
- },
39
- {
40
- name: '--cpp-output-path <path>',
41
- description:
42
- 'Specifies the relative path to the output directory intended for storing generated C++ files',
43
- default: './harmony/entry/src/main/cpp/generated',
44
- },
45
- {
46
- name: '--project-root-path <path>',
47
- description: 'Relative path to package root',
48
- default: '.',
49
- },
50
- {
51
- name: '--debug [boolean]',
52
- description: 'Enables logging details',
53
- default: false,
54
- },
55
- {
56
- name: '--no-safety-check [boolean]',
57
- description:
58
- 'Skips the check that prevents file operations outside the current working directory. This command permanently deletes previously generated files. Files are generated in the path specified by cpp-output-path.',
59
- },
60
- ],
61
- func: async (_argv, _config, args: any) => {
62
- const logger = new Logger();
63
- const fs = new RealFS();
64
- try {
65
- const MAX_SUPPORTED_CODEGEN_VERSION = 2;
66
- // prepare the input data
67
- validateArgs(args);
68
- const etsOutputPath = new AbsolutePath(
69
- args.rnohModulePath
70
- ).copyWithNewSegment('generated');
71
- const enableSafetyCheck: boolean = args.safetyCheck;
72
- const cppOutputPath = new AbsolutePath(args.cppOutputPath);
73
- const projectRootPath = new AbsolutePath(args.projectRootPath);
74
- const uberSchemaFromArkTSLibraries = await UberSchema.fromProject(
75
- fs,
76
- projectRootPath,
77
- (codegenVersion, packageName) => {
78
- throwErrorIfUnsupportedCodegenVersion(
79
- codegenVersion,
80
- MAX_SUPPORTED_CODEGEN_VERSION,
81
- packageName
82
- );
83
- return codegenVersion === 1;
84
- }
85
- );
86
- const cApiLibrariesData = await collectLibrariesData(
87
- fs,
88
- projectRootPath,
89
- (codegenVersion, packageName) => {
90
- throwErrorIfUnsupportedCodegenVersion(
91
- codegenVersion,
92
- MAX_SUPPORTED_CODEGEN_VERSION,
93
- packageName
94
- );
95
- return codegenVersion === 2;
96
- }
97
- );
98
-
99
- // instantiate objects
100
- const codegenNoticeLines = [
101
- 'This code was generated by "react-native codegen-harmony"',
102
- '',
103
- 'Do not edit this file as changes may cause incorrect behavior and will be',
104
- 'lost once the code is regenerated.',
105
- ];
106
- const uberGeneratorV1 = new UberGeneratorV1(
107
- cppOutputPath,
108
- etsOutputPath,
109
- [...codegenNoticeLines, '', '@generatorVersion: 1']
110
- );
111
- const uberGeneratorV2 = new UberGeneratorV2(
112
- cppOutputPath,
113
- etsOutputPath,
114
- [...codegenNoticeLines, '', '@generatorVersion: 2']
115
- );
116
- const glueCodeGenerator = new AppBuildTimeGlueCodeGenerator(
117
- cppOutputPath,
118
- etsOutputPath,
119
- codegenNoticeLines
120
- );
121
-
122
- // generate the code
123
- const fileContentByPath = new Map<AbsolutePath, string>();
124
- const appendToFileContentByPath = (
125
- fileContent: string,
126
- path: AbsolutePath
127
- ) => {
128
- fileContentByPath.set(path, fileContent);
129
- };
130
- uberGeneratorV1
131
- .generate(uberSchemaFromArkTSLibraries)
132
- .forEach(appendToFileContentByPath);
133
- uberGeneratorV2
134
- .generate(cApiLibrariesData)
135
- .forEach(appendToFileContentByPath);
136
- glueCodeGenerator
137
- .generate({
138
- v1: uberGeneratorV1.getGlueCodeData(),
139
- v2: uberGeneratorV2.getGlueCodeData(),
140
- })
141
- .forEach(appendToFileContentByPath);
142
-
143
- // output the results
144
- if (args.debug) {
145
- const uberSchema = await UberSchema.fromProject(fs, projectRootPath);
146
- logger.debug((styles) =>
147
- styles.gray(JSON.stringify(uberSchema.getValue(), null, 2))
148
- );
149
- }
150
- saveCodegenResult(
151
- fs,
152
- fileContentByPath,
153
- cppOutputPath,
154
- etsOutputPath,
155
- enableSafetyCheck
156
- );
157
- logCodegenResult(logger, fileContentByPath, projectRootPath);
158
- } catch (err) {
159
- if (err instanceof DescriptiveError) {
160
- logger.descriptiveError(err);
161
- process.exit(1);
162
- }
163
- throw err;
164
- }
165
- },
166
- };
167
-
168
- function validateArgs(args: any) {
169
- if (!args.rnohModulePath) {
170
- throw new DescriptiveError({
171
- whatHappened: "--rnoh-module-path argument wasn't provided",
172
- whatCanUserDo: [
173
- 'Please provide a path to the native React Native for Open Harmony module (rnoh) which is probably located somewhere in "<PROJECT_ROOT>/harmony" directory',
174
- ],
175
- });
176
- }
177
- }
178
-
179
- async function collectLibrariesData(
180
- fs: FS,
181
- projectRootPath: AbsolutePath,
182
- onShouldAcceptCodegenConfig: (version: number, packageName: string) => boolean
183
- ): Promise<LibraryData[]> {
184
- const packageJSONs: PackageJSON[] = [
185
- PackageJSON.fromProjectRootPath(fs, projectRootPath, projectRootPath),
186
- ];
187
- await new ProjectDependenciesManager(fs, projectRootPath).forEachAsync(
188
- (dependency) => {
189
- packageJSONs.push(dependency.readPackageJSON());
190
- }
191
- );
192
- const results: LibraryData[] = [];
193
- for (const packageJSON of packageJSONs) {
194
- const codegenConfigs = packageJSON.getCodegenConfigs();
195
- for (const codegenConfig of codegenConfigs) {
196
- if (
197
- codegenConfig &&
198
- onShouldAcceptCodegenConfig(
199
- codegenConfig.getVersion(),
200
- packageJSON.name
201
- )
202
- ) {
203
- results.push({
204
- libraryCppName: deriveCppDirectoryNameFromNpmPackageName(
205
- packageJSON.name
206
- ),
207
- uberSchema: UberSchema.fromCodegenConfig(codegenConfig),
208
- });
209
- }
210
- }
211
- }
212
- return results;
213
- }
214
-
215
- function throwErrorIfUnsupportedCodegenVersion(
216
- codegenVersion: number,
217
- maxSupportedCodegenVersion: number,
218
- packageName: string
219
- ) {
220
- if (codegenVersion > maxSupportedCodegenVersion) {
221
- throw new CodegenError({
222
- whatHappened: `Package "${packageName}" requires codegenVersion: ${codegenVersion}, which is not supported (maxSupportedCodegenVersion=${maxSupportedCodegenVersion}).`,
223
- whatCanUserDo: [
224
- `Try downgrading "${packageName}".`,
225
- 'Update the "@react-native-oh/react-native-harmony-cli" package.',
226
- ],
227
- });
228
- }
229
- }
230
-
231
- function saveCodegenResult(
232
- fs: FS,
233
- fileContentByPath: Map<AbsolutePath, string>,
234
- cppOutputPath: AbsolutePath,
235
- etsOutputPath: AbsolutePath,
236
- enableSafetyCheck: boolean
237
- ) {
238
- prepareDirectory(cppOutputPath, enableSafetyCheck);
239
- prepareDirectory(etsOutputPath, enableSafetyCheck);
240
- prepareDirectory(
241
- etsOutputPath.copyWithNewSegment('components'),
242
- enableSafetyCheck
243
- );
244
- prepareDirectory(
245
- etsOutputPath.copyWithNewSegment('turboModules'),
246
- enableSafetyCheck
247
- );
248
- fileContentByPath.forEach((_fileContent, path) => {
249
- prepareDirectory(path.getDirectoryPath(), enableSafetyCheck);
250
- });
251
- fileContentByPath.forEach((fileContent, path) => {
252
- fs.writeTextSync(path, fileContent);
253
- });
254
- }
255
-
256
- function prepareDirectory(path: AbsolutePath, enableSafetyCheck: boolean) {
257
- maybeMakeDirectories(path);
258
- if (enableSafetyCheck && !path.getValue().startsWith(process.cwd())) {
259
- throw new DescriptiveError({
260
- whatHappened: `Tried to remove files in ${path.getValue()}\nand that path is outside current working directory`,
261
- whatCanUserDo: ['Run codegen from different location'],
262
- });
263
- }
264
- maybeRemoveFilesInDirectory(path);
265
- }
266
-
267
- function logCodegenResult(
268
- logger: Logger,
269
- fileContentByPath: Map<AbsolutePath, string>,
270
- projectRootPath: AbsolutePath
271
- ) {
272
- const sortedRelativePathStrings = Array.from(fileContentByPath.keys()).map(
273
- (path) => pathUtils.relative(projectRootPath.getValue(), path.getValue())
274
- );
275
- sortedRelativePathStrings.sort();
276
- sortedRelativePathStrings.forEach((pathStr) => {
277
- logger.debug((styles) => styles.gray(`• ${pathStr}`));
278
- });
279
- logger.debug(() => '');
280
- logger.info(
281
- (styles) =>
282
- `Generated ${styles.green(styles.bold(fileContentByPath.size))} file(s)`
283
- );
284
- logger.debug(() => '');
285
- }
286
-
287
- function deriveCppDirectoryNameFromNpmPackageName(
288
- npmPackageName: string
289
- ): string {
290
- let result = npmPackageName;
291
- if (npmPackageName.includes('/')) {
292
- result.replace('@', '');
293
- result = npmPackageName.replace('/', '__');
294
- }
295
- result = Case.snake(result);
296
- return result;
297
- }
@@ -1,389 +0,0 @@
1
- /**
2
- * Copyright (c) 2024-2025 Huawei Technologies Co., Ltd.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE-MIT file in the root directory of this source tree.
6
- */
7
-
8
- import { Command } from './types';
9
- import {
10
- AbsolutePath,
11
- DescriptiveError,
12
- maybeMakeDirectories,
13
- maybeRemoveFilesInDirectory,
14
- } from '../core';
15
- import { Logger, findFilePathsWithExtensions } from '../io';
16
- import fs from 'node:fs';
17
- import {
18
- ArkTSComponentCodeGeneratorCAPI,
19
- CppComponentCodeGenerator,
20
- NativeModuleCodeGenerator,
21
- UberSchema,
22
- SharedComponentCodeGenerator,
23
- } from '../codegen';
24
- import Case from 'case';
25
- import { LibGlueCodeGenerator } from '../codegen/generators/LibGlueCodeGenerator';
26
-
27
- const COMMAND_NAME = 'codegen-lib-harmony';
28
-
29
- export const commandCodegenLibHarmony: Command = {
30
- name: COMMAND_NAME,
31
- description:
32
- 'Generates boilerplate, types, and utilities from Turbo Module and Fabric Component specifications. Designed for library developers who want to include generated code in their libraries.',
33
- options: [
34
- {
35
- name: '--npm-package-name <string>',
36
- description:
37
- 'Name of your React Native library. This value is processed and used as a directory name for C++ files to reduce the chances of conflicts between libraries.',
38
- },
39
- {
40
- name: '--turbo-modules-spec-paths [path]',
41
- description:
42
- 'Path or paths to Turbo Module spec files. Each path can point to a spec file or a directory containing spec files.',
43
- parse: (val: string) => val.split(' '),
44
- },
45
- {
46
- name: '--arkts-components-spec-paths [path]',
47
- description:
48
- 'Path or paths to component spec files used to generate code for components to be implemented on the ArkTS side. Each path can point to a spec file or a directory containing spec files.',
49
- parse: (val: string) => val.split(' '),
50
- },
51
- {
52
- name: '--cpp-components-spec-paths [path]',
53
- description:
54
- 'Path or paths to component spec files used to generate code for components to be implemented on the C++ side. Each path can point to a spec file or a directory containing spec files.',
55
- parse: (val: string) => val.split(' '),
56
- },
57
- {
58
- name: '--cpp-output-path <path>',
59
- description:
60
- 'Specifies the relative path to the output directory intended for storing generated C++ files.',
61
- },
62
- {
63
- name: '--ets-output-path <path>',
64
- description:
65
- 'Specifies the relative path to the output directory intended for storing generated ETS files.',
66
- },
67
- {
68
- name: '--no-safety-check [boolean]',
69
- description:
70
- 'Skips the check that prevents file operations outside the current working directory. This command permanently deletes previously generated files. Files are generated in the path specified by cpp-output-path.',
71
- },
72
- ],
73
- func: async (_argv, _config, rawArgs: any) => {
74
- const logger = new Logger();
75
- try {
76
- const { args, uberSchemaByType } =
77
- validateArgsAndRetrieveUberSchemaByType(rawArgs);
78
- const fileContentByPath = generateCodeInMemory({
79
- args,
80
- uberSchemaByType,
81
- });
82
- saveAndLogCodegenResult(args, logger, fileContentByPath);
83
- } catch (err) {
84
- if (err instanceof DescriptiveError && !err.isUnexpected()) {
85
- logger.descriptiveError(err);
86
- return;
87
- }
88
- throw err;
89
- }
90
- },
91
- };
92
-
93
- type RawArgs = {
94
- npmPackageName?: string;
95
- turboModulesSpecPaths?: string[];
96
- arktsComponentsSpecPaths?: string[];
97
- cppComponentsSpecPaths?: string[];
98
- cppOutputPath?: string;
99
- etsOutputPath?: string;
100
- safetyCheck?: boolean;
101
- };
102
-
103
- function validateArgsAndRetrieveUberSchemaByType(rawArgs: RawArgs) {
104
- const args = validateRawArgs(rawArgs);
105
- const arkTSComponentSpecPaths = specPathsToSpecFilePaths(
106
- args.arkTSComponentsSpecPaths
107
- );
108
- const turboModulesUberSchema = UberSchema.fromSpecFilePaths(
109
- specPathsToSpecFilePaths(args.tmSpecPaths)
110
- );
111
- const arkTSComponentsUberSchema = UberSchema.fromSpecFilePaths(
112
- arkTSComponentSpecPaths
113
- );
114
- const cppComponentSpecPaths = specPathsToSpecFilePaths(
115
- args.cppComponentsSpecPaths
116
- );
117
- const cppComponentsUberSchema = UberSchema.fromSpecFilePaths(
118
- cppComponentSpecPaths
119
- );
120
- const componentsUberSchema = UberSchema.fromSpecFilePaths([
121
- ...arkTSComponentSpecPaths,
122
- ...cppComponentSpecPaths,
123
- ]);
124
-
125
- return {
126
- args,
127
- uberSchemaByType: {
128
- turboModulesUberSchema,
129
- arkTSComponentsUberSchema,
130
- cppComponentsUberSchema,
131
- componentsUberSchema,
132
- },
133
- };
134
- }
135
-
136
- type Args = {
137
- npmPackageName: string;
138
- tmSpecPaths: AbsolutePath[];
139
- arkTSComponentsSpecPaths: AbsolutePath[];
140
- cppComponentsSpecPaths: AbsolutePath[];
141
- cppOutputPath: AbsolutePath;
142
- etsOutputPath: AbsolutePath;
143
- safetyCheck: boolean;
144
- };
145
-
146
- function validateRawArgs(rawArgs: RawArgs): Args {
147
- if (!rawArgs.npmPackageName) {
148
- throw new DescriptiveError({
149
- whatHappened: '--npm-package-name is required',
150
- whatCanUserDo: ['Please specify --npm-package-name'],
151
- });
152
- }
153
- if (!rawArgs.cppOutputPath) {
154
- throw new DescriptiveError({
155
- whatHappened: '--cpp-output-path is required',
156
- whatCanUserDo: ['Please specify --cpp-output-path'],
157
- });
158
- }
159
- if (!rawArgs.etsOutputPath) {
160
- throw new DescriptiveError({
161
- whatHappened: '--ets-output-path is required',
162
- whatCanUserDo: ['Please specify --ets-output-path'],
163
- });
164
- }
165
- return {
166
- npmPackageName: rawArgs.npmPackageName!,
167
- tmSpecPaths: (rawArgs.turboModulesSpecPaths ?? []).map(
168
- (path) => new AbsolutePath(path)
169
- ),
170
- arkTSComponentsSpecPaths: (rawArgs.arktsComponentsSpecPaths ?? []).map(
171
- (path) => new AbsolutePath(path)
172
- ),
173
- cppComponentsSpecPaths: (rawArgs.cppComponentsSpecPaths ?? []).map(
174
- (path) => new AbsolutePath(path)
175
- ),
176
- etsOutputPath: new AbsolutePath(rawArgs.etsOutputPath!),
177
- cppOutputPath: new AbsolutePath(rawArgs.cppOutputPath!),
178
- safetyCheck: !!rawArgs.safetyCheck,
179
- };
180
- }
181
-
182
- function specPathsToSpecFilePaths(specPaths: AbsolutePath[]): AbsolutePath[] {
183
- const SUPPORTED_SPEC_EXTENSIONS = ['js', 'jsx', 'ts', 'tsx'];
184
- return specPaths.flatMap((specPath) => {
185
- if (!fs.existsSync(specPath.getValue())) {
186
- throw new DescriptiveError({
187
- whatHappened: `No such file or directory: ${specPath.getValue()}`,
188
- whatCanUserDo: [`Are you sure provided specPath exists?`],
189
- });
190
- }
191
- if (fs.lstatSync(specPath.getValue()).isDirectory()) {
192
- return findFilePathsWithExtensions(specPath, SUPPORTED_SPEC_EXTENSIONS);
193
- } else {
194
- const ext = specPath.getExtension();
195
- if (ext && SUPPORTED_SPEC_EXTENSIONS.includes(ext)) {
196
- return [specPath];
197
- }
198
- return [];
199
- }
200
- });
201
- }
202
-
203
- function generateCodeInMemory({
204
- args,
205
- uberSchemaByType: {
206
- arkTSComponentsUberSchema,
207
- componentsUberSchema,
208
- cppComponentsUberSchema,
209
- turboModulesUberSchema,
210
- },
211
- }: ReturnType<typeof validateArgsAndRetrieveUberSchemaByType>) {
212
- const CODEGEN_NOTICE_LINES = [
213
- `This code was generated by "react-native ${COMMAND_NAME}"`,
214
- ];
215
- const fileContentByPath = new Map<AbsolutePath, string>();
216
- const appendToFileContentByPath = (
217
- fileContent: string,
218
- path: AbsolutePath
219
- ) => {
220
- fileContentByPath.set(path, fileContent);
221
- };
222
-
223
- const turboModuleGlueCodeData = turboModulesUberSchema
224
- .findAllSpecSchemasByType('NativeModule')
225
- .map((specSchema) => {
226
- const nativeModuleCodeGenerator = new NativeModuleCodeGenerator(
227
- args.cppOutputPath.copyWithNewSegment(
228
- 'RNOH',
229
- 'generated',
230
- 'turbo_modules'
231
- ),
232
- args.etsOutputPath.copyWithNewSegment('turboModules'),
233
- CODEGEN_NOTICE_LINES,
234
- '@rnoh/react-native-openharmony/ts'
235
- );
236
- nativeModuleCodeGenerator
237
- .generate(specSchema)
238
- .forEach(appendToFileContentByPath);
239
- return nativeModuleCodeGenerator.getGlueCodeData();
240
- })
241
- .flat();
242
-
243
- const arkTSComponentCodeGeneratorCAPI = new ArkTSComponentCodeGeneratorCAPI(
244
- args.cppOutputPath.copyWithNewSegment('RNOH', 'generated', 'components'),
245
- args.etsOutputPath.copyWithNewSegment('components'),
246
- CODEGEN_NOTICE_LINES,
247
- '@rnoh/react-native-openharmony/ts'
248
- );
249
- arkTSComponentCodeGeneratorCAPI
250
- .generate(arkTSComponentsUberSchema)
251
- .forEach(appendToFileContentByPath);
252
-
253
- const libraryCppName = deriveLibraryCppNameFromNpmPackageName(
254
- args.npmPackageName
255
- );
256
- const cppComponentCodeGenerator = new CppComponentCodeGenerator(
257
- (filename) => {
258
- return args.cppOutputPath.copyWithNewSegment(
259
- 'RNOH',
260
- 'generated',
261
- 'components',
262
- filename
263
- );
264
- },
265
- CODEGEN_NOTICE_LINES
266
- );
267
- cppComponentCodeGenerator
268
- .generate({
269
- libraryCppName: libraryCppName,
270
- uberSchema: cppComponentsUberSchema,
271
- })
272
- .forEach(appendToFileContentByPath);
273
-
274
- new SharedComponentCodeGenerator((filename) => {
275
- return args.cppOutputPath.copyWithNewSegment(
276
- 'react',
277
- 'renderer',
278
- 'components',
279
- libraryCppName,
280
- filename
281
- );
282
- })
283
- .generate({
284
- libraryCppName: libraryCppName,
285
- uberSchema: componentsUberSchema,
286
- })
287
- .forEach(appendToFileContentByPath);
288
-
289
- new LibGlueCodeGenerator(
290
- args.cppOutputPath,
291
- args.etsOutputPath,
292
- CODEGEN_NOTICE_LINES
293
- )
294
- .generate({
295
- libraryCppName,
296
- arkTSComponents: arkTSComponentCodeGeneratorCAPI.getLibGlueCodeData(),
297
- cppComponents: cppComponentCodeGenerator
298
- .getGlueCodeData()
299
- .map(({ name }) => ({ componentName: name })),
300
- turboModules: turboModuleGlueCodeData,
301
- })
302
- .forEach(appendToFileContentByPath);
303
-
304
- return fileContentByPath;
305
- }
306
-
307
- function deriveLibraryCppNameFromNpmPackageName(
308
- npmPackageName: string
309
- ): string {
310
- let result = npmPackageName;
311
- if (npmPackageName.includes('/')) {
312
- result.replace('@', '');
313
- result = npmPackageName.replace('/', '__');
314
- }
315
- result = Case.snake(result);
316
- return result;
317
- }
318
-
319
- function saveAndLogCodegenResult(
320
- args: Args,
321
- logger: Logger,
322
- fileContentByPath: ReturnType<typeof generateCodeInMemory>
323
- ) {
324
- saveCodegenResultToFileSystem(
325
- fileContentByPath,
326
- args.cppOutputPath,
327
- args.etsOutputPath,
328
- args.safetyCheck
329
- );
330
- logCodegenResult(logger, fileContentByPath, new AbsolutePath(''));
331
- }
332
-
333
- function saveCodegenResultToFileSystem(
334
- fileContentByPath: Map<AbsolutePath, string>,
335
- cppOutputPath: AbsolutePath,
336
- etsOutputPath: AbsolutePath,
337
- enableSafetyCheck: boolean
338
- ) {
339
- prepareDirectory(cppOutputPath, enableSafetyCheck);
340
- prepareDirectory(etsOutputPath, enableSafetyCheck);
341
- prepareDirectory(
342
- etsOutputPath.copyWithNewSegment('components'),
343
- enableSafetyCheck
344
- );
345
- prepareDirectory(
346
- etsOutputPath.copyWithNewSegment('turboModules'),
347
- enableSafetyCheck
348
- );
349
- fileContentByPath.forEach((_fileContent, path) => {
350
- prepareDirectory(path.getDirectoryPath(), enableSafetyCheck);
351
- });
352
- fileContentByPath.forEach((fileContent, path) => {
353
- fs.writeFileSync(path.getValue(), fileContent);
354
- });
355
- }
356
-
357
- function prepareDirectory(path: AbsolutePath, enableSafetyCheck: boolean) {
358
- maybeMakeDirectories(path);
359
- if (enableSafetyCheck && !path.getValue().startsWith(process.cwd())) {
360
- throw new DescriptiveError({
361
- whatHappened: `Tried to remove files in ${path.getValue()}\nand that path is outside current working directory`,
362
- whatCanUserDo: [
363
- 'Run this command with --no-safety-check flag',
364
- 'Run codegen from different location',
365
- ],
366
- });
367
- }
368
- maybeRemoveFilesInDirectory(path);
369
- }
370
-
371
- function logCodegenResult(
372
- logger: Logger,
373
- fileContentByPath: Map<AbsolutePath, string>,
374
- rootPath: AbsolutePath
375
- ) {
376
- const sortedRelativePathStrings = Array.from(fileContentByPath.keys()).map(
377
- (path) => path.relativeTo(rootPath).getValue()
378
- );
379
- sortedRelativePathStrings.sort();
380
- sortedRelativePathStrings.forEach((pathStr) => {
381
- logger.info((styles) => styles.gray(`• ${pathStr}`));
382
- });
383
- logger.info(() => '');
384
- logger.info(
385
- (styles) =>
386
- `Generated ${styles.green(styles.bold(fileContentByPath.size))} file(s)`
387
- );
388
- logger.info(() => '');
389
- }