package-config.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. "use strict";
  2. /**
  3. * @license
  4. * Copyright Google LLC All Rights Reserved.
  5. *
  6. * Use of this source code is governed by an MIT-style license that can be
  7. * found in the LICENSE file at https://angular.dev/license
  8. */
  9. Object.defineProperty(exports, "__esModule", { value: true });
  10. exports.addPackageToPackageJson = addPackageToPackageJson;
  11. exports.getPackageVersionFromPackageJson = getPackageVersionFromPackageJson;
  12. /**
  13. * Sorts the keys of the given object.
  14. * @returns A new object instance with sorted keys
  15. */
  16. function sortObjectByKeys(obj) {
  17. return Object.keys(obj)
  18. .sort()
  19. .reduce((result, key) => {
  20. result[key] = obj[key];
  21. return result;
  22. }, {});
  23. }
  24. /** Adds a package to the package.json in the given host tree. */
  25. function addPackageToPackageJson(host, pkg, version) {
  26. if (host.exists('package.json')) {
  27. const sourceText = host.read('package.json').toString('utf-8');
  28. const json = JSON.parse(sourceText);
  29. if (!json.dependencies) {
  30. json.dependencies = {};
  31. }
  32. if (!json.dependencies[pkg]) {
  33. json.dependencies[pkg] = version;
  34. json.dependencies = sortObjectByKeys(json.dependencies);
  35. }
  36. host.overwrite('package.json', JSON.stringify(json, null, 2));
  37. }
  38. return host;
  39. }
  40. /** Gets the version of the specified package by looking at the package.json in the given tree. */
  41. function getPackageVersionFromPackageJson(tree, name) {
  42. if (!tree.exists('package.json')) {
  43. return null;
  44. }
  45. const packageJson = JSON.parse(tree.read('package.json').toString('utf8'));
  46. if (packageJson.dependencies && packageJson.dependencies[name]) {
  47. return packageJson.dependencies[name];
  48. }
  49. return null;
  50. }
  51. //# sourceMappingURL=package-config.js.map