UNPKG

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