/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45// First group matches a double quoted string6// Second group matches a single quoted string7// Third group matches a multi line comment8// Forth group matches a single line comment9// Fifth group matches a trailing comma10const regexp = /("[^"\\]*(?:\\.[^"\\]*)*")|('[^'\\]*(?:\\.[^'\\]*)*')|(\/\*[^\/\*]*(?:(?:\*|\/)[^\/\*]*)*?\*\/)|(\/{2,}.*?(?:(?:\r?\n)|$))|(,\s*[}\]])/g;1112/**13* Strips single and multi line JavaScript comments from JSON14* content. Ignores characters in strings BUT doesn't support15* string continuation across multiple lines since it is not16* supported in JSON.17*18* @param content the content to strip comments from19* @returns the content without comments20*/21export function stripComments(content: string): string {22return content.replace(regexp, function (match, _m1, _m2, m3, m4, m5) {23// Only one of m1, m2, m3, m4, m5 matches24if (m3) {25// A block comment. Replace with nothing26return '';27} else if (m4) {28// Since m4 is a single line comment is is at least of length 2 (e.g. //)29// If it ends in \r?\n then keep it.30const length = m4.length;31if (m4[length - 1] === '\n') {32return m4[length - 2] === '\r' ? '\r\n' : '\n';33}34else {35return '';36}37} else if (m5) {38// Remove the trailing comma39return match.substring(1);40} else {41// We match a string42return match;43}44});45}4647/**48* A drop-in replacement for JSON.parse that can parse49* JSON with comments and trailing commas.50*51* @param content the content to strip comments from52* @returns the parsed content as JSON53*/54export function parse<T>(content: string): T {55const commentsStripped = stripComments(content);5657try {58return JSON.parse(commentsStripped);59} catch (error) {60const trailingCommasStriped = commentsStripped.replace(/,\s*([}\]])/g, '$1');61return JSON.parse(trailingCommasStriped);62}63}646566