diff --git a/src/ng-add.ts b/src/ng-add.ts index 9131c87..c6d71a2 100644 --- a/src/ng-add.ts +++ b/src/ng-add.ts @@ -1,4 +1,5 @@ -import { JsonParseMode, parseJson } from '@angular-devkit/core'; +import { ParseError, parse, printParseErrorCode } from 'jsonc-parser'; +import { JsonValue } from '@angular-devkit/core'; import { SchematicContext, SchematicsException, @@ -6,6 +7,23 @@ import { } from '@angular-devkit/schematics'; import { Workspace } from './interfaces'; +export function parseJsonFile(json: string): JsonValue { + const errors: ParseError[] = []; + const content = parse(json, errors, { allowTrailingComma: true }); + + if (errors.length) { + const { error, offset } = errors[0]; + throw new Error( + `Failed to parse as JSON AST Object. ${printParseErrorCode( + error, + )} at location: ${offset}.`, + ); + } + + return content; +} + + function getWorkspace(host: Tree): { path: string; workspace: Workspace } { const possibleFiles = ['/angular.json', '/.angular.json']; const path = possibleFiles.filter(path => host.exists(path))[0]; @@ -18,7 +36,7 @@ function getWorkspace(host: Tree): { path: string; workspace: Workspace } { let workspace: Workspace; try { - workspace = (parseJson(content, JsonParseMode.Loose) as {}) as Workspace; + workspace = (parseJsonFile(content) as {}) as Workspace; } catch (e) { throw new SchematicsException(`Could not parse angular.json: ` + e.message); } diff --git a/src/package-lock.json b/src/package-lock.json index a3bf3bd..4782493 100644 --- a/src/package-lock.json +++ b/src/package-lock.json @@ -3630,6 +3630,11 @@ "minimist": "^1.2.5" } }, + "jsonc-parser": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.0.0.tgz", + "integrity": "sha512-fQzRfAbIBnR0IQvftw9FJveWiHp72Fg20giDrHz6TdfB12UH/uue0D3hm57UB5KgAVuniLMCaS8P1IMj9NR7cA==" + }, "jsonfile": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", diff --git a/src/package.json b/src/package.json index 647423a..bcb1f83 100644 --- a/src/package.json +++ b/src/package.json @@ -74,7 +74,8 @@ "dependencies": { "commander": "^3.0.0-0", "fs-extra": "^9.0.1", - "gh-pages": "^3.1.0" + "gh-pages": "^3.1.0", + "jsonc-parser": "^3.0.0" }, "husky": { "hooks": {