@react-native-oh/react-native-harmony-cli 0.0.37 → 0.0.40-1

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 (84) hide show
  1. package/dist/autolinking/Autolinking.js +14 -11
  2. package/dist/codegen/generators/UberGeneratorV1.js +9 -2
  3. package/dist/codegen/generators/UberGeneratorV2.js +8 -1
  4. package/dist/commands/codegen-harmony.js +16 -5
  5. package/dist/commands/run-harmony.js +0 -2
  6. package/dist/core/ProjectDependenciesManager.js +5 -7
  7. package/dist/simulator/LaunchSimulator.js +9 -2
  8. package/harmony/rnoh-hvigor-plugin-0.3.0.tgz +0 -0
  9. package/package.json +10 -2
  10. package/.prettierrc +0 -6
  11. package/src/assetResolver.ts +0 -134
  12. package/src/autolinking/Autolinking.test.ts +0 -483
  13. package/src/autolinking/Autolinking.ts +0 -382
  14. package/src/autolinking/index.ts +0 -8
  15. package/src/codegen/core/CodeGenerator.ts +0 -16
  16. package/src/codegen/core/CodegenError.ts +0 -10
  17. package/src/codegen/core/EventUtils.ts +0 -23
  18. package/src/codegen/core/TypeAnnotationToTS.test.ts +0 -82
  19. package/src/codegen/core/TypeAnnotationToTS.ts +0 -195
  20. package/src/codegen/core/UberSchema.ts +0 -152
  21. package/src/codegen/core/index.ts +0 -12
  22. package/src/codegen/generators/AppBuildTimeGlueCodeGenerator.ts +0 -124
  23. package/src/codegen/generators/ArkTSComponentCodeGeneratorArkTS.ts +0 -128
  24. package/src/codegen/generators/ArkTSComponentCodeGeneratorCAPI.ts +0 -122
  25. package/src/codegen/generators/CppComponentCodeGenerator.ts +0 -95
  26. package/src/codegen/generators/LibGlueCodeGenerator.ts +0 -98
  27. package/src/codegen/generators/NativeModuleCodeGenerator.ts +0 -124
  28. package/src/codegen/generators/SharedComponentCodeGenerator.ts +0 -57
  29. package/src/codegen/generators/UberGeneratorV1.ts +0 -75
  30. package/src/codegen/generators/UberGeneratorV2.ts +0 -114
  31. package/src/codegen/generators/index.ts +0 -15
  32. package/src/codegen/index.ts +0 -9
  33. package/src/codegen/templates/BaseComponentInstanceHTemplate.ts +0 -128
  34. package/src/codegen/templates/BasePackageHTemplate.ts +0 -159
  35. package/src/codegen/templates/ComponentDescriptorHTemplate.ts +0 -63
  36. package/src/codegen/templates/ComponentJSIBinderHTemplate.ts +0 -121
  37. package/src/codegen/templates/ComponentUtilsTSTemplate.ts +0 -222
  38. package/src/codegen/templates/IndexTSTemplate.ts +0 -62
  39. package/src/codegen/templates/RNOHGeneratedPackageHTemplate.ts +0 -150
  40. package/src/codegen/templates/TurboModuleCppTemplate.ts +0 -61
  41. package/src/codegen/templates/TurboModuleHTemplate.ts +0 -42
  42. package/src/codegen/templates/TurboModuleSpecTSTemplate.ts +0 -101
  43. package/src/codegen/templates/index.ts +0 -16
  44. package/src/commands/bundle-harmony.ts +0 -134
  45. package/src/commands/codegen-harmony.ts +0 -297
  46. package/src/commands/codegen-lib-harmony.ts +0 -389
  47. package/src/commands/create-metro-host-constants.ts +0 -55
  48. package/src/commands/index.ts +0 -16
  49. package/src/commands/init.ts +0 -755
  50. package/src/commands/link-harmony.ts +0 -102
  51. package/src/commands/pack-harmony.ts +0 -128
  52. package/src/commands/run-harmony.ts +0 -506
  53. package/src/commands/types.ts +0 -21
  54. package/src/commands/unpack-harmony.ts +0 -238
  55. package/src/commands/verify-package-harmony.ts +0 -113
  56. package/src/core/AbsolutePath.ts +0 -66
  57. package/src/core/CodegenConfig.ts +0 -67
  58. package/src/core/DescriptiveError.ts +0 -68
  59. package/src/core/FileSystem.ts +0 -57
  60. package/src/core/OHPackageJSON5.ts +0 -30
  61. package/src/core/PackageJSON.ts +0 -104
  62. package/src/core/ProjectDependenciesManager.ts +0 -103
  63. package/src/core/ValidationError.ts +0 -8
  64. package/src/core/ValueObject.ts +0 -9
  65. package/src/core/fs.ts +0 -38
  66. package/src/core/index.ts +0 -17
  67. package/src/index.ts +0 -33
  68. package/src/io/CliExecutor.ts +0 -69
  69. package/src/io/Logger.ts +0 -112
  70. package/src/io/RealFS.ts +0 -62
  71. package/src/io/TarGz.ts +0 -33
  72. package/src/io/__fixtures__.ts +0 -139
  73. package/src/io/fsUtils.ts +0 -44
  74. package/src/io/index.ts +0 -11
  75. package/src/package-verifier/checks/HarmonyDirContainsOnlyHarsCheck.ts +0 -35
  76. package/src/package-verifier/checks/HarmonyDirExistsCheck.ts +0 -31
  77. package/src/package-verifier/checks/NpmAnAndOhPackageVersionsAreEqual.ts +0 -25
  78. package/src/package-verifier/checks/OhPackageNameFollowsNamingConventionCheck.ts +0 -54
  79. package/src/package-verifier/checks/index.ts +0 -11
  80. package/src/package-verifier/index.ts +0 -9
  81. package/src/package-verifier/types.ts +0 -19
  82. package/src/package-verifier/verify-package.ts +0 -123
  83. package/src/simulator/LaunchSimulator.ts +0 -352
  84. package/src/simulator/index.ts +0 -8
@@ -23,6 +23,7 @@ const json5_1 = __importDefault(require("json5"));
23
23
  const core_1 = require("../core");
24
24
  const mustache_1 = __importDefault(require("mustache"));
25
25
  const case_1 = __importDefault(require("case"));
26
+ const node_path_1 = __importDefault(require("node:path"));
26
27
  const ETS_RNOH_PACKAGES_FACTORY_TEMPLATE = `
27
28
  /*
28
29
  * This file was generated by RNOH autolinking.
@@ -50,7 +51,7 @@ const CPP_RNOH_PACKAGES_FACTORY_TEMPLATE = `
50
51
  #pragma once
51
52
  #include "RNOH/Package.h"
52
53
  {{#libraries}}
53
- #include "{{etsRNOHPackageClassName}}.h"
54
+ #include "{{cppRNOHPackageClassName}}.h"
54
55
  {{/libraries}}
55
56
 
56
57
  std::vector<rnoh::Package::Shared> createRNOHPackages(const rnoh::Package::Context &ctx) {
@@ -66,7 +67,7 @@ const CMAKE_AUTOLINKING_TEMPLATE = `
66
67
  # DO NOT modify it manually, your changes WILL be overwritten.
67
68
  cmake_minimum_required(VERSION 3.5)
68
69
 
69
- # @api
70
+ # @actor RNOH_APP
70
71
  function(autolink_libraries target)
71
72
  {{#libraries}}
72
73
  add_subdirectory("\${OH_MODULES_DIR}/{{{ohPackageName}}}/src/main/cpp" ./{{cmakeLibraryTargetName}})
@@ -111,11 +112,11 @@ class Autolinking {
111
112
  const skippedLibraryNpmPackageNames = [];
112
113
  yield new core_1.ProjectDependenciesManager(this.fs, projectRootPath).forEachAsync((dependency) => {
113
114
  var _a;
114
- const harFilePath = dependency.getHarFilePath();
115
- if (!harFilePath) {
115
+ const harFilePaths = dependency.getHarFilePaths();
116
+ if (harFilePaths.length === 0) {
116
117
  return;
117
118
  }
118
- nodeModuleHarPaths.push(harFilePath);
119
+ nodeModuleHarPaths.push(...harFilePaths);
119
120
  const packageJson = dependency.readPackageJSON();
120
121
  const providedAutolinkingConfig = (_a = packageJson.harmony) === null || _a === void 0 ? void 0 : _a.autolinking;
121
122
  if (providedAutolinkingConfig === undefined ||
@@ -123,7 +124,8 @@ class Autolinking {
123
124
  (config.excludedNpmPackageNames.has(packageJson.name) &&
124
125
  config.excludedNpmPackageNames.size > 0) ||
125
126
  (!config.includedNpmPackageNames.has(packageJson.name) &&
126
- config.includedNpmPackageNames.size > 0)) {
127
+ config.includedNpmPackageNames.size > 0) ||
128
+ harFilePaths.length !== 1) {
127
129
  skippedLibraryNpmPackageNames.push(packageJson.name);
128
130
  return;
129
131
  }
@@ -134,7 +136,7 @@ class Autolinking {
134
136
  cppRNOHPackageClassName: autolinkingConfig === null || autolinkingConfig === void 0 ? void 0 : autolinkingConfig.cppPackageClassName,
135
137
  cmakeLibraryTargetName: autolinkingConfig === null || autolinkingConfig === void 0 ? void 0 : autolinkingConfig.cmakeLibraryTargetName,
136
138
  ohPackageName: autolinkingConfig === null || autolinkingConfig === void 0 ? void 0 : autolinkingConfig.ohPackageName,
137
- harFilePathRelativeToHarmony: harFilePath
139
+ harFilePathRelativeToHarmony: harFilePaths[0]
138
140
  .relativeTo(harmonyProjectPath)
139
141
  .toString(),
140
142
  });
@@ -171,13 +173,14 @@ class Autolinking {
171
173
  const autolinkableHarFilePathsRelativeToHarmony = autolinkableLibraries.map((lib) => lib.harFilePathRelativeToHarmony);
172
174
  const unmanagedNativeDependencySpecifierByName = {};
173
175
  Object.entries(ohPackage.dependencies).forEach(([name, dependencySpecifier]) => {
174
- if (!dependencySpecifier.includes('file:')) {
176
+ if (!(dependencySpecifier.includes('file:') &&
177
+ dependencySpecifier.includes('node_modules'))) {
175
178
  unmanagedNativeDependencySpecifierByName[name] = dependencySpecifier;
176
179
  }
177
180
  else {
178
181
  const harFilePathRelativeToHarmony = dependencySpecifier.replace('file:', '');
179
- if (!autolinkableHarFilePathsRelativeToHarmony.includes(harFilePathRelativeToHarmony) &&
180
- input.nodeModuleHarFilePathsRelativeToHarmony.includes(harFilePathRelativeToHarmony)) {
182
+ if (!autolinkableHarFilePathsRelativeToHarmony.includes(node_path_1.default.normalize(harFilePathRelativeToHarmony)) &&
183
+ input.nodeModuleHarFilePathsRelativeToHarmony.includes(node_path_1.default.normalize(harFilePathRelativeToHarmony))) {
181
184
  unmanagedNativeDependencySpecifierByName[name] =
182
185
  dependencySpecifier;
183
186
  }
@@ -186,7 +189,7 @@ class Autolinking {
186
189
  const managedNativeDependencySpecifierByName = {};
187
190
  for (const library of autolinkableLibraries) {
188
191
  managedNativeDependencySpecifierByName[library.ohPackageName] =
189
- 'file:' + library.harFilePathRelativeToHarmony;
192
+ `file:${library.harFilePathRelativeToHarmony}`.split(node_path_1.default.sep).join('/');
190
193
  }
191
194
  return {
192
195
  skippedLibraryNpmPackageNames: input.skippedLibraryNpmPackageNames,
@@ -5,11 +5,17 @@
5
5
  * This source code is licensed under the MIT license found in the
6
6
  * LICENSE-MIT file in the root directory of this source tree.
7
7
  */
8
+ var __importDefault = (this && this.__importDefault) || function (mod) {
9
+ return (mod && mod.__esModule) ? mod : { "default": mod };
10
+ };
8
11
  Object.defineProperty(exports, "__esModule", { value: true });
9
12
  exports.UberGeneratorV1 = void 0;
13
+ const path_1 = __importDefault(require("path"));
10
14
  const core_1 = require("../core");
11
15
  const NativeModuleCodeGenerator_1 = require("./NativeModuleCodeGenerator");
12
16
  const ArkTSComponentCodeGeneratorArkTS_1 = require("./ArkTSComponentCodeGeneratorArkTS");
17
+ // The name of rnoh OHOS module
18
+ const RNOH_OHOS_NAME = '@rnoh/react-native-openharmony';
13
19
  /**
14
20
  * Generates code for libraries built on top of RNOH's ArkTS architecture.
15
21
  */
@@ -25,8 +31,9 @@ class UberGeneratorV1 {
25
31
  }
26
32
  generate(uberSchema) {
27
33
  const fileContentByPath = new Map();
28
- const componentCodeGenerator = new ArkTSComponentCodeGeneratorArkTS_1.ArkTSComponentCodeGeneratorArkTS(this.cppOutputPath, this.etsOutputPath.copyWithNewSegment('components'), this.codegenNoticeLines, '../../ts');
29
- const nativeModuleCodeGenerator = new NativeModuleCodeGenerator_1.NativeModuleCodeGenerator(this.cppOutputPath, this.etsOutputPath.copyWithNewSegment('turboModules'), this.codegenNoticeLines, '../../ts');
34
+ const isRNOHModulePath = this.etsOutputPath.getValue().endsWith(`${RNOH_OHOS_NAME}/generated`.replace(/\//g, path_1.default.sep));
35
+ const componentCodeGenerator = new ArkTSComponentCodeGeneratorArkTS_1.ArkTSComponentCodeGeneratorArkTS(this.cppOutputPath, this.etsOutputPath.copyWithNewSegment('components'), this.codegenNoticeLines, isRNOHModulePath ? '../../ts' : `${RNOH_OHOS_NAME}/ts`);
36
+ const nativeModuleCodeGenerator = new NativeModuleCodeGenerator_1.NativeModuleCodeGenerator(this.cppOutputPath, this.etsOutputPath.copyWithNewSegment('turboModules'), this.codegenNoticeLines, isRNOHModulePath ? '../../ts' : `${RNOH_OHOS_NAME}/ts`);
30
37
  const generatorBySpecType = {
31
38
  Component: componentCodeGenerator,
32
39
  NativeModule: nativeModuleCodeGenerator,
@@ -5,11 +5,17 @@
5
5
  * This source code is licensed under the MIT license found in the
6
6
  * LICENSE-MIT file in the root directory of this source tree.
7
7
  */
8
+ var __importDefault = (this && this.__importDefault) || function (mod) {
9
+ return (mod && mod.__esModule) ? mod : { "default": mod };
10
+ };
8
11
  Object.defineProperty(exports, "__esModule", { value: true });
9
12
  exports.UberGeneratorV2 = void 0;
13
+ const path_1 = __importDefault(require("path"));
10
14
  const CppComponentCodeGenerator_1 = require("./CppComponentCodeGenerator");
11
15
  const NativeModuleCodeGenerator_1 = require("./NativeModuleCodeGenerator");
12
16
  const SharedComponentCodeGenerator_1 = require("./SharedComponentCodeGenerator");
17
+ // The name of rnoh OHOS module
18
+ const RNOH_OHOS_NAME = '@rnoh/react-native-openharmony';
13
19
  /**
14
20
  * Generates code for libraries built on top of RNOH's C-API architecture.
15
21
  */
@@ -57,7 +63,8 @@ class UberGeneratorV2 {
57
63
  .getSpecSchemaByFilenameMap()
58
64
  .entries()) {
59
65
  if (specSchema.type === 'NativeModule') {
60
- const nativeModuleCodeGenerator = new NativeModuleCodeGenerator_1.NativeModuleCodeGenerator(libraryCppOutput.copyWithNewSegment('RNOH', 'generated', 'turbo_modules'), this.etsOutputPath.copyWithNewSegment('turboModules'), this.codegenNoticeLines, '../../ts');
66
+ const isRNOHModulePath = this.etsOutputPath.getValue().endsWith(`${RNOH_OHOS_NAME}/generated`.replace(/\//g, path_1.default.sep));
67
+ const nativeModuleCodeGenerator = new NativeModuleCodeGenerator_1.NativeModuleCodeGenerator(libraryCppOutput.copyWithNewSegment('RNOH', 'generated', 'turbo_modules'), this.etsOutputPath.copyWithNewSegment('turboModules'), this.codegenNoticeLines, isRNOHModulePath ? '../../ts' : `${RNOH_OHOS_NAME}/ts`);
61
68
  nativeModuleCodeGenerator
62
69
  .generate(specSchema)
63
70
  .forEach((fileContent, filePath) => {
@@ -30,7 +30,11 @@ exports.commandCodegenHarmony = {
30
30
  options: [
31
31
  {
32
32
  name: '--rnoh-module-path <path>',
33
- description: 'Specifies the relative path to the rnoh OHOS module',
33
+ description: '[deprecated] Specifies the relative path to the rnoh OHOS module',
34
+ },
35
+ {
36
+ name: '--ets-output-path <path>',
37
+ description: 'Specifies the relative path to the output directory intended for storing generated ETS files.',
34
38
  },
35
39
  {
36
40
  name: '--cpp-output-path <path>',
@@ -59,7 +63,12 @@ exports.commandCodegenHarmony = {
59
63
  const MAX_SUPPORTED_CODEGEN_VERSION = 2;
60
64
  // prepare the input data
61
65
  validateArgs(args);
62
- const etsOutputPath = new core_1.AbsolutePath(args.rnohModulePath).copyWithNewSegment('generated');
66
+ let etsOutputPath = args.etsOutputPath || args.rnohModulePath;
67
+ const isEndWithGenerated = /\/generated\/?$/.test(etsOutputPath);
68
+ etsOutputPath = new core_1.AbsolutePath(etsOutputPath);
69
+ if (!isEndWithGenerated) {
70
+ etsOutputPath = etsOutputPath.copyWithNewSegment('generated');
71
+ }
63
72
  const enableSafetyCheck = args.safetyCheck;
64
73
  const cppOutputPath = new core_1.AbsolutePath(args.cppOutputPath);
65
74
  const projectRootPath = new core_1.AbsolutePath(args.projectRootPath);
@@ -116,11 +125,13 @@ exports.commandCodegenHarmony = {
116
125
  }),
117
126
  };
118
127
  function validateArgs(args) {
119
- if (!args.rnohModulePath) {
128
+ if (!args.rnohModulePath && !args.etsOutputPath) {
120
129
  throw new core_1.DescriptiveError({
121
- whatHappened: "--rnoh-module-path argument wasn't provided",
130
+ whatHappened: '--ets-output-path is required',
122
131
  whatCanUserDo: [
123
- 'Please provide a path to the native React Native for Open Harmony module (rnoh) which is probably located somewhere in "<PROJECT_ROOT>/harmony" directory',
132
+ 'Please provide an output path for the ETS file.',
133
+ 'It is recommended to place it in the same directory as the custom component or TurboModule.',
134
+ 'Do not place it inside @rnoh/react-native-openharmony, otherwise a jscrash may occur when using react_native_openharmony_release2.har.'
124
135
  ],
125
136
  });
126
137
  }
@@ -245,8 +245,6 @@ exports.commandRunHarmony = {
245
245
  args: [
246
246
  'install',
247
247
  '--all',
248
- '--strict_ssl',
249
- 'true',
250
248
  ],
251
249
  cwd: harmonyProjectPath,
252
250
  shell: true,
@@ -29,16 +29,14 @@ class ProjectDependency {
29
29
  getCodegenConfigs() {
30
30
  return this.readPackageJSON().getCodegenConfigs();
31
31
  }
32
- getHarFilePath() {
32
+ getHarFilePaths() {
33
33
  const packageHarmonyPath = this.packageRootPath.copyWithNewSegment('harmony');
34
- if (!this.fs.existsSync(packageHarmonyPath)) {
35
- return null;
34
+ if (this.fs.existsSync(packageHarmonyPath)) {
35
+ return this.fs.findFilePathsWithExtensions(packageHarmonyPath, ['har']);
36
36
  }
37
- const harFilePaths = this.fs.findFilePathsWithExtensions(packageHarmonyPath, ['har']);
38
- if (harFilePaths.length !== 1) {
39
- return null;
37
+ else {
38
+ return this.fs.findFilePathsWithExtensions(this.packageRootPath, ['har']);
40
39
  }
41
- return harFilePaths[0];
42
40
  }
43
41
  readPackageJSON() {
44
42
  return PackageJSON_1.PackageJSON.fromProjectRootPath(this.fs, this.packageRootPath, this.projectRootPath);
@@ -45,13 +45,20 @@ function getCreatedSimulators(cli, emulator) {
45
45
  return __awaiter(this, void 0, void 0, function* () {
46
46
  try {
47
47
  let simulatorInfos = '';
48
+ let simulatorInfosFromStderr = '';
48
49
  yield cli.run(`"${emulator}"`, {
49
50
  args: ['--list'],
50
51
  shell: true,
51
- onStderr: (msg) => {
52
+ onStdout: (msg) => {
52
53
  simulatorInfos += msg;
53
54
  },
55
+ onStderr: (msg) => {
56
+ simulatorInfosFromStderr += msg;
57
+ },
54
58
  });
59
+ if (simulatorInfos == null || simulatorInfos.trim() === '') {
60
+ simulatorInfos = simulatorInfosFromStderr;
61
+ }
55
62
  if (!simulatorInfos || simulatorInfos.trim() === '' ||
56
63
  simulatorInfos.trim() === '[Empty]' ||
57
64
  simulatorInfos.includes('not ')) {
@@ -281,7 +288,7 @@ function launchHarmonySimulator(opt) {
281
288
  const quoteIfNeeded = (p) => process.platform === 'win32' ? `"${p}"` : p;
282
289
  const args = [
283
290
  '-hvd',
284
- simulatorName[0].trim(),
291
+ quoteIfNeeded(simulatorName[0].trim()),
285
292
  '-path',
286
293
  quoteIfNeeded(paths.instancePath),
287
294
  '-imageRoot',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@react-native-oh/react-native-harmony-cli",
3
- "version": "0.0.37",
3
+ "version": "0.0.40-1",
4
4
  "description": "",
5
5
  "publishConfig": {
6
6
  "registry": "https://registry.npmjs.org/",
@@ -8,7 +8,8 @@
8
8
  },
9
9
  "scripts": {
10
10
  "build": "tsc --outDir dist -p tsconfig.build.json",
11
- "prepack": "npm run build",
11
+ "prepack": "npm run build && npm run _recreate-hvigor-plugin",
12
+ "_recreate-hvigor-plugin": "cd ../react-native-harmony-hvigor-plugin && npm i && npm run deploy && cd ../react-native-harmony-cli",
12
13
  "verify": "tsc --noEmit && npm run test",
13
14
  "test": "npm run build && jest",
14
15
  "test:codegen": "jest ./src/codegen/.* && npm run build && jest tests/codegen.*",
@@ -25,6 +26,13 @@
25
26
  "metro": "*"
26
27
  },
27
28
  "main": "dist/index.js",
29
+ "files": [
30
+ "./*.js",
31
+ "./*.json",
32
+ "./dist/*",
33
+ "./harmony/*",
34
+ "./README.md"
35
+ ],
28
36
  "devDependencies": {
29
37
  "@react-native-community/cli": "^15.0.0",
30
38
  "@react-native-community/cli-types": "^11.3.0",
package/.prettierrc DELETED
@@ -1,6 +0,0 @@
1
- {
2
- "trailingComma": "es5",
3
- "tabWidth": 2,
4
- "semi": true,
5
- "singleQuote": true
6
- }
@@ -1,134 +0,0 @@
1
- /**
2
- * Copyright (c) 2024 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
- import fs from 'fs';
8
- import pathUtils from 'path';
9
- import type { AssetData } from 'metro';
10
- import { Logger } from './io';
11
-
12
- type Path = string;
13
- type CopiedFiles = Record<Path, Path>;
14
-
15
- const ALLOWED_SCALES: number[] = [1, 2, 3, 4];
16
-
17
- function filterAssetScales(
18
- scales: readonly number[],
19
- ): readonly number[] {
20
- const result = scales.filter(scale => ALLOWED_SCALES.includes(scale));
21
- if (result.length === 0 && scales.length > 0) {
22
- // No matching scale found, but there are some available. Ideally we don't
23
- // want to be in this situation and should throw, but for now as a fallback
24
- // let's just use the closest larger image
25
- const maxScale = ALLOWED_SCALES[ALLOWED_SCALES.length - 1];
26
- for (const scale of scales) {
27
- if (scale > maxScale) {
28
- result.push(scale);
29
- break;
30
- }
31
- }
32
- // There is no larger scales available, use the largest we have
33
- if (result.length === 0) {
34
- result.push(scales[scales.length - 1]);
35
- }
36
- }
37
- return result;
38
- }
39
-
40
- export async function copyAssets(
41
- logger: Logger,
42
- assetsData: readonly AssetData[],
43
- assetsDest: Path
44
- ): Promise<void> {
45
- if (assetsDest == null) {
46
- logger.warn((s) => 'Assets destination folder is not set, skipping...');
47
- return;
48
- }
49
-
50
- const filesToCopy: CopiedFiles = {};
51
- const addAssetToCopy = (asset: AssetData) => {
52
- const validScales = filterAssetScales(asset.scales);
53
- asset.scales.forEach((scale, idx) => {
54
- if (!validScales.includes(scale)) {
55
- return;
56
- }
57
- const src = asset.files[idx];
58
- const dest = pathUtils.join(assetsDest, getAssetDestRelativePath(asset, scale));
59
- filesToCopy[src] = dest;
60
- });
61
- };
62
-
63
- assetsData.forEach(addAssetToCopy);
64
-
65
- return copyFiles(logger, filesToCopy);
66
- }
67
-
68
- function getAssetDestRelativePath(asset: AssetData, scale: number = 1): string {
69
- const suffix = scale === 1 ? '' : `@${scale}x`;
70
- const fileName = getResourceIdentifier(asset);
71
- // Assets can have relative paths outside of the project root.
72
- // Replace `../` with `_` to make sure they don't end up outside of
73
- // the expected assets directory.
74
- return `${fileName + suffix}.${asset.type}`.replace(/\.\.\//g, '_');
75
- }
76
-
77
- function getResourceIdentifier(asset: AssetData): string {
78
- const folderPath = getBasePath(asset);
79
- return `${folderPath}/${asset.name}`.replace(/^assets\//, '');
80
- }
81
-
82
- function getBasePath(asset: AssetData): string {
83
- const basePath = asset.httpServerLocation;
84
- return basePath.startsWith('/') ? basePath.slice(1) : basePath;
85
- }
86
-
87
- function copyFiles(logger: Logger, fileDestBySrc: CopiedFiles) {
88
- const fileSources = Object.keys(fileDestBySrc);
89
- if (fileSources.length === 0) {
90
- return Promise.resolve();
91
- }
92
-
93
- const assetFilesCount = fileSources.length;
94
- return new Promise<void>((resolve, reject) => {
95
- const copyNext = (error?: Error) => {
96
- if (error) {
97
- reject(error);
98
- return;
99
- }
100
- if (fileSources.length === 0) {
101
- logger.info(
102
- () =>
103
- `Copied ${assetFilesCount} ${
104
- assetFilesCount === 1 ? 'asset' : 'assets'
105
- }`
106
- );
107
- resolve();
108
- } else {
109
- // fileSources.length === 0 is checked in previous branch, so this is string
110
- const src = fileSources.shift()!;
111
- const dest = fileDestBySrc[src];
112
- copyFile(src, dest, copyNext);
113
- }
114
- };
115
- copyNext();
116
- });
117
- }
118
-
119
- function copyFile(
120
- src: string,
121
- dest: string,
122
- onFinished: (error?: Error) => void
123
- ): void {
124
- const destDir = pathUtils.dirname(dest);
125
- fs.mkdir(destDir, { recursive: true }, (err?) => {
126
- if (err) {
127
- onFinished(err);
128
- return;
129
- }
130
- fs.createReadStream(src)
131
- .pipe(fs.createWriteStream(dest))
132
- .on('finish', onFinished);
133
- });
134
- }