json-file.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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.JSONFile = void 0;
  11. const jsonc_parser_1 = require("jsonc-parser");
  12. const eol_1 = require("./eol");
  13. /** @private */
  14. class JSONFile {
  15. host;
  16. path;
  17. content;
  18. eol;
  19. constructor(host, path) {
  20. this.host = host;
  21. this.path = path;
  22. this.content = this.host.readText(this.path);
  23. this.eol = (0, eol_1.getEOL)(this.content);
  24. }
  25. _jsonAst;
  26. get JsonAst() {
  27. if (this._jsonAst) {
  28. return this._jsonAst;
  29. }
  30. const errors = [];
  31. this._jsonAst = (0, jsonc_parser_1.parseTree)(this.content, errors, { allowTrailingComma: true });
  32. if (errors.length) {
  33. const { error, offset } = errors[0];
  34. throw new Error(`Failed to parse "${this.path}" as JSON AST Object. ${(0, jsonc_parser_1.printParseErrorCode)(error)} at location: ${offset}.`);
  35. }
  36. return this._jsonAst;
  37. }
  38. get(jsonPath) {
  39. const jsonAstNode = this.JsonAst;
  40. if (!jsonAstNode) {
  41. return undefined;
  42. }
  43. if (jsonPath.length === 0) {
  44. return (0, jsonc_parser_1.getNodeValue)(jsonAstNode);
  45. }
  46. const node = (0, jsonc_parser_1.findNodeAtLocation)(jsonAstNode, jsonPath);
  47. return node === undefined ? undefined : (0, jsonc_parser_1.getNodeValue)(node);
  48. }
  49. modify(jsonPath, value, insertInOrder) {
  50. let getInsertionIndex;
  51. if (insertInOrder === undefined) {
  52. const property = jsonPath.slice(-1)[0];
  53. getInsertionIndex = (properties) => [...properties, property].sort().findIndex((p) => p === property);
  54. }
  55. else if (insertInOrder !== false) {
  56. getInsertionIndex = insertInOrder;
  57. }
  58. const edits = (0, jsonc_parser_1.modify)(this.content, jsonPath, value, {
  59. getInsertionIndex,
  60. formattingOptions: {
  61. eol: this.eol,
  62. insertSpaces: true,
  63. tabSize: 2,
  64. },
  65. });
  66. this.content = (0, jsonc_parser_1.applyEdits)(this.content, edits);
  67. this.host.overwrite(this.path, this.content);
  68. this._jsonAst = undefined;
  69. }
  70. remove(jsonPath) {
  71. if (this.get(jsonPath) !== undefined) {
  72. this.modify(jsonPath, undefined);
  73. }
  74. }
  75. }
  76. exports.JSONFile = JSONFile;