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