/*!--------------------------------------------------------
 * Copyright (C) 周登祥. All rights reserved.
 *--------------------------------------------------------*/
(function() {
var __m = ["exports","require","vs/platform/instantiation/common/instantiation","vs/base/common/path","vs/base/common/types","vs/platform/log/common/log","vs/base/common/event","vs/base/common/objects","vs/nls!vs/code/node/cliProcessMain","vs/nls","vs/base/common/lifecycle","vs/base/node/pfs","vs/platform/configuration/common/configuration","vs/platform/extensionManagement/common/extensionManagementUtil","vs/platform/environment/common/environment","vs/platform/registry/common/platform","vs/base/common/strings","vs/base/common/arrays","vs/base/common/platform","vs/platform/configuration/common/configurationRegistry","vs/base/common/uri","vs/platform/product/node/package","vs/platform/product/node/product","vs/platform/extensionManagement/common/extensionManagement","vs/base/common/async","vs/base/common/errors","os","vs/platform/telemetry/common/telemetry","vs/base/common/network","fs","vs/platform/extensions/common/extensions","vs/platform/instantiation/common/descriptors","vs/base/common/amd","vs/base/common/json","vs/base/common/errorMessage","vs/platform/extensions/node/extensionsUtil","vs/platform/instantiation/common/serviceCollection","vs/platform/extensionManagement/node/extensionManagementUtil","vs/base/node/extfs","vs/platform/configuration/common/configurationModels","vs/platform/request/node/request","vs/platform/extensions/node/extensionValidator","vs/base/node/request","vs/base/common/uuid","vs/base/node/zip","vs/base/common/cancellation","vs/platform/download/common/download","vs/platform/instantiation/common/graph","vs/base/node/paths","vs/nls!vs/base/common/errorMessage","vs/base/common/labels","vs/base/node/proxy","url","vs/platform/instantiation/common/instantiationService","vs/base/common/decorators","vs/platform/localizations/common/localizations","vs/nls!vs/base/node/zip","vs/platform/log/node/spdlogService","vs/nls!vs/platform/configuration/common/configurationRegistry","vs/nls!vs/platform/extensionManagement/common/extensionManagement","vs/platform/environment/node/environmentService","crypto","vs/nls!vs/platform/extensionManagement/node/extensionManagementService","vs/nls!vs/platform/extensionManagement/node/extensionManagementUtil","vs/nls!vs/platform/extensions/node/extensionValidator","vs/platform/localizations/node/localizations","vs/nls!vs/platform/request/node/request","vs/platform/jsonschemas/common/jsonContributionRegistry","vs/nls!vs/platform/telemetry/common/telemetryService","vs/base/node/config","vs/platform/extensionManagement/common/extensionNls","vs/base/common/map","vs/platform/configuration/node/configuration","vs/platform/configuration/node/configurationService","vs/platform/extensionManagement/node/extensionLifecycle","vs/platform/state/common/state","vs/platform/state/node/stateService","vs/platform/extensionManagement/node/extensionGalleryService","vs/platform/telemetry/common/telemetryService","vs/platform/telemetry/common/telemetryUtils","vs/platform/telemetry/node/appInsightsAppender","vs/base/common/assert","vs/platform/telemetry/node/commonProperties","vs/base/common/date","vs/base/common/collections","vs/platform/extensionManagement/node/extensionsManifestCache","semver","vs/platform/request/node/requestService","vs/platform/extensionManagement/node/extensionManagementService","yazl","yauzl","applicationinsights","zlib","child_process","vs/base/common/resources","vs/code/node/cliProcessMain"];
var __M = function(deps) {
  var result = [];
  for (var i = 0, len = deps.length; i < len; i++) {
    result[i] = __m[deps[i]];
  }
  return result;
};
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[81/*vs/base/common/assert*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * Throws an error with the provided message if the provided value does not evaluate to a true Javascript value.
     */
    function ok(value, message) {
        if (!value) {
            throw new Error(message ? 'Assertion failed (' + message + ')' : 'Assertion Failed');
        }
    }
    exports.ok = ok;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[84/*vs/base/common/collections*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const hasOwnProperty = Object.prototype.hasOwnProperty;
    /**
     * Returns an array which contains all values that reside
     * in the given set.
     */
    function values(from) {
        const result = [];
        for (let key in from) {
            if (hasOwnProperty.call(from, key)) {
                result.push(from[key]);
            }
        }
        return result;
    }
    exports.values = values;
    function size(from) {
        let count = 0;
        for (let key in from) {
            if (hasOwnProperty.call(from, key)) {
                count += 1;
            }
        }
        return count;
    }
    exports.size = size;
    function first(from) {
        for (let key in from) {
            if (hasOwnProperty.call(from, key)) {
                return from[key];
            }
        }
        return undefined;
    }
    exports.first = first;
    /**
     * Iterates over each entry in the provided set. The iterator allows
     * to remove elements and will stop when the callback returns {{false}}.
     */
    function forEach(from, callback) {
        for (let key in from) {
            if (hasOwnProperty.call(from, key)) {
                const result = callback({ key: key, value: from[key] }, function () {
                    delete from[key];
                });
                if (result === false) {
                    return;
                }
            }
        }
    }
    exports.forEach = forEach;
    /**
     * Groups the collection into a dictionary based on the provided
     * group function.
     */
    function groupBy(data, groupFn) {
        const result = Object.create(null);
        for (const element of data) {
            const key = groupFn(element);
            let target = result[key];
            if (!target) {
                target = result[key] = [];
            }
            target.push(element);
        }
        return result;
    }
    exports.groupBy = groupBy;
    function fromMap(original) {
        const result = Object.create(null);
        if (original) {
            original.forEach((value, key) => {
                result[key] = value;
            });
        }
        return result;
    }
    exports.fromMap = fromMap;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[54/*vs/base/common/decorators*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function createDecorator(mapFn) {
        return (target, key, descriptor) => {
            let fnKey = null;
            let fn = null;
            if (typeof descriptor.value === 'function') {
                fnKey = 'value';
                fn = descriptor.value;
            }
            else if (typeof descriptor.get === 'function') {
                fnKey = 'get';
                fn = descriptor.get;
            }
            if (!fn) {
                throw new Error('not supported');
            }
            descriptor[fnKey] = mapFn(fn, key);
        };
    }
    exports.createDecorator = createDecorator;
    function memoize(target, key, descriptor) {
        let fnKey = null;
        let fn = null;
        if (typeof descriptor.value === 'function') {
            fnKey = 'value';
            fn = descriptor.value;
            if (fn.length !== 0) {
                console.warn('Memoize should only be used in functions with zero parameters');
            }
        }
        else if (typeof descriptor.get === 'function') {
            fnKey = 'get';
            fn = descriptor.get;
        }
        if (!fn) {
            throw new Error('not supported');
        }
        const memoizeKey = `$memoize$${key}`;
        descriptor[fnKey] = function (...args) {
            if (!this.hasOwnProperty(memoizeKey)) {
                Object.defineProperty(this, memoizeKey, {
                    configurable: false,
                    enumerable: false,
                    writable: false,
                    value: fn.apply(this, args)
                });
            }
            return this[memoizeKey];
        };
    }
    exports.memoize = memoize;
    function debounce(delay, reducer, initialValueProvider) {
        return createDecorator((fn, key) => {
            const timerKey = `$debounce$${key}`;
            const resultKey = `$debounce$result$${key}`;
            return function (...args) {
                if (!this[resultKey]) {
                    this[resultKey] = initialValueProvider ? initialValueProvider() : undefined;
                }
                clearTimeout(this[timerKey]);
                if (reducer) {
                    this[resultKey] = reducer(this[resultKey], ...args);
                    args = [this[resultKey]];
                }
                this[timerKey] = setTimeout(() => {
                    fn.apply(this, args);
                    this[resultKey] = initialValueProvider ? initialValueProvider() : undefined;
                }, delay);
            };
        });
    }
    exports.debounce = debounce;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[33/*vs/base/common/json*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var ScanError;
    (function (ScanError) {
        ScanError[ScanError["None"] = 0] = "None";
        ScanError[ScanError["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
        ScanError[ScanError["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
        ScanError[ScanError["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
        ScanError[ScanError["InvalidUnicode"] = 4] = "InvalidUnicode";
        ScanError[ScanError["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
        ScanError[ScanError["InvalidCharacter"] = 6] = "InvalidCharacter";
    })(ScanError = exports.ScanError || (exports.ScanError = {}));
    var SyntaxKind;
    (function (SyntaxKind) {
        SyntaxKind[SyntaxKind["OpenBraceToken"] = 1] = "OpenBraceToken";
        SyntaxKind[SyntaxKind["CloseBraceToken"] = 2] = "CloseBraceToken";
        SyntaxKind[SyntaxKind["OpenBracketToken"] = 3] = "OpenBracketToken";
        SyntaxKind[SyntaxKind["CloseBracketToken"] = 4] = "CloseBracketToken";
        SyntaxKind[SyntaxKind["CommaToken"] = 5] = "CommaToken";
        SyntaxKind[SyntaxKind["ColonToken"] = 6] = "ColonToken";
        SyntaxKind[SyntaxKind["NullKeyword"] = 7] = "NullKeyword";
        SyntaxKind[SyntaxKind["TrueKeyword"] = 8] = "TrueKeyword";
        SyntaxKind[SyntaxKind["FalseKeyword"] = 9] = "FalseKeyword";
        SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral";
        SyntaxKind[SyntaxKind["NumericLiteral"] = 11] = "NumericLiteral";
        SyntaxKind[SyntaxKind["LineCommentTrivia"] = 12] = "LineCommentTrivia";
        SyntaxKind[SyntaxKind["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
        SyntaxKind[SyntaxKind["LineBreakTrivia"] = 14] = "LineBreakTrivia";
        SyntaxKind[SyntaxKind["Trivia"] = 15] = "Trivia";
        SyntaxKind[SyntaxKind["Unknown"] = 16] = "Unknown";
        SyntaxKind[SyntaxKind["EOF"] = 17] = "EOF";
    })(SyntaxKind = exports.SyntaxKind || (exports.SyntaxKind = {}));
    var ParseErrorCode;
    (function (ParseErrorCode) {
        ParseErrorCode[ParseErrorCode["InvalidSymbol"] = 1] = "InvalidSymbol";
        ParseErrorCode[ParseErrorCode["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
        ParseErrorCode[ParseErrorCode["PropertyNameExpected"] = 3] = "PropertyNameExpected";
        ParseErrorCode[ParseErrorCode["ValueExpected"] = 4] = "ValueExpected";
        ParseErrorCode[ParseErrorCode["ColonExpected"] = 5] = "ColonExpected";
        ParseErrorCode[ParseErrorCode["CommaExpected"] = 6] = "CommaExpected";
        ParseErrorCode[ParseErrorCode["CloseBraceExpected"] = 7] = "CloseBraceExpected";
        ParseErrorCode[ParseErrorCode["CloseBracketExpected"] = 8] = "CloseBracketExpected";
        ParseErrorCode[ParseErrorCode["EndOfFileExpected"] = 9] = "EndOfFileExpected";
        ParseErrorCode[ParseErrorCode["InvalidCommentToken"] = 10] = "InvalidCommentToken";
        ParseErrorCode[ParseErrorCode["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
        ParseErrorCode[ParseErrorCode["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
        ParseErrorCode[ParseErrorCode["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
        ParseErrorCode[ParseErrorCode["InvalidUnicode"] = 14] = "InvalidUnicode";
        ParseErrorCode[ParseErrorCode["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
        ParseErrorCode[ParseErrorCode["InvalidCharacter"] = 16] = "InvalidCharacter";
    })(ParseErrorCode = exports.ParseErrorCode || (exports.ParseErrorCode = {}));
    var ParseOptions;
    (function (ParseOptions) {
        ParseOptions.DEFAULT = {
            allowTrailingComma: true
        };
    })(ParseOptions = exports.ParseOptions || (exports.ParseOptions = {}));
    /**
     * Creates a JSON scanner on the given text.
     * If ignoreTrivia is set, whitespaces or comments are ignored.
     */
    function createScanner(text, ignoreTrivia = false) {
        let pos = 0, len = text.length, value = '', tokenOffset = 0, token = 16 /* Unknown */, scanError = 0 /* None */;
        function scanHexDigits(count) {
            let digits = 0;
            let value = 0;
            while (digits < count) {
                const ch = text.charCodeAt(pos);
                if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) {
                    value = value * 16 + ch - 48 /* _0 */;
                }
                else if (ch >= 65 /* A */ && ch <= 70 /* F */) {
                    value = value * 16 + ch - 65 /* A */ + 10;
                }
                else if (ch >= 97 /* a */ && ch <= 102 /* f */) {
                    value = value * 16 + ch - 97 /* a */ + 10;
                }
                else {
                    break;
                }
                pos++;
                digits++;
            }
            if (digits < count) {
                value = -1;
            }
            return value;
        }
        function setPosition(newPosition) {
            pos = newPosition;
            value = '';
            tokenOffset = 0;
            token = 16 /* Unknown */;
            scanError = 0 /* None */;
        }
        function scanNumber() {
            const start = pos;
            if (text.charCodeAt(pos) === 48 /* _0 */) {
                pos++;
            }
            else {
                pos++;
                while (pos < text.length && isDigit(text.charCodeAt(pos))) {
                    pos++;
                }
            }
            if (pos < text.length && text.charCodeAt(pos) === 46 /* dot */) {
                pos++;
                if (pos < text.length && isDigit(text.charCodeAt(pos))) {
                    pos++;
                    while (pos < text.length && isDigit(text.charCodeAt(pos))) {
                        pos++;
                    }
                }
                else {
                    scanError = 3 /* UnexpectedEndOfNumber */;
                    return text.substring(start, pos);
                }
            }
            let end = pos;
            if (pos < text.length && (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */)) {
                pos++;
                if (pos < text.length && text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) {
                    pos++;
                }
                if (pos < text.length && isDigit(text.charCodeAt(pos))) {
                    pos++;
                    while (pos < text.length && isDigit(text.charCodeAt(pos))) {
                        pos++;
                    }
                    end = pos;
                }
                else {
                    scanError = 3 /* UnexpectedEndOfNumber */;
                }
            }
            return text.substring(start, end);
        }
        function scanString() {
            let result = '', start = pos;
            while (true) {
                if (pos >= len) {
                    result += text.substring(start, pos);
                    scanError = 2 /* UnexpectedEndOfString */;
                    break;
                }
                let ch = text.charCodeAt(pos);
                if (ch === 34 /* doubleQuote */) {
                    result += text.substring(start, pos);
                    pos++;
                    break;
                }
                if (ch === 92 /* backslash */) {
                    result += text.substring(start, pos);
                    pos++;
                    if (pos >= len) {
                        scanError = 2 /* UnexpectedEndOfString */;
                        break;
                    }
                    ch = text.charCodeAt(pos++);
                    switch (ch) {
                        case 34 /* doubleQuote */:
                            result += '\"';
                            break;
                        case 92 /* backslash */:
                            result += '\\';
                            break;
                        case 47 /* slash */:
                            result += '/';
                            break;
                        case 98 /* b */:
                            result += '\b';
                            break;
                        case 102 /* f */:
                            result += '\f';
                            break;
                        case 110 /* n */:
                            result += '\n';
                            break;
                        case 114 /* r */:
                            result += '\r';
                            break;
                        case 116 /* t */:
                            result += '\t';
                            break;
                        case 117 /* u */:
                            const ch = scanHexDigits(4);
                            if (ch >= 0) {
                                result += String.fromCharCode(ch);
                            }
                            else {
                                scanError = 4 /* InvalidUnicode */;
                            }
                            break;
                        default:
                            scanError = 5 /* InvalidEscapeCharacter */;
                    }
                    start = pos;
                    continue;
                }
                if (ch >= 0 && ch <= 0x1F) {
                    if (isLineBreak(ch)) {
                        result += text.substring(start, pos);
                        scanError = 2 /* UnexpectedEndOfString */;
                        break;
                    }
                    else {
                        scanError = 6 /* InvalidCharacter */;
                        // mark as error but continue with string
                    }
                }
                pos++;
            }
            return result;
        }
        function scanNext() {
            value = '';
            scanError = 0 /* None */;
            tokenOffset = pos;
            if (pos >= len) {
                // at the end
                tokenOffset = len;
                return token = 17 /* EOF */;
            }
            let code = text.charCodeAt(pos);
            // trivia: whitespace
            if (isWhiteSpace(code)) {
                do {
                    pos++;
                    value += String.fromCharCode(code);
                    code = text.charCodeAt(pos);
                } while (isWhiteSpace(code));
                return token = 15 /* Trivia */;
            }
            // trivia: newlines
            if (isLineBreak(code)) {
                pos++;
                value += String.fromCharCode(code);
                if (code === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
                    pos++;
                    value += '\n';
                }
                return token = 14 /* LineBreakTrivia */;
            }
            switch (code) {
                // tokens: []{}:,
                case 123 /* openBrace */:
                    pos++;
                    return token = 1 /* OpenBraceToken */;
                case 125 /* closeBrace */:
                    pos++;
                    return token = 2 /* CloseBraceToken */;
                case 91 /* openBracket */:
                    pos++;
                    return token = 3 /* OpenBracketToken */;
                case 93 /* closeBracket */:
                    pos++;
                    return token = 4 /* CloseBracketToken */;
                case 58 /* colon */:
                    pos++;
                    return token = 6 /* ColonToken */;
                case 44 /* comma */:
                    pos++;
                    return token = 5 /* CommaToken */;
                // strings
                case 34 /* doubleQuote */:
                    pos++;
                    value = scanString();
                    return token = 10 /* StringLiteral */;
                // comments
                case 47 /* slash */:
                    const start = pos - 1;
                    // Single-line comment
                    if (text.charCodeAt(pos + 1) === 47 /* slash */) {
                        pos += 2;
                        while (pos < len) {
                            if (isLineBreak(text.charCodeAt(pos))) {
                                break;
                            }
                            pos++;
                        }
                        value = text.substring(start, pos);
                        return token = 12 /* LineCommentTrivia */;
                    }
                    // Multi-line comment
                    if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
                        pos += 2;
                        const safeLength = len - 1; // For lookahead.
                        let commentClosed = false;
                        while (pos < safeLength) {
                            const ch = text.charCodeAt(pos);
                            if (ch === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
                                pos += 2;
                                commentClosed = true;
                                break;
                            }
                            pos++;
                        }
                        if (!commentClosed) {
                            pos++;
                            scanError = 1 /* UnexpectedEndOfComment */;
                        }
                        value = text.substring(start, pos);
                        return token = 13 /* BlockCommentTrivia */;
                    }
                    // just a single slash
                    value += String.fromCharCode(code);
                    pos++;
                    return token = 16 /* Unknown */;
                // numbers
                case 45 /* minus */:
                    value += String.fromCharCode(code);
                    pos++;
                    if (pos === len || !isDigit(text.charCodeAt(pos))) {
                        return token = 16 /* Unknown */;
                    }
                // found a minus, followed by a number so
                // we fall through to proceed with scanning
                // numbers
                case 48 /* _0 */:
                case 49 /* _1 */:
                case 50 /* _2 */:
                case 51 /* _3 */:
                case 52 /* _4 */:
                case 53 /* _5 */:
                case 54 /* _6 */:
                case 55 /* _7 */:
                case 56 /* _8 */:
                case 57 /* _9 */:
                    value += scanNumber();
                    return token = 11 /* NumericLiteral */;
                // literals and unknown symbols
                default:
                    // is a literal? Read the full word.
                    while (pos < len && isUnknownContentCharacter(code)) {
                        pos++;
                        code = text.charCodeAt(pos);
                    }
                    if (tokenOffset !== pos) {
                        value = text.substring(tokenOffset, pos);
                        // keywords: true, false, null
                        switch (value) {
                            case 'true': return token = 8 /* TrueKeyword */;
                            case 'false': return token = 9 /* FalseKeyword */;
                            case 'null': return token = 7 /* NullKeyword */;
                        }
                        return token = 16 /* Unknown */;
                    }
                    // some
                    value += String.fromCharCode(code);
                    pos++;
                    return token = 16 /* Unknown */;
            }
        }
        function isUnknownContentCharacter(code) {
            if (isWhiteSpace(code) || isLineBreak(code)) {
                return false;
            }
            switch (code) {
                case 125 /* closeBrace */:
                case 93 /* closeBracket */:
                case 123 /* openBrace */:
                case 91 /* openBracket */:
                case 34 /* doubleQuote */:
                case 58 /* colon */:
                case 44 /* comma */:
                case 47 /* slash */:
                    return false;
            }
            return true;
        }
        function scanNextNonTrivia() {
            let result;
            do {
                result = scanNext();
            } while (result >= 12 /* LineCommentTrivia */ && result <= 15 /* Trivia */);
            return result;
        }
        return {
            setPosition: setPosition,
            getPosition: () => pos,
            scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
            getToken: () => token,
            getTokenValue: () => value,
            getTokenOffset: () => tokenOffset,
            getTokenLength: () => pos - tokenOffset,
            getTokenError: () => scanError
        };
    }
    exports.createScanner = createScanner;
    function isWhiteSpace(ch) {
        return ch === 32 /* space */ || ch === 9 /* tab */ || ch === 11 /* verticalTab */ || ch === 12 /* formFeed */ ||
            ch === 160 /* nonBreakingSpace */ || ch === 5760 /* ogham */ || ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
            ch === 8239 /* narrowNoBreakSpace */ || ch === 8287 /* mathematicalSpace */ || ch === 12288 /* ideographicSpace */ || ch === 65279 /* byteOrderMark */;
    }
    function isLineBreak(ch) {
        return ch === 10 /* lineFeed */ || ch === 13 /* carriageReturn */ || ch === 8232 /* lineSeparator */ || ch === 8233 /* paragraphSeparator */;
    }
    function isDigit(ch) {
        return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
    }
    var CharacterCodes;
    (function (CharacterCodes) {
        CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter";
        CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
        CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
        CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
        CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator";
        CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator";
        // REVIEW: do we need to support this?  The scanner doesn't, but our IText does.  This seems
        // like an odd disparity?  (Or maybe it's completely fine for them to be different).
        CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine";
        // Unicode 3.0 space characters
        CharacterCodes[CharacterCodes["space"] = 32] = "space";
        CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace";
        CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad";
        CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad";
        CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace";
        CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace";
        CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace";
        CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
        CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
        CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace";
        CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace";
        CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace";
        CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace";
        CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
        CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
        CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace";
        CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace";
        CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham";
        CharacterCodes[CharacterCodes["_"] = 95] = "_";
        CharacterCodes[CharacterCodes["$"] = 36] = "$";
        CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
        CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
        CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
        CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
        CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
        CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
        CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
        CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
        CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
        CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
        CharacterCodes[CharacterCodes["a"] = 97] = "a";
        CharacterCodes[CharacterCodes["b"] = 98] = "b";
        CharacterCodes[CharacterCodes["c"] = 99] = "c";
        CharacterCodes[CharacterCodes["d"] = 100] = "d";
        CharacterCodes[CharacterCodes["e"] = 101] = "e";
        CharacterCodes[CharacterCodes["f"] = 102] = "f";
        CharacterCodes[CharacterCodes["g"] = 103] = "g";
        CharacterCodes[CharacterCodes["h"] = 104] = "h";
        CharacterCodes[CharacterCodes["i"] = 105] = "i";
        CharacterCodes[CharacterCodes["j"] = 106] = "j";
        CharacterCodes[CharacterCodes["k"] = 107] = "k";
        CharacterCodes[CharacterCodes["l"] = 108] = "l";
        CharacterCodes[CharacterCodes["m"] = 109] = "m";
        CharacterCodes[CharacterCodes["n"] = 110] = "n";
        CharacterCodes[CharacterCodes["o"] = 111] = "o";
        CharacterCodes[CharacterCodes["p"] = 112] = "p";
        CharacterCodes[CharacterCodes["q"] = 113] = "q";
        CharacterCodes[CharacterCodes["r"] = 114] = "r";
        CharacterCodes[CharacterCodes["s"] = 115] = "s";
        CharacterCodes[CharacterCodes["t"] = 116] = "t";
        CharacterCodes[CharacterCodes["u"] = 117] = "u";
        CharacterCodes[CharacterCodes["v"] = 118] = "v";
        CharacterCodes[CharacterCodes["w"] = 119] = "w";
        CharacterCodes[CharacterCodes["x"] = 120] = "x";
        CharacterCodes[CharacterCodes["y"] = 121] = "y";
        CharacterCodes[CharacterCodes["z"] = 122] = "z";
        CharacterCodes[CharacterCodes["A"] = 65] = "A";
        CharacterCodes[CharacterCodes["B"] = 66] = "B";
        CharacterCodes[CharacterCodes["C"] = 67] = "C";
        CharacterCodes[CharacterCodes["D"] = 68] = "D";
        CharacterCodes[CharacterCodes["E"] = 69] = "E";
        CharacterCodes[CharacterCodes["F"] = 70] = "F";
        CharacterCodes[CharacterCodes["G"] = 71] = "G";
        CharacterCodes[CharacterCodes["H"] = 72] = "H";
        CharacterCodes[CharacterCodes["I"] = 73] = "I";
        CharacterCodes[CharacterCodes["J"] = 74] = "J";
        CharacterCodes[CharacterCodes["K"] = 75] = "K";
        CharacterCodes[CharacterCodes["L"] = 76] = "L";
        CharacterCodes[CharacterCodes["M"] = 77] = "M";
        CharacterCodes[CharacterCodes["N"] = 78] = "N";
        CharacterCodes[CharacterCodes["O"] = 79] = "O";
        CharacterCodes[CharacterCodes["P"] = 80] = "P";
        CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
        CharacterCodes[CharacterCodes["R"] = 82] = "R";
        CharacterCodes[CharacterCodes["S"] = 83] = "S";
        CharacterCodes[CharacterCodes["T"] = 84] = "T";
        CharacterCodes[CharacterCodes["U"] = 85] = "U";
        CharacterCodes[CharacterCodes["V"] = 86] = "V";
        CharacterCodes[CharacterCodes["W"] = 87] = "W";
        CharacterCodes[CharacterCodes["X"] = 88] = "X";
        CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
        CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
        CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand";
        CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
        CharacterCodes[CharacterCodes["at"] = 64] = "at";
        CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
        CharacterCodes[CharacterCodes["bar"] = 124] = "bar";
        CharacterCodes[CharacterCodes["caret"] = 94] = "caret";
        CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
        CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
        CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen";
        CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
        CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
        CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
        CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
        CharacterCodes[CharacterCodes["equals"] = 61] = "equals";
        CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation";
        CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan";
        CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan";
        CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
        CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
        CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
        CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen";
        CharacterCodes[CharacterCodes["percent"] = 37] = "percent";
        CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
        CharacterCodes[CharacterCodes["question"] = 63] = "question";
        CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon";
        CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote";
        CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
        CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde";
        CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace";
        CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
        CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark";
        CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
        CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab";
    })(CharacterCodes || (CharacterCodes = {}));
    /**
     * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.
     */
    function getLocation(text, position) {
        const segments = []; // strings or numbers
        const earlyReturnException = new Object();
        let previousNode = undefined;
        const previousNodeInst = {
            value: {},
            offset: 0,
            length: 0,
            type: 'object',
            parent: undefined
        };
        let isAtPropertyKey = false;
        function setPreviousNode(value, offset, length, type) {
            previousNodeInst.value = value;
            previousNodeInst.offset = offset;
            previousNodeInst.length = length;
            previousNodeInst.type = type;
            previousNodeInst.colonOffset = undefined;
            previousNode = previousNodeInst;
        }
        try {
            visit(text, {
                onObjectBegin: (offset, length) => {
                    if (position <= offset) {
                        throw earlyReturnException;
                    }
                    previousNode = undefined;
                    isAtPropertyKey = position > offset;
                    segments.push(''); // push a placeholder (will be replaced)
                },
                onObjectProperty: (name, offset, length) => {
                    if (position < offset) {
                        throw earlyReturnException;
                    }
                    setPreviousNode(name, offset, length, 'property');
                    segments[segments.length - 1] = name;
                    if (position <= offset + length) {
                        throw earlyReturnException;
                    }
                },
                onObjectEnd: (offset, length) => {
                    if (position <= offset) {
                        throw earlyReturnException;
                    }
                    previousNode = undefined;
                    segments.pop();
                },
                onArrayBegin: (offset, length) => {
                    if (position <= offset) {
                        throw earlyReturnException;
                    }
                    previousNode = undefined;
                    segments.push(0);
                },
                onArrayEnd: (offset, length) => {
                    if (position <= offset) {
                        throw earlyReturnException;
                    }
                    previousNode = undefined;
                    segments.pop();
                },
                onLiteralValue: (value, offset, length) => {
                    if (position < offset) {
                        throw earlyReturnException;
                    }
                    setPreviousNode(value, offset, length, getLiteralNodeType(value));
                    if (position <= offset + length) {
                        throw earlyReturnException;
                    }
                },
                onSeparator: (sep, offset, length) => {
                    if (position <= offset) {
                        throw earlyReturnException;
                    }
                    if (sep === ':' && previousNode && previousNode.type === 'property') {
                        previousNode.colonOffset = offset;
                        isAtPropertyKey = false;
                        previousNode = undefined;
                    }
                    else if (sep === ',') {
                        const last = segments[segments.length - 1];
                        if (typeof last === 'number') {
                            segments[segments.length - 1] = last + 1;
                        }
                        else {
                            isAtPropertyKey = true;
                            segments[segments.length - 1] = '';
                        }
                        previousNode = undefined;
                    }
                }
            });
        }
        catch (e) {
            if (e !== earlyReturnException) {
                throw e;
            }
        }
        return {
            path: segments,
            previousNode,
            isAtPropertyKey,
            matches: (pattern) => {
                let k = 0;
                for (let i = 0; k < pattern.length && i < segments.length; i++) {
                    if (pattern[k] === segments[i] || pattern[k] === '*') {
                        k++;
                    }
                    else if (pattern[k] !== '**') {
                        return false;
                    }
                }
                return k === pattern.length;
            }
        };
    }
    exports.getLocation = getLocation;
    /**
     * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
     * Therefore always check the errors list to find out if the input was valid.
     */
    function parse(text, errors = [], options = ParseOptions.DEFAULT) {
        let currentProperty = null;
        let currentParent = [];
        const previousParents = [];
        function onValue(value) {
            if (Array.isArray(currentParent)) {
                currentParent.push(value);
            }
            else if (currentProperty) {
                currentParent[currentProperty] = value;
            }
        }
        const visitor = {
            onObjectBegin: () => {
                const object = {};
                onValue(object);
                previousParents.push(currentParent);
                currentParent = object;
                currentProperty = null;
            },
            onObjectProperty: (name) => {
                currentProperty = name;
            },
            onObjectEnd: () => {
                currentParent = previousParents.pop();
            },
            onArrayBegin: () => {
                const array = [];
                onValue(array);
                previousParents.push(currentParent);
                currentParent = array;
                currentProperty = null;
            },
            onArrayEnd: () => {
                currentParent = previousParents.pop();
            },
            onLiteralValue: onValue,
            onError: (error, offset, length) => {
                errors.push({ error, offset, length });
            }
        };
        visit(text, visitor, options);
        return currentParent[0];
    }
    exports.parse = parse;
    /**
     * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
     */
    function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {
        let currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root
        function ensurePropertyComplete(endOffset) {
            if (currentParent.type === 'property') {
                currentParent.length = endOffset - currentParent.offset;
                currentParent = currentParent.parent;
            }
        }
        function onValue(valueNode) {
            currentParent.children.push(valueNode);
            return valueNode;
        }
        const visitor = {
            onObjectBegin: (offset) => {
                currentParent = onValue({ type: 'object', offset, length: -1, parent: currentParent, children: [] });
            },
            onObjectProperty: (name, offset, length) => {
                currentParent = onValue({ type: 'property', offset, length: -1, parent: currentParent, children: [] });
                currentParent.children.push({ type: 'string', value: name, offset, length, parent: currentParent });
            },
            onObjectEnd: (offset, length) => {
                currentParent.length = offset + length - currentParent.offset;
                currentParent = currentParent.parent;
                ensurePropertyComplete(offset + length);
            },
            onArrayBegin: (offset, length) => {
                currentParent = onValue({ type: 'array', offset, length: -1, parent: currentParent, children: [] });
            },
            onArrayEnd: (offset, length) => {
                currentParent.length = offset + length - currentParent.offset;
                currentParent = currentParent.parent;
                ensurePropertyComplete(offset + length);
            },
            onLiteralValue: (value, offset, length) => {
                onValue({ type: getLiteralNodeType(value), offset, length, parent: currentParent, value });
                ensurePropertyComplete(offset + length);
            },
            onSeparator: (sep, offset, length) => {
                if (currentParent.type === 'property') {
                    if (sep === ':') {
                        currentParent.colonOffset = offset;
                    }
                    else if (sep === ',') {
                        ensurePropertyComplete(offset);
                    }
                }
            },
            onError: (error, offset, length) => {
                errors.push({ error, offset, length });
            }
        };
        visit(text, visitor, options);
        const result = currentParent.children[0];
        if (result) {
            delete result.parent;
        }
        return result;
    }
    exports.parseTree = parseTree;
    /**
     * Finds the node at the given path in a JSON DOM.
     */
    function findNodeAtLocation(root, path) {
        if (!root) {
            return undefined;
        }
        let node = root;
        for (let segment of path) {
            if (typeof segment === 'string') {
                if (node.type !== 'object' || !Array.isArray(node.children)) {
                    return undefined;
                }
                let found = false;
                for (const propertyNode of node.children) {
                    if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment) {
                        node = propertyNode.children[1];
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    return undefined;
                }
            }
            else {
                const index = segment;
                if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {
                    return undefined;
                }
                node = node.children[index];
            }
        }
        return node;
    }
    exports.findNodeAtLocation = findNodeAtLocation;
    /**
     * Gets the JSON path of the given JSON DOM node
     */
    function getNodePath(node) {
        if (!node.parent || !node.parent.children) {
            return [];
        }
        const path = getNodePath(node.parent);
        if (node.parent.type === 'property') {
            const key = node.parent.children[0].value;
            path.push(key);
        }
        else if (node.parent.type === 'array') {
            const index = node.parent.children.indexOf(node);
            if (index !== -1) {
                path.push(index);
            }
        }
        return path;
    }
    exports.getNodePath = getNodePath;
    /**
     * Evaluates the JavaScript object of the given JSON DOM node
     */
    function getNodeValue(node) {
        switch (node.type) {
            case 'array':
                return node.children.map(getNodeValue);
            case 'object':
                const obj = Object.create(null);
                for (let prop of node.children) {
                    const valueNode = prop.children[1];
                    if (valueNode) {
                        obj[prop.children[0].value] = getNodeValue(valueNode);
                    }
                }
                return obj;
            case 'null':
            case 'string':
            case 'number':
            case 'boolean':
                return node.value;
            default:
                return undefined;
        }
    }
    exports.getNodeValue = getNodeValue;
    function contains(node, offset, includeRightBound = false) {
        return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length));
    }
    exports.contains = contains;
    /**
     * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
     */
    function findNodeAtOffset(node, offset, includeRightBound = false) {
        if (contains(node, offset, includeRightBound)) {
            const children = node.children;
            if (Array.isArray(children)) {
                for (let i = 0; i < children.length && children[i].offset <= offset; i++) {
                    const item = findNodeAtOffset(children[i], offset, includeRightBound);
                    if (item) {
                        return item;
                    }
                }
            }
            return node;
        }
        return undefined;
    }
    exports.findNodeAtOffset = findNodeAtOffset;
    /**
     * Parses the given text and invokes the visitor functions for each object, array and literal reached.
     */
    function visit(text, visitor, options = ParseOptions.DEFAULT) {
        const _scanner = createScanner(text, false);
        function toNoArgVisit(visitFunction) {
            return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength()) : () => true;
        }
        function toOneArgVisit(visitFunction) {
            return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength()) : () => true;
        }
        const onObjectBegin = toNoArgVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisit(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisit(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisit(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
        const disallowComments = options && options.disallowComments;
        const allowTrailingComma = options && options.allowTrailingComma;
        function scanNext() {
            while (true) {
                const token = _scanner.scan();
                switch (_scanner.getTokenError()) {
                    case 4 /* InvalidUnicode */:
                        handleError(14 /* InvalidUnicode */);
                        break;
                    case 5 /* InvalidEscapeCharacter */:
                        handleError(15 /* InvalidEscapeCharacter */);
                        break;
                    case 3 /* UnexpectedEndOfNumber */:
                        handleError(13 /* UnexpectedEndOfNumber */);
                        break;
                    case 1 /* UnexpectedEndOfComment */:
                        if (!disallowComments) {
                            handleError(11 /* UnexpectedEndOfComment */);
                        }
                        break;
                    case 2 /* UnexpectedEndOfString */:
                        handleError(12 /* UnexpectedEndOfString */);
                        break;
                    case 6 /* InvalidCharacter */:
                        handleError(16 /* InvalidCharacter */);
                        break;
                }
                switch (token) {
                    case 12 /* LineCommentTrivia */:
                    case 13 /* BlockCommentTrivia */:
                        if (disallowComments) {
                            handleError(10 /* InvalidCommentToken */);
                        }
                        else {
                            onComment();
                        }
                        break;
                    case 16 /* Unknown */:
                        handleError(1 /* InvalidSymbol */);
                        break;
                    case 15 /* Trivia */:
                    case 14 /* LineBreakTrivia */:
                        break;
                    default:
                        return token;
                }
            }
        }
        function handleError(error, skipUntilAfter = [], skipUntil = []) {
            onError(error);
            if (skipUntilAfter.length + skipUntil.length > 0) {
                let token = _scanner.getToken();
                while (token !== 17 /* EOF */) {
                    if (skipUntilAfter.indexOf(token) !== -1) {
                        scanNext();
                        break;
                    }
                    else if (skipUntil.indexOf(token) !== -1) {
                        break;
                    }
                    token = scanNext();
                }
            }
        }
        function parseString(isValue) {
            const value = _scanner.getTokenValue();
            if (isValue) {
                onLiteralValue(value);
            }
            else {
                onObjectProperty(value);
            }
            scanNext();
            return true;
        }
        function parseLiteral() {
            switch (_scanner.getToken()) {
                case 11 /* NumericLiteral */:
                    let value = 0;
                    try {
                        value = JSON.parse(_scanner.getTokenValue());
                        if (typeof value !== 'number') {
                            handleError(2 /* InvalidNumberFormat */);
                            value = 0;
                        }
                    }
                    catch (e) {
                        handleError(2 /* InvalidNumberFormat */);
                    }
                    onLiteralValue(value);
                    break;
                case 7 /* NullKeyword */:
                    onLiteralValue(null);
                    break;
                case 8 /* TrueKeyword */:
                    onLiteralValue(true);
                    break;
                case 9 /* FalseKeyword */:
                    onLiteralValue(false);
                    break;
                default:
                    return false;
            }
            scanNext();
            return true;
        }
        function parseProperty() {
            if (_scanner.getToken() !== 10 /* StringLiteral */) {
                handleError(3 /* PropertyNameExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
                return false;
            }
            parseString(false);
            if (_scanner.getToken() === 6 /* ColonToken */) {
                onSeparator(':');
                scanNext(); // consume colon
                if (!parseValue()) {
                    handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
                }
            }
            else {
                handleError(5 /* ColonExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
            }
            return true;
        }
        function parseObject() {
            onObjectBegin();
            scanNext(); // consume open brace
            let needsComma = false;
            while (_scanner.getToken() !== 2 /* CloseBraceToken */ && _scanner.getToken() !== 17 /* EOF */) {
                if (_scanner.getToken() === 5 /* CommaToken */) {
                    if (!needsComma) {
                        handleError(4 /* ValueExpected */, [], []);
                    }
                    onSeparator(',');
                    scanNext(); // consume comma
                    if (_scanner.getToken() === 2 /* CloseBraceToken */ && allowTrailingComma) {
                        break;
                    }
                }
                else if (needsComma) {
                    handleError(6 /* CommaExpected */, [], []);
                }
                if (!parseProperty()) {
                    handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
                }
                needsComma = true;
            }
            onObjectEnd();
            if (_scanner.getToken() !== 2 /* CloseBraceToken */) {
                handleError(7 /* CloseBraceExpected */, [2 /* CloseBraceToken */], []);
            }
            else {
                scanNext(); // consume close brace
            }
            return true;
        }
        function parseArray() {
            onArrayBegin();
            scanNext(); // consume open bracket
            let needsComma = false;
            while (_scanner.getToken() !== 4 /* CloseBracketToken */ && _scanner.getToken() !== 17 /* EOF */) {
                if (_scanner.getToken() === 5 /* CommaToken */) {
                    if (!needsComma) {
                        handleError(4 /* ValueExpected */, [], []);
                    }
                    onSeparator(',');
                    scanNext(); // consume comma
                    if (_scanner.getToken() === 4 /* CloseBracketToken */ && allowTrailingComma) {
                        break;
                    }
                }
                else if (needsComma) {
                    handleError(6 /* CommaExpected */, [], []);
                }
                if (!parseValue()) {
                    handleError(4 /* ValueExpected */, [], [4 /* CloseBracketToken */, 5 /* CommaToken */]);
                }
                needsComma = true;
            }
            onArrayEnd();
            if (_scanner.getToken() !== 4 /* CloseBracketToken */) {
                handleError(8 /* CloseBracketExpected */, [4 /* CloseBracketToken */], []);
            }
            else {
                scanNext(); // consume close bracket
            }
            return true;
        }
        function parseValue() {
            switch (_scanner.getToken()) {
                case 3 /* OpenBracketToken */:
                    return parseArray();
                case 1 /* OpenBraceToken */:
                    return parseObject();
                case 10 /* StringLiteral */:
                    return parseString(true);
                default:
                    return parseLiteral();
            }
        }
        scanNext();
        if (_scanner.getToken() === 17 /* EOF */) {
            return true;
        }
        if (!parseValue()) {
            handleError(4 /* ValueExpected */, [], []);
            return false;
        }
        if (_scanner.getToken() !== 17 /* EOF */) {
            handleError(9 /* EndOfFileExpected */, [], []);
        }
        return true;
    }
    exports.visit = visit;
    /**
     * Takes JSON with JavaScript-style comments and remove
     * them. Optionally replaces every none-newline character
     * of comments with a replaceCharacter
     */
    function stripComments(text, replaceCh) {
        let _scanner = createScanner(text), parts = [], kind, offset = 0, pos;
        do {
            pos = _scanner.getPosition();
            kind = _scanner.scan();
            switch (kind) {
                case 12 /* LineCommentTrivia */:
                case 13 /* BlockCommentTrivia */:
                case 17 /* EOF */:
                    if (offset !== pos) {
                        parts.push(text.substring(offset, pos));
                    }
                    if (replaceCh !== undefined) {
                        parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh));
                    }
                    offset = _scanner.getPosition();
                    break;
            }
        } while (kind !== 17 /* EOF */);
        return parts.join('');
    }
    exports.stripComments = stripComments;
    function getLiteralNodeType(value) {
        switch (typeof value) {
            case 'boolean': return 'boolean';
            case 'number': return 'number';
            case 'string': return 'string';
            default: return 'null';
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[83/*vs/base/common/date*/], __M([1/*require*/,0/*exports*/,16/*vs/base/common/strings*/]), function (require, exports, strings_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function toLocalISOString(date) {
        return date.getFullYear() +
            '-' + strings_1.pad(date.getMonth() + 1, 2) +
            '-' + strings_1.pad(date.getDate(), 2) +
            'T' + strings_1.pad(date.getHours(), 2) +
            ':' + strings_1.pad(date.getMinutes(), 2) +
            ':' + strings_1.pad(date.getSeconds(), 2) +
            '.' + (date.getMilliseconds() / 1000).toFixed(3).slice(2, 5) +
            'Z';
    }
    exports.toLocalISOString = toLocalISOString;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[50/*vs/base/common/labels*/], __M([1/*require*/,0/*exports*/,20/*vs/base/common/uri*/,3/*vs/base/common/path*/,16/*vs/base/common/strings*/,28/*vs/base/common/network*/,18/*vs/base/common/platform*/,94/*vs/base/common/resources*/]), function (require, exports, uri_1, path_1, strings_1, network_1, platform_1, resources_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * @deprecated use LabelService instead
     */
    function getPathLabel(resource, userHomeProvider, rootProvider) {
        if (typeof resource === 'string') {
            resource = uri_1.URI.file(resource);
        }
        // return early if we can resolve a relative path label from the root
        if (rootProvider) {
            const baseResource = rootProvider.getWorkspaceFolder(resource);
            if (baseResource) {
                const hasMultipleRoots = rootProvider.getWorkspace().folders.length > 1;
                let pathLabel;
                if (resources_1.isEqual(baseResource.uri, resource)) {
                    pathLabel = ''; // no label if paths are identical
                }
                else {
                    // TODO: isidor use resources.relative
                    pathLabel = path_1.normalize(strings_1.ltrim(resource.path.substr(baseResource.uri.path.length), path_1.posix.sep));
                }
                if (hasMultipleRoots) {
                    const rootName = (baseResource && baseResource.name) ? baseResource.name : resources_1.basename(baseResource.uri);
                    pathLabel = pathLabel ? (rootName + ' • ' + pathLabel) : rootName; // always show root basename if there are multiple
                }
                return pathLabel;
            }
        }
        // return if the resource is neither file:// nor untitled:// and no baseResource was provided
        if (resource.scheme !== network_1.Schemas.file && resource.scheme !== network_1.Schemas.untitled) {
            return resource.with({ query: null, fragment: null }).toString(true);
        }
        // convert c:\something => C:\something
        if (hasDriveLetter(resource.fsPath)) {
            return path_1.normalize(normalizeDriveLetter(resource.fsPath));
        }
        // normalize and tildify (macOS, Linux only)
        let res = path_1.normalize(resource.fsPath);
        if (!platform_1.isWindows && userHomeProvider) {
            res = tildify(res, userHomeProvider.userHome);
        }
        return res;
    }
    exports.getPathLabel = getPathLabel;
    function getBaseLabel(resource) {
        if (!resource) {
            return undefined;
        }
        if (typeof resource === 'string') {
            resource = uri_1.URI.file(resource);
        }
        const base = resources_1.basename(resource) || (resource.scheme === network_1.Schemas.file ? resource.fsPath : resource.path) /* can be empty string if '/' is passed in */;
        // convert c: => C:
        if (hasDriveLetter(base)) {
            return normalizeDriveLetter(base);
        }
        return base;
    }
    exports.getBaseLabel = getBaseLabel;
    function hasDriveLetter(path) {
        return !!(platform_1.isWindows && path && path[1] === ':');
    }
    function normalizeDriveLetter(path) {
        if (hasDriveLetter(path)) {
            return path.charAt(0).toUpperCase() + path.slice(1);
        }
        return path;
    }
    exports.normalizeDriveLetter = normalizeDriveLetter;
    let normalizedUserHomeCached = Object.create(null);
    function tildify(path, userHome) {
        if (platform_1.isWindows || !path || !userHome) {
            return path; // unsupported
        }
        // Keep a normalized user home path as cache to prevent accumulated string creation
        let normalizedUserHome = normalizedUserHomeCached.original === userHome ? normalizedUserHomeCached.normalized : undefined;
        if (!normalizedUserHome) {
            normalizedUserHome = `${strings_1.rtrim(userHome, path_1.posix.sep)}${path_1.posix.sep}`;
            normalizedUserHomeCached = { original: userHome, normalized: normalizedUserHome };
        }
        // Linux: case sensitive, macOS: case insensitive
        if (platform_1.isLinux ? strings_1.startsWith(path, normalizedUserHome) : strings_1.startsWithIgnoreCase(path, normalizedUserHome)) {
            path = `~/${path.substr(normalizedUserHome.length)}`;
        }
        return path;
    }
    exports.tildify = tildify;
    function untildify(path, userHome) {
        return path.replace(/^~($|\/|\\)/, `${userHome}$1`);
    }
    exports.untildify = untildify;
    /**
     * Shortens the paths but keeps them easy to distinguish.
     * Replaces not important parts with ellipsis.
     * Every shorten path matches only one original path and vice versa.
     *
     * Algorithm for shortening paths is as follows:
     * 1. For every path in list, find unique substring of that path.
     * 2. Unique substring along with ellipsis is shortened path of that path.
     * 3. To find unique substring of path, consider every segment of length from 1 to path.length of path from end of string
     *    and if present segment is not substring to any other paths then present segment is unique path,
     *    else check if it is not present as suffix of any other path and present segment is suffix of path itself,
     *    if it is true take present segment as unique path.
     * 4. Apply ellipsis to unique segment according to whether segment is present at start/in-between/end of path.
     *
     * Example 1
     * 1. consider 2 paths i.e. ['a\\b\\c\\d', 'a\\f\\b\\c\\d']
     * 2. find unique path of first path,
     * 	a. 'd' is present in path2 and is suffix of path2, hence not unique of present path.
     * 	b. 'c' is present in path2 and 'c' is not suffix of present path, similarly for 'b' and 'a' also.
     * 	c. 'd\\c' is suffix of path2.
     *  d. 'b\\c' is not suffix of present path.
     *  e. 'a\\b' is not present in path2, hence unique path is 'a\\b...'.
     * 3. for path2, 'f' is not present in path1 hence unique is '...\\f\\...'.
     *
     * Example 2
     * 1. consider 2 paths i.e. ['a\\b', 'a\\b\\c'].
     * 	a. Even if 'b' is present in path2, as 'b' is suffix of path1 and is not suffix of path2, unique path will be '...\\b'.
     * 2. for path2, 'c' is not present in path1 hence unique path is '..\\c'.
     */
    const ellipsis = '\u2026';
    const unc = '\\\\';
    const home = '~';
    function shorten(paths) {
        const shortenedPaths = new Array(paths.length);
        // for every path
        let match = false;
        for (let pathIndex = 0; pathIndex < paths.length; pathIndex++) {
            let path = paths[pathIndex];
            if (path === '') {
                shortenedPaths[pathIndex] = `.${path_1.sep}`;
                continue;
            }
            if (!path) {
                shortenedPaths[pathIndex] = path;
                continue;
            }
            match = true;
            // trim for now and concatenate unc path (e.g. \\network) or root path (/etc, ~/etc) later
            let prefix = '';
            if (path.indexOf(unc) === 0) {
                prefix = path.substr(0, path.indexOf(unc) + unc.length);
                path = path.substr(path.indexOf(unc) + unc.length);
            }
            else if (path.indexOf(path_1.sep) === 0) {
                prefix = path.substr(0, path.indexOf(path_1.sep) + path_1.sep.length);
                path = path.substr(path.indexOf(path_1.sep) + path_1.sep.length);
            }
            else if (path.indexOf(home) === 0) {
                prefix = path.substr(0, path.indexOf(home) + home.length);
                path = path.substr(path.indexOf(home) + home.length);
            }
            // pick the first shortest subpath found
            const segments = path.split(path_1.sep);
            for (let subpathLength = 1; match && subpathLength <= segments.length; subpathLength++) {
                for (let start = segments.length - subpathLength; match && start >= 0; start--) {
                    match = false;
                    let subpath = segments.slice(start, start + subpathLength).join(path_1.sep);
                    // that is unique to any other path
                    for (let otherPathIndex = 0; !match && otherPathIndex < paths.length; otherPathIndex++) {
                        // suffix subpath treated specially as we consider no match 'x' and 'x/...'
                        if (otherPathIndex !== pathIndex && paths[otherPathIndex] && paths[otherPathIndex].indexOf(subpath) > -1) {
                            const isSubpathEnding = (start + subpathLength === segments.length);
                            // Adding separator as prefix for subpath, such that 'endsWith(src, trgt)' considers subpath as directory name instead of plain string.
                            // prefix is not added when either subpath is root directory or path[otherPathIndex] does not have multiple directories.
                            const subpathWithSep = (start > 0 && paths[otherPathIndex].indexOf(path_1.sep) > -1) ? path_1.sep + subpath : subpath;
                            const isOtherPathEnding = strings_1.endsWith(paths[otherPathIndex], subpathWithSep);
                            match = !isSubpathEnding || isOtherPathEnding;
                        }
                    }
                    // found unique subpath
                    if (!match) {
                        let result = '';
                        // preserve disk drive or root prefix
                        if (strings_1.endsWith(segments[0], ':') || prefix !== '') {
                            if (start === 1) {
                                // extend subpath to include disk drive prefix
                                start = 0;
                                subpathLength++;
                                subpath = segments[0] + path_1.sep + subpath;
                            }
                            if (start > 0) {
                                result = segments[0] + path_1.sep;
                            }
                            result = prefix + result;
                        }
                        // add ellipsis at the beginning if neeeded
                        if (start > 0) {
                            result = result + ellipsis + path_1.sep;
                        }
                        result = result + subpath;
                        // add ellipsis at the end if needed
                        if (start + subpathLength < segments.length) {
                            result = result + path_1.sep + ellipsis;
                        }
                        shortenedPaths[pathIndex] = result;
                    }
                }
            }
            if (match) {
                shortenedPaths[pathIndex] = path; // use full path if no unique subpaths found
            }
        }
        return shortenedPaths;
    }
    exports.shorten = shorten;
    var Type;
    (function (Type) {
        Type[Type["TEXT"] = 0] = "TEXT";
        Type[Type["VARIABLE"] = 1] = "VARIABLE";
        Type[Type["SEPARATOR"] = 2] = "SEPARATOR";
    })(Type || (Type = {}));
    /**
     * Helper to insert values for specific template variables into the string. E.g. "this $(is) a $(template)" can be
     * passed to this function together with an object that maps "is" and "template" to strings to have them replaced.
     * @param value string to which templating is applied
     * @param values the values of the templates to use
     */
    function template(template, values = Object.create(null)) {
        const segments = [];
        let inVariable = false;
        let curVal = '';
        for (const char of template) {
            // Beginning of variable
            if (char === '$' || (inVariable && char === '{')) {
                if (curVal) {
                    segments.push({ value: curVal, type: Type.TEXT });
                }
                curVal = '';
                inVariable = true;
            }
            // End of variable
            else if (char === '}' && inVariable) {
                const resolved = values[curVal];
                // Variable
                if (typeof resolved === 'string') {
                    if (resolved.length) {
                        segments.push({ value: resolved, type: Type.VARIABLE });
                    }
                }
                // Separator
                else if (resolved) {
                    const prevSegment = segments[segments.length - 1];
                    if (!prevSegment || prevSegment.type !== Type.SEPARATOR) {
                        segments.push({ value: resolved.label, type: Type.SEPARATOR }); // prevent duplicate separators
                    }
                }
                curVal = '';
                inVariable = false;
            }
            // Text or Variable Name
            else {
                curVal += char;
            }
        }
        // Tail
        if (curVal && !inVariable) {
            segments.push({ value: curVal, type: Type.TEXT });
        }
        return segments.filter((segment, index) => {
            // Only keep separator if we have values to the left and right
            if (segment.type === Type.SEPARATOR) {
                const left = segments[index - 1];
                const right = segments[index + 1];
                return [left, right].every(segment => segment && (segment.type === Type.VARIABLE || segment.type === Type.TEXT) && segment.value.length > 0);
            }
            // accept any TEXT and VARIABLE
            return true;
        }).map(segment => segment.value).join('');
    }
    exports.template = template;
    /**
     * Handles mnemonics for menu items. Depending on OS:
     * - Windows: Supported via & character (replace && with &)
     * -   Linux: Supported via & character (replace && with &)
     * -   macOS: Unsupported (replace && with empty string)
     */
    function mnemonicMenuLabel(label, forceDisableMnemonics) {
        if (platform_1.isMacintosh || forceDisableMnemonics) {
            return label.replace(/\(&&\w\)|&&/g, '').replace(/&/g, platform_1.isMacintosh ? '&' : '&&');
        }
        return label.replace(/&&|&/g, m => m === '&' ? '&&' : '&');
    }
    exports.mnemonicMenuLabel = mnemonicMenuLabel;
    /**
     * Handles mnemonics for buttons. Depending on OS:
     * - Windows: Supported via & character (replace && with & and & with && for escaping)
     * -   Linux: Supported via _ character (replace && with _)
     * -   macOS: Unsupported (replace && with empty string)
     */
    function mnemonicButtonLabel(label) {
        if (platform_1.isMacintosh) {
            return label.replace(/\(&&\w\)|&&/g, '');
        }
        if (platform_1.isWindows) {
            return label.replace(/&&|&/g, m => m === '&' ? '&&' : '&');
        }
        return label.replace(/&&/g, '_');
    }
    exports.mnemonicButtonLabel = mnemonicButtonLabel;
    function unmnemonicLabel(label) {
        return label.replace(/&/g, '&&');
    }
    exports.unmnemonicLabel = unmnemonicLabel;
    /**
     * Splits a path in name and parent path, supporting both '/' and '\'
     */
    function splitName(fullPath) {
        for (let i = fullPath.length - 1; i >= 1; i--) {
            const code = fullPath.charCodeAt(i);
            if (code === 47 /* Slash */ || code === 92 /* Backslash */) {
                return { parentPath: fullPath.substr(0, i), name: fullPath.substr(i + 1) };
            }
        }
        return { parentPath: '', name: fullPath };
    }
    exports.splitName = splitName;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[48/*vs/base/node/paths*/], __M([1/*require*/,0/*exports*/,32/*vs/base/common/amd*/]), function (require, exports, amd_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const pathsPath = amd_1.getPathFromAmdModule(require, 'paths');
    const paths = require.__$__nodeRequire(pathsPath);
    exports.getAppDataPath = paths.getAppDataPath;
    exports.getDefaultUserDataPath = paths.getDefaultUserDataPath;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
define(__m[51/*vs/base/node/proxy*/], __M([1/*require*/,0/*exports*/,52/*url*/,4/*vs/base/common/types*/]), function (require, exports, url_1, types_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function getSystemProxyURI(requestURL) {
        if (requestURL.protocol === 'http:') {
            return process.env.HTTP_PROXY || process.env.http_proxy || null;
        }
        else if (requestURL.protocol === 'https:') {
            return process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy || null;
        }
        return null;
    }
    function getProxyAgent(rawRequestURL, options = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            const requestURL = url_1.parse(rawRequestURL);
            const proxyURL = options.proxyUrl || getSystemProxyURI(requestURL);
            if (!proxyURL) {
                return null;
            }
            const proxyEndpoint = url_1.parse(proxyURL);
            if (!/^https?:$/.test(proxyEndpoint.protocol || '')) {
                return null;
            }
            const opts = {
                host: proxyEndpoint.hostname || '',
                port: Number(proxyEndpoint.port),
                auth: proxyEndpoint.auth,
                rejectUnauthorized: types_1.isBoolean(options.strictSSL) ? options.strictSSL : true
            };
            const Ctor = requestURL.protocol === 'http:'
                ? yield new Promise((resolve_1, reject_1) => { require(['http-proxy-agent'], resolve_1, reject_1); })
                : yield new Promise((resolve_2, reject_2) => { require(['https-proxy-agent'], resolve_2, reject_2); });
            return new Ctor(opts);
        });
    }
    exports.getProxyAgent = getProxyAgent;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[69/*vs/base/node/config*/], __M([1/*require*/,0/*exports*/,29/*fs*/,3/*vs/base/common/path*/,7/*vs/base/common/objects*/,10/*vs/base/common/lifecycle*/,6/*vs/base/common/event*/,33/*vs/base/common/json*/,38/*vs/base/node/extfs*/,18/*vs/base/common/platform*/]), function (require, exports, fs, path_1, objects, lifecycle_1, event_1, json, extfs, platform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * A simple helper to watch a configured file for changes and process its contents as JSON object.
     * Supports:
     * - comments in JSON files and errors
     * - symlinks for the config file itself
     * - delayed processing of changes to accomodate for lots of changes
     * - configurable defaults
     */
    class ConfigWatcher {
        constructor(_path, options = { defaultConfig: Object.create(null), onError: error => console.error(error) }) {
            this._path = _path;
            this.options = options;
            this.disposables = [];
            this.configName = path_1.basename(this._path);
            this._onDidUpdateConfiguration = new event_1.Emitter();
            this.disposables.push(this._onDidUpdateConfiguration);
            this.registerWatcher();
            this.initAsync();
        }
        get path() {
            return this._path;
        }
        get hasParseErrors() {
            return this.parseErrors && this.parseErrors.length > 0;
        }
        get onDidUpdateConfiguration() {
            return this._onDidUpdateConfiguration.event;
        }
        initAsync() {
            this.loadAsync(config => {
                if (!this.loaded) {
                    this.updateCache(config); // prevent race condition if config was loaded sync already
                }
                if (this.options.initCallback) {
                    this.options.initCallback(this.getConfig());
                }
            });
        }
        updateCache(value) {
            this.cache = value;
            this.loaded = true;
        }
        loadSync() {
            try {
                return this.parse(fs.readFileSync(this._path).toString());
            }
            catch (error) {
                return this.options.defaultConfig;
            }
        }
        loadAsync(callback) {
            fs.readFile(this._path, (error, raw) => {
                if (error) {
                    return callback(this.options.defaultConfig);
                }
                return callback(this.parse(raw.toString()));
            });
        }
        parse(raw) {
            let res;
            try {
                this.parseErrors = [];
                res = this.options.parse ? this.options.parse(raw, this.parseErrors) : json.parse(raw, this.parseErrors);
                return res || this.options.defaultConfig;
            }
            catch (error) {
                // Ignore parsing errors
                return this.options.defaultConfig;
            }
        }
        registerWatcher() {
            // Watch the parent of the path so that we detect ADD and DELETES
            const parentFolder = path_1.dirname(this._path);
            this.watch(parentFolder, true);
            // Check if the path is a symlink and watch its target if so
            fs.lstat(this._path, (err, stat) => {
                if (err || stat.isDirectory()) {
                    return; // path is not a valid file
                }
                // We found a symlink
                if (stat.isSymbolicLink()) {
                    fs.readlink(this._path, (err, realPath) => {
                        if (err) {
                            return; // path is not a valid symlink
                        }
                        this.watch(realPath, false);
                    });
                }
            });
        }
        watch(path, isParentFolder) {
            if (this.disposed) {
                return; // avoid watchers that will never get disposed by checking for being disposed
            }
            this.disposables.push(extfs.watch(path, (type, file) => this.onConfigFileChange(type, file, isParentFolder), (error) => this.options.onError(error)));
        }
        onConfigFileChange(eventType, filename, isParentFolder) {
            if (isParentFolder) {
                // Windows: in some cases the filename contains artifacts from the absolute path
                // see https://github.com/nodejs/node/issues/19170
                // As such, we have to ensure that the filename basename is used for comparison.
                if (platform_1.isWindows && filename && filename !== this.configName) {
                    filename = path_1.basename(filename);
                }
                if (filename !== this.configName) {
                    return; // a change to a sibling file that is not our config file
                }
            }
            if (this.timeoutHandle) {
                global.clearTimeout(this.timeoutHandle);
                this.timeoutHandle = null;
            }
            // we can get multiple change events for one change, so we buffer through a timeout
            this.timeoutHandle = global.setTimeout(() => this.reload(), this.options.changeBufferDelay || 0);
        }
        reload(callback) {
            this.loadAsync(currentConfig => {
                if (!objects.equals(currentConfig, this.cache)) {
                    this.updateCache(currentConfig);
                    this._onDidUpdateConfiguration.fire({ config: this.cache });
                }
                if (callback) {
                    return callback(currentConfig);
                }
            });
        }
        getConfig() {
            this.ensureLoaded();
            return this.cache;
        }
        ensureLoaded() {
            if (!this.loaded) {
                this.updateCache(this.loadSync());
            }
        }
        dispose() {
            this.disposed = true;
            this.disposables = lifecycle_1.dispose(this.disposables);
        }
    }
    exports.ConfigWatcher = ConfigWatcher;
});

define(__m[49/*vs/nls!vs/base/common/errorMessage*/], __M([9/*vs/nls*/,8/*vs/nls!vs/code/node/cliProcessMain*/]), function(nls, data) { return nls.create("vs/base/common/errorMessage", data); });
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[34/*vs/base/common/errorMessage*/], __M([1/*require*/,0/*exports*/,49/*vs/nls!vs/base/common/errorMessage*/,4/*vs/base/common/types*/,17/*vs/base/common/arrays*/]), function (require, exports, nls, types, arrays) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function exceptionToErrorMessage(exception, verbose) {
        if (exception.message) {
            if (verbose && (exception.stack || exception.stacktrace)) {
                return nls.localize(0, null, detectSystemErrorMessage(exception), exception.stack || exception.stacktrace);
            }
            return detectSystemErrorMessage(exception);
        }
        return nls.localize(1, null);
    }
    function detectSystemErrorMessage(exception) {
        // See https://nodejs.org/api/errors.html#errors_class_system_error
        if (typeof exception.code === 'string' && typeof exception.errno === 'number' && typeof exception.syscall === 'string') {
            return nls.localize(2, null, exception.message);
        }
        return exception.message;
    }
    /**
     * Tries to generate a human readable error message out of the error. If the verbose parameter
     * is set to true, the error message will include stacktrace details if provided.
     *
     * @returns A string containing the error message.
     */
    function toErrorMessage(error = null, verbose = false) {
        if (!error) {
            return nls.localize(3, null);
        }
        if (Array.isArray(error)) {
            const errors = arrays.coalesce(error);
            const msg = toErrorMessage(errors[0], verbose);
            if (errors.length > 1) {
                return nls.localize(4, null, msg, errors.length);
            }
            return msg;
        }
        if (types.isString(error)) {
            return error;
        }
        if (error.detail) {
            const detail = error.detail;
            if (detail.error) {
                return exceptionToErrorMessage(detail.error, verbose);
            }
            if (detail.exception) {
                return exceptionToErrorMessage(detail.exception, verbose);
            }
        }
        if (error.stack) {
            return exceptionToErrorMessage(error, verbose);
        }
        if (error.message) {
            return error.message;
        }
        return nls.localize(5, null);
    }
    exports.toErrorMessage = toErrorMessage;
});

define(__m[56/*vs/nls!vs/base/node/zip*/], __M([9/*vs/nls*/,8/*vs/nls!vs/code/node/cliProcessMain*/]), function(nls, data) { return nls.create("vs/base/node/zip", data); });

define(__m[58/*vs/nls!vs/platform/configuration/common/configurationRegistry*/], __M([9/*vs/nls*/,8/*vs/nls!vs/code/node/cliProcessMain*/]), function(nls, data) { return nls.create("vs/platform/configuration/common/configurationRegistry", data); });
define(__m[59/*vs/nls!vs/platform/extensionManagement/common/extensionManagement*/], __M([9/*vs/nls*/,8/*vs/nls!vs/code/node/cliProcessMain*/]), function(nls, data) { return nls.create("vs/platform/extensionManagement/common/extensionManagement", data); });
define(__m[62/*vs/nls!vs/platform/extensionManagement/node/extensionManagementService*/], __M([9/*vs/nls*/,8/*vs/nls!vs/code/node/cliProcessMain*/]), function(nls, data) { return nls.create("vs/platform/extensionManagement/node/extensionManagementService", data); });
define(__m[63/*vs/nls!vs/platform/extensionManagement/node/extensionManagementUtil*/], __M([9/*vs/nls*/,8/*vs/nls!vs/code/node/cliProcessMain*/]), function(nls, data) { return nls.create("vs/platform/extensionManagement/node/extensionManagementUtil", data); });
define(__m[64/*vs/nls!vs/platform/extensions/node/extensionValidator*/], __M([9/*vs/nls*/,8/*vs/nls!vs/code/node/cliProcessMain*/]), function(nls, data) { return nls.create("vs/platform/extensions/node/extensionValidator", data); });
define(__m[66/*vs/nls!vs/platform/request/node/request*/], __M([9/*vs/nls*/,8/*vs/nls!vs/code/node/cliProcessMain*/]), function(nls, data) { return nls.create("vs/platform/request/node/request", data); });
define(__m[68/*vs/nls!vs/platform/telemetry/common/telemetryService*/], __M([9/*vs/nls*/,8/*vs/nls!vs/code/node/cliProcessMain*/]), function(nls, data) { return nls.create("vs/platform/telemetry/common/telemetryService", data); });
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[13/*vs/platform/extensionManagement/common/extensionManagementUtil*/], __M([1/*require*/,0/*exports*/,16/*vs/base/common/strings*/]), function (require, exports, strings_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function areSameExtensions(a, b) {
        if (a.uuid && b.uuid) {
            return a.uuid === b.uuid;
        }
        if (a.id === b.id) {
            return true;
        }
        return strings_1.compareIgnoreCase(a.id, b.id) === 0;
    }
    exports.areSameExtensions = areSameExtensions;
    function adoptToGalleryExtensionId(id) {
        return id.toLocaleLowerCase();
    }
    exports.adoptToGalleryExtensionId = adoptToGalleryExtensionId;
    function getGalleryExtensionId(publisher, name) {
        return `${publisher.toLocaleLowerCase()}.${name.toLocaleLowerCase()}`;
    }
    exports.getGalleryExtensionId = getGalleryExtensionId;
    function groupByExtension(extensions, getExtensionIdentifier) {
        const byExtension = [];
        const findGroup = extension => {
            for (const group of byExtension) {
                if (group.some(e => areSameExtensions(getExtensionIdentifier(e), getExtensionIdentifier(extension)))) {
                    return group;
                }
            }
            return null;
        };
        for (const extension of extensions) {
            const group = findGroup(extension);
            if (group) {
                group.push(extension);
            }
            else {
                byExtension.push([extension]);
            }
        }
        return byExtension;
    }
    exports.groupByExtension = groupByExtension;
    function getLocalExtensionTelemetryData(extension) {
        return {
            id: extension.identifier.id,
            name: extension.manifest.name,
            galleryId: null,
            publisherId: extension.metadata ? extension.metadata.publisherId : null,
            publisherName: extension.manifest.publisher,
            publisherDisplayName: extension.metadata ? extension.metadata.publisherDisplayName : null,
            dependencies: extension.manifest.extensionDependencies && extension.manifest.extensionDependencies.length > 0
        };
    }
    exports.getLocalExtensionTelemetryData = getLocalExtensionTelemetryData;
    /* __GDPR__FRAGMENT__
        "GalleryExtensionTelemetryData" : {
            "id" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
            "name": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
            "galleryId": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
            "publisherId": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
            "publisherName": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
            "publisherDisplayName": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
            "dependencies": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
            "${include}": [
                "${GalleryExtensionTelemetryData2}"
            ]
        }
    */
    function getGalleryExtensionTelemetryData(extension) {
        return Object.assign({ id: extension.identifier.id, name: extension.name, galleryId: extension.identifier.uuid, publisherId: extension.publisherId, publisherName: extension.publisher, publisherDisplayName: extension.publisherDisplayName, dependencies: !!(extension.properties.dependencies && extension.properties.dependencies.length > 0) }, extension.telemetryData);
    }
    exports.getGalleryExtensionTelemetryData = getGalleryExtensionTelemetryData;
    exports.BetterMergeId = 'pprice.better-merge';
    function getMaliciousExtensionsSet(report) {
        const result = new Set();
        for (const extension of report) {
            if (extension.malicious) {
                result.add(extension.id.id);
            }
        }
        return result;
    }
    exports.getMaliciousExtensionsSet = getMaliciousExtensionsSet;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[70/*vs/platform/extensionManagement/common/extensionNls*/], __M([1/*require*/,0/*exports*/,7/*vs/base/common/objects*/]), function (require, exports, objects_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const nlsRegex = /^%([\w\d.-]+)%$/i;
    function localizeManifest(manifest, translations) {
        const patcher = value => {
            if (typeof value !== 'string') {
                return undefined;
            }
            const match = nlsRegex.exec(value);
            if (!match) {
                return undefined;
            }
            return translations[match[1]] || value;
        };
        return objects_1.cloneAndChange(manifest, patcher);
    }
    exports.localizeManifest = localizeManifest;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/








define(__m[74/*vs/platform/extensionManagement/node/extensionLifecycle*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/lifecycle*/,93/*child_process*/,34/*vs/base/common/errorMessage*/,3/*vs/base/common/path*/,24/*vs/base/common/async*/,6/*vs/base/common/event*/,28/*vs/base/common/network*/,11/*vs/base/node/pfs*/]), function (require, exports, lifecycle_1, child_process_1, errorMessage_1, path_1, async_1, event_1, network_1, pfs_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    class ExtensionsLifecycle extends lifecycle_1.Disposable {
        constructor(environmentService, logService) {
            super();
            this.environmentService = environmentService;
            this.logService = logService;
            this.processesLimiter = new async_1.Limiter(5); // Run max 5 processes in parallel
        }
        postUninstall(extension) {
            return __awaiter(this, void 0, void 0, function* () {
                const script = this.parseScript(extension, 'uninstall');
                if (script) {
                    this.logService.info(extension.identifier.id, extension.manifest.version, `Running post uninstall script`);
                    yield this.processesLimiter.queue(() => this.runLifecycleHook(script.script, 'uninstall', script.args, true, extension)
                        .then(() => this.logService.info(extension.identifier.id, extension.manifest.version, `Finished running post uninstall script`), err => this.logService.error(extension.identifier.id, extension.manifest.version, `Failed to run post uninstall script: ${err}`)));
                }
                return pfs_1.rimraf(this.getExtensionStoragePath(extension)).then(undefined, e => this.logService.error('Error while removing extension storage path', e));
            });
        }
        parseScript(extension, type) {
            const scriptKey = `vscode:${type}`;
            if (extension.location.scheme === network_1.Schemas.file && extension.manifest && extension.manifest['scripts'] && typeof extension.manifest['scripts'][scriptKey] === 'string') {
                const script = extension.manifest['scripts'][scriptKey].split(' ');
                if (script.length < 2 || script[0] !== 'node' || !script[1]) {
                    this.logService.warn(extension.identifier.id, extension.manifest.version, `${scriptKey} should be a node script`);
                    return null;
                }
                return { script: path_1.join(extension.location.fsPath, script[1]), args: script.slice(2) || [] };
            }
            return null;
        }
        runLifecycleHook(lifecycleHook, lifecycleType, args, timeout, extension) {
            return new Promise((c, e) => {
                const extensionLifecycleProcess = this.start(lifecycleHook, lifecycleType, args, extension);
                let timeoutHandler;
                const onexit = (error) => {
                    if (timeoutHandler) {
                        clearTimeout(timeoutHandler);
                        timeoutHandler = null;
                    }
                    if (error) {
                        e(error);
                    }
                    else {
                        c(undefined);
                    }
                };
                // on error
                extensionLifecycleProcess.on('error', (err) => {
                    onexit(errorMessage_1.toErrorMessage(err) || 'Unknown');
                });
                // on exit
                extensionLifecycleProcess.on('exit', (code, signal) => {
                    onexit(code ? `post-${lifecycleType} process exited with code ${code}` : undefined);
                });
                if (timeout) {
                    // timeout: kill process after waiting for 5s
                    timeoutHandler = setTimeout(() => {
                        timeoutHandler = null;
                        extensionLifecycleProcess.kill();
                        e('timed out');
                    }, 5000);
                }
            });
        }
        start(uninstallHook, lifecycleType, args, extension) {
            const opts = {
                silent: true,
                execArgv: undefined
            };
            const extensionUninstallProcess = child_process_1.fork(uninstallHook, [`--type=extension-post-${lifecycleType}`, ...args], opts);
            extensionUninstallProcess.stdout.setEncoding('utf8');
            extensionUninstallProcess.stderr.setEncoding('utf8');
            const onStdout = event_1.Event.fromNodeEventEmitter(extensionUninstallProcess.stdout, 'data');
            const onStderr = event_1.Event.fromNodeEventEmitter(extensionUninstallProcess.stderr, 'data');
            // Log output
            onStdout(data => this.logService.info(extension.identifier.id, extension.manifest.version, `post-${lifecycleType}`, data));
            onStderr(data => this.logService.error(extension.identifier.id, extension.manifest.version, `post-${lifecycleType}`, data));
            const onOutput = event_1.Event.any(event_1.Event.map(onStdout, o => ({ data: `%c${o}`, format: [''] })), event_1.Event.map(onStderr, o => ({ data: `%c${o}`, format: ['color: red'] })));
            // Debounce all output, so we can render it in the Chrome console as a group
            const onDebouncedOutput = event_1.Event.debounce(onOutput, (r, o) => {
                return r
                    ? { data: r.data + o.data, format: [...r.format, ...o.format] }
                    : { data: o.data, format: o.format };
            }, 100);
            // Print out output
            onDebouncedOutput(data => {
                console.group(extension.identifier.id);
                console.log(data.data, ...data.format);
                console.groupEnd();
            });
            return extensionUninstallProcess;
        }
        getExtensionStoragePath(extension) {
            return path_1.join(this.environmentService.globalStorageHome, extension.identifier.id.toLowerCase());
        }
    }
    exports.ExtensionsLifecycle = ExtensionsLifecycle;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[30/*vs/platform/extensions/common/extensions*/], __M([1/*require*/,0/*exports*/,13/*vs/platform/extensionManagement/common/extensionManagementUtil*/,16/*vs/base/common/strings*/]), function (require, exports, extensionManagementUtil_1, strings) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MANIFEST_CACHE_FOLDER = 'CachedExtensions';
    exports.USER_MANIFEST_CACHE_FILE = 'user';
    exports.BUILTIN_MANIFEST_CACHE_FILE = 'builtin';
    class ExtensionIdentifierWithVersion {
        constructor(identifier, version) {
            this.identifier = identifier;
            this.version = version;
        }
        key() {
            return `${this.identifier.id}-${this.version}`;
        }
        equals(o) {
            if (!(o instanceof ExtensionIdentifierWithVersion)) {
                return false;
            }
            return extensionManagementUtil_1.areSameExtensions(this.identifier, o.identifier) && this.version === o.version;
        }
    }
    exports.ExtensionIdentifierWithVersion = ExtensionIdentifierWithVersion;
    function isIExtensionIdentifier(thing) {
        return thing
            && typeof thing === 'object'
            && typeof thing.id === 'string'
            && (!thing.uuid || typeof thing.uuid === 'string');
    }
    exports.isIExtensionIdentifier = isIExtensionIdentifier;
    var ExtensionType;
    (function (ExtensionType) {
        ExtensionType[ExtensionType["System"] = 0] = "System";
        ExtensionType[ExtensionType["User"] = 1] = "User";
    })(ExtensionType = exports.ExtensionType || (exports.ExtensionType = {}));
    /**
     * **!Do not construct directly!**
     *
     * **!Only static methods because it gets serialized!**
     *
     * This represents the "canonical" version for an extension identifier. Extension ids
     * have to be case-insensitive (due to the marketplace), but we must ensure case
     * preservation because the extension API is already public at this time.
     *
     * For example, given an extension with the publisher `"Hello"` and the name `"World"`,
     * its canonical extension identifier is `"Hello.World"`. This extension could be
     * referenced in some other extension's dependencies using the string `"hello.world"`.
     *
     * To make matters more complicated, an extension can optionally have an UUID. When two
     * extensions have the same UUID, they are considered equal even if their identifier is different.
     */
    class ExtensionIdentifier {
        constructor(value) {
            this.value = value;
            this._lower = value.toLowerCase();
        }
        static equals(a, b) {
            if (typeof a === 'undefined' || a === null) {
                return (typeof b === 'undefined' || b === null);
            }
            if (typeof b === 'undefined' || b === null) {
                return false;
            }
            if (typeof a === 'string' || typeof b === 'string') {
                // At least one of the arguments is an extension id in string form,
                // so we have to use the string comparison which ignores case.
                let aValue = (typeof a === 'string' ? a : a.value);
                let bValue = (typeof b === 'string' ? b : b.value);
                return strings.equalsIgnoreCase(aValue, bValue);
            }
            // Now we know both arguments are ExtensionIdentifier
            return (a._lower === b._lower);
        }
        /**
         * Gives the value by which to index (for equality).
         */
        static toKey(id) {
            if (typeof id === 'string') {
                return id.toLowerCase();
            }
            return id._lower;
        }
    }
    exports.ExtensionIdentifier = ExtensionIdentifier;
    function isLanguagePackExtension(manifest) {
        return manifest.contributes && manifest.contributes.localizations ? manifest.contributes.localizations.length > 0 : false;
    }
    exports.isLanguagePackExtension = isLanguagePackExtension;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[85/*vs/platform/extensionManagement/node/extensionsManifestCache*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/lifecycle*/,3/*vs/base/common/path*/,30/*vs/platform/extensions/common/extensions*/,11/*vs/base/node/pfs*/]), function (require, exports, lifecycle_1, path_1, extensions_1, pfs) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    class ExtensionsManifestCache extends lifecycle_1.Disposable {
        constructor(environmentService, extensionsManagementServuce) {
            super();
            this.environmentService = environmentService;
            this.extensionsManifestCache = path_1.join(this.environmentService.userDataPath, extensions_1.MANIFEST_CACHE_FOLDER, extensions_1.USER_MANIFEST_CACHE_FILE);
            this._register(extensionsManagementServuce.onDidInstallExtension(e => this.onDidInstallExtension(e)));
            this._register(extensionsManagementServuce.onDidUninstallExtension(e => this.onDidUnInstallExtension(e)));
        }
        onDidInstallExtension(e) {
            if (!e.error) {
                this.invalidate();
            }
        }
        onDidUnInstallExtension(e) {
            if (!e.error) {
                this.invalidate();
            }
        }
        invalidate() {
            pfs.del(this.extensionsManifestCache).then(() => { }, () => { });
        }
    }
    exports.ExtensionsManifestCache = ExtensionsManifestCache;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[31/*vs/platform/instantiation/common/descriptors*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    class SyncDescriptor {
        constructor(ctor, staticArguments = [], supportsDelayedInstantiation = false) {
            this.ctor = ctor;
            this.staticArguments = staticArguments;
            this.supportsDelayedInstantiation = supportsDelayedInstantiation;
        }
    }
    exports.SyncDescriptor = SyncDescriptor;
    exports.createSyncDescriptor = (ctor, ...staticArguments) => {
        return new SyncDescriptor(ctor, staticArguments);
    };
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[47/*vs/platform/instantiation/common/graph*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/types*/,84/*vs/base/common/collections*/]), function (require, exports, types_1, collections_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function newNode(data) {
        return {
            data: data,
            incoming: Object.create(null),
            outgoing: Object.create(null)
        };
    }
    class Graph {
        constructor(_hashFn) {
            this._hashFn = _hashFn;
            this._nodes = Object.create(null);
            // empty
        }
        roots() {
            const ret = [];
            collections_1.forEach(this._nodes, entry => {
                if (types_1.isEmptyObject(entry.value.outgoing)) {
                    ret.push(entry.value);
                }
            });
            return ret;
        }
        insertEdge(from, to) {
            const fromNode = this.lookupOrInsertNode(from), toNode = this.lookupOrInsertNode(to);
            fromNode.outgoing[this._hashFn(to)] = toNode;
            toNode.incoming[this._hashFn(from)] = fromNode;
        }
        removeNode(data) {
            const key = this._hashFn(data);
            delete this._nodes[key];
            collections_1.forEach(this._nodes, (entry) => {
                delete entry.value.outgoing[key];
                delete entry.value.incoming[key];
            });
        }
        lookupOrInsertNode(data) {
            const key = this._hashFn(data);
            let node = this._nodes[key];
            if (!node) {
                node = newNode(data);
                this._nodes[key] = node;
            }
            return node;
        }
        lookup(data) {
            return this._nodes[this._hashFn(data)];
        }
        isEmpty() {
            for (const _key in this._nodes) {
                return false;
            }
            return true;
        }
        toString() {
            let data = [];
            collections_1.forEach(this._nodes, entry => {
                data.push(`${entry.key}, (incoming)[${Object.keys(entry.value.incoming).join(', ')}], (outgoing)[${Object.keys(entry.value.outgoing).join(',')}]`);
            });
            return data.join('\n');
        }
    }
    exports.Graph = Graph;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[46/*vs/platform/download/common/download*/], __M([1/*require*/,0/*exports*/,2/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IDownloadService = instantiation_1.createDecorator('downloadService');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[14/*vs/platform/environment/common/environment*/], __M([1/*require*/,0/*exports*/,2/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IEnvironmentService = instantiation_1.createDecorator('environmentService');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[23/*vs/platform/extensionManagement/common/extensionManagement*/], __M([1/*require*/,0/*exports*/,59/*vs/nls!vs/platform/extensionManagement/common/extensionManagement*/,2/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, nls_1, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EXTENSION_IDENTIFIER_PATTERN = '^([a-z0-9A-Z][a-z0-9\-A-Z]*)\\.([a-z0-9A-Z][a-z0-9\-A-Z]*)$';
    exports.EXTENSION_IDENTIFIER_REGEX = new RegExp(exports.EXTENSION_IDENTIFIER_PATTERN);
    function isIExtensionIdentifier(thing) {
        return thing
            && typeof thing === 'object'
            && typeof thing.id === 'string'
            && (!thing.uuid || typeof thing.uuid === 'string');
    }
    exports.isIExtensionIdentifier = isIExtensionIdentifier;
    exports.IExtensionManagementService = instantiation_1.createDecorator('extensionManagementService');
    exports.IExtensionGalleryService = instantiation_1.createDecorator('extensionGalleryService');
    var SortBy;
    (function (SortBy) {
        SortBy[SortBy["NoneOrRelevance"] = 0] = "NoneOrRelevance";
        SortBy[SortBy["LastUpdatedDate"] = 1] = "LastUpdatedDate";
        SortBy[SortBy["Title"] = 2] = "Title";
        SortBy[SortBy["PublisherName"] = 3] = "PublisherName";
        SortBy[SortBy["InstallCount"] = 4] = "InstallCount";
        SortBy[SortBy["PublishedDate"] = 5] = "PublishedDate";
        SortBy[SortBy["AverageRating"] = 6] = "AverageRating";
        SortBy[SortBy["WeightedRating"] = 12] = "WeightedRating";
    })(SortBy = exports.SortBy || (exports.SortBy = {}));
    var SortOrder;
    (function (SortOrder) {
        SortOrder[SortOrder["Default"] = 0] = "Default";
        SortOrder[SortOrder["Ascending"] = 1] = "Ascending";
        SortOrder[SortOrder["Descending"] = 2] = "Descending";
    })(SortOrder = exports.SortOrder || (exports.SortOrder = {}));
    var StatisticType;
    (function (StatisticType) {
        StatisticType["Uninstall"] = "uninstall";
    })(StatisticType = exports.StatisticType || (exports.StatisticType = {}));
    var InstallOperation;
    (function (InstallOperation) {
        InstallOperation[InstallOperation["None"] = 0] = "None";
        InstallOperation[InstallOperation["Install"] = 1] = "Install";
        InstallOperation[InstallOperation["Update"] = 2] = "Update";
    })(InstallOperation = exports.InstallOperation || (exports.InstallOperation = {}));
    exports.INSTALL_ERROR_MALICIOUS = 'malicious';
    exports.INSTALL_ERROR_INCOMPATIBLE = 'incompatible';
    exports.IExtensionManagementServerService = instantiation_1.createDecorator('extensionManagementServerService');
    var EnablementState;
    (function (EnablementState) {
        EnablementState[EnablementState["Disabled"] = 0] = "Disabled";
        EnablementState[EnablementState["WorkspaceDisabled"] = 1] = "WorkspaceDisabled";
        EnablementState[EnablementState["Enabled"] = 2] = "Enabled";
        EnablementState[EnablementState["WorkspaceEnabled"] = 3] = "WorkspaceEnabled";
    })(EnablementState = exports.EnablementState || (exports.EnablementState = {}));
    exports.IExtensionEnablementService = instantiation_1.createDecorator('extensionEnablementService');
    exports.IExtensionTipsService = instantiation_1.createDecorator('extensionTipsService');
    var ExtensionRecommendationReason;
    (function (ExtensionRecommendationReason) {
        ExtensionRecommendationReason[ExtensionRecommendationReason["Workspace"] = 0] = "Workspace";
        ExtensionRecommendationReason[ExtensionRecommendationReason["File"] = 1] = "File";
        ExtensionRecommendationReason[ExtensionRecommendationReason["Executable"] = 2] = "Executable";
        ExtensionRecommendationReason[ExtensionRecommendationReason["DynamicWorkspace"] = 3] = "DynamicWorkspace";
        ExtensionRecommendationReason[ExtensionRecommendationReason["Experimental"] = 4] = "Experimental";
    })(ExtensionRecommendationReason = exports.ExtensionRecommendationReason || (exports.ExtensionRecommendationReason = {}));
    exports.ExtensionsLabel = nls_1.localize(0, null);
    exports.ExtensionsChannelId = 'extensions';
    exports.PreferencesLabel = nls_1.localize(1, null);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[36/*vs/platform/instantiation/common/serviceCollection*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    class ServiceCollection {
        constructor(...entries) {
            this._entries = new Map();
            for (let [id, service] of entries) {
                this.set(id, service);
            }
        }
        set(id, instanceOrDescriptor) {
            const result = this._entries.get(id);
            this._entries.set(id, instanceOrDescriptor);
            return result;
        }
        forEach(callback) {
            this._entries.forEach((value, key) => callback(key, value));
        }
        has(id) {
            return this._entries.has(id);
        }
        get(id) {
            return this._entries.get(id);
        }
    }
    exports.ServiceCollection = ServiceCollection;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[53/*vs/platform/instantiation/common/instantiationService*/], __M([1/*require*/,0/*exports*/,25/*vs/base/common/errors*/,4/*vs/base/common/types*/,47/*vs/platform/instantiation/common/graph*/,31/*vs/platform/instantiation/common/descriptors*/,2/*vs/platform/instantiation/common/instantiation*/,36/*vs/platform/instantiation/common/serviceCollection*/,24/*vs/base/common/async*/]), function (require, exports, errors_1, types_1, graph_1, descriptors_1, instantiation_1, serviceCollection_1, async_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    // TRACING
    const _enableTracing = false;
    const _canUseProxy = typeof Proxy === 'function';
    class InstantiationService {
        constructor(services = new serviceCollection_1.ServiceCollection(), strict = false, parent) {
            this._services = services;
            this._strict = strict;
            this._parent = parent;
            this._services.set(instantiation_1.IInstantiationService, this);
        }
        createChild(services) {
            return new InstantiationService(services, this._strict, this);
        }
        invokeFunction(fn, ...args) {
            let _trace = Trace.traceInvocation(fn);
            let _done = false;
            try {
                const accessor = {
                    get: (id, isOptional) => {
                        if (_done) {
                            throw errors_1.illegalState('service accessor is only valid during the invocation of its target method');
                        }
                        const result = this._getOrCreateServiceInstance(id, _trace);
                        if (!result && isOptional !== instantiation_1.optional) {
                            throw new Error(`[invokeFunction] unknown service '${id}'`);
                        }
                        return result;
                    }
                };
                return fn.apply(undefined, [accessor, ...args]);
            }
            finally {
                _done = true;
                _trace.stop();
            }
        }
        createInstance(ctorOrDescriptor, ...rest) {
            let _trace;
            let result;
            if (ctorOrDescriptor instanceof descriptors_1.SyncDescriptor) {
                _trace = Trace.traceCreation(ctorOrDescriptor.ctor);
                result = this._createInstance(ctorOrDescriptor.ctor, ctorOrDescriptor.staticArguments.concat(rest), _trace);
            }
            else {
                _trace = Trace.traceCreation(ctorOrDescriptor);
                result = this._createInstance(ctorOrDescriptor, rest, _trace);
            }
            _trace.stop();
            return result;
        }
        _createInstance(ctor, args = [], _trace) {
            // arguments defined by service decorators
            let serviceDependencies = instantiation_1._util.getServiceDependencies(ctor).sort((a, b) => a.index - b.index);
            let serviceArgs = [];
            for (const dependency of serviceDependencies) {
                let service = this._getOrCreateServiceInstance(dependency.id, _trace);
                if (!service && this._strict && !dependency.optional) {
                    throw new Error(`[createInstance] ${ctor.name} depends on UNKNOWN service ${dependency.id}.`);
                }
                serviceArgs.push(service);
            }
            let firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : args.length;
            // check for argument mismatches, adjust static args if needed
            if (args.length !== firstServiceArgPos) {
                console.warn(`[createInstance] First service dependency of ${ctor.name} at position ${firstServiceArgPos + 1} conflicts with ${args.length} static arguments`);
                let delta = firstServiceArgPos - args.length;
                if (delta > 0) {
                    args = args.concat(new Array(delta));
                }
                else {
                    args = args.slice(0, firstServiceArgPos);
                }
            }
            // now create the instance
            return types_1.create.apply(null, [ctor].concat(args, serviceArgs));
        }
        _setServiceInstance(id, instance) {
            if (this._services.get(id) instanceof descriptors_1.SyncDescriptor) {
                this._services.set(id, instance);
            }
            else if (this._parent) {
                this._parent._setServiceInstance(id, instance);
            }
            else {
                throw new Error('illegalState - setting UNKNOWN service instance');
            }
        }
        _getServiceInstanceOrDescriptor(id) {
            let instanceOrDesc = this._services.get(id);
            if (!instanceOrDesc && this._parent) {
                return this._parent._getServiceInstanceOrDescriptor(id);
            }
            else {
                return instanceOrDesc;
            }
        }
        _getOrCreateServiceInstance(id, _trace) {
            let thing = this._getServiceInstanceOrDescriptor(id);
            if (thing instanceof descriptors_1.SyncDescriptor) {
                return this._createAndCacheServiceInstance(id, thing, _trace.branch(id, true));
            }
            else {
                _trace.branch(id, false);
                return thing;
            }
        }
        _createAndCacheServiceInstance(id, desc, _trace) {
            const graph = new graph_1.Graph(data => data.id.toString());
            function throwCycleError() {
                const err = new Error('[createInstance] cyclic dependency between services');
                err.message = graph.toString();
                throw err;
            }
            let count = 0;
            const stack = [{ id, desc, _trace }];
            while (stack.length) {
                const item = stack.pop();
                graph.lookupOrInsertNode(item);
                // TODO@joh use the graph to find a cycle
                // a weak heuristic for cycle checks
                if (count++ > 100) {
                    throwCycleError();
                }
                // check all dependencies for existence and if they need to be created first
                let dependencies = instantiation_1._util.getServiceDependencies(item.desc.ctor);
                for (let dependency of dependencies) {
                    let instanceOrDesc = this._getServiceInstanceOrDescriptor(dependency.id);
                    if (!instanceOrDesc && !dependency.optional) {
                        console.warn(`[createInstance] ${id} depends on ${dependency.id} which is NOT registered.`);
                    }
                    if (instanceOrDesc instanceof descriptors_1.SyncDescriptor) {
                        const d = { id: dependency.id, desc: instanceOrDesc, _trace: item._trace.branch(dependency.id, true) };
                        graph.insertEdge(item, d);
                        stack.push(d);
                    }
                }
            }
            while (true) {
                let roots = graph.roots();
                // if there is no more roots but still
                // nodes in the graph we have a cycle
                if (roots.length === 0) {
                    if (!graph.isEmpty()) {
                        throwCycleError();
                    }
                    break;
                }
                for (let { data } of roots) {
                    // create instance and overwrite the service collections
                    const instance = this._createServiceInstanceWithOwner(data.id, data.desc.ctor, data.desc.staticArguments, data.desc.supportsDelayedInstantiation, data._trace);
                    this._setServiceInstance(data.id, instance);
                    graph.removeNode(data);
                }
            }
            return this._getServiceInstanceOrDescriptor(id);
        }
        _createServiceInstanceWithOwner(id, ctor, args = [], supportsDelayedInstantiation, _trace) {
            if (this._services.get(id) instanceof descriptors_1.SyncDescriptor) {
                return this._createServiceInstance(ctor, args, supportsDelayedInstantiation, _trace);
            }
            else if (this._parent) {
                return this._parent._createServiceInstanceWithOwner(id, ctor, args, supportsDelayedInstantiation, _trace);
            }
            else {
                throw new Error('illegalState - creating UNKNOWN service instance');
            }
        }
        _createServiceInstance(ctor, args = [], _supportsDelayedInstantiation, _trace) {
            if (!_supportsDelayedInstantiation || !_canUseProxy) {
                // eager instantiation or no support JS proxies (e.g. IE11)
                return this._createInstance(ctor, args, _trace);
            }
            else {
                // Return a proxy object that's backed by an idle value. That
                // strategy is to instantiate services in our idle time or when actually
                // needed but not when injected into a consumer
                const idle = new async_1.IdleValue(() => this._createInstance(ctor, args, _trace));
                return new Proxy(Object.create(null), {
                    get(_target, prop) {
                        return idle.getValue()[prop];
                    },
                    set(_target, p, value) {
                        idle.getValue()[p] = value;
                        return true;
                    }
                });
            }
        }
    }
    exports.InstantiationService = InstantiationService;
    //#region -- tracing ---
    var TraceType;
    (function (TraceType) {
        TraceType[TraceType["Creation"] = 0] = "Creation";
        TraceType[TraceType["Invocation"] = 1] = "Invocation";
        TraceType[TraceType["Branch"] = 2] = "Branch";
    })(TraceType || (TraceType = {}));
    class Trace {
        constructor(type, name) {
            this.type = type;
            this.name = name;
            this._start = Date.now();
            this._dep = [];
        }
        static traceInvocation(ctor) {
            return !_enableTracing ? Trace._None : new Trace(1 /* Invocation */, ctor.name || ctor.toString().substring(0, 42).replace(/\n/g, ''));
        }
        static traceCreation(ctor) {
            return !_enableTracing ? Trace._None : new Trace(0 /* Creation */, ctor.name);
        }
        branch(id, first) {
            let child = new Trace(2 /* Branch */, id.toString());
            this._dep.push([id, first, child]);
            return child;
        }
        stop() {
            let dur = Date.now() - this._start;
            Trace._totals += dur;
            let causedCreation = false;
            function printChild(n, trace) {
                let res = [];
                let prefix = new Array(n + 1).join('\t');
                for (const [id, first, child] of trace._dep) {
                    if (first && child) {
                        causedCreation = true;
                        res.push(`${prefix}CREATES -> ${id}`);
                        let nested = printChild(n + 1, child);
                        if (nested) {
                            res.push(nested);
                        }
                    }
                    else {
                        res.push(`${prefix}uses -> ${id}`);
                    }
                }
                return res.join('\n');
            }
            let lines = [
                `${this.type === 0 /* Creation */ ? 'CREATE' : 'CALL'} ${this.name}`,
                `${printChild(1, this)}`,
                `DONE, took ${dur.toFixed(2)}ms (grand total ${Trace._totals.toFixed(2)}ms)`
            ];
            if (dur > 2 || causedCreation) {
                console.log(lines.join('\n'));
            }
        }
    }
    Trace._None = new class extends Trace {
        constructor() { super(-1, null); }
        stop() { }
        branch() { return this; }
    };
    Trace._totals = 0;
});
//#endregion

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[55/*vs/platform/localizations/common/localizations*/], __M([1/*require*/,0/*exports*/,2/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var LanguageType;
    (function (LanguageType) {
        LanguageType[LanguageType["Core"] = 1] = "Core";
        LanguageType[LanguageType["Contributed"] = 2] = "Contributed";
    })(LanguageType = exports.LanguageType || (exports.LanguageType = {}));
    exports.ILocalizationsService = instantiation_1.createDecorator('localizationsService');
    function isValidLocalization(localization) {
        if (typeof localization.languageId !== 'string') {
            return false;
        }
        if (!Array.isArray(localization.translations) || localization.translations.length === 0) {
            return false;
        }
        for (const translation of localization.translations) {
            if (typeof translation.id !== 'string') {
                return false;
            }
            if (typeof translation.path !== 'string') {
                return false;
            }
        }
        if (localization.languageName && typeof localization.languageName !== 'string') {
            return false;
        }
        if (localization.localizedLanguageName && typeof localization.localizedLanguageName !== 'string') {
            return false;
        }
        return true;
    }
    exports.isValidLocalization = isValidLocalization;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[5/*vs/platform/log/common/log*/], __M([1/*require*/,0/*exports*/,2/*vs/platform/instantiation/common/instantiation*/,10/*vs/base/common/lifecycle*/,18/*vs/base/common/platform*/,6/*vs/base/common/event*/]), function (require, exports, instantiation_1, lifecycle_1, platform_1, event_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ILogService = instantiation_1.createDecorator('logService');
    function now() {
        return new Date().toISOString();
    }
    var LogLevel;
    (function (LogLevel) {
        LogLevel[LogLevel["Trace"] = 0] = "Trace";
        LogLevel[LogLevel["Debug"] = 1] = "Debug";
        LogLevel[LogLevel["Info"] = 2] = "Info";
        LogLevel[LogLevel["Warning"] = 3] = "Warning";
        LogLevel[LogLevel["Error"] = 4] = "Error";
        LogLevel[LogLevel["Critical"] = 5] = "Critical";
        LogLevel[LogLevel["Off"] = 6] = "Off";
    })(LogLevel = exports.LogLevel || (exports.LogLevel = {}));
    exports.DEFAULT_LOG_LEVEL = LogLevel.Info;
    class AbstractLogService extends lifecycle_1.Disposable {
        constructor() {
            super(...arguments);
            this.level = exports.DEFAULT_LOG_LEVEL;
            this._onDidChangeLogLevel = this._register(new event_1.Emitter());
            this.onDidChangeLogLevel = this._onDidChangeLogLevel.event;
        }
        setLevel(level) {
            if (this.level !== level) {
                this.level = level;
                this._onDidChangeLogLevel.fire(this.level);
            }
        }
        getLevel() {
            return this.level;
        }
    }
    exports.AbstractLogService = AbstractLogService;
    class ConsoleLogMainService extends AbstractLogService {
        constructor(logLevel = exports.DEFAULT_LOG_LEVEL) {
            super();
            this.setLevel(logLevel);
            this.useColors = !platform_1.isWindows;
        }
        trace(message, ...args) {
            if (this.getLevel() <= LogLevel.Trace) {
                if (this.useColors) {
                    console.log(`\x1b[90m[main ${now()}]\x1b[0m`, message, ...args);
                }
                else {
                    console.log(`[main ${now()}]`, message, ...args);
                }
            }
        }
        debug(message, ...args) {
            if (this.getLevel() <= LogLevel.Debug) {
                if (this.useColors) {
                    console.log(`\x1b[90m[main ${now()}]\x1b[0m`, message, ...args);
                }
                else {
                    console.log(`[main ${now()}]`, message, ...args);
                }
            }
        }
        info(message, ...args) {
            if (this.getLevel() <= LogLevel.Info) {
                if (this.useColors) {
                    console.log(`\x1b[90m[main ${now()}]\x1b[0m`, message, ...args);
                }
                else {
                    console.log(`[main ${now()}]`, message, ...args);
                }
            }
        }
        warn(message, ...args) {
            if (this.getLevel() <= LogLevel.Warning) {
                if (this.useColors) {
                    console.warn(`\x1b[93m[main ${now()}]\x1b[0m`, message, ...args);
                }
                else {
                    console.warn(`[main ${now()}]`, message, ...args);
                }
            }
        }
        error(message, ...args) {
            if (this.getLevel() <= LogLevel.Error) {
                if (this.useColors) {
                    console.error(`\x1b[91m[main ${now()}]\x1b[0m`, message, ...args);
                }
                else {
                    console.error(`[main ${now()}]`, message, ...args);
                }
            }
        }
        critical(message, ...args) {
            if (this.getLevel() <= LogLevel.Critical) {
                if (this.useColors) {
                    console.error(`\x1b[90m[main ${now()}]\x1b[0m`, message, ...args);
                }
                else {
                    console.error(`[main ${now()}]`, message, ...args);
                }
            }
        }
        dispose() {
            // noop
        }
    }
    exports.ConsoleLogMainService = ConsoleLogMainService;
    class ConsoleLogService extends AbstractLogService {
        constructor(logLevel = exports.DEFAULT_LOG_LEVEL) {
            super();
            this.setLevel(logLevel);
        }
        trace(message, ...args) {
            if (this.getLevel() <= LogLevel.Trace) {
                console.log('%cTRACE', 'color: #888', message, ...args);
            }
        }
        debug(message, ...args) {
            if (this.getLevel() <= LogLevel.Debug) {
                console.log('%cDEBUG', 'background: #eee; color: #888', message, ...args);
            }
        }
        info(message, ...args) {
            if (this.getLevel() <= LogLevel.Info) {
                console.log('%c INFO', 'color: #33f', message, ...args);
            }
        }
        warn(message, ...args) {
            if (this.getLevel() <= LogLevel.Warning) {
                console.log('%c WARN', 'color: #993', message, ...args);
            }
        }
        error(message, ...args) {
            if (this.getLevel() <= LogLevel.Error) {
                console.log('%c  ERR', 'color: #f33', message, ...args);
            }
        }
        critical(message, ...args) {
            if (this.getLevel() <= LogLevel.Critical) {
                console.log('%cCRITI', 'background: #f33; color: white', message, ...args);
            }
        }
        dispose() { }
    }
    exports.ConsoleLogService = ConsoleLogService;
    class MultiplexLogService extends AbstractLogService {
        constructor(logServices) {
            super();
            this.logServices = logServices;
            if (logServices.length) {
                this.setLevel(logServices[0].getLevel());
            }
        }
        setLevel(level) {
            for (const logService of this.logServices) {
                logService.setLevel(level);
            }
            super.setLevel(level);
        }
        trace(message, ...args) {
            for (const logService of this.logServices) {
                logService.trace(message, ...args);
            }
        }
        debug(message, ...args) {
            for (const logService of this.logServices) {
                logService.debug(message, ...args);
            }
        }
        info(message, ...args) {
            for (const logService of this.logServices) {
                logService.info(message, ...args);
            }
        }
        warn(message, ...args) {
            for (const logService of this.logServices) {
                logService.warn(message, ...args);
            }
        }
        error(message, ...args) {
            for (const logService of this.logServices) {
                logService.error(message, ...args);
            }
        }
        critical(message, ...args) {
            for (const logService of this.logServices) {
                logService.critical(message, ...args);
            }
        }
        dispose() {
            for (const logService of this.logServices) {
                logService.dispose();
            }
        }
    }
    exports.MultiplexLogService = MultiplexLogService;
    class DelegatedLogService extends lifecycle_1.Disposable {
        constructor(logService) {
            super();
            this.logService = logService;
            this._register(logService);
        }
        get onDidChangeLogLevel() {
            return this.logService.onDidChangeLogLevel;
        }
        setLevel(level) {
            this.logService.setLevel(level);
        }
        getLevel() {
            return this.logService.getLevel();
        }
        trace(message, ...args) {
            this.logService.trace(message, ...args);
        }
        debug(message, ...args) {
            this.logService.debug(message, ...args);
        }
        info(message, ...args) {
            this.logService.info(message, ...args);
        }
        warn(message, ...args) {
            this.logService.warn(message, ...args);
        }
        error(message, ...args) {
            this.logService.error(message, ...args);
        }
        critical(message, ...args) {
            this.logService.critical(message, ...args);
        }
    }
    exports.DelegatedLogService = DelegatedLogService;
    class NullLogService {
        constructor() {
            this.onDidChangeLogLevel = new event_1.Emitter().event;
        }
        setLevel(level) { }
        getLevel() { return LogLevel.Info; }
        trace(message, ...args) { }
        debug(message, ...args) { }
        info(message, ...args) { }
        warn(message, ...args) { }
        error(message, ...args) { }
        critical(message, ...args) { }
        dispose() { }
    }
    exports.NullLogService = NullLogService;
    function getLogLevel(environmentService) {
        if (environmentService.verbose) {
            return LogLevel.Trace;
        }
        if (typeof environmentService.args.log === 'string') {
            const logLevel = environmentService.args.log.toLowerCase();
            switch (logLevel) {
                case 'trace':
                    return LogLevel.Trace;
                case 'debug':
                    return LogLevel.Debug;
                case 'info':
                    return LogLevel.Info;
                case 'warn':
                    return LogLevel.Warning;
                case 'error':
                    return LogLevel.Error;
                case 'critical':
                    return LogLevel.Critical;
                case 'off':
                    return LogLevel.Off;
            }
        }
        return exports.DEFAULT_LOG_LEVEL;
    }
    exports.getLogLevel = getLogLevel;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[57/*vs/platform/log/node/spdlogService*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/path*/,5/*vs/platform/log/common/log*/]), function (require, exports, path, log_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function createSpdLogService(processName, logLevel, logsFolder) {
        // Do not crash if spdlog cannot be loaded
        try {
            const _spdlog = require.__$__nodeRequire('spdlog');
            _spdlog.setAsyncMode(8192, 500);
            const logfilePath = path.join(logsFolder, `${processName}.log`);
            const logger = new _spdlog.RotatingLogger(processName, logfilePath, 1024 * 1024 * 5, 6);
            logger.setLevel(0);
            return new SpdLogService(logger, logLevel);
        }
        catch (e) {
            console.error(e);
        }
        return new log_1.NullLogService();
    }
    exports.createSpdLogService = createSpdLogService;
    function createRotatingLogger(name, filename, filesize, filecount) {
        const _spdlog = require.__$__nodeRequire('spdlog');
        return new _spdlog.RotatingLogger(name, filename, filesize, filecount);
    }
    exports.createRotatingLogger = createRotatingLogger;
    class SpdLogService extends log_1.AbstractLogService {
        constructor(logger, level = log_1.LogLevel.Error) {
            super();
            this.logger = logger;
            this.setLevel(level);
        }
        trace() {
            if (this.getLevel() <= log_1.LogLevel.Trace) {
                this.logger.trace(this.format(arguments));
            }
        }
        debug() {
            if (this.getLevel() <= log_1.LogLevel.Debug) {
                this.logger.debug(this.format(arguments));
            }
        }
        info() {
            if (this.getLevel() <= log_1.LogLevel.Info) {
                this.logger.info(this.format(arguments));
            }
        }
        warn() {
            if (this.getLevel() <= log_1.LogLevel.Warning) {
                this.logger.warn(this.format(arguments));
            }
        }
        error() {
            if (this.getLevel() <= log_1.LogLevel.Error) {
                const arg = arguments[0];
                if (arg instanceof Error) {
                    const array = Array.prototype.slice.call(arguments);
                    array[0] = arg.stack;
                    this.logger.error(this.format(array));
                }
                else {
                    this.logger.error(this.format(arguments));
                }
            }
        }
        critical() {
            if (this.getLevel() <= log_1.LogLevel.Critical) {
                this.logger.critical(this.format(arguments));
            }
        }
        dispose() {
            this.logger.drop();
        }
        format(args) {
            let result = '';
            for (let i = 0; i < args.length; i++) {
                let a = args[i];
                if (typeof a === 'object') {
                    try {
                        a = JSON.stringify(a);
                    }
                    catch (e) { }
                }
                result += (i > 0 ? ' ' : '') + a;
            }
            return result;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[41/*vs/platform/extensions/node/extensionValidator*/], __M([1/*require*/,0/*exports*/,64/*vs/nls!vs/platform/extensions/node/extensionValidator*/,21/*vs/platform/product/node/package*/]), function (require, exports, nls, package_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const VERSION_REGEXP = /^(\^|>=)?((\d+)|x)\.((\d+)|x)\.((\d+)|x)(\-.*)?$/;
    function isValidVersionStr(version) {
        version = version.trim();
        return (version === '*' || VERSION_REGEXP.test(version));
    }
    exports.isValidVersionStr = isValidVersionStr;
    function parseVersion(version) {
        if (!isValidVersionStr(version)) {
            return null;
        }
        version = version.trim();
        if (version === '*') {
            return {
                hasCaret: false,
                hasGreaterEquals: false,
                majorBase: 0,
                majorMustEqual: false,
                minorBase: 0,
                minorMustEqual: false,
                patchBase: 0,
                patchMustEqual: false,
                preRelease: null
            };
        }
        let m = version.match(VERSION_REGEXP);
        if (!m) {
            return null;
        }
        return {
            hasCaret: m[1] === '^',
            hasGreaterEquals: m[1] === '>=',
            majorBase: m[2] === 'x' ? 0 : parseInt(m[2], 10),
            majorMustEqual: (m[2] === 'x' ? false : true),
            minorBase: m[4] === 'x' ? 0 : parseInt(m[4], 10),
            minorMustEqual: (m[4] === 'x' ? false : true),
            patchBase: m[6] === 'x' ? 0 : parseInt(m[6], 10),
            patchMustEqual: (m[6] === 'x' ? false : true),
            preRelease: m[8] || null
        };
    }
    exports.parseVersion = parseVersion;
    function normalizeVersion(version) {
        if (!version) {
            return null;
        }
        let majorBase = version.majorBase, majorMustEqual = version.majorMustEqual, minorBase = version.minorBase, minorMustEqual = version.minorMustEqual, patchBase = version.patchBase, patchMustEqual = version.patchMustEqual;
        if (version.hasCaret) {
            if (majorBase === 0) {
                patchMustEqual = false;
            }
            else {
                minorMustEqual = false;
                patchMustEqual = false;
            }
        }
        return {
            majorBase: majorBase,
            majorMustEqual: majorMustEqual,
            minorBase: minorBase,
            minorMustEqual: minorMustEqual,
            patchBase: patchBase,
            patchMustEqual: patchMustEqual,
            isMinimum: version.hasGreaterEquals
        };
    }
    exports.normalizeVersion = normalizeVersion;
    function isValidVersion(_version, _desiredVersion) {
        let version;
        if (typeof _version === 'string') {
            version = normalizeVersion(parseVersion(_version));
        }
        else {
            version = _version;
        }
        let desiredVersion;
        if (typeof _desiredVersion === 'string') {
            desiredVersion = normalizeVersion(parseVersion(_desiredVersion));
        }
        else {
            desiredVersion = _desiredVersion;
        }
        if (!version || !desiredVersion) {
            return false;
        }
        let majorBase = version.majorBase;
        let minorBase = version.minorBase;
        let patchBase = version.patchBase;
        let desiredMajorBase = desiredVersion.majorBase;
        let desiredMinorBase = desiredVersion.minorBase;
        let desiredPatchBase = desiredVersion.patchBase;
        let majorMustEqual = desiredVersion.majorMustEqual;
        let minorMustEqual = desiredVersion.minorMustEqual;
        let patchMustEqual = desiredVersion.patchMustEqual;
        if (desiredVersion.isMinimum) {
            if (majorBase > desiredMajorBase) {
                return true;
            }
            if (majorBase < desiredMajorBase) {
                return false;
            }
            if (minorBase > desiredMinorBase) {
                return true;
            }
            if (minorBase < desiredMinorBase) {
                return false;
            }
            return patchBase >= desiredPatchBase;
        }
        // Anything < 1.0.0 is compatible with >= 1.0.0, except exact matches
        if (majorBase === 1 && desiredMajorBase === 0 && (!majorMustEqual || !minorMustEqual || !patchMustEqual)) {
            desiredMajorBase = 1;
            desiredMinorBase = 0;
            desiredPatchBase = 0;
            majorMustEqual = true;
            minorMustEqual = false;
            patchMustEqual = false;
        }
        if (majorBase < desiredMajorBase) {
            // smaller major version
            return false;
        }
        if (majorBase > desiredMajorBase) {
            // higher major version
            return (!majorMustEqual);
        }
        // at this point, majorBase are equal
        if (minorBase < desiredMinorBase) {
            // smaller minor version
            return false;
        }
        if (minorBase > desiredMinorBase) {
            // higher minor version
            return (!minorMustEqual);
        }
        // at this point, minorBase are equal
        if (patchBase < desiredPatchBase) {
            // smaller patch version
            return false;
        }
        if (patchBase > desiredPatchBase) {
            // higher patch version
            return (!patchMustEqual);
        }
        // at this point, patchBase are equal
        return true;
    }
    exports.isValidVersion = isValidVersion;
    function isValidExtensionVersion(version, extensionDesc, notices) {
        if (extensionDesc.isBuiltin || typeof extensionDesc.main === 'undefined') {
            // No version check for builtin or declarative extensions
            return true;
        }
        return isVersionValid(version, extensionDesc.engines.vscode, notices);
    }
    exports.isValidExtensionVersion = isValidExtensionVersion;
    function isEngineValid(engine) {
        // TODO@joao: discuss with alex '*' doesn't seem to be a valid engine version
        return engine === '*' || isVersionValid(package_1.default.version, engine);
    }
    exports.isEngineValid = isEngineValid;
    function isVersionValid(currentVersion, requestedVersion, notices = []) {
        let desiredVersion = normalizeVersion(parseVersion(requestedVersion));
        if (!desiredVersion) {
            notices.push(nls.localize(0, null, requestedVersion));
            return false;
        }
        // enforce that a breaking API version is specified.
        // for 0.X.Y, that means up to 0.X must be specified
        // otherwise for Z.X.Y, that means Z must be specified
        if (desiredVersion.majorBase === 0) {
            // force that major and minor must be specific
            if (!desiredVersion.majorMustEqual || !desiredVersion.minorMustEqual) {
                notices.push(nls.localize(1, null, requestedVersion));
                return false;
            }
        }
        else {
            // force that major must be specific
            if (!desiredVersion.majorMustEqual) {
                notices.push(nls.localize(2, null, requestedVersion));
                return false;
            }
        }
        if (!isValidVersion(currentVersion, desiredVersion)) {
            notices.push(nls.localize(3, null, currentVersion, requestedVersion));
            return false;
        }
        return true;
    }
    exports.isVersionValid = isVersionValid;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
define(__m[60/*vs/platform/environment/node/environmentService*/], __M([1/*require*/,0/*exports*/,61/*crypto*/,48/*vs/base/node/paths*/,26/*os*/,3/*vs/base/common/path*/,54/*vs/base/common/decorators*/,21/*vs/platform/product/node/package*/,22/*vs/platform/product/node/product*/,83/*vs/base/common/date*/,18/*vs/base/common/platform*/,32/*vs/base/common/amd*/,20/*vs/base/common/uri*/]), function (require, exports, crypto, paths, os, path, decorators_1, package_1, product_1, date_1, platform_1, amd_1, uri_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    // Read this before there's any chance it is overwritten
    // Related to https://github.com/Microsoft/vscode/issues/30624
    const xdgRuntimeDir = process.env['XDG_RUNTIME_DIR'];
    function getNixIPCHandle(userDataPath, type) {
        if (xdgRuntimeDir) {
            const scope = crypto.createHash('md5').update(userDataPath).digest('hex').substr(0, 8);
            return path.join(xdgRuntimeDir, `vscode-${scope}-${package_1.default.version}-${type}.sock`);
        }
        return path.join(userDataPath, `${package_1.default.version}-${type}.sock`);
    }
    function getWin32IPCHandle(userDataPath, type) {
        const scope = crypto.createHash('md5').update(userDataPath).digest('hex');
        return `\\\\.\\pipe\\${scope}-${package_1.default.version}-${type}-sock`;
    }
    function getIPCHandle(userDataPath, type) {
        if (platform_1.isWindows) {
            return getWin32IPCHandle(userDataPath, type);
        }
        return getNixIPCHandle(userDataPath, type);
    }
    function getCLIPath(execPath, appRoot, isBuilt) {
        // Windows
        if (platform_1.isWindows) {
            if (isBuilt) {
                return path.join(path.dirname(execPath), 'bin', `${product_1.default.applicationName}.cmd`);
            }
            return path.join(appRoot, 'scripts', 'code-cli.bat');
        }
        // Linux
        if (platform_1.isLinux) {
            if (isBuilt) {
                return path.join(path.dirname(execPath), 'bin', `${product_1.default.applicationName}`);
            }
            return path.join(appRoot, 'scripts', 'code-cli.sh');
        }
        // macOS
        if (isBuilt) {
            return path.join(appRoot, 'bin', 'code');
        }
        return path.join(appRoot, 'scripts', 'code-cli.sh');
    }
    class EnvironmentService {
        constructor(_args, _execPath) {
            this._args = _args;
            this._execPath = _execPath;
            if (!process.env['VSCODE_LOGS']) {
                const key = date_1.toLocalISOString(new Date()).replace(/-|:|\.\d+Z$/g, '');
                process.env['VSCODE_LOGS'] = path.join(this.userDataPath, 'logs', key);
            }
            this.logsPath = process.env['VSCODE_LOGS'];
        }
        get args() { return this._args; }
        get appRoot() { return path.dirname(amd_1.getPathFromAmdModule(require, '')); }
        get execPath() { return this._execPath; }
        get cliPath() { return getCLIPath(this.execPath, this.appRoot, this.isBuilt); }
        get userHome() { return os.homedir(); }
        get userDataPath() {
            const vscodePortable = process.env['VSCODE_PORTABLE'];
            if (vscodePortable) {
                return path.join(vscodePortable, 'user-data');
            }
            return parseUserDataDir(this._args, process);
        }
        get appNameLong() { return product_1.default.nameLong; }
        get appQuality() { return product_1.default.quality; }
        get appSettingsHome() { return path.join(this.userDataPath, 'User'); }
        get appSettingsPath() { return path.join(this.appSettingsHome, 'settings.json'); }
        get globalStorageHome() { return path.join(this.appSettingsHome, 'globalStorage'); }
        get workspaceStorageHome() { return path.join(this.appSettingsHome, 'workspaceStorage'); }
        get settingsSearchBuildId() { return product_1.default.settingsSearchBuildId; }
        get settingsSearchUrl() { return product_1.default.settingsSearchUrl; }
        get appKeybindingsPath() { return path.join(this.appSettingsHome, 'keybindings.json'); }
        get isExtensionDevelopment() { return !!this._args.extensionDevelopmentPath; }
        get backupHome() { return path.join(this.userDataPath, 'Backups'); }
        get backupWorkspacesPath() { return path.join(this.backupHome, 'workspaces.json'); }
        get untitledWorkspacesHome() { return uri_1.URI.file(path.join(this.userDataPath, 'Workspaces')); }
        get installSourcePath() { return path.join(this.userDataPath, 'installSource'); }
        get builtinExtensionsPath() {
            const fromArgs = parsePathArg(this._args['builtin-extensions-dir'], process);
            if (fromArgs) {
                return fromArgs;
            }
            else {
                return path.normalize(path.join(amd_1.getPathFromAmdModule(require, ''), '..', 'extensions'));
            }
        }
        get extensionsPath() {
            const fromArgs = parsePathArg(this._args['extensions-dir'], process);
            if (fromArgs) {
                return fromArgs;
            }
            const vscodeExtensions = process.env['VSCODE_EXTENSIONS'];
            if (vscodeExtensions) {
                return vscodeExtensions;
            }
            const vscodePortable = process.env['VSCODE_PORTABLE'];
            if (vscodePortable) {
                return path.join(vscodePortable, 'extensions');
            }
            return path.join(this.userHome, product_1.default.dataFolderName, 'extensions');
        }
        get extensionDevelopmentLocationURI() {
            const s = this._args.extensionDevelopmentPath;
            if (s) {
                if (/^[^:/?#]+?:\/\//.test(s)) {
                    return uri_1.URI.parse(s);
                }
                return uri_1.URI.file(path.normalize(s));
            }
            return undefined;
        }
        get extensionTestsLocationURI() {
            const s = this._args.extensionTestsPath;
            if (s) {
                if (/^[^:/?#]+?:\/\//.test(s)) {
                    return uri_1.URI.parse(s);
                }
                return uri_1.URI.file(path.normalize(s));
            }
            return undefined;
        }
        get disableExtensions() {
            if (this._args['disable-extensions']) {
                return true;
            }
            const disableExtensions = this._args['disable-extension'];
            if (disableExtensions) {
                if (typeof disableExtensions === 'string') {
                    return [disableExtensions];
                }
                if (Array.isArray(disableExtensions) && disableExtensions.length > 0) {
                    return disableExtensions;
                }
            }
            return false;
        }
        get skipGettingStarted() { return !!this._args['skip-getting-started']; }
        get skipReleaseNotes() { return !!this._args['skip-release-notes']; }
        get skipAddToRecentlyOpened() { return !!this._args['skip-add-to-recently-opened']; }
        get debugExtensionHost() { return parseExtensionHostPort(this._args, this.isBuilt); }
        get debugSearch() { return parseSearchPort(this._args, this.isBuilt); }
        get isBuilt() { return !process.env['VSCODE_DEV']; }
        get verbose() { return !!this._args.verbose; }
        get log() { return this._args.log; }
        get wait() { return !!this._args.wait; }
        get logExtensionHostCommunication() { return !!this._args.logExtensionHostCommunication; }
        get status() { return !!this._args.status; }
        get mainIPCHandle() { return getIPCHandle(this.userDataPath, 'main'); }
        get sharedIPCHandle() { return getIPCHandle(this.userDataPath, 'shared'); }
        get nodeCachedDataDir() { return process.env['VSCODE_NODE_CACHED_DATA_DIR'] || undefined; }
        get disableUpdates() { return !!this._args['disable-updates']; }
        get disableCrashReporter() { return !!this._args['disable-crash-reporter']; }
        get driverHandle() { return this._args['driver']; }
        get driverVerbose() { return !!this._args['driver-verbose']; }
    }
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "appRoot", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "cliPath", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "userHome", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "userDataPath", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "appSettingsHome", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "appSettingsPath", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "globalStorageHome", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "workspaceStorageHome", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "settingsSearchBuildId", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "settingsSearchUrl", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "appKeybindingsPath", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "isExtensionDevelopment", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "backupHome", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "backupWorkspacesPath", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "untitledWorkspacesHome", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "installSourcePath", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "builtinExtensionsPath", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "extensionsPath", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "extensionDevelopmentLocationURI", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "extensionTestsLocationURI", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "debugExtensionHost", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "debugSearch", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "mainIPCHandle", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "sharedIPCHandle", null);
    __decorate([
        decorators_1.memoize
    ], EnvironmentService.prototype, "nodeCachedDataDir", null);
    exports.EnvironmentService = EnvironmentService;
    function parseExtensionHostPort(args, isBuild) {
        return parseDebugPort(args['inspect-extensions'], args['inspect-brk-extensions'], 5870, isBuild, args.debugId);
    }
    exports.parseExtensionHostPort = parseExtensionHostPort;
    function parseSearchPort(args, isBuild) {
        return parseDebugPort(args['inspect-search'], args['inspect-brk-search'], 5876, isBuild);
    }
    exports.parseSearchPort = parseSearchPort;
    function parseDebugPort(debugArg, debugBrkArg, defaultBuildPort, isBuild, debugId) {
        const portStr = debugBrkArg || debugArg;
        const port = Number(portStr) || (!isBuild ? defaultBuildPort : null);
        const brk = port ? Boolean(!!debugBrkArg) : false;
        return { port, break: brk, debugId };
    }
    exports.parseDebugPort = parseDebugPort;
    function parsePathArg(arg, process) {
        if (!arg) {
            return undefined;
        }
        // Determine if the arg is relative or absolute, if relative use the original CWD
        // (VSCODE_CWD), not the potentially overridden one (process.cwd()).
        const resolved = path.resolve(arg);
        if (path.normalize(arg) === resolved) {
            return resolved;
        }
        else {
            return path.resolve(process.env['VSCODE_CWD'] || process.cwd(), arg);
        }
    }
    function parseUserDataDir(args, process) {
        return parsePathArg(args['user-data-dir'], process) || path.resolve(paths.getDefaultUserDataPath(process.platform));
    }
    exports.parseUserDataDir = parseUserDataDir;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[35/*vs/platform/extensions/node/extensionsUtil*/], __M([1/*require*/,0/*exports*/,13/*vs/platform/extensionManagement/common/extensionManagementUtil*/,17/*vs/base/common/arrays*/,22/*vs/platform/product/node/product*/]), function (require, exports, extensionManagementUtil_1, arrays_1, product_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function isUIExtension(manifest, uiContributions, configurationService) {
        const extensionId = extensionManagementUtil_1.getGalleryExtensionId(manifest.publisher, manifest.name);
        const configuredUIExtensions = configurationService.getValue('_workbench.uiExtensions') || [];
        if (configuredUIExtensions.length) {
            if (configuredUIExtensions.indexOf(extensionId) !== -1) {
                return true;
            }
            if (configuredUIExtensions.indexOf(`-${extensionId}`) !== -1) {
                return false;
            }
        }
        switch (manifest.extensionKind) {
            case 'ui': return true;
            case 'workspace': return false;
            default: {
                if (arrays_1.isNonEmptyArray(product_1.default.uiExtensions) && product_1.default.uiExtensions.some(id => extensionManagementUtil_1.areSameExtensions({ id }, { id: extensionId }))) {
                    return true;
                }
                if (manifest.main) {
                    return false;
                }
                if (manifest.contributes) {
                    if (!uiContributions.length || Object.keys(manifest.contributes).some(contribution => uiContributions.indexOf(contribution) === -1)) {
                        return false;
                    }
                }
                // Default is UI Extension
                return true;
            }
        }
    }
    exports.isUIExtension = isUIExtension;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
define(__m[65/*vs/platform/localizations/node/localizations*/], __M([1/*require*/,0/*exports*/,11/*vs/base/node/pfs*/,61/*crypto*/,23/*vs/platform/extensionManagement/common/extensionManagement*/,10/*vs/base/common/lifecycle*/,14/*vs/platform/environment/common/environment*/,24/*vs/base/common/async*/,13/*vs/platform/extensionManagement/common/extensionManagementUtil*/,5/*vs/platform/log/common/log*/,55/*vs/platform/localizations/common/localizations*/,22/*vs/platform/product/node/product*/,17/*vs/base/common/arrays*/,6/*vs/base/common/event*/,28/*vs/base/common/network*/,3/*vs/base/common/path*/]), function (require, exports, pfs, crypto_1, extensionManagement_1, lifecycle_1, environment_1, async_1, extensionManagementUtil_1, log_1, localizations_1, product_1, arrays_1, event_1, network_1, path_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const systemLanguages = ['de', 'en', 'en-US', 'es', 'fr', 'it', 'ja', 'ko', 'ru', 'zh-CN', 'zh-TW'];
    if (product_1.default.quality !== 'stable') {
        systemLanguages.push('hu');
    }
    let LocalizationsService = class LocalizationsService extends lifecycle_1.Disposable {
        constructor(extensionManagementService, environmentService, logService) {
            super();
            this.extensionManagementService = extensionManagementService;
            this.logService = logService;
            this._onDidLanguagesChange = this._register(new event_1.Emitter());
            this.onDidLanguagesChange = this._onDidLanguagesChange.event;
            this.cache = this._register(new LanguagePacksCache(environmentService, logService));
            this._register(extensionManagementService.onDidInstallExtension(({ local }) => this.onDidInstallExtension(local)));
            this._register(extensionManagementService.onDidUninstallExtension(({ identifier }) => this.onDidUninstallExtension(identifier)));
        }
        getLanguageIds(type) {
            if (type === 1 /* Core */) {
                return Promise.resolve([...systemLanguages]);
            }
            return this.cache.getLanguagePacks()
                .then(languagePacks => {
                const languages = type === 2 /* Contributed */ ? Object.keys(languagePacks) : [...systemLanguages, ...Object.keys(languagePacks)];
                return arrays_1.distinct(languages);
            });
        }
        onDidInstallExtension(extension) {
            if (extension && extension.manifest && extension.manifest.contributes && extension.manifest.contributes.localizations && extension.manifest.contributes.localizations.length) {
                this.logService.debug('Adding language packs from the extension', extension.identifier.id);
                this.update().then(changed => { if (changed) {
                    this._onDidLanguagesChange.fire();
                } });
            }
        }
        onDidUninstallExtension(identifier) {
            this.cache.getLanguagePacks()
                .then(languagePacks => {
                if (Object.keys(languagePacks).some(language => languagePacks[language] && languagePacks[language].extensions.some(e => extensionManagementUtil_1.areSameExtensions(e.extensionIdentifier, identifier)))) {
                    this.logService.debug('Removing language packs from the extension', identifier.id);
                    this.update().then(changed => { if (changed) {
                        this._onDidLanguagesChange.fire();
                    } });
                }
            });
        }
        update() {
            return Promise.all([this.cache.getLanguagePacks(), this.extensionManagementService.getInstalled()])
                .then(([current, installed]) => this.cache.update(installed)
                .then(updated => !arrays_1.equals(Object.keys(current), Object.keys(updated))));
        }
    };
    LocalizationsService = __decorate([
        __param(0, extensionManagement_1.IExtensionManagementService),
        __param(1, environment_1.IEnvironmentService),
        __param(2, log_1.ILogService)
    ], LocalizationsService);
    exports.LocalizationsService = LocalizationsService;
    let LanguagePacksCache = class LanguagePacksCache extends lifecycle_1.Disposable {
        constructor(environmentService, logService) {
            super();
            this.environmentService = environmentService;
            this.logService = logService;
            this.languagePacks = {};
            this.languagePacksFilePath = path_1.join(environmentService.userDataPath, 'languagepacks.json');
            this.languagePacksFileLimiter = new async_1.Queue();
        }
        getLanguagePacks() {
            // if queue is not empty, fetch from disk
            if (this.languagePacksFileLimiter.size || !this.initializedCache) {
                return this.withLanguagePacks()
                    .then(() => this.languagePacks);
            }
            return Promise.resolve(this.languagePacks);
        }
        update(extensions) {
            return this.withLanguagePacks(languagePacks => {
                Object.keys(languagePacks).forEach(language => delete languagePacks[language]);
                this.createLanguagePacksFromExtensions(languagePacks, ...extensions);
            }).then(() => this.languagePacks);
        }
        createLanguagePacksFromExtensions(languagePacks, ...extensions) {
            for (const extension of extensions) {
                if (extension && extension.manifest && extension.manifest.contributes && extension.manifest.contributes.localizations && extension.manifest.contributes.localizations.length) {
                    this.createLanguagePacksFromExtension(languagePacks, extension);
                }
            }
            Object.keys(languagePacks).forEach(languageId => this.updateHash(languagePacks[languageId]));
        }
        createLanguagePacksFromExtension(languagePacks, extension) {
            const extensionIdentifier = extension.identifier;
            const localizations = extension.manifest.contributes && extension.manifest.contributes.localizations ? extension.manifest.contributes.localizations : [];
            for (const localizationContribution of localizations) {
                if (extension.location.scheme === network_1.Schemas.file && localizations_1.isValidLocalization(localizationContribution)) {
                    let languagePack = languagePacks[localizationContribution.languageId];
                    if (!languagePack) {
                        languagePack = { hash: '', extensions: [], translations: {} };
                        languagePacks[localizationContribution.languageId] = languagePack;
                    }
                    let extensionInLanguagePack = languagePack.extensions.filter(e => extensionManagementUtil_1.areSameExtensions(e.extensionIdentifier, extensionIdentifier))[0];
                    if (extensionInLanguagePack) {
                        extensionInLanguagePack.version = extension.manifest.version;
                    }
                    else {
                        languagePack.extensions.push({ extensionIdentifier, version: extension.manifest.version });
                    }
                    for (const translation of localizationContribution.translations) {
                        languagePack.translations[translation.id] = path_1.join(extension.location.fsPath, translation.path);
                    }
                }
            }
        }
        updateHash(languagePack) {
            if (languagePack) {
                const md5 = crypto_1.createHash('md5');
                for (const extension of languagePack.extensions) {
                    md5.update(extension.extensionIdentifier.uuid || extension.extensionIdentifier.id).update(extension.version);
                }
                languagePack.hash = md5.digest('hex');
            }
        }
        withLanguagePacks(fn = () => null) {
            return this.languagePacksFileLimiter.queue(() => {
                let result = null;
                return pfs.readFile(this.languagePacksFilePath, 'utf8')
                    .then(undefined, err => err.code === 'ENOENT' ? Promise.resolve('{}') : Promise.reject(err))
                    .then(raw => {
                    try {
                        let l = JSON.parse(raw);
                        // this.logService.info('#####raw:', raw);
                        // this.logService.info('#####languagePacksFilePath:', this.languagePacksFilePath);
                        if (!l['zh-cn']) {
                            l['zh-cn'] = {
                                'hash': '6ba9112a84248a812cb3f1c6129b041b',
                                'extensions': [
                                    {
                                        'extensionIdentifier': {
                                            'id': 'ms-ceintl.vscode-language-pack-zh-hans',
                                            'uuid': null
                                        },
                                        'version': '1.35.0'
                                    }
                                ],
                                'translations': {
                                    'vscode': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/main.i18n.json',
                                    'vscode.bat': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/bat.i18n.json',
                                    'vscode.clojure': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/clojure.i18n.json',
                                    'vscode.coffeescript': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/coffeescript.i18n.json',
                                    'vscode.configuration-editing': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/configuration-editing.i18n.json',
                                    'vscode.cpp': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/cpp.i18n.json',
                                    'vscode.csharp': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/csharp.i18n.json',
                                    'vscode.css-language-features': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/css-language-features.i18n.json',
                                    'vscode.css': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/css.i18n.json',
                                    'vscode.debug-auto-launch': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/debug-auto-launch.i18n.json',
                                    'vscode.debug-server-ready': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/debug-server-ready.i18n.json',
                                    'vscode.docker': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/docker.i18n.json',
                                    'vscode.emmet': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/emmet.i18n.json',
                                    'vscode.extension-editing': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/extension-editing.i18n.json',
                                    'vscode.fsharp': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/fsharp.i18n.json',
                                    'vscode.git': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/git.i18n.json',
                                    'vscode.go': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/go.i18n.json',
                                    'vscode.groovy': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/groovy.i18n.json',
                                    'vscode.grunt': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/grunt.i18n.json',
                                    'vscode.gulp': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/gulp.i18n.json',
                                    'vscode.handlebars': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/handlebars.i18n.json',
                                    'vscode.hlsl': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/hlsl.i18n.json',
                                    'vscode.html-language-features': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/html-language-features.i18n.json',
                                    'vscode.html': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/html.i18n.json',
                                    'vscode.ini': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/ini.i18n.json',
                                    'vscode.jake': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/jake.i18n.json',
                                    'vscode.java': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/java.i18n.json',
                                    'vscode.javascript': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/javascript.i18n.json',
                                    'vscode.json-language-features': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/json-language-features.i18n.json',
                                    'vscode.json': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/json.i18n.json',
                                    'vscode.less': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/less.i18n.json',
                                    'vscode.log': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/log.i18n.json',
                                    'vscode.lua': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/lua.i18n.json',
                                    'vscode.make': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/make.i18n.json',
                                    'vscode.markdown-basics': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/markdown-basics.i18n.json',
                                    'vscode.markdown-language-features': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/markdown-language-features.i18n.json',
                                    'vscode.merge-conflict': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/merge-conflict.i18n.json',
                                    'vscode.npm': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/npm.i18n.json',
                                    'vscode.objective-c': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/objective-c.i18n.json',
                                    'vscode.perl': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/perl.i18n.json',
                                    'vscode.php-language-features': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/php-language-features.i18n.json',
                                    'vscode.php': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/php.i18n.json',
                                    'vscode.powershell': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/powershell.i18n.json',
                                    'vscode.pug': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/pug.i18n.json',
                                    'vscode.python': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/python.i18n.json',
                                    'vscode.r': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/r.i18n.json',
                                    'vscode.razor': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/razor.i18n.json',
                                    'vscode.ruby': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/ruby.i18n.json',
                                    'vscode.rust': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/rust.i18n.json',
                                    'vscode.scss': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/scss.i18n.json',
                                    'vscode.shaderlab': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/shaderlab.i18n.json',
                                    'vscode.shellscript': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/shellscript.i18n.json',
                                    'vscode.sql': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/sql.i18n.json',
                                    'vscode.swift': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/swift.i18n.json',
                                    'vscode.theme-abyss': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/theme-abyss.i18n.json',
                                    'vscode.theme-defaults': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/theme-defaults.i18n.json',
                                    'vscode.theme-kimbie-dark': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/theme-kimbie-dark.i18n.json',
                                    'vscode.theme-monokai-dimmed': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/theme-monokai-dimmed.i18n.json',
                                    'vscode.theme-monokai': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/theme-monokai.i18n.json',
                                    'vscode.theme-quietlight': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/theme-quietlight.i18n.json',
                                    'vscode.theme-red': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/theme-red.i18n.json',
                                    'vscode.theme-seti': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/theme-seti.i18n.json',
                                    'vscode.theme-solarized-dark': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/theme-solarized-dark.i18n.json',
                                    'vscode.theme-solarized-light': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/theme-solarized-light.i18n.json',
                                    'vscode.theme-tomorrow-night-blue': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/theme-tomorrow-night-blue.i18n.json',
                                    'vscode.typescript-basics': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/typescript-basics.i18n.json',
                                    'vscode.typescript-language-features': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/typescript-language-features.i18n.json',
                                    'vscode.vb': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/vb.i18n.json',
                                    'vscode.vscode-chrome-debug-core': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/vscode-chrome-debug-core.i18n.json',
                                    'ms-vscode.node-debug': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/vscode-node-debug.i18n.json',
                                    'ms-vscode.node-debug2': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/vscode-node-debug2.i18n.json',
                                    'vscode.xml': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/xml.i18n.json',
                                    'vscode.yaml': this.environmentService.builtinExtensionsPath + '/vscode-language-pack-zh-hans/translations/extensions/yaml.i18n.json'
                                }
                            };
                        }
                        return l;
                    }
                    catch (e) {
                        return {};
                    }
                })
                    .then(languagePacks => { result = fn(languagePacks); return languagePacks; })
                    .then(languagePacks => {
                    for (const language of Object.keys(languagePacks)) {
                        if (!languagePacks[language]) {
                            delete languagePacks[language];
                        }
                    }
                    this.languagePacks = languagePacks;
                    this.initializedCache = true;
                    const raw = JSON.stringify(this.languagePacks);
                    this.logService.debug('Writing language packs', raw);
                    return pfs.writeFile(this.languagePacksFilePath, raw);
                })
                    .then(() => result, error => this.logService.error(error));
            });
        }
    };
    LanguagePacksCache = __decorate([
        __param(0, environment_1.IEnvironmentService),
        __param(1, log_1.ILogService)
    ], LanguagePacksCache);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[15/*vs/platform/registry/common/platform*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/types*/,81/*vs/base/common/assert*/]), function (require, exports, Types, Assert) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    class RegistryImpl {
        constructor() {
            this.data = {};
        }
        add(id, data) {
            Assert.ok(Types.isString(id));
            Assert.ok(Types.isObject(data));
            Assert.ok(!this.data.hasOwnProperty(id), 'There is already an extension with this id');
            this.data[id] = data;
        }
        knows(id) {
            return this.data.hasOwnProperty(id);
        }
        as(id) {
            return this.data[id] || null;
        }
    }
    exports.Registry = new RegistryImpl();
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[67/*vs/platform/jsonschemas/common/jsonContributionRegistry*/], __M([1/*require*/,0/*exports*/,15/*vs/platform/registry/common/platform*/,6/*vs/base/common/event*/]), function (require, exports, platform, event_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Extensions = {
        JSONContribution: 'base.contributions.json'
    };
    function normalizeId(id) {
        if (id.length > 0 && id.charAt(id.length - 1) === '#') {
            return id.substring(0, id.length - 1);
        }
        return id;
    }
    class JSONContributionRegistry {
        constructor() {
            this._onDidChangeSchema = new event_1.Emitter();
            this.onDidChangeSchema = this._onDidChangeSchema.event;
            this.schemasById = {};
        }
        registerSchema(uri, unresolvedSchemaContent) {
            this.schemasById[normalizeId(uri)] = unresolvedSchemaContent;
            this._onDidChangeSchema.fire(uri);
        }
        notifySchemaChanged(uri) {
            this._onDidChangeSchema.fire(uri);
        }
        getSchemaContributions() {
            return {
                schemas: this.schemasById,
            };
        }
    }
    const jsonContributionRegistry = new JSONContributionRegistry();
    platform.Registry.add(exports.Extensions.JSONContribution, jsonContributionRegistry);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[19/*vs/platform/configuration/common/configurationRegistry*/], __M([1/*require*/,0/*exports*/,58/*vs/nls!vs/platform/configuration/common/configurationRegistry*/,6/*vs/base/common/event*/,15/*vs/platform/registry/common/platform*/,4/*vs/base/common/types*/,16/*vs/base/common/strings*/,67/*vs/platform/jsonschemas/common/jsonContributionRegistry*/]), function (require, exports, nls, event_1, platform_1, types, strings, jsonContributionRegistry_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Extensions = {
        Configuration: 'base.contributions.configuration'
    };
    var ConfigurationScope;
    (function (ConfigurationScope) {
        ConfigurationScope[ConfigurationScope["APPLICATION"] = 1] = "APPLICATION";
        ConfigurationScope[ConfigurationScope["WINDOW"] = 2] = "WINDOW";
        ConfigurationScope[ConfigurationScope["RESOURCE"] = 3] = "RESOURCE";
    })(ConfigurationScope = exports.ConfigurationScope || (exports.ConfigurationScope = {}));
    exports.allSettings = { properties: {}, patternProperties: {} };
    exports.applicationSettings = { properties: {}, patternProperties: {} };
    exports.windowSettings = { properties: {}, patternProperties: {} };
    exports.resourceSettings = { properties: {}, patternProperties: {} };
    exports.editorConfigurationSchemaId = 'vscode://schemas/settings/editor';
    const contributionRegistry = platform_1.Registry.as(jsonContributionRegistry_1.Extensions.JSONContribution);
    class ConfigurationRegistry {
        constructor() {
            this.overrideIdentifiers = [];
            this._onDidSchemaChange = new event_1.Emitter();
            this.onDidSchemaChange = this._onDidSchemaChange.event;
            this._onDidUpdateConfiguration = new event_1.Emitter();
            this.onDidUpdateConfiguration = this._onDidUpdateConfiguration.event;
            this.defaultOverridesConfigurationNode = {
                id: 'defaultOverrides',
                title: nls.localize(0, null),
                properties: {}
            };
            this.configurationContributors = [this.defaultOverridesConfigurationNode];
            this.editorConfigurationSchema = { properties: {}, patternProperties: {}, additionalProperties: false, errorMessage: 'Unknown editor configuration setting' };
            this.configurationProperties = {};
            this.excludedConfigurationProperties = {};
            this.computeOverridePropertyPattern();
            contributionRegistry.registerSchema(exports.editorConfigurationSchemaId, this.editorConfigurationSchema);
        }
        registerConfiguration(configuration, validate = true) {
            this.registerConfigurations([configuration], validate);
        }
        registerConfigurations(configurations, validate = true) {
            const properties = [];
            configurations.forEach(configuration => {
                properties.push(...this.validateAndRegisterProperties(configuration, validate)); // fills in defaults
                this.configurationContributors.push(configuration);
                this.registerJSONConfiguration(configuration);
                this.updateSchemaForOverrideSettingsConfiguration(configuration);
            });
            this._onDidSchemaChange.fire();
            this._onDidUpdateConfiguration.fire(properties);
        }
        deregisterConfigurations(configurations) {
            const properties = [];
            const deregisterConfiguration = (configuration) => {
                if (configuration.properties) {
                    for (const key in configuration.properties) {
                        properties.push(key);
                        delete this.configurationProperties[key];
                        delete this.editorConfigurationSchema.properties[key];
                        // Delete from schema
                        delete exports.allSettings.properties[key];
                        switch (configuration.properties[key].scope) {
                            case 1 /* APPLICATION */:
                                delete exports.applicationSettings.properties[key];
                                break;
                            case 2 /* WINDOW */:
                                delete exports.windowSettings.properties[key];
                                break;
                            case 3 /* RESOURCE */:
                                delete exports.resourceSettings.properties[key];
                                break;
                        }
                    }
                }
                if (configuration.allOf) {
                    configuration.allOf.forEach(node => deregisterConfiguration(node));
                }
            };
            for (const configuration of configurations) {
                deregisterConfiguration(configuration);
                const index = this.configurationContributors.indexOf(configuration);
                if (index !== -1) {
                    this.configurationContributors.splice(index, 1);
                }
            }
            contributionRegistry.registerSchema(exports.editorConfigurationSchemaId, this.editorConfigurationSchema);
            this._onDidSchemaChange.fire();
            this._onDidUpdateConfiguration.fire(properties);
        }
        registerDefaultConfigurations(defaultConfigurations) {
            const properties = [];
            for (const defaultConfiguration of defaultConfigurations) {
                for (const key in defaultConfiguration.defaults) {
                    const defaultValue = defaultConfiguration.defaults[key];
                    if (exports.OVERRIDE_PROPERTY_PATTERN.test(key) && typeof defaultValue === 'object') {
                        const propertySchema = {
                            type: 'object',
                            default: defaultValue,
                            description: nls.localize(1, null, key),
                            $ref: exports.editorConfigurationSchemaId
                        };
                        exports.allSettings.properties[key] = propertySchema;
                        this.defaultOverridesConfigurationNode.properties[key] = propertySchema;
                        this.configurationProperties[key] = propertySchema;
                        properties.push(key);
                    }
                }
            }
            this._onDidSchemaChange.fire();
            this._onDidUpdateConfiguration.fire(properties);
        }
        deregisterDefaultConfigurations(defaultConfigurations) {
            const properties = [];
            for (const defaultConfiguration of defaultConfigurations) {
                for (const key in defaultConfiguration.defaults) {
                    properties.push(key);
                    delete exports.allSettings.properties[key];
                    delete this.defaultOverridesConfigurationNode.properties[key];
                    delete this.configurationProperties[key];
                }
            }
            this._onDidSchemaChange.fire();
            this._onDidUpdateConfiguration.fire(properties);
        }
        notifyConfigurationSchemaUpdated(...configurations) {
            this._onDidSchemaChange.fire();
        }
        registerOverrideIdentifiers(overrideIdentifiers) {
            this.overrideIdentifiers.push(...overrideIdentifiers);
            this.updateOverridePropertyPatternKey();
        }
        validateAndRegisterProperties(configuration, validate = true, scope = 2 /* WINDOW */, overridable = false) {
            scope = types.isUndefinedOrNull(configuration.scope) ? scope : configuration.scope;
            overridable = configuration.overridable || overridable;
            let propertyKeys = [];
            let properties = configuration.properties;
            if (properties) {
                for (let key in properties) {
                    let message;
                    if (validate && (message = validateProperty(key))) {
                        console.warn(message);
                        delete properties[key];
                        continue;
                    }
                    // fill in default values
                    let property = properties[key];
                    let defaultValue = property.default;
                    if (types.isUndefined(defaultValue)) {
                        property.default = getDefaultValue(property.type);
                    }
                    // Inherit overridable property from parent
                    if (overridable) {
                        property.overridable = true;
                    }
                    if (exports.OVERRIDE_PROPERTY_PATTERN.test(key)) {
                        property.scope = undefined; // No scope for overridable properties `[${identifier}]`
                    }
                    else {
                        property.scope = types.isUndefinedOrNull(property.scope) ? scope : property.scope;
                    }
                    // Add to properties maps
                    // Property is included by default if 'included' is unspecified
                    if (properties[key].hasOwnProperty('included') && !properties[key].included) {
                        this.excludedConfigurationProperties[key] = properties[key];
                        delete properties[key];
                        continue;
                    }
                    else {
                        this.configurationProperties[key] = properties[key];
                    }
                    propertyKeys.push(key);
                }
            }
            let subNodes = configuration.allOf;
            if (subNodes) {
                for (let node of subNodes) {
                    propertyKeys.push(...this.validateAndRegisterProperties(node, validate, scope, overridable));
                }
            }
            return propertyKeys;
        }
        getConfigurations() {
            return this.configurationContributors;
        }
        getConfigurationProperties() {
            return this.configurationProperties;
        }
        getExcludedConfigurationProperties() {
            return this.excludedConfigurationProperties;
        }
        registerJSONConfiguration(configuration) {
            function register(configuration) {
                let properties = configuration.properties;
                if (properties) {
                    for (const key in properties) {
                        exports.allSettings.properties[key] = properties[key];
                        switch (properties[key].scope) {
                            case 1 /* APPLICATION */:
                                exports.applicationSettings.properties[key] = properties[key];
                                break;
                            case 2 /* WINDOW */:
                                exports.windowSettings.properties[key] = properties[key];
                                break;
                            case 3 /* RESOURCE */:
                                exports.resourceSettings.properties[key] = properties[key];
                                break;
                        }
                    }
                }
                let subNodes = configuration.allOf;
                if (subNodes) {
                    subNodes.forEach(register);
                }
            }
            register(configuration);
        }
        updateSchemaForOverrideSettingsConfiguration(configuration) {
            if (configuration.id !== SETTINGS_OVERRRIDE_NODE_ID) {
                this.update(configuration);
                contributionRegistry.registerSchema(exports.editorConfigurationSchemaId, this.editorConfigurationSchema);
            }
        }
        updateOverridePropertyPatternKey() {
            let patternProperties = exports.allSettings.patternProperties[this.overridePropertyPattern];
            if (!patternProperties) {
                patternProperties = {
                    type: 'object',
                    description: nls.localize(2, null),
                    errorMessage: 'Unknown Identifier. Use language identifiers',
                    $ref: exports.editorConfigurationSchemaId
                };
            }
            delete exports.allSettings.patternProperties[this.overridePropertyPattern];
            delete exports.applicationSettings.patternProperties[this.overridePropertyPattern];
            delete exports.windowSettings.patternProperties[this.overridePropertyPattern];
            delete exports.resourceSettings.patternProperties[this.overridePropertyPattern];
            this.computeOverridePropertyPattern();
            exports.allSettings.patternProperties[this.overridePropertyPattern] = patternProperties;
            exports.applicationSettings.patternProperties[this.overridePropertyPattern] = patternProperties;
            exports.windowSettings.patternProperties[this.overridePropertyPattern] = patternProperties;
            exports.resourceSettings.patternProperties[this.overridePropertyPattern] = patternProperties;
            this._onDidSchemaChange.fire();
        }
        update(configuration) {
            let properties = configuration.properties;
            if (properties) {
                for (let key in properties) {
                    if (properties[key].overridable) {
                        this.editorConfigurationSchema.properties[key] = this.getConfigurationProperties()[key];
                    }
                }
            }
            let subNodes = configuration.allOf;
            if (subNodes) {
                subNodes.forEach(subNode => this.update(subNode));
            }
        }
        computeOverridePropertyPattern() {
            this.overridePropertyPattern = this.overrideIdentifiers.length ? OVERRIDE_PATTERN_WITH_SUBSTITUTION.replace('${0}', this.overrideIdentifiers.map(identifier => strings.createRegExp(identifier, false).source).join('|')) : OVERRIDE_PROPERTY;
        }
    }
    const SETTINGS_OVERRRIDE_NODE_ID = 'override';
    const OVERRIDE_PROPERTY = '\\[.*\\]$';
    const OVERRIDE_PATTERN_WITH_SUBSTITUTION = '\\[(${0})\\]$';
    exports.OVERRIDE_PROPERTY_PATTERN = new RegExp(OVERRIDE_PROPERTY);
    function getDefaultValue(type) {
        const t = Array.isArray(type) ? type[0] : type;
        switch (t) {
            case 'boolean':
                return false;
            case 'integer':
            case 'number':
                return 0;
            case 'string':
                return '';
            case 'array':
                return [];
            case 'object':
                return {};
            default:
                return null;
        }
    }
    exports.getDefaultValue = getDefaultValue;
    const configurationRegistry = new ConfigurationRegistry();
    platform_1.Registry.add(exports.Extensions.Configuration, configurationRegistry);
    function validateProperty(property) {
        if (exports.OVERRIDE_PROPERTY_PATTERN.test(property)) {
            return nls.localize(3, null, property);
        }
        if (configurationRegistry.getConfigurationProperties()[property] !== undefined) {
            return nls.localize(4, null, property);
        }
        return null;
    }
    exports.validateProperty = validateProperty;
    function getScopes() {
        const scopes = {};
        const configurationProperties = configurationRegistry.getConfigurationProperties();
        for (const key of Object.keys(configurationProperties)) {
            scopes[key] = configurationProperties[key].scope;
        }
        scopes['launch'] = 3 /* RESOURCE */;
        scopes['task'] = 3 /* RESOURCE */;
        return scopes;
    }
    exports.getScopes = getScopes;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[12/*vs/platform/configuration/common/configuration*/], __M([1/*require*/,0/*exports*/,7/*vs/base/common/objects*/,4/*vs/base/common/types*/,20/*vs/base/common/uri*/,15/*vs/platform/registry/common/platform*/,2/*vs/platform/instantiation/common/instantiation*/,19/*vs/platform/configuration/common/configurationRegistry*/]), function (require, exports, objects, types, uri_1, platform_1, instantiation_1, configurationRegistry_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IConfigurationService = instantiation_1.createDecorator('configurationService');
    function isConfigurationOverrides(thing) {
        return thing
            && typeof thing === 'object'
            && (!thing.overrideIdentifier || typeof thing.overrideIdentifier === 'string')
            && (!thing.resource || thing.resource instanceof uri_1.URI);
    }
    exports.isConfigurationOverrides = isConfigurationOverrides;
    var ConfigurationTarget;
    (function (ConfigurationTarget) {
        ConfigurationTarget[ConfigurationTarget["USER"] = 1] = "USER";
        ConfigurationTarget[ConfigurationTarget["WORKSPACE"] = 2] = "WORKSPACE";
        ConfigurationTarget[ConfigurationTarget["WORKSPACE_FOLDER"] = 3] = "WORKSPACE_FOLDER";
        ConfigurationTarget[ConfigurationTarget["DEFAULT"] = 4] = "DEFAULT";
        ConfigurationTarget[ConfigurationTarget["MEMORY"] = 5] = "MEMORY";
    })(ConfigurationTarget = exports.ConfigurationTarget || (exports.ConfigurationTarget = {}));
    function ConfigurationTargetToString(configurationTarget) {
        switch (configurationTarget) {
            case 1 /* USER */: return 'USER';
            case 2 /* WORKSPACE */: return 'WORKSPACE';
            case 3 /* WORKSPACE_FOLDER */: return 'WORKSPACE_FOLDER';
            case 4 /* DEFAULT */: return 'DEFAULT';
            case 5 /* MEMORY */: return 'MEMORY';
        }
    }
    exports.ConfigurationTargetToString = ConfigurationTargetToString;
    function compare(from, to) {
        const added = to.keys.filter(key => from.keys.indexOf(key) === -1);
        const removed = from.keys.filter(key => to.keys.indexOf(key) === -1);
        const updated = [];
        for (const key of from.keys) {
            const value1 = getConfigurationValue(from.contents, key);
            const value2 = getConfigurationValue(to.contents, key);
            if (!objects.equals(value1, value2)) {
                updated.push(key);
            }
        }
        return { added, removed, updated };
    }
    exports.compare = compare;
    function toOverrides(raw, conflictReporter) {
        const overrides = [];
        const configurationProperties = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).getConfigurationProperties();
        for (const key of Object.keys(raw)) {
            if (configurationRegistry_1.OVERRIDE_PROPERTY_PATTERN.test(key)) {
                const overrideRaw = {};
                for (const keyInOverrideRaw in raw[key]) {
                    if (configurationProperties[keyInOverrideRaw] && configurationProperties[keyInOverrideRaw].overridable) {
                        overrideRaw[keyInOverrideRaw] = raw[key][keyInOverrideRaw];
                    }
                }
                overrides.push({
                    identifiers: [overrideIdentifierFromKey(key).trim()],
                    contents: toValuesTree(overrideRaw, conflictReporter)
                });
            }
        }
        return overrides;
    }
    exports.toOverrides = toOverrides;
    function toValuesTree(properties, conflictReporter) {
        const root = Object.create(null);
        for (let key in properties) {
            addToValueTree(root, key, properties[key], conflictReporter);
        }
        return root;
    }
    exports.toValuesTree = toValuesTree;
    function addToValueTree(settingsTreeRoot, key, value, conflictReporter) {
        const segments = key.split('.');
        const last = segments.pop();
        let curr = settingsTreeRoot;
        for (let i = 0; i < segments.length; i++) {
            let s = segments[i];
            let obj = curr[s];
            switch (typeof obj) {
                case 'undefined':
                    obj = curr[s] = Object.create(null);
                    break;
                case 'object':
                    break;
                default:
                    conflictReporter(`Ignoring ${key} as ${segments.slice(0, i + 1).join('.')} is ${JSON.stringify(obj)}`);
                    return;
            }
            curr = obj;
        }
        if (typeof curr === 'object') {
            curr[last] = value; // workaround https://github.com/Microsoft/vscode/issues/13606
        }
        else {
            conflictReporter(`Ignoring ${key} as ${segments.join('.')} is ${JSON.stringify(curr)}`);
        }
    }
    exports.addToValueTree = addToValueTree;
    function removeFromValueTree(valueTree, key) {
        const segments = key.split('.');
        doRemoveFromValueTree(valueTree, segments);
    }
    exports.removeFromValueTree = removeFromValueTree;
    function doRemoveFromValueTree(valueTree, segments) {
        const first = segments.shift();
        if (segments.length === 0) {
            // Reached last segment
            delete valueTree[first];
            return;
        }
        if (Object.keys(valueTree).indexOf(first) !== -1) {
            const value = valueTree[first];
            if (typeof value === 'object' && !Array.isArray(value)) {
                doRemoveFromValueTree(value, segments);
                if (Object.keys(value).length === 0) {
                    delete valueTree[first];
                }
            }
        }
    }
    /**
     * A helper function to get the configuration value with a specific settings path (e.g. config.some.setting)
     */
    function getConfigurationValue(config, settingPath, defaultValue) {
        function accessSetting(config, path) {
            let current = config;
            for (const component of path) {
                if (typeof current !== 'object' || current === null) {
                    return undefined;
                }
                current = current[component];
            }
            return current;
        }
        const path = settingPath.split('.');
        const result = accessSetting(config, path);
        return typeof result === 'undefined' ? defaultValue : result;
    }
    exports.getConfigurationValue = getConfigurationValue;
    function merge(base, add, overwrite) {
        Object.keys(add).forEach(key => {
            if (key in base) {
                if (types.isObject(base[key]) && types.isObject(add[key])) {
                    merge(base[key], add[key], overwrite);
                }
                else if (overwrite) {
                    base[key] = add[key];
                }
            }
            else {
                base[key] = add[key];
            }
        });
    }
    exports.merge = merge;
    function getConfigurationKeys() {
        const properties = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).getConfigurationProperties();
        return Object.keys(properties);
    }
    exports.getConfigurationKeys = getConfigurationKeys;
    function getDefaultValues() {
        const valueTreeRoot = Object.create(null);
        const properties = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).getConfigurationProperties();
        for (let key in properties) {
            let value = properties[key].default;
            addToValueTree(valueTreeRoot, key, value, message => console.error(`Conflict in default settings: ${message}`));
        }
        return valueTreeRoot;
    }
    exports.getDefaultValues = getDefaultValues;
    function overrideIdentifierFromKey(key) {
        return key.substring(1, key.length - 1);
    }
    exports.overrideIdentifierFromKey = overrideIdentifierFromKey;
    function keyFromOverrideIdentifier(overrideIdentifier) {
        return `[${overrideIdentifier}]`;
    }
    exports.keyFromOverrideIdentifier = keyFromOverrideIdentifier;
    function getMigratedSettingValue(configurationService, currentSettingName, legacySettingName) {
        const setting = configurationService.inspect(currentSettingName);
        const legacySetting = configurationService.inspect(legacySettingName);
        if (typeof setting.user !== 'undefined' || typeof setting.workspace !== 'undefined' || typeof setting.workspaceFolder !== 'undefined') {
            return setting.value;
        }
        else if (typeof legacySetting.user !== 'undefined' || typeof legacySetting.workspace !== 'undefined' || typeof legacySetting.workspaceFolder !== 'undefined') {
            return legacySetting.value;
        }
        else {
            return setting.default;
        }
    }
    exports.getMigratedSettingValue = getMigratedSettingValue;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[39/*vs/platform/configuration/common/configurationModels*/], __M([1/*require*/,0/*exports*/,33/*vs/base/common/json*/,71/*vs/base/common/map*/,17/*vs/base/common/arrays*/,4/*vs/base/common/types*/,7/*vs/base/common/objects*/,19/*vs/platform/configuration/common/configurationRegistry*/,12/*vs/platform/configuration/common/configuration*/]), function (require, exports, json, map_1, arrays, types, objects, configurationRegistry_1, configuration_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    class ConfigurationModel {
        constructor(_contents = {}, _keys = [], _overrides = []) {
            this._contents = _contents;
            this._keys = _keys;
            this._overrides = _overrides;
            this.isFrozen = false;
        }
        get contents() {
            return this.checkAndFreeze(this._contents);
        }
        get overrides() {
            return this.checkAndFreeze(this._overrides);
        }
        get keys() {
            return this.checkAndFreeze(this._keys);
        }
        getValue(section) {
            return section ? configuration_1.getConfigurationValue(this.contents, section) : this.contents;
        }
        override(identifier) {
            const overrideContents = this.getContentsForOverrideIdentifer(identifier);
            if (!overrideContents || typeof overrideContents !== 'object' || !Object.keys(overrideContents).length) {
                // If there are no valid overrides, return self
                return this;
            }
            let contents = {};
            for (const key of arrays.distinct([...Object.keys(this.contents), ...Object.keys(overrideContents)])) {
                let contentsForKey = this.contents[key];
                let overrideContentsForKey = overrideContents[key];
                // If there are override contents for the key, clone and merge otherwise use base contents
                if (overrideContentsForKey) {
                    // Clone and merge only if base contents and override contents are of type object otherwise just override
                    if (typeof contentsForKey === 'object' && typeof overrideContentsForKey === 'object') {
                        contentsForKey = objects.deepClone(contentsForKey);
                        this.mergeContents(contentsForKey, overrideContentsForKey);
                    }
                    else {
                        contentsForKey = overrideContentsForKey;
                    }
                }
                contents[key] = contentsForKey;
            }
            return new ConfigurationModel(contents);
        }
        merge(...others) {
            const contents = objects.deepClone(this.contents);
            const overrides = objects.deepClone(this.overrides);
            const keys = [...this.keys];
            for (const other of others) {
                this.mergeContents(contents, other.contents);
                for (const otherOverride of other.overrides) {
                    const [override] = overrides.filter(o => arrays.equals(o.identifiers, otherOverride.identifiers));
                    if (override) {
                        this.mergeContents(override.contents, otherOverride.contents);
                    }
                    else {
                        overrides.push(objects.deepClone(otherOverride));
                    }
                }
                for (const key of other.keys) {
                    if (keys.indexOf(key) === -1) {
                        keys.push(key);
                    }
                }
            }
            return new ConfigurationModel(contents, keys, overrides);
        }
        freeze() {
            this.isFrozen = true;
            return this;
        }
        mergeContents(source, target) {
            for (const key of Object.keys(target)) {
                if (key in source) {
                    if (types.isObject(source[key]) && types.isObject(target[key])) {
                        this.mergeContents(source[key], target[key]);
                        continue;
                    }
                }
                source[key] = objects.deepClone(target[key]);
            }
        }
        checkAndFreeze(data) {
            if (this.isFrozen && !Object.isFrozen(data)) {
                return objects.deepFreeze(data);
            }
            return data;
        }
        getContentsForOverrideIdentifer(identifier) {
            for (const override of this.overrides) {
                if (override.identifiers.indexOf(identifier) !== -1) {
                    return override.contents;
                }
            }
            return null;
        }
        toJSON() {
            return {
                contents: this.contents,
                overrides: this.overrides,
                keys: this.keys
            };
        }
        // Update methods
        setValue(key, value) {
            this.addKey(key);
            configuration_1.addToValueTree(this.contents, key, value, e => { throw new Error(e); });
        }
        removeValue(key) {
            if (this.removeKey(key)) {
                configuration_1.removeFromValueTree(this.contents, key);
            }
        }
        addKey(key) {
            let index = this.keys.length;
            for (let i = 0; i < index; i++) {
                if (key.indexOf(this.keys[i]) === 0) {
                    index = i;
                }
            }
            this.keys.splice(index, 1, key);
        }
        removeKey(key) {
            let index = this.keys.indexOf(key);
            if (index !== -1) {
                this.keys.splice(index, 1);
                return true;
            }
            return false;
        }
    }
    exports.ConfigurationModel = ConfigurationModel;
    class DefaultConfigurationModel extends ConfigurationModel {
        constructor() {
            const contents = configuration_1.getDefaultValues();
            const keys = configuration_1.getConfigurationKeys();
            const overrides = [];
            for (const key of Object.keys(contents)) {
                if (configurationRegistry_1.OVERRIDE_PROPERTY_PATTERN.test(key)) {
                    overrides.push({
                        identifiers: [configuration_1.overrideIdentifierFromKey(key).trim()],
                        contents: configuration_1.toValuesTree(contents[key], message => console.error(`Conflict in default settings file: ${message}`))
                    });
                }
            }
            super(contents, keys, overrides);
        }
    }
    exports.DefaultConfigurationModel = DefaultConfigurationModel;
    class ConfigurationModelParser {
        constructor(_name) {
            this._name = _name;
            this._configurationModel = null;
            this._parseErrors = [];
        }
        get configurationModel() {
            return this._configurationModel || new ConfigurationModel();
        }
        get errors() {
            return this._parseErrors;
        }
        parse(content) {
            if (content) {
                const raw = this.parseContent(content);
                const configurationModel = this.parseRaw(raw);
                this._configurationModel = new ConfigurationModel(configurationModel.contents, configurationModel.keys, configurationModel.overrides);
            }
        }
        parseContent(content) {
            let raw = {};
            let currentProperty = null;
            let currentParent = [];
            let previousParents = [];
            let parseErrors = [];
            function onValue(value) {
                if (Array.isArray(currentParent)) {
                    currentParent.push(value);
                }
                else if (currentProperty) {
                    currentParent[currentProperty] = value;
                }
            }
            let visitor = {
                onObjectBegin: () => {
                    let object = {};
                    onValue(object);
                    previousParents.push(currentParent);
                    currentParent = object;
                    currentProperty = null;
                },
                onObjectProperty: (name) => {
                    currentProperty = name;
                },
                onObjectEnd: () => {
                    currentParent = previousParents.pop();
                },
                onArrayBegin: () => {
                    let array = [];
                    onValue(array);
                    previousParents.push(currentParent);
                    currentParent = array;
                    currentProperty = null;
                },
                onArrayEnd: () => {
                    currentParent = previousParents.pop();
                },
                onLiteralValue: onValue,
                onError: (error, offset, length) => {
                    parseErrors.push({ error, offset, length });
                }
            };
            if (content) {
                try {
                    json.visit(content, visitor);
                    raw = currentParent[0] || {};
                }
                catch (e) {
                    console.error(`Error while parsing settings file ${this._name}: ${e}`);
                    this._parseErrors = [e];
                }
            }
            return raw;
        }
        parseRaw(raw) {
            const contents = configuration_1.toValuesTree(raw, message => console.error(`Conflict in settings file ${this._name}: ${message}`));
            const keys = Object.keys(raw);
            const overrides = configuration_1.toOverrides(raw, message => console.error(`Conflict in settings file ${this._name}: ${message}`));
            return { contents, keys, overrides };
        }
    }
    exports.ConfigurationModelParser = ConfigurationModelParser;
    class Configuration {
        constructor(_defaultConfiguration, _userConfiguration, _workspaceConfiguration = new ConfigurationModel(), _folderConfigurations = new map_1.ResourceMap(), _memoryConfiguration = new ConfigurationModel(), _memoryConfigurationByResource = new map_1.ResourceMap(), _freeze = true) {
            this._defaultConfiguration = _defaultConfiguration;
            this._userConfiguration = _userConfiguration;
            this._workspaceConfiguration = _workspaceConfiguration;
            this._folderConfigurations = _folderConfigurations;
            this._memoryConfiguration = _memoryConfiguration;
            this._memoryConfigurationByResource = _memoryConfigurationByResource;
            this._freeze = _freeze;
            this._workspaceConsolidatedConfiguration = null;
            this._foldersConsolidatedConfigurations = new map_1.ResourceMap();
        }
        getValue(section, overrides, workspace) {
            const consolidateConfigurationModel = this.getConsolidateConfigurationModel(overrides, workspace);
            return consolidateConfigurationModel.getValue(section);
        }
        updateValue(key, value, overrides = {}) {
            let memoryConfiguration;
            if (overrides.resource) {
                memoryConfiguration = this._memoryConfigurationByResource.get(overrides.resource);
                if (!memoryConfiguration) {
                    memoryConfiguration = new ConfigurationModel();
                    this._memoryConfigurationByResource.set(overrides.resource, memoryConfiguration);
                }
            }
            else {
                memoryConfiguration = this._memoryConfiguration;
            }
            if (value === undefined) {
                memoryConfiguration.removeValue(key);
            }
            else {
                memoryConfiguration.setValue(key, value);
            }
            if (!overrides.resource) {
                this._workspaceConsolidatedConfiguration = null;
            }
        }
        inspect(key, overrides, workspace) {
            const consolidateConfigurationModel = this.getConsolidateConfigurationModel(overrides, workspace);
            const folderConfigurationModel = this.getFolderConfigurationModelForResource(overrides.resource, workspace);
            const memoryConfigurationModel = overrides.resource ? this._memoryConfigurationByResource.get(overrides.resource) || this._memoryConfiguration : this._memoryConfiguration;
            return {
                default: overrides.overrideIdentifier ? this._defaultConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this._defaultConfiguration.freeze().getValue(key),
                user: overrides.overrideIdentifier ? this._userConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this._userConfiguration.freeze().getValue(key),
                workspace: workspace ? overrides.overrideIdentifier ? this._workspaceConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this._workspaceConfiguration.freeze().getValue(key) : undefined,
                workspaceFolder: folderConfigurationModel ? overrides.overrideIdentifier ? folderConfigurationModel.freeze().override(overrides.overrideIdentifier).getValue(key) : folderConfigurationModel.freeze().getValue(key) : undefined,
                memory: overrides.overrideIdentifier ? memoryConfigurationModel.override(overrides.overrideIdentifier).getValue(key) : memoryConfigurationModel.getValue(key),
                value: consolidateConfigurationModel.getValue(key)
            };
        }
        keys(workspace) {
            const folderConfigurationModel = this.getFolderConfigurationModelForResource(undefined, workspace);
            return {
                default: this._defaultConfiguration.freeze().keys,
                user: this._userConfiguration.freeze().keys,
                workspace: this._workspaceConfiguration.freeze().keys,
                workspaceFolder: folderConfigurationModel ? folderConfigurationModel.freeze().keys : []
            };
        }
        updateDefaultConfiguration(defaultConfiguration) {
            this._defaultConfiguration = defaultConfiguration;
            this._workspaceConsolidatedConfiguration = null;
            this._foldersConsolidatedConfigurations.clear();
        }
        updateUserConfiguration(userConfiguration) {
            this._userConfiguration = userConfiguration;
            this._workspaceConsolidatedConfiguration = null;
            this._foldersConsolidatedConfigurations.clear();
        }
        updateWorkspaceConfiguration(workspaceConfiguration) {
            this._workspaceConfiguration = workspaceConfiguration;
            this._workspaceConsolidatedConfiguration = null;
            this._foldersConsolidatedConfigurations.clear();
        }
        updateFolderConfiguration(resource, configuration) {
            this._folderConfigurations.set(resource, configuration);
            this._foldersConsolidatedConfigurations.delete(resource);
        }
        deleteFolderConfiguration(resource) {
            this.folders.delete(resource);
            this._foldersConsolidatedConfigurations.delete(resource);
        }
        get defaults() {
            return this._defaultConfiguration;
        }
        get user() {
            return this._userConfiguration;
        }
        get workspace() {
            return this._workspaceConfiguration;
        }
        get folders() {
            return this._folderConfigurations;
        }
        getConsolidateConfigurationModel(overrides, workspace) {
            let configurationModel = this.getConsolidatedConfigurationModelForResource(overrides, workspace);
            return overrides.overrideIdentifier ? configurationModel.override(overrides.overrideIdentifier) : configurationModel;
        }
        getConsolidatedConfigurationModelForResource({ resource }, workspace) {
            let consolidateConfiguration = this.getWorkspaceConsolidatedConfiguration();
            if (workspace && resource) {
                const root = workspace.getFolder(resource);
                if (root) {
                    consolidateConfiguration = this.getFolderConsolidatedConfiguration(root.uri) || consolidateConfiguration;
                }
                const memoryConfigurationForResource = this._memoryConfigurationByResource.get(resource);
                if (memoryConfigurationForResource) {
                    consolidateConfiguration = consolidateConfiguration.merge(memoryConfigurationForResource);
                }
            }
            return consolidateConfiguration;
        }
        getWorkspaceConsolidatedConfiguration() {
            if (!this._workspaceConsolidatedConfiguration) {
                this._workspaceConsolidatedConfiguration = this._defaultConfiguration.merge(this._userConfiguration, this._workspaceConfiguration, this._memoryConfiguration);
                if (this._freeze) {
                    this._workspaceConfiguration = this._workspaceConfiguration.freeze();
                }
            }
            return this._workspaceConsolidatedConfiguration;
        }
        getFolderConsolidatedConfiguration(folder) {
            let folderConsolidatedConfiguration = this._foldersConsolidatedConfigurations.get(folder);
            if (!folderConsolidatedConfiguration) {
                const workspaceConsolidateConfiguration = this.getWorkspaceConsolidatedConfiguration();
                const folderConfiguration = this._folderConfigurations.get(folder);
                if (folderConfiguration) {
                    folderConsolidatedConfiguration = workspaceConsolidateConfiguration.merge(folderConfiguration);
                    if (this._freeze) {
                        folderConsolidatedConfiguration = folderConsolidatedConfiguration.freeze();
                    }
                    this._foldersConsolidatedConfigurations.set(folder, folderConsolidatedConfiguration);
                }
                else {
                    folderConsolidatedConfiguration = workspaceConsolidateConfiguration;
                }
            }
            return folderConsolidatedConfiguration;
        }
        getFolderConfigurationModelForResource(resource, workspace) {
            if (workspace && resource) {
                const root = workspace.getFolder(resource);
                if (root) {
                    return this._folderConfigurations.get(root.uri) || null;
                }
            }
            return null;
        }
        toData() {
            return {
                defaults: {
                    contents: this._defaultConfiguration.contents,
                    overrides: this._defaultConfiguration.overrides,
                    keys: this._defaultConfiguration.keys
                },
                user: {
                    contents: this._userConfiguration.contents,
                    overrides: this._userConfiguration.overrides,
                    keys: this._userConfiguration.keys
                },
                workspace: {
                    contents: this._workspaceConfiguration.contents,
                    overrides: this._workspaceConfiguration.overrides,
                    keys: this._workspaceConfiguration.keys
                },
                folders: this._folderConfigurations.keys().reduce((result, folder) => {
                    const { contents, overrides, keys } = this._folderConfigurations.get(folder);
                    result[folder.toString()] = { contents, overrides, keys };
                    return result;
                }, Object.create({})),
                isComplete: true
            };
        }
        allKeys(workspace) {
            let keys = this.keys(workspace);
            let all = [...keys.default];
            const addKeys = (keys) => {
                for (const key of keys) {
                    if (all.indexOf(key) === -1) {
                        all.push(key);
                    }
                }
            };
            addKeys(keys.user);
            addKeys(keys.workspace);
            for (const resource of this.folders.keys()) {
                addKeys(this.folders.get(resource).keys);
            }
            return all;
        }
    }
    exports.Configuration = Configuration;
    class AbstractConfigurationChangeEvent {
        doesConfigurationContains(configuration, config) {
            let changedKeysTree = configuration.contents;
            let requestedTree = configuration_1.toValuesTree({ [config]: true }, () => { });
            let key;
            while (typeof requestedTree === 'object' && (key = Object.keys(requestedTree)[0])) { // Only one key should present, since we added only one property
                changedKeysTree = changedKeysTree[key];
                if (!changedKeysTree) {
                    return false; // Requested tree is not found
                }
                requestedTree = requestedTree[key];
            }
            return true;
        }
        updateKeys(configuration, keys, resource) {
            for (const key of keys) {
                configuration.setValue(key, {});
            }
        }
    }
    exports.AbstractConfigurationChangeEvent = AbstractConfigurationChangeEvent;
    class ConfigurationChangeEvent extends AbstractConfigurationChangeEvent {
        constructor(_changedConfiguration = new ConfigurationModel(), _changedConfigurationByResource = new map_1.ResourceMap()) {
            super();
            this._changedConfiguration = _changedConfiguration;
            this._changedConfigurationByResource = _changedConfigurationByResource;
        }
        get changedConfiguration() {
            return this._changedConfiguration;
        }
        get changedConfigurationByResource() {
            return this._changedConfigurationByResource;
        }
        change(arg1, arg2) {
            if (arg1 instanceof ConfigurationChangeEvent) {
                this._changedConfiguration = this._changedConfiguration.merge(arg1._changedConfiguration);
                for (const resource of arg1._changedConfigurationByResource.keys()) {
                    let changedConfigurationByResource = this.getOrSetChangedConfigurationForResource(resource);
                    changedConfigurationByResource = changedConfigurationByResource.merge(arg1._changedConfigurationByResource.get(resource));
                    this._changedConfigurationByResource.set(resource, changedConfigurationByResource);
                }
            }
            else {
                this.changeWithKeys(arg1, arg2);
            }
            return this;
        }
        telemetryData(source, sourceConfig) {
            this._source = source;
            this._sourceConfig = sourceConfig;
            return this;
        }
        get affectedKeys() {
            const keys = [...this._changedConfiguration.keys];
            this._changedConfigurationByResource.forEach(model => keys.push(...model.keys));
            return arrays.distinct(keys);
        }
        get source() {
            return this._source;
        }
        get sourceConfig() {
            return this._sourceConfig;
        }
        affectsConfiguration(config, resource) {
            let configurationModelsToSearch = [this._changedConfiguration];
            if (resource) {
                let model = this._changedConfigurationByResource.get(resource);
                if (model) {
                    configurationModelsToSearch.push(model);
                }
            }
            else {
                configurationModelsToSearch.push(...this._changedConfigurationByResource.values());
            }
            for (const configuration of configurationModelsToSearch) {
                if (this.doesConfigurationContains(configuration, config)) {
                    return true;
                }
            }
            return false;
        }
        changeWithKeys(keys, resource) {
            let changedConfiguration = resource ? this.getOrSetChangedConfigurationForResource(resource) : this._changedConfiguration;
            this.updateKeys(changedConfiguration, keys);
        }
        getOrSetChangedConfigurationForResource(resource) {
            let changedConfigurationByResource = this._changedConfigurationByResource.get(resource);
            if (!changedConfigurationByResource) {
                changedConfigurationByResource = new ConfigurationModel();
                this._changedConfigurationByResource.set(resource, changedConfigurationByResource);
            }
            return changedConfigurationByResource;
        }
    }
    exports.ConfigurationChangeEvent = ConfigurationChangeEvent;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[72/*vs/platform/configuration/node/configuration*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/lifecycle*/,25/*vs/base/common/errors*/,39/*vs/platform/configuration/common/configurationModels*/,69/*vs/base/node/config*/,6/*vs/base/common/event*/]), function (require, exports, lifecycle_1, errors_1, configurationModels_1, config_1, event_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    class UserConfiguration extends lifecycle_1.Disposable {
        constructor(settingsPath) {
            super();
            this.settingsPath = settingsPath;
            this._onDidChangeConfiguration = this._register(new event_1.Emitter());
            this.onDidChangeConfiguration = this._onDidChangeConfiguration.event;
        }
        initialize() {
            if (!this.initializePromise) {
                this.initializePromise = new Promise((c, e) => {
                    this.userConfigModelWatcher = new config_1.ConfigWatcher(this.settingsPath, {
                        changeBufferDelay: 300, onError: error => errors_1.onUnexpectedError(error), defaultConfig: new configurationModels_1.ConfigurationModelParser(this.settingsPath), parse: (content, parseErrors) => {
                            const userConfigModelParser = new configurationModels_1.ConfigurationModelParser(this.settingsPath);
                            userConfigModelParser.parse(content);
                            parseErrors = [...userConfigModelParser.errors];
                            return userConfigModelParser;
                        }, initCallback: () => c(undefined)
                    });
                    this._register(this.userConfigModelWatcher);
                    // Listeners
                    this._register(this.userConfigModelWatcher.onDidUpdateConfiguration(() => this._onDidChangeConfiguration.fire(this.userConfigModelWatcher.getConfig().configurationModel)));
                });
            }
            return this.initializePromise.then(() => this.userConfigModelWatcher.getConfig().configurationModel);
        }
        initializeSync() {
            this.initialize();
            return this.userConfigModelWatcher.getConfig().configurationModel;
        }
        reload() {
            return this.initialize().then(() => new Promise(c => this.userConfigModelWatcher.reload(userConfigModelParser => c(userConfigModelParser.configurationModel))));
        }
    }
    exports.UserConfiguration = UserConfiguration;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[73/*vs/platform/configuration/node/configurationService*/], __M([1/*require*/,0/*exports*/,15/*vs/platform/registry/common/platform*/,19/*vs/platform/configuration/common/configurationRegistry*/,10/*vs/base/common/lifecycle*/,12/*vs/platform/configuration/common/configuration*/,39/*vs/platform/configuration/common/configurationModels*/,6/*vs/base/common/event*/,14/*vs/platform/environment/common/environment*/,72/*vs/platform/configuration/node/configuration*/]), function (require, exports, platform_1, configurationRegistry_1, lifecycle_1, configuration_1, configurationModels_1, event_1, environment_1, configuration_2) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    let ConfigurationService = class ConfigurationService extends lifecycle_1.Disposable {
        constructor(environmentService) {
            super();
            this._onDidChangeConfiguration = this._register(new event_1.Emitter());
            this.onDidChangeConfiguration = this._onDidChangeConfiguration.event;
            this.userConfiguration = this._register(new configuration_2.UserConfiguration(environmentService.appSettingsPath));
            // Initialize
            const defaults = new configurationModels_1.DefaultConfigurationModel();
            const user = this.userConfiguration.initializeSync();
            this._configuration = new configurationModels_1.Configuration(defaults, user);
            // Listeners
            this._register(this.userConfiguration.onDidChangeConfiguration(userConfigurationModel => this.onDidChangeUserConfiguration(userConfigurationModel)));
            this._register(platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).onDidUpdateConfiguration(configurationProperties => this.onDidDefaultConfigurationChange(configurationProperties)));
        }
        get configuration() {
            return this._configuration;
        }
        getConfigurationData() {
            return this.configuration.toData();
        }
        getValue(arg1, arg2) {
            const section = typeof arg1 === 'string' ? arg1 : undefined;
            const overrides = configuration_1.isConfigurationOverrides(arg1) ? arg1 : configuration_1.isConfigurationOverrides(arg2) ? arg2 : {};
            return this.configuration.getValue(section, overrides, undefined);
        }
        updateValue(key, value, arg3, arg4) {
            return Promise.reject(new Error('not supported'));
        }
        inspect(key) {
            return this.configuration.inspect(key, {}, undefined);
        }
        keys() {
            return this.configuration.keys(undefined);
        }
        reloadConfiguration(folder) {
            return folder ? Promise.resolve(undefined) :
                this.userConfiguration.reload().then(userConfigurationModel => this.onDidChangeUserConfiguration(userConfigurationModel));
        }
        onDidChangeUserConfiguration(userConfigurationModel) {
            const { added, updated, removed } = configuration_1.compare(this._configuration.user, userConfigurationModel);
            const changedKeys = [...added, ...updated, ...removed];
            if (changedKeys.length) {
                this._configuration.updateUserConfiguration(userConfigurationModel);
                this.trigger(changedKeys, 1 /* USER */);
            }
        }
        onDidDefaultConfigurationChange(keys) {
            this._configuration.updateDefaultConfiguration(new configurationModels_1.DefaultConfigurationModel());
            this.trigger(keys, 4 /* DEFAULT */);
        }
        trigger(keys, source) {
            this._onDidChangeConfiguration.fire(new configurationModels_1.ConfigurationChangeEvent().change(keys).telemetryData(source, this.getTargetConfiguration(source)));
        }
        getTargetConfiguration(target) {
            switch (target) {
                case 4 /* DEFAULT */:
                    return this._configuration.defaults.contents;
                case 1 /* USER */:
                    return this._configuration.user.contents;
            }
            return {};
        }
    };
    ConfigurationService = __decorate([
        __param(0, environment_1.IEnvironmentService)
    ], ConfigurationService);
    exports.ConfigurationService = ConfigurationService;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[40/*vs/platform/request/node/request*/], __M([1/*require*/,0/*exports*/,66/*vs/nls!vs/platform/request/node/request*/,2/*vs/platform/instantiation/common/instantiation*/,19/*vs/platform/configuration/common/configurationRegistry*/,15/*vs/platform/registry/common/platform*/]), function (require, exports, nls_1, instantiation_1, configurationRegistry_1, platform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IRequestService = instantiation_1.createDecorator('requestService');
    platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration)
        .registerConfiguration({
        id: 'http',
        order: 15,
        title: nls_1.localize(0, null),
        type: 'object',
        properties: {
            'http.proxy': {
                type: 'string',
                pattern: '^https?://([^:]*(:[^@]*)?@)?([^:]+)(:\\d+)?/?$|^$',
                description: nls_1.localize(1, null)
            },
            'http.proxyStrictSSL': {
                type: 'boolean',
                default: true,
                description: nls_1.localize(2, null)
            },
            'http.proxyAuthorization': {
                type: ['null', 'string'],
                default: null,
                description: nls_1.localize(3, null)
            },
            'http.proxySupport': {
                type: 'string',
                enum: ['off', 'on', 'override'],
                enumDescriptions: [
                    nls_1.localize(4, null),
                    nls_1.localize(5, null),
                    nls_1.localize(6, null),
                ],
                default: 'override',
                description: nls_1.localize(7, null)
            },
            'http.systemCertificates': {
                type: 'boolean',
                default: true,
                description: nls_1.localize(8, null)
            }
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[75/*vs/platform/state/common/state*/], __M([1/*require*/,0/*exports*/,2/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IStateService = instantiation_1.createDecorator('stateService');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[76/*vs/platform/state/node/stateService*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/path*/,29/*fs*/,14/*vs/platform/environment/common/environment*/,38/*vs/base/node/extfs*/,4/*vs/base/common/types*/,5/*vs/platform/log/common/log*/,11/*vs/base/node/pfs*/]), function (require, exports, path, fs, environment_1, extfs_1, types_1, log_1, pfs_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    class FileStorage {
        constructor(dbPath, onError) {
            this.dbPath = dbPath;
            this.onError = onError;
            this._database = null;
            this.lastFlushedSerializedDatabase = null;
        }
        get database() {
            if (!this._database) {
                this._database = this.loadSync();
            }
            return this._database;
        }
        init() {
            return pfs_1.readFile(this.dbPath).then(contents => {
                try {
                    this.lastFlushedSerializedDatabase = contents.toString();
                    this._database = JSON.parse(this.lastFlushedSerializedDatabase);
                }
                catch (error) {
                    this._database = {};
                }
            }, error => {
                if (error.code !== 'ENOENT') {
                    this.onError(error);
                }
                this._database = {};
            });
        }
        loadSync() {
            try {
                this.lastFlushedSerializedDatabase = fs.readFileSync(this.dbPath).toString();
                return JSON.parse(this.lastFlushedSerializedDatabase);
            }
            catch (error) {
                if (error.code !== 'ENOENT') {
                    this.onError(error);
                }
                return {};
            }
        }
        getItem(key, defaultValue) {
            const res = this.database[key];
            if (types_1.isUndefinedOrNull(res)) {
                return defaultValue;
            }
            return res;
        }
        setItem(key, data) {
            // Remove an item when it is undefined or null
            if (types_1.isUndefinedOrNull(data)) {
                return this.removeItem(key);
            }
            // Shortcut for primitives that did not change
            if (typeof data === 'string' || typeof data === 'number' || typeof data === 'boolean') {
                if (this.database[key] === data) {
                    return;
                }
            }
            this.database[key] = data;
            this.saveSync();
        }
        removeItem(key) {
            // Only update if the key is actually present (not undefined)
            if (!types_1.isUndefined(this.database[key])) {
                this.database[key] = undefined;
                this.saveSync();
            }
        }
        saveSync() {
            const serializedDatabase = JSON.stringify(this.database, null, 4);
            if (serializedDatabase === this.lastFlushedSerializedDatabase) {
                return; // return early if the database has not changed
            }
            try {
                extfs_1.writeFileAndFlushSync(this.dbPath, serializedDatabase); // permission issue can happen here
                this.lastFlushedSerializedDatabase = serializedDatabase;
            }
            catch (error) {
                this.onError(error);
            }
        }
    }
    exports.FileStorage = FileStorage;
    let StateService = class StateService {
        constructor(environmentService, logService) {
            this.fileStorage = new FileStorage(path.join(environmentService.userDataPath, StateService.STATE_FILE), error => logService.error(error));
        }
        init() {
            return this.fileStorage.init();
        }
        getItem(key, defaultValue) {
            return this.fileStorage.getItem(key, defaultValue);
        }
        setItem(key, data) {
            this.fileStorage.setItem(key, data);
        }
        removeItem(key) {
            this.fileStorage.removeItem(key);
        }
    };
    StateService.STATE_FILE = 'storage.json';
    StateService = __decorate([
        __param(0, environment_1.IEnvironmentService),
        __param(1, log_1.ILogService)
    ], StateService);
    exports.StateService = StateService;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[27/*vs/platform/telemetry/common/telemetry*/], __M([1/*require*/,0/*exports*/,2/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ITelemetryService = instantiation_1.createDecorator('telemetryService');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[78/*vs/platform/telemetry/common/telemetryService*/], __M([1/*require*/,0/*exports*/,68/*vs/nls!vs/platform/telemetry/common/telemetryService*/,16/*vs/base/common/strings*/,2/*vs/platform/instantiation/common/instantiation*/,12/*vs/platform/configuration/common/configuration*/,19/*vs/platform/configuration/common/configurationRegistry*/,10/*vs/base/common/lifecycle*/,7/*vs/base/common/objects*/,15/*vs/platform/registry/common/platform*/]), function (require, exports, nls_1, strings_1, instantiation_1, configuration_1, configurationRegistry_1, lifecycle_1, objects_1, platform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    let TelemetryService = class TelemetryService {
        constructor(config, _configurationService) {
            this._configurationService = _configurationService;
            this._disposables = [];
            this._cleanupPatterns = [];
            this._appender = config.appender;
            this._commonProperties = config.commonProperties || Promise.resolve({});
            this._piiPaths = config.piiPaths || [];
            this._userOptIn = true;
            // static cleanup pattern for: `file:///DANGEROUS/PATH/resources/app/Useful/Information`
            this._cleanupPatterns = [/file:\/\/\/.*?\/resources\/app\//gi];
            for (let piiPath of this._piiPaths) {
                this._cleanupPatterns.push(new RegExp(strings_1.escapeRegExpCharacters(piiPath), 'gi'));
            }
            if (this._configurationService) {
                this._updateUserOptIn();
                this._configurationService.onDidChangeConfiguration(this._updateUserOptIn, this, this._disposables);
                /* __GDPR__
                    "optInStatus" : {
                        "optIn" : { "classification": "SystemMetaData", "purpose": "BusinessInsight", "isMeasurement": true }
                    }
                */
                this.publicLog('optInStatus', { optIn: this._userOptIn });
                this._commonProperties.then(values => {
                    const isHashedId = /^[a-f0-9]+$/i.test(values['common.machineId']);
                    /* __GDPR__
                        "machineIdFallback" : {
                            "usingFallbackGuid" : { "classification": "SystemMetaData", "purpose": "BusinessInsight", "isMeasurement": true }
                        }
                    */
                    this.publicLog('machineIdFallback', { usingFallbackGuid: !isHashedId });
                });
            }
        }
        _updateUserOptIn() {
            const config = this._configurationService.getValue(TELEMETRY_SECTION_ID);
            this._userOptIn = config ? config.enableTelemetry : this._userOptIn;
        }
        get isOptedIn() {
            return this._userOptIn;
        }
        getTelemetryInfo() {
            return this._commonProperties.then(values => {
                // well known properties
                let sessionId = values['sessionID'];
                let instanceId = values['common.instanceId'];
                let machineId = values['common.machineId'];
                return { sessionId, instanceId, machineId };
            });
        }
        dispose() {
            this._disposables = lifecycle_1.dispose(this._disposables);
        }
        publicLog(eventName, data, anonymizeFilePaths) {
            // don't send events when the user is optout
            if (!this._userOptIn) {
                return Promise.resolve(undefined);
            }
            return this._commonProperties.then(values => {
                // (first) add common properties
                data = objects_1.mixin(data, values);
                // (last) remove all PII from data
                data = objects_1.cloneAndChange(data, value => {
                    if (typeof value === 'string') {
                        return this._cleanupInfo(value, anonymizeFilePaths);
                    }
                    return undefined;
                });
                this._appender.log(eventName, data);
            }, err => {
                // unsure what to do now...
                console.error(err);
            });
        }
        _cleanupInfo(stack, anonymizeFilePaths) {
            let updatedStack = stack;
            if (anonymizeFilePaths) {
                const cleanUpIndexes = [];
                for (let regexp of this._cleanupPatterns) {
                    while (true) {
                        const result = regexp.exec(stack);
                        if (!result) {
                            break;
                        }
                        cleanUpIndexes.push([result.index, regexp.lastIndex]);
                    }
                }
                const nodeModulesRegex = /^[\\\/]?(node_modules|node_modules\.asar)[\\\/]/;
                const fileRegex = /(file:\/\/)?([a-zA-Z]:(\\\\|\\|\/)|(\\\\|\\|\/))?([\w-\._]+(\\\\|\\|\/))+[\w-\._]*/g;
                let lastIndex = 0;
                updatedStack = '';
                while (true) {
                    const result = fileRegex.exec(stack);
                    if (!result) {
                        break;
                    }
                    // Anoynimize user file paths that do not need to be retained or cleaned up.
                    if (!nodeModulesRegex.test(result[0]) && cleanUpIndexes.every(([x, y]) => result.index < x || result.index >= y)) {
                        updatedStack += stack.substring(lastIndex, result.index) + '<REDACTED: user-file-path>';
                        lastIndex = fileRegex.lastIndex;
                    }
                }
                if (lastIndex < stack.length) {
                    updatedStack += stack.substr(lastIndex);
                }
            }
            // sanitize with configured cleanup patterns
            for (let regexp of this._cleanupPatterns) {
                updatedStack = updatedStack.replace(regexp, '');
            }
            return updatedStack;
        }
    };
    TelemetryService.IDLE_START_EVENT_NAME = 'UserIdleStart';
    TelemetryService.IDLE_STOP_EVENT_NAME = 'UserIdleStop';
    TelemetryService = __decorate([
        __param(1, instantiation_1.optional(configuration_1.IConfigurationService))
    ], TelemetryService);
    exports.TelemetryService = TelemetryService;
    const TELEMETRY_SECTION_ID = 'telemetry';
    platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).registerConfiguration({
        'id': TELEMETRY_SECTION_ID,
        'order': 110,
        'type': 'object',
        'title': nls_1.localize(0, null),
        'properties': {
            'telemetry.enableTelemetry': {
                'type': 'boolean',
                'description': nls_1.localize(1, null),
                'default': true,
                'tags': ['usesOnlineServices']
            }
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[79/*vs/platform/telemetry/common/telemetryUtils*/], __M([1/*require*/,0/*exports*/,12/*vs/platform/configuration/common/configuration*/,5/*vs/platform/log/common/log*/]), function (require, exports, configuration_1, log_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NullTelemetryService = new class {
        publicLog(eventName, data) {
            return Promise.resolve(undefined);
        }
        getTelemetryInfo() {
            return Promise.resolve({
                instanceId: 'someValue.instanceId',
                sessionId: 'someValue.sessionId',
                machineId: 'someValue.machineId'
            });
        }
    };
    function combinedAppender(...appenders) {
        return {
            log: (e, d) => appenders.forEach(a => a.log(e, d)),
            dispose: () => Promise.all(appenders.map(a => a.dispose()))
        };
    }
    exports.combinedAppender = combinedAppender;
    exports.NullAppender = { log: () => null, dispose: () => Promise.resolve(null) };
    let LogAppender = class LogAppender {
        constructor(_logService) {
            this._logService = _logService;
            this.commonPropertiesRegex = /^sessionID$|^version$|^timestamp$|^commitHash$|^common\./;
        }
        dispose() {
            return Promise.resolve(undefined);
        }
        log(eventName, data) {
            const strippedData = {};
            Object.keys(data).forEach(key => {
                if (!this.commonPropertiesRegex.test(key)) {
                    strippedData[key] = data[key];
                }
            });
            this._logService.trace(`telemetry/${eventName}`, strippedData);
        }
    };
    LogAppender = __decorate([
        __param(0, log_1.ILogService)
    ], LogAppender);
    exports.LogAppender = LogAppender;
    /**
     * Only add settings that cannot contain any personal/private information of users (PII).
     */
    const configurationValueWhitelist = [
        'editor.fontFamily',
        'editor.fontWeight',
        'editor.fontSize',
        'editor.lineHeight',
        'editor.letterSpacing',
        'editor.lineNumbers',
        'editor.rulers',
        'editor.wordSeparators',
        'editor.tabSize',
        'editor.indentSize',
        'editor.insertSpaces',
        'editor.detectIndentation',
        'editor.roundedSelection',
        'editor.scrollBeyondLastLine',
        'editor.minimap.enabled',
        'editor.minimap.side',
        'editor.minimap.renderCharacters',
        'editor.minimap.maxColumn',
        'editor.find.seedSearchStringFromSelection',
        'editor.find.autoFindInSelection',
        'editor.wordWrap',
        'editor.wordWrapColumn',
        'editor.wrappingIndent',
        'editor.mouseWheelScrollSensitivity',
        'editor.multiCursorModifier',
        'editor.quickSuggestions',
        'editor.quickSuggestionsDelay',
        'editor.parameterHints.enabled',
        'editor.parameterHints.cycle',
        'editor.autoClosingBrackets',
        'editor.autoClosingQuotes',
        'editor.autoSurround',
        'editor.autoIndent',
        'editor.formatOnType',
        'editor.formatOnPaste',
        'editor.suggestOnTriggerCharacters',
        'editor.acceptSuggestionOnEnter',
        'editor.acceptSuggestionOnCommitCharacter',
        'editor.snippetSuggestions',
        'editor.emptySelectionClipboard',
        'editor.wordBasedSuggestions',
        'editor.suggestSelection',
        'editor.suggestFontSize',
        'editor.suggestLineHeight',
        'editor.tabCompletion',
        'editor.selectionHighlight',
        'editor.occurrencesHighlight',
        'editor.overviewRulerLanes',
        'editor.overviewRulerBorder',
        'editor.cursorBlinking',
        'editor.cursorSmoothCaretAnimation',
        'editor.cursorStyle',
        'editor.mouseWheelZoom',
        'editor.fontLigatures',
        'editor.hideCursorInOverviewRuler',
        'editor.renderWhitespace',
        'editor.renderControlCharacters',
        'editor.renderIndentGuides',
        'editor.renderLineHighlight',
        'editor.codeLens',
        'editor.folding',
        'editor.showFoldingControls',
        'editor.matchBrackets',
        'editor.glyphMargin',
        'editor.useTabStops',
        'editor.trimAutoWhitespace',
        'editor.stablePeek',
        'editor.dragAndDrop',
        'editor.formatOnSave',
        'editor.colorDecorators',
        'breadcrumbs.enabled',
        'breadcrumbs.filePath',
        'breadcrumbs.symbolPath',
        'breadcrumbs.symbolSortOrder',
        'breadcrumbs.useQuickPick',
        'explorer.openEditors.visible',
        'extensions.autoUpdate',
        'files.associations',
        'files.autoGuessEncoding',
        'files.autoSave',
        'files.autoSaveDelay',
        'files.encoding',
        'files.eol',
        'files.hotExit',
        'files.trimTrailingWhitespace',
        'git.confirmSync',
        'git.enabled',
        'http.proxyStrictSSL',
        'javascript.validate.enable',
        'php.builtInCompletions.enable',
        'php.validate.enable',
        'php.validate.run',
        'terminal.integrated.fontFamily',
        'window.openFilesInNewWindow',
        'window.restoreWindows',
        'window.zoomLevel',
        'workbench.editor.enablePreview',
        'workbench.editor.enablePreviewFromQuickOpen',
        'workbench.editor.showTabs',
        'workbench.editor.highlightModifiedTabs',
        'workbench.editor.swipeToNavigate',
        'workbench.sideBar.location',
        'workbench.startupEditor',
        'workbench.statusBar.visible',
        'workbench.welcome.enabled',
    ];
    function configurationTelemetry(telemetryService, configurationService) {
        return configurationService.onDidChangeConfiguration(event => {
            if (event.source !== 4 /* DEFAULT */) {
                /* __GDPR__
                    "updateConfiguration" : {
                        "configurationSource" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
                        "configurationKeys": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
                    }
                */
                telemetryService.publicLog('updateConfiguration', {
                    configurationSource: configuration_1.ConfigurationTargetToString(event.source),
                    configurationKeys: flattenKeys(event.sourceConfig)
                });
                /* __GDPR__
                    "updateConfigurationValues" : {
                        "configurationSource" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
                        "configurationValues": { "classification": "CustomerContent", "purpose": "FeatureInsight" }
                    }
                */
                telemetryService.publicLog('updateConfigurationValues', {
                    configurationSource: configuration_1.ConfigurationTargetToString(event.source),
                    configurationValues: flattenValues(event.sourceConfig, configurationValueWhitelist)
                });
            }
        });
    }
    exports.configurationTelemetry = configurationTelemetry;
    function keybindingsTelemetry(telemetryService, keybindingService) {
        return keybindingService.onDidUpdateKeybindings(event => {
            if (event.source === 2 /* User */ && event.keybindings) {
                /* __GDPR__
                    "updateKeybindings" : {
                        "bindings": { "classification": "CustomerContent", "purpose": "FeatureInsight" }
                    }
                */
                telemetryService.publicLog('updateKeybindings', {
                    bindings: event.keybindings.map(binding => ({
                        key: binding.key,
                        command: binding.command,
                        when: binding.when,
                        args: binding.args ? true : undefined
                    }))
                });
            }
        });
    }
    exports.keybindingsTelemetry = keybindingsTelemetry;
    function flattenKeys(value) {
        if (!value) {
            return [];
        }
        const result = [];
        flatKeys(result, '', value);
        return result;
    }
    function flatKeys(result, prefix, value) {
        if (value && typeof value === 'object' && !Array.isArray(value)) {
            Object.keys(value)
                .forEach(key => flatKeys(result, prefix ? `${prefix}.${key}` : key, value[key]));
        }
        else {
            result.push(prefix);
        }
    }
    function flattenValues(value, keys) {
        if (!value) {
            return [];
        }
        return keys.reduce((array, key) => {
            const v = key.split('.')
                .reduce((tmp, k) => tmp && typeof tmp === 'object' ? tmp[k] : undefined, value);
            if (typeof v !== 'undefined') {
                array.push({ [key]: v });
            }
            return array;
        }, []);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[80/*vs/platform/telemetry/node/appInsightsAppender*/], __M([1/*require*/,0/*exports*/,91/*applicationinsights*/,4/*vs/base/common/types*/,7/*vs/base/common/objects*/,5/*vs/platform/log/common/log*/]), function (require, exports, appInsights, types_1, objects_1, log_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function getClient(aiKey) {
        let client;
        if (appInsights.defaultClient) {
            client = new appInsights.TelemetryClient(aiKey);
            client.channel.setUseDiskRetryCaching(true);
        }
        else {
            appInsights.setup(aiKey)
                .setAutoCollectRequests(false)
                .setAutoCollectPerformance(false)
                .setAutoCollectExceptions(false)
                .setAutoCollectDependencies(false)
                .setAutoDependencyCorrelation(false)
                .setAutoCollectConsole(false)
                .setInternalLogging(false, false)
                .setUseDiskRetryCaching(true)
                .start();
            client = appInsights.defaultClient;
        }
        if (aiKey.indexOf('AIF-') === 0) {
            client.config.endpointUrl = 'https://vortex.data.microsoft.com/collect/v1';
        }
        return client;
    }
    let AppInsightsAppender = class AppInsightsAppender {
        constructor(_eventPrefix, _defaultData, aiKeyOrClientFactory, // allow factory function for testing
        _logService) {
            this._eventPrefix = _eventPrefix;
            this._defaultData = _defaultData;
            this._logService = _logService;
            if (!this._defaultData) {
                this._defaultData = Object.create(null);
            }
            if (typeof aiKeyOrClientFactory === 'string') {
                this._aiClient = getClient(aiKeyOrClientFactory);
            }
            else if (typeof aiKeyOrClientFactory === 'function') {
                this._aiClient = aiKeyOrClientFactory();
            }
        }
        static _getData(data) {
            const properties = Object.create(null);
            const measurements = Object.create(null);
            const flat = Object.create(null);
            AppInsightsAppender._flaten(data, flat);
            for (let prop in flat) {
                // enforce property names less than 150 char, take the last 150 char
                prop = prop.length > 150 ? prop.substr(prop.length - 149) : prop;
                const value = flat[prop];
                if (typeof value === 'number') {
                    measurements[prop] = value;
                }
                else if (typeof value === 'boolean') {
                    measurements[prop] = value ? 1 : 0;
                }
                else if (typeof value === 'string') {
                    //enforce property value to be less than 1024 char, take the first 1024 char
                    properties[prop] = value.substring(0, 1023);
                }
                else if (typeof value !== 'undefined' && value !== null) {
                    properties[prop] = value;
                }
            }
            return {
                properties,
                measurements
            };
        }
        static _flaten(obj, result, order = 0, prefix) {
            if (!obj) {
                return;
            }
            for (let item of Object.getOwnPropertyNames(obj)) {
                const value = obj[item];
                const index = prefix ? prefix + item : item;
                if (Array.isArray(value)) {
                    result[index] = objects_1.safeStringify(value);
                }
                else if (value instanceof Date) {
                    // TODO unsure why this is here and not in _getData
                    result[index] = value.toISOString();
                }
                else if (types_1.isObject(value)) {
                    if (order < 2) {
                        AppInsightsAppender._flaten(value, result, order + 1, index + '.');
                    }
                    else {
                        result[index] = objects_1.safeStringify(value);
                    }
                }
                else {
                    result[index] = value;
                }
            }
        }
        log(eventName, data) {
            if (!this._aiClient) {
                return;
            }
            data = objects_1.mixin(data, this._defaultData);
            data = AppInsightsAppender._getData(data);
            if (this._logService) {
                this._logService.trace(`telemetry/${eventName}`, data);
            }
            this._aiClient.trackEvent({
                name: this._eventPrefix + '/' + eventName,
                properties: data.properties,
                measurements: data.measurements
            });
        }
        dispose() {
            if (this._aiClient) {
                return new Promise(resolve => {
                    this._aiClient.flush({
                        callback: () => {
                            // all data flushed
                            this._aiClient = undefined;
                            resolve(undefined);
                        }
                    });
                });
            }
            return undefined;
        }
    };
    AppInsightsAppender = __decorate([
        __param(3, log_1.ILogService)
    ], AppInsightsAppender);
    exports.AppInsightsAppender = AppInsightsAppender;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[82/*vs/platform/telemetry/node/commonProperties*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/platform*/,26/*os*/,43/*vs/base/common/uuid*/,11/*vs/base/node/pfs*/]), function (require, exports, Platform, os, uuid, pfs_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function resolveCommonProperties(commit, version, machineId, installSourcePath) {
        const result = Object.create(null);
        // __GDPR__COMMON__ "common.machineId" : { "endPoint": "MacAddressHash", "classification": "EndUserPseudonymizedInformation", "purpose": "FeatureInsight" }
        result['common.machineId'] = machineId;
        // __GDPR__COMMON__ "sessionID" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
        result['sessionID'] = uuid.generateUuid() + Date.now();
        // __GDPR__COMMON__ "commitHash" : { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth" }
        result['commitHash'] = commit;
        // __GDPR__COMMON__ "version" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
        result['version'] = version;
        // __GDPR__COMMON__ "common.platformVersion" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
        result['common.platformVersion'] = (os.release() || '').replace(/^(\d+)(\.\d+)?(\.\d+)?(.*)/, '$1$2$3');
        // __GDPR__COMMON__ "common.platform" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
        result['common.platform'] = Platform.PlatformToString(Platform.platform);
        // __GDPR__COMMON__ "common.nodePlatform" : { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth" }
        result['common.nodePlatform'] = process.platform;
        // __GDPR__COMMON__ "common.nodeArch" : { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth" }
        result['common.nodeArch'] = process.arch;
        // dynamic properties which value differs on each call
        let seq = 0;
        const startTime = Date.now();
        Object.defineProperties(result, {
            // __GDPR__COMMON__ "timestamp" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
            'timestamp': {
                get: () => new Date(),
                enumerable: true
            },
            // __GDPR__COMMON__ "common.timesincesessionstart" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
            'common.timesincesessionstart': {
                get: () => Date.now() - startTime,
                enumerable: true
            },
            // __GDPR__COMMON__ "common.sequence" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
            'common.sequence': {
                get: () => seq++,
                enumerable: true
            }
        });
        return pfs_1.readFile(installSourcePath, 'utf8').then(contents => {
            // __GDPR__COMMON__ "common.source" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
            result['common.source'] = contents.slice(0, 30);
            return result;
        }, error => {
            return result;
        });
    }
    exports.resolveCommonProperties = resolveCommonProperties;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[44/*vs/base/node/zip*/], __M([1/*require*/,0/*exports*/,56/*vs/nls!vs/base/node/zip*/,3/*vs/base/common/path*/,29/*fs*/,24/*vs/base/common/async*/,11/*vs/base/node/pfs*/,90/*yauzl*/,89/*yazl*/,6/*vs/base/common/event*/]), function (require, exports, nls, path, fs_1, async_1, pfs_1, yauzl_1, yazl, event_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    class ExtractError extends Error {
        constructor(type, cause) {
            let message = cause.message;
            switch (type) {
                case 'CorruptZip':
                    message = `Corrupt ZIP: ${message}`;
                    break;
            }
            super(message);
            this.type = type;
            this.cause = cause;
        }
    }
    exports.ExtractError = ExtractError;
    function modeFromEntry(entry) {
        const attr = entry.externalFileAttributes >> 16 || 33188;
        return [448 /* S_IRWXU */, 56 /* S_IRWXG */, 7 /* S_IRWXO */]
            .map(mask => attr & mask)
            .reduce((a, b) => a + b, attr & 61440 /* S_IFMT */);
    }
    function toExtractError(err) {
        if (err instanceof ExtractError) {
            return err;
        }
        let type = undefined;
        if (/end of central directory record signature not found/.test(err.message)) {
            type = 'CorruptZip';
        }
        return new ExtractError(type, err);
    }
    function extractEntry(stream, fileName, mode, targetPath, options, token) {
        const dirName = path.dirname(fileName);
        const targetDirName = path.join(targetPath, dirName);
        if (targetDirName.indexOf(targetPath) !== 0) {
            return Promise.reject(new Error(nls.localize(0, null, fileName)));
        }
        const targetFileName = path.join(targetPath, fileName);
        let istream;
        event_1.Event.once(token.onCancellationRequested)(() => {
            if (istream) {
                istream.destroy();
            }
        });
        return Promise.resolve(pfs_1.mkdirp(targetDirName, undefined, token)).then(() => new Promise((c, e) => {
            if (token.isCancellationRequested) {
                return;
            }
            try {
                istream = fs_1.createWriteStream(targetFileName, { mode });
                istream.once('close', () => c());
                istream.once('error', e);
                stream.once('error', e);
                stream.pipe(istream);
            }
            catch (error) {
                e(error);
            }
        }));
    }
    function extractZip(zipfile, targetPath, options, token) {
        let last = async_1.createCancelablePromise(() => Promise.resolve());
        let extractedEntriesCount = 0;
        event_1.Event.once(token.onCancellationRequested)(() => {
            last.cancel();
            zipfile.close();
        });
        return new Promise((c, e) => {
            const throttler = new async_1.Sequencer();
            const readNextEntry = (token) => {
                if (token.isCancellationRequested) {
                    return;
                }
                extractedEntriesCount++;
                zipfile.readEntry();
            };
            zipfile.once('error', e);
            zipfile.once('close', () => last.then(() => {
                if (token.isCancellationRequested || zipfile.entryCount === extractedEntriesCount) {
                    c();
                }
                else {
                    e(new ExtractError('Incomplete', new Error(nls.localize(1, null, extractedEntriesCount, zipfile.entryCount))));
                }
            }, e));
            zipfile.readEntry();
            zipfile.on('entry', (entry) => {
                if (token.isCancellationRequested) {
                    return;
                }
                if (!options.sourcePathRegex.test(entry.fileName)) {
                    readNextEntry(token);
                    return;
                }
                const fileName = entry.fileName.replace(options.sourcePathRegex, '');
                // directory file names end with '/'
                if (/\/$/.test(fileName)) {
                    const targetFileName = path.join(targetPath, fileName);
                    last = async_1.createCancelablePromise(token => pfs_1.mkdirp(targetFileName, undefined, token).then(() => readNextEntry(token)).then(undefined, e));
                    return;
                }
                const stream = async_1.ninvoke(zipfile, zipfile.openReadStream, entry);
                const mode = modeFromEntry(entry);
                last = async_1.createCancelablePromise(token => throttler.queue(() => stream.then(stream => extractEntry(stream, fileName, mode, targetPath, options, token).then(() => readNextEntry(token)))).then(null, e));
            });
        });
    }
    function openZip(zipFile, lazy = false) {
        return async_1.nfcall(yauzl_1.open, zipFile, lazy ? { lazyEntries: true } : undefined)
            .then(undefined, err => Promise.reject(toExtractError(err)));
    }
    function zip(zipPath, files) {
        return new Promise((c, e) => {
            const zip = new yazl.ZipFile();
            files.forEach(f => {
                if (f.contents) {
                    zip.addBuffer(typeof f.contents === 'string' ? Buffer.from(f.contents, 'utf8') : f.contents, f.path);
                }
                else if (f.localPath) {
                    zip.addFile(f.localPath, f.path);
                }
            });
            zip.end();
            const zipStream = fs_1.createWriteStream(zipPath);
            zip.outputStream.pipe(zipStream);
            zip.outputStream.once('error', e);
            zipStream.once('error', e);
            zipStream.once('finish', () => c(zipPath));
        });
    }
    exports.zip = zip;
    function extract(zipPath, targetPath, options = {}, token) {
        const sourcePathRegex = new RegExp(options.sourcePath ? `^${options.sourcePath}` : '');
        let promise = openZip(zipPath, true);
        if (options.overwrite) {
            promise = promise.then(zipfile => pfs_1.rimraf(targetPath).then(() => zipfile));
        }
        return promise.then(zipfile => extractZip(zipfile, targetPath, { sourcePathRegex }, token));
    }
    exports.extract = extract;
    function read(zipPath, filePath) {
        return openZip(zipPath).then(zipfile => {
            return new Promise((c, e) => {
                zipfile.on('entry', (entry) => {
                    if (entry.fileName === filePath) {
                        async_1.ninvoke(zipfile, zipfile.openReadStream, entry).then(stream => c(stream), err => e(err));
                    }
                });
                zipfile.once('close', () => e(new Error(nls.localize(2, null, filePath))));
            });
        });
    }
    function buffer(zipPath, filePath) {
        return read(zipPath, filePath).then(stream => {
            return new Promise((c, e) => {
                const buffers = [];
                stream.once('error', e);
                stream.on('data', b => buffers.push(b));
                stream.on('end', () => c(Buffer.concat(buffers)));
            });
        });
    }
    exports.buffer = buffer;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[37/*vs/platform/extensionManagement/node/extensionManagementUtil*/], __M([1/*require*/,0/*exports*/,44/*vs/base/node/zip*/,63/*vs/nls!vs/platform/extensionManagement/node/extensionManagementUtil*/]), function (require, exports, zip_1, nls_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function getManifest(vsix) {
        return zip_1.buffer(vsix, 'extension/package.json')
            .then(buffer => {
            try {
                return JSON.parse(buffer.toString('utf8'));
            }
            catch (err) {
                throw new Error(nls_1.localize(0, null));
            }
        });
    }
    exports.getManifest = getManifest;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

















define(__m[88/*vs/platform/extensionManagement/node/extensionManagementService*/], __M([1/*require*/,0/*exports*/,62/*vs/nls!vs/platform/extensionManagement/node/extensionManagementService*/,3/*vs/base/common/path*/,11/*vs/base/node/pfs*/,7/*vs/base/common/objects*/,10/*vs/base/common/lifecycle*/,17/*vs/base/common/arrays*/,44/*vs/base/node/zip*/,23/*vs/platform/extensionManagement/common/extensionManagement*/,13/*vs/platform/extensionManagement/common/extensionManagementUtil*/,70/*vs/platform/extensionManagement/common/extensionNls*/,14/*vs/platform/environment/common/environment*/,24/*vs/base/common/async*/,6/*vs/base/common/event*/,86/*semver*/,20/*vs/base/common/uri*/,21/*vs/platform/product/node/package*/,18/*vs/base/common/platform*/,5/*vs/platform/log/common/log*/,85/*vs/platform/extensionManagement/node/extensionsManifestCache*/,74/*vs/platform/extensionManagement/node/extensionLifecycle*/,34/*vs/base/common/errorMessage*/,27/*vs/platform/telemetry/common/telemetry*/,41/*vs/platform/extensions/node/extensionValidator*/,26/*os*/,43/*vs/base/common/uuid*/,46/*vs/platform/download/common/download*/,2/*vs/platform/instantiation/common/instantiation*/,28/*vs/base/common/network*/,45/*vs/base/common/cancellation*/,32/*vs/base/common/amd*/,37/*vs/platform/extensionManagement/node/extensionManagementUtil*/,30/*vs/platform/extensions/common/extensions*/,12/*vs/platform/configuration/common/configuration*/,35/*vs/platform/extensions/node/extensionsUtil*/]), function (require, exports, nls, path, pfs, objects_1, lifecycle_1, arrays_1, zip_1, extensionManagement_1, extensionManagementUtil_1, extensionNls_1, environment_1, async_1, event_1, semver, uri_1, package_1, platform_1, log_1, extensionsManifestCache_1, extensionLifecycle_1, errorMessage_1, telemetry_1, extensionValidator_1, os_1, uuid_1, download_1, instantiation_1, network_1, cancellation_1, amd_1, extensionManagementUtil_2, extensions_1, configuration_1, extensionsUtil_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const ERROR_SCANNING_SYS_EXTENSIONS = 'scanningSystem';
    const ERROR_SCANNING_USER_EXTENSIONS = 'scanningUser';
    const INSTALL_ERROR_UNSET_UNINSTALLED = 'unsetUninstalled';
    const INSTALL_ERROR_DOWNLOADING = 'downloading';
    const INSTALL_ERROR_VALIDATING = 'validating';
    const INSTALL_ERROR_LOCAL = 'local';
    const INSTALL_ERROR_EXTRACTING = 'extracting';
    const INSTALL_ERROR_RENAMING = 'renaming';
    const INSTALL_ERROR_DELETING = 'deleting';
    const ERROR_UNKNOWN = 'unknown';
    class ExtensionManagementError extends Error {
        constructor(message, code) {
            super(message);
            this.code = code;
        }
    }
    exports.ExtensionManagementError = ExtensionManagementError;
    function parseManifest(raw) {
        return new Promise((c, e) => {
            try {
                const manifest = JSON.parse(raw);
                const metadata = manifest.__metadata || null;
                delete manifest.__metadata;
                c({ manifest, metadata });
            }
            catch (err) {
                e(new Error(nls.localize(0, null)));
            }
        });
    }
    function readManifest(extensionPath) {
        const promises = [
            pfs.readFile(path.join(extensionPath, 'package.json'), 'utf8')
                .then(raw => parseManifest(raw)),
            pfs.readFile(path.join(extensionPath, 'package.nls.json'), 'utf8')
                .then(undefined, err => err.code !== 'ENOENT' ? Promise.reject(err) : '{}')
                .then(raw => JSON.parse(raw))
        ];
        return Promise.all(promises).then(([{ manifest, metadata }, translations]) => {
            return {
                manifest: extensionNls_1.localizeManifest(manifest, translations),
                metadata
            };
        });
    }
    let ExtensionManagementService = class ExtensionManagementService extends lifecycle_1.Disposable {
        constructor(remote, environmentService, configurationService, galleryService, logService, downloadService, telemetryService) {
            super();
            this.remote = remote;
            this.environmentService = environmentService;
            this.configurationService = configurationService;
            this.galleryService = galleryService;
            this.logService = logService;
            this.downloadService = downloadService;
            this.telemetryService = telemetryService;
            this.lastReportTimestamp = 0;
            this.installingExtensions = new Map();
            this.uninstallingExtensions = new Map();
            this._onInstallExtension = new event_1.Emitter();
            this.onInstallExtension = this._onInstallExtension.event;
            this._onDidInstallExtension = new event_1.Emitter();
            this.onDidInstallExtension = this._onDidInstallExtension.event;
            this._onUninstallExtension = new event_1.Emitter();
            this.onUninstallExtension = this._onUninstallExtension.event;
            this._onDidUninstallExtension = new event_1.Emitter();
            this.onDidUninstallExtension = this._onDidUninstallExtension.event;
            this._devSystemExtensionsPath = null;
            this._devSystemExtensionsFilePath = null;
            this.systemExtensionsPath = environmentService.builtinExtensionsPath;
            this.extensionsPath = environmentService.extensionsPath;
            this.uninstalledPath = path.join(this.extensionsPath, '.obsolete');
            this.uninstalledFileLimiter = new async_1.Queue();
            this.manifestCache = this._register(new extensionsManifestCache_1.ExtensionsManifestCache(environmentService, this));
            this.extensionLifecycle = this._register(new extensionLifecycle_1.ExtensionsLifecycle(environmentService, this.logService));
            this._register(lifecycle_1.toDisposable(() => {
                this.installingExtensions.forEach(promise => promise.cancel());
                this.uninstallingExtensions.forEach(promise => promise.cancel());
                this.installingExtensions.clear();
                this.uninstallingExtensions.clear();
            }));
        }
        zip(extension) {
            this.logService.trace('ExtensionManagementService#zip', extension.identifier.id);
            return this.collectFiles(extension)
                .then(files => zip_1.zip(path.join(os_1.tmpdir(), uuid_1.generateUuid()), files))
                .then(path => uri_1.URI.file(path));
        }
        unzip(zipLocation, type) {
            this.logService.trace('ExtensionManagementService#unzip', zipLocation.toString());
            return this.install(zipLocation, type);
        }
        collectFiles(extension) {
            const collectFilesFromDirectory = (dir) => __awaiter(this, void 0, void 0, function* () {
                let entries = yield pfs.readdir(dir);
                entries = entries.map(e => path.join(dir, e));
                const stats = yield Promise.all(entries.map(e => pfs.stat(e)));
                let promise = Promise.resolve([]);
                stats.forEach((stat, index) => {
                    const entry = entries[index];
                    if (stat.isFile()) {
                        promise = promise.then(result => ([...result, entry]));
                    }
                    if (stat.isDirectory()) {
                        promise = promise
                            .then(result => collectFilesFromDirectory(entry)
                            .then(files => ([...result, ...files])));
                    }
                });
                return promise;
            });
            return collectFilesFromDirectory(extension.location.fsPath)
                .then(files => files.map(f => ({ path: `extension/${path.relative(extension.location.fsPath, f)}`, localPath: f })));
        }
        install(vsix, type = 1 /* User */) {
            this.logService.trace('ExtensionManagementService#install', vsix.toString());
            return async_1.createCancelablePromise(token => {
                return this.downloadVsix(vsix).then(downloadLocation => {
                    const zipPath = path.resolve(downloadLocation.fsPath);
                    return extensionManagementUtil_2.getManifest(zipPath)
                        .then(manifest => {
                        const identifier = { id: extensionManagementUtil_1.getGalleryExtensionId(manifest.publisher, manifest.name) };
                        let operation = 1 /* Install */;
                        if (manifest.engines && manifest.engines.vscode && !extensionValidator_1.isEngineValid(manifest.engines.vscode)) {
                            return Promise.reject(new Error(nls.localize(1, null, identifier.id, package_1.default.version)));
                        }
                        const identifierWithVersion = new extensions_1.ExtensionIdentifierWithVersion(identifier, manifest.version);
                        return this.getInstalled(1 /* User */)
                            .then(installedExtensions => {
                            const existing = installedExtensions.filter(i => extensionManagementUtil_1.areSameExtensions(identifier, i.identifier))[0];
                            if (existing) {
                                operation = 2 /* Update */;
                                if (identifierWithVersion.equals(new extensions_1.ExtensionIdentifierWithVersion(existing.identifier, existing.manifest.version))) {
                                    return this.removeExtension(existing, 'existing').then(null, e => Promise.reject(new Error(nls.localize(2, null, manifest.displayName || manifest.name))));
                                }
                                else if (semver.gt(existing.manifest.version, manifest.version)) {
                                    return this.uninstall(existing, true);
                                }
                            }
                            return undefined;
                        })
                            .then(() => {
                            this.logService.info('Installing the extension:', identifier.id);
                            this._onInstallExtension.fire({ identifier, zipPath });
                            return this.getMetadata(extensionManagementUtil_1.getGalleryExtensionId(manifest.publisher, manifest.name))
                                .then(metadata => this.installFromZipPath(identifierWithVersion, zipPath, metadata, type, operation, token), () => this.installFromZipPath(identifierWithVersion, zipPath, null, type, operation, token))
                                .then(() => { this.logService.info('Successfully installed the extension:', identifier.id); return identifier; }, e => {
                                this.logService.error('Failed to install the extension:', identifier.id, e.message);
                                return Promise.reject(e);
                            });
                        });
                    });
                });
            });
        }
        downloadVsix(vsix) {
            if (vsix.scheme === network_1.Schemas.file) {
                return Promise.resolve(vsix);
            }
            if (!this.downloadService) {
                throw new Error('Download service is not available');
            }
            const downloadedLocation = path.join(os_1.tmpdir(), uuid_1.generateUuid());
            return this.downloadService.download(vsix, downloadedLocation).then(() => uri_1.URI.file(downloadedLocation));
        }
        installFromZipPath(identifierWithVersion, zipPath, metadata, type, operation, token) {
            return this.toNonCancellablePromise(this.installExtension({ zipPath, identifierWithVersion, metadata }, type, token)
                .then(local => this.installDependenciesAndPackExtensions(local, null).then(() => local, error => this.uninstall(local, true).then(() => Promise.reject(error), () => Promise.reject(error))))
                .then(local => { this._onDidInstallExtension.fire({ identifier: identifierWithVersion.identifier, zipPath, local, operation }); return local; }, error => { this._onDidInstallExtension.fire({ identifier: identifierWithVersion.identifier, zipPath, operation, error }); return Promise.reject(error); }));
        }
        installFromGallery(extension) {
            return __awaiter(this, void 0, void 0, function* () {
                const startTime = new Date().getTime();
                this.logService.info('Installing extension:', extension.identifier.id);
                this._onInstallExtension.fire({ identifier: extension.identifier, gallery: extension });
                const onDidInstallExtensionSuccess = (extension, operation, local) => {
                    this.logService.info(`Extensions installed successfully:`, extension.identifier.id);
                    this._onDidInstallExtension.fire({ identifier: extension.identifier, gallery: extension, local, operation });
                    this.reportTelemetry(this.getTelemetryEvent(operation), extensionManagementUtil_1.getGalleryExtensionTelemetryData(extension), new Date().getTime() - startTime, undefined);
                };
                const onDidInstallExtensionFailure = (extension, operation, error) => {
                    const errorCode = error && error.code ? error.code : ERROR_UNKNOWN;
                    this.logService.error(`Failed to install extension:`, extension.identifier.id, error ? error.message : errorCode);
                    this._onDidInstallExtension.fire({ identifier: extension.identifier, gallery: extension, operation, error: errorCode });
                    this.reportTelemetry(this.getTelemetryEvent(operation), extensionManagementUtil_1.getGalleryExtensionTelemetryData(extension), new Date().getTime() - startTime, error);
                    if (error instanceof Error) {
                        error.name = errorCode;
                    }
                };
                try {
                    extension = yield this.checkAndGetCompatibleVersion(extension);
                }
                catch (error) {
                    onDidInstallExtensionFailure(extension, 1 /* Install */, error);
                    return Promise.reject(error);
                }
                const key = new extensions_1.ExtensionIdentifierWithVersion(extension.identifier, extension.version).key();
                let cancellablePromise = this.installingExtensions.get(key);
                if (!cancellablePromise) {
                    let operation = 1 /* Install */;
                    let cancellationToken, successCallback, errorCallback;
                    cancellablePromise = async_1.createCancelablePromise(token => { cancellationToken = token; return new Promise((c, e) => { successCallback = c; errorCallback = e; }); });
                    this.installingExtensions.set(key, cancellablePromise);
                    try {
                        const installed = yield this.getInstalled(1 /* User */);
                        const existingExtension = installed.filter(i => extensionManagementUtil_1.areSameExtensions(i.identifier, extension.identifier))[0];
                        if (existingExtension) {
                            operation = 2 /* Update */;
                            if (semver.gt(existingExtension.manifest.version, extension.version)) {
                                yield this.uninstall(existingExtension, true);
                            }
                        }
                        this.downloadInstallableExtension(extension, operation)
                            .then(installableExtension => this.installExtension(installableExtension, 1 /* User */, cancellationToken)
                            .then(local => pfs.rimraf(installableExtension.zipPath).finally(() => null).then(() => local)))
                            .then(local => this.installDependenciesAndPackExtensions(local, existingExtension)
                            .then(() => local, error => this.uninstall(local, true).then(() => Promise.reject(error), () => Promise.reject(error))))
                            .then(local => {
                            this.installingExtensions.delete(key);
                            onDidInstallExtensionSuccess(extension, operation, local);
                            successCallback(null);
                        }, error => {
                            this.installingExtensions.delete(key);
                            onDidInstallExtensionFailure(extension, operation, error);
                            errorCallback(error);
                        });
                    }
                    catch (error) {
                        this.installingExtensions.delete(key);
                        onDidInstallExtensionFailure(extension, operation, error);
                        return Promise.reject(error);
                    }
                }
                return cancellablePromise;
            });
        }
        checkAndGetCompatibleVersion(extension) {
            return __awaiter(this, void 0, void 0, function* () {
                if (yield this.isMalicious(extension)) {
                    return Promise.reject(new ExtensionManagementError(nls.localize(3, null), extensionManagement_1.INSTALL_ERROR_MALICIOUS));
                }
                const compatibleExtension = yield this.galleryService.getCompatibleExtension(extension);
                if (!compatibleExtension) {
                    return Promise.reject(new ExtensionManagementError(nls.localize(4, null, extension.identifier.id, package_1.default.version), extensionManagement_1.INSTALL_ERROR_INCOMPATIBLE));
                }
                if (this.remote) {
                    const manifest = yield this.galleryService.getManifest(extension, cancellation_1.CancellationToken.None);
                    if (manifest && extensionsUtil_1.isUIExtension(manifest, [], this.configurationService) && !extensions_1.isLanguagePackExtension(manifest)) {
                        return Promise.reject(new Error(nls.localize(5, null, extension.identifier.id)));
                    }
                }
                return compatibleExtension;
            });
        }
        reinstallFromGallery(extension) {
            this.logService.trace('ExtensionManagementService#reinstallFromGallery', extension.identifier.id);
            if (!this.galleryService.isEnabled()) {
                return Promise.reject(new Error(nls.localize(6, null)));
            }
            return this.findGalleryExtension(extension)
                .then(galleryExtension => {
                if (galleryExtension) {
                    return this.setUninstalled(extension)
                        .then(() => this.removeUninstalledExtension(extension)
                        .then(() => this.installFromGallery(galleryExtension), e => Promise.reject(new Error(nls.localize(7, null, errorMessage_1.toErrorMessage(e))))));
                }
                return Promise.reject(new Error(nls.localize(8, null)));
            });
        }
        getTelemetryEvent(operation) {
            return operation === 2 /* Update */ ? 'extensionGallery:update' : 'extensionGallery:install';
        }
        isMalicious(extension) {
            return this.getExtensionsReport()
                .then(report => extensionManagementUtil_1.getMaliciousExtensionsSet(report).has(extension.identifier.id));
        }
        downloadInstallableExtension(extension, operation) {
            const metadata = {
                id: extension.identifier.uuid,
                publisherId: extension.publisherId,
                publisherDisplayName: extension.publisherDisplayName,
            };
            this.logService.trace('Started downloading extension:', extension.identifier.id);
            return this.galleryService.download(extension, operation)
                .then(zipPath => {
                this.logService.info('Downloaded extension:', extension.identifier.id, zipPath);
                return extensionManagementUtil_2.getManifest(zipPath)
                    .then(manifest => ({ zipPath, identifierWithVersion: new extensions_1.ExtensionIdentifierWithVersion(extension.identifier, manifest.version), metadata }), error => Promise.reject(new ExtensionManagementError(this.joinErrors(error).message, INSTALL_ERROR_VALIDATING)));
            }, error => Promise.reject(new ExtensionManagementError(this.joinErrors(error).message, INSTALL_ERROR_DOWNLOADING)));
        }
        installExtension(installableExtension, type, token) {
            return this.unsetUninstalledAndGetLocal(installableExtension.identifierWithVersion)
                .then(local => {
                if (local) {
                    return local;
                }
                return this.extractAndInstall(installableExtension, type, token);
            }, e => {
                if (platform_1.isMacintosh) {
                    return Promise.reject(new ExtensionManagementError(nls.localize(9, null), INSTALL_ERROR_UNSET_UNINSTALLED));
                }
                return Promise.reject(new ExtensionManagementError(nls.localize(10, null), INSTALL_ERROR_UNSET_UNINSTALLED));
            });
        }
        unsetUninstalledAndGetLocal(identifierWithVersion) {
            return this.isUninstalled(identifierWithVersion)
                .then(isUninstalled => {
                if (isUninstalled) {
                    this.logService.trace('Removing the extension from uninstalled list:', identifierWithVersion.identifier.id);
                    // If the same version of extension is marked as uninstalled, remove it from there and return the local.
                    return this.unsetUninstalled(identifierWithVersion)
                        .then(() => {
                        this.logService.info('Removed the extension from uninstalled list:', identifierWithVersion.identifier.id);
                        return this.getInstalled(1 /* User */);
                    })
                        .then(installed => installed.filter(i => new extensions_1.ExtensionIdentifierWithVersion(i.identifier, i.manifest.version).equals(identifierWithVersion))[0]);
                }
                return null;
            });
        }
        extractAndInstall({ zipPath, identifierWithVersion, metadata }, type, token) {
            const { identifier } = identifierWithVersion;
            const location = type === 1 /* User */ ? this.extensionsPath : this.systemExtensionsPath;
            const folderName = identifierWithVersion.key();
            const tempPath = path.join(location, `.${folderName}`);
            const extensionPath = path.join(location, folderName);
            return pfs.rimraf(extensionPath)
                .then(() => this.extractAndRename(identifier, zipPath, tempPath, extensionPath, token), e => Promise.reject(new ExtensionManagementError(nls.localize(11, null, extensionPath, identifier.id), INSTALL_ERROR_DELETING)))
                .then(() => this.scanExtension(folderName, location, type))
                .then(local => {
                if (!local) {
                    return Promise.reject(nls.localize(12, null, location));
                }
                this.logService.info('Installation completed.', identifier.id);
                if (metadata) {
                    local.metadata = metadata;
                    return this.saveMetadataForLocalExtension(local);
                }
                return local;
            }, error => pfs.rimraf(extensionPath).then(() => Promise.reject(error), () => Promise.reject(error)));
        }
        extractAndRename(identifier, zipPath, extractPath, renamePath, token) {
            return this.extract(identifier, zipPath, extractPath, token)
                .then(() => this.rename(identifier, extractPath, renamePath, Date.now() + (2 * 60 * 1000) /* Retry for 2 minutes */)
                .then(() => this.logService.info('Renamed to', renamePath), e => {
                this.logService.info('Rename failed. Deleting from extracted location', extractPath);
                return pfs.rimraf(extractPath).finally(() => null).then(() => Promise.reject(e));
            }));
        }
        extract(identifier, zipPath, extractPath, token) {
            this.logService.trace(`Started extracting the extension from ${zipPath} to ${extractPath}`);
            return pfs.rimraf(extractPath)
                .then(() => zip_1.extract(zipPath, extractPath, { sourcePath: 'extension', overwrite: true }, token)
                .then(() => this.logService.info(`Extracted extension to ${extractPath}:`, identifier.id), e => pfs.rimraf(extractPath).finally(() => null)
                .then(() => Promise.reject(new ExtensionManagementError(e.message, e instanceof zip_1.ExtractError && e.type ? e.type : INSTALL_ERROR_EXTRACTING)))), e => Promise.reject(new ExtensionManagementError(this.joinErrors(e).message, INSTALL_ERROR_DELETING)));
        }
        rename(identfier, extractPath, renamePath, retryUntil) {
            return pfs.rename(extractPath, renamePath)
                .then(undefined, error => {
                if (platform_1.isWindows && error && error.code === 'EPERM' && Date.now() < retryUntil) {
                    this.logService.info(`Failed renaming ${extractPath} to ${renamePath} with 'EPERM' error. Trying again...`, identfier.id);
                    return this.rename(identfier, extractPath, renamePath, retryUntil);
                }
                return Promise.reject(new ExtensionManagementError(error.message || nls.localize(13, null, extractPath, renamePath), error.code || INSTALL_ERROR_RENAMING));
            });
        }
        installDependenciesAndPackExtensions(installed, existing) {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.galleryService.isEnabled()) {
                    const dependenciesAndPackExtensions = installed.manifest.extensionDependencies || [];
                    if (installed.manifest.extensionPack) {
                        for (const extension of installed.manifest.extensionPack) {
                            // add only those extensions which are new in currently installed extension
                            if (!(existing && existing.manifest.extensionPack && existing.manifest.extensionPack.some(old => extensionManagementUtil_1.areSameExtensions({ id: old }, { id: extension })))) {
                                if (dependenciesAndPackExtensions.every(e => !extensionManagementUtil_1.areSameExtensions({ id: e }, { id: extension }))) {
                                    dependenciesAndPackExtensions.push(extension);
                                }
                            }
                        }
                    }
                    if (dependenciesAndPackExtensions.length) {
                        return this.getInstalled()
                            .then(installed => {
                            // filter out installed extensions
                            const names = dependenciesAndPackExtensions.filter(id => installed.every(({ identifier: galleryIdentifier }) => !extensionManagementUtil_1.areSameExtensions(galleryIdentifier, { id })));
                            if (names.length) {
                                return this.galleryService.query({ names, pageSize: dependenciesAndPackExtensions.length })
                                    .then(galleryResult => {
                                    const extensionsToInstall = galleryResult.firstPage;
                                    return Promise.all(extensionsToInstall.map((e) => __awaiter(this, void 0, void 0, function* () {
                                        if (this.remote) {
                                            const manifest = yield this.galleryService.getManifest(e, cancellation_1.CancellationToken.None);
                                            if (manifest && extensionsUtil_1.isUIExtension(manifest, [], this.configurationService) && !extensions_1.isLanguagePackExtension(manifest)) {
                                                this.logService.info('Ignored installing the UI dependency', e.identifier.id);
                                                return;
                                            }
                                        }
                                        return this.installFromGallery(e);
                                    })))
                                        .then(() => null, errors => this.rollback(extensionsToInstall).then(() => Promise.reject(errors), () => Promise.reject(errors)));
                                });
                            }
                            return null;
                        });
                    }
                }
                return Promise.resolve(undefined);
            });
        }
        rollback(extensions) {
            return this.getInstalled(1 /* User */)
                .then(installed => Promise.all(installed.filter(local => extensions.some(galleryExtension => new extensions_1.ExtensionIdentifierWithVersion(local.identifier, local.manifest.version).equals(new extensions_1.ExtensionIdentifierWithVersion(galleryExtension.identifier, galleryExtension.version)))) // Check with version because we want to rollback the exact version
                .map(local => this.uninstall(local, true))))
                .then(() => undefined, () => undefined);
        }
        uninstall(extension, force = false) {
            this.logService.trace('ExtensionManagementService#uninstall', extension.identifier.id);
            return this.toNonCancellablePromise(this.getInstalled(1 /* User */)
                .then(installed => {
                const extensionToUninstall = installed.filter(e => extensionManagementUtil_1.areSameExtensions(e.identifier, extension.identifier))[0];
                if (extensionToUninstall) {
                    return this.checkForDependenciesAndUninstall(extensionToUninstall, installed).then(() => null, error => Promise.reject(this.joinErrors(error)));
                }
                else {
                    return Promise.reject(new Error(nls.localize(14, null, extension.manifest.displayName || extension.manifest.name)));
                }
            }));
        }
        updateMetadata(local, metadata) {
            this.logService.trace('ExtensionManagementService#updateMetadata', local.identifier.id);
            local.metadata = metadata;
            return this.saveMetadataForLocalExtension(local)
                .then(localExtension => {
                this.manifestCache.invalidate();
                return localExtension;
            });
        }
        saveMetadataForLocalExtension(local) {
            if (!local.metadata) {
                return Promise.resolve(local);
            }
            const manifestPath = path.join(local.location.fsPath, 'package.json');
            return pfs.readFile(manifestPath, 'utf8')
                .then(raw => parseManifest(raw))
                .then(({ manifest }) => objects_1.assign(manifest, { __metadata: local.metadata }))
                .then(manifest => pfs.writeFile(manifestPath, JSON.stringify(manifest, null, '\t')))
                .then(() => local);
        }
        getMetadata(extensionName) {
            return this.findGalleryExtensionByName(extensionName)
                .then(galleryExtension => galleryExtension ? { id: galleryExtension.identifier.uuid, publisherDisplayName: galleryExtension.publisherDisplayName, publisherId: galleryExtension.publisherId } : null);
        }
        findGalleryExtension(local) {
            if (local.identifier.uuid) {
                return this.findGalleryExtensionById(local.identifier.uuid)
                    .then(galleryExtension => galleryExtension ? galleryExtension : this.findGalleryExtensionByName(local.identifier.id));
            }
            return this.findGalleryExtensionByName(local.identifier.id);
        }
        findGalleryExtensionById(uuid) {
            return this.galleryService.query({ ids: [uuid], pageSize: 1 }).then(galleryResult => galleryResult.firstPage[0]);
        }
        findGalleryExtensionByName(name) {
            return this.galleryService.query({ names: [name], pageSize: 1 }).then(galleryResult => galleryResult.firstPage[0]);
        }
        joinErrors(errorOrErrors) {
            const errors = Array.isArray(errorOrErrors) ? errorOrErrors : [errorOrErrors];
            if (errors.length === 1) {
                return errors[0] instanceof Error ? errors[0] : new Error(errors[0]);
            }
            return errors.reduce((previousValue, currentValue) => {
                return new Error(`${previousValue.message}${previousValue.message ? ',' : ''}${currentValue instanceof Error ? currentValue.message : currentValue}`);
            }, new Error(''));
        }
        checkForDependenciesAndUninstall(extension, installed) {
            return this.preUninstallExtension(extension)
                .then(() => {
                const packedExtensions = this.getAllPackExtensionsToUninstall(extension, installed);
                if (packedExtensions.length) {
                    return this.uninstallExtensions(extension, packedExtensions, installed);
                }
                return this.uninstallExtensions(extension, [], installed);
            })
                .then(() => this.postUninstallExtension(extension), error => {
                this.postUninstallExtension(extension, new ExtensionManagementError(error instanceof Error ? error.message : error, INSTALL_ERROR_LOCAL));
                return Promise.reject(error);
            });
        }
        uninstallExtensions(extension, otherExtensionsToUninstall, installed) {
            const dependents = this.getDependents(extension, installed);
            if (dependents.length) {
                const remainingDependents = dependents.filter(dependent => extension !== dependent && otherExtensionsToUninstall.indexOf(dependent) === -1);
                if (remainingDependents.length) {
                    return Promise.reject(new Error(this.getDependentsErrorMessage(extension, remainingDependents)));
                }
            }
            return Promise.all([this.uninstallExtension(extension), ...otherExtensionsToUninstall.map(d => this.doUninstall(d))]).then(() => undefined);
        }
        getDependentsErrorMessage(extension, dependents) {
            if (dependents.length === 1) {
                return nls.localize(15, null, extension.manifest.displayName || extension.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name);
            }
            if (dependents.length === 2) {
                return nls.localize(16, null, extension.manifest.displayName || extension.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name, dependents[1].manifest.displayName || dependents[1].manifest.name);
            }
            return nls.localize(17, null, extension.manifest.displayName || extension.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name, dependents[1].manifest.displayName || dependents[1].manifest.name);
        }
        getAllPackExtensionsToUninstall(extension, installed, checked = []) {
            if (checked.indexOf(extension) !== -1) {
                return [];
            }
            checked.push(extension);
            const extensionsPack = extension.manifest.extensionPack ? extension.manifest.extensionPack : [];
            if (extensionsPack.length) {
                const packedExtensions = installed.filter(i => extensionsPack.some(id => extensionManagementUtil_1.areSameExtensions({ id }, i.identifier)));
                const packOfPackedExtensions = [];
                for (const packedExtension of packedExtensions) {
                    packOfPackedExtensions.push(...this.getAllPackExtensionsToUninstall(packedExtension, installed, checked));
                }
                return [...packedExtensions, ...packOfPackedExtensions];
            }
            return [];
        }
        getDependents(extension, installed) {
            return installed.filter(e => e.manifest.extensionDependencies && e.manifest.extensionDependencies.some(id => extensionManagementUtil_1.areSameExtensions({ id }, extension.identifier)));
        }
        doUninstall(extension) {
            return this.preUninstallExtension(extension)
                .then(() => this.uninstallExtension(extension))
                .then(() => this.postUninstallExtension(extension), error => {
                this.postUninstallExtension(extension, new ExtensionManagementError(error instanceof Error ? error.message : error, INSTALL_ERROR_LOCAL));
                return Promise.reject(error);
            });
        }
        preUninstallExtension(extension) {
            return Promise.resolve(pfs.exists(extension.location.fsPath))
                .then(exists => exists ? null : Promise.reject(new Error(nls.localize(18, null))))
                .then(() => {
                this.logService.info('Uninstalling extension:', extension.identifier.id);
                this._onUninstallExtension.fire(extension.identifier);
            });
        }
        uninstallExtension(local) {
            let promise = this.uninstallingExtensions.get(local.identifier.id);
            if (!promise) {
                // Set all versions of the extension as uninstalled
                promise = async_1.createCancelablePromise(token => this.scanUserExtensions(false)
                    .then(userExtensions => this.setUninstalled(...userExtensions.filter(u => extensionManagementUtil_1.areSameExtensions(u.identifier, local.identifier))))
                    .then(() => { this.uninstallingExtensions.delete(local.identifier.id); }));
                this.uninstallingExtensions.set(local.identifier.id, promise);
            }
            return promise;
        }
        postUninstallExtension(extension, error) {
            return __awaiter(this, void 0, void 0, function* () {
                if (error) {
                    this.logService.error('Failed to uninstall extension:', extension.identifier.id, error.message);
                }
                else {
                    this.logService.info('Successfully uninstalled extension:', extension.identifier.id);
                    // only report if extension has a mapped gallery extension. UUID identifies the gallery extension.
                    if (extension.identifier.uuid) {
                        yield this.galleryService.reportStatistic(extension.manifest.publisher, extension.manifest.name, extension.manifest.version, "uninstall" /* Uninstall */);
                    }
                }
                this.reportTelemetry('extensionGallery:uninstall', extensionManagementUtil_1.getLocalExtensionTelemetryData(extension), undefined, error);
                const errorcode = error ? error instanceof ExtensionManagementError ? error.code : ERROR_UNKNOWN : undefined;
                this._onDidUninstallExtension.fire({ identifier: extension.identifier, error: errorcode });
            });
        }
        getInstalled(type = null) {
            const promises = [];
            if (type === null || type === 0 /* System */) {
                promises.push(this.scanSystemExtensions().then(null, e => Promise.reject(new ExtensionManagementError(this.joinErrors(e).message, ERROR_SCANNING_SYS_EXTENSIONS))));
            }
            if (type === null || type === 1 /* User */) {
                promises.push(this.scanUserExtensions(true).then(null, e => Promise.reject(new ExtensionManagementError(this.joinErrors(e).message, ERROR_SCANNING_USER_EXTENSIONS))));
            }
            return Promise.all(promises).then(arrays_1.flatten, errors => Promise.reject(this.joinErrors(errors)));
        }
        scanSystemExtensions() {
            this.logService.trace('Started scanning system extensions');
            const systemExtensionsPromise = this.scanExtensions(this.systemExtensionsPath, 0 /* System */)
                .then(result => {
                this.logService.info('Scanned system extensions:', result.length);
                return result;
            });
            if (this.environmentService.isBuilt) {
                return systemExtensionsPromise;
            }
            // Scan other system extensions during development
            const devSystemExtensionsPromise = this.getDevSystemExtensionsList()
                .then(devSystemExtensionsList => {
                if (devSystemExtensionsList.length) {
                    return this.scanExtensions(this.devSystemExtensionsPath, 0 /* System */)
                        .then(result => {
                        this.logService.info('Scanned dev system extensions:', result.length);
                        return result.filter(r => devSystemExtensionsList.some(id => extensionManagementUtil_1.areSameExtensions(r.identifier, { id })));
                    });
                }
                else {
                    return [];
                }
            });
            return Promise.all([systemExtensionsPromise, devSystemExtensionsPromise])
                .then(([systemExtensions, devSystemExtensions]) => [...systemExtensions, ...devSystemExtensions]);
        }
        scanUserExtensions(excludeOutdated) {
            this.logService.trace('Started scanning user extensions');
            return Promise.all([this.getUninstalledExtensions(), this.scanExtensions(this.extensionsPath, 1 /* User */)])
                .then(([uninstalled, extensions]) => {
                extensions = extensions.filter(e => !uninstalled[new extensions_1.ExtensionIdentifierWithVersion(e.identifier, e.manifest.version).key()]);
                if (excludeOutdated) {
                    const byExtension = extensionManagementUtil_1.groupByExtension(extensions, e => e.identifier);
                    extensions = byExtension.map(p => p.sort((a, b) => semver.rcompare(a.manifest.version, b.manifest.version))[0]);
                }
                this.logService.info('Scanned user extensions:', extensions.length);
                return extensions;
            });
        }
        scanExtensions(root, type) {
            const limiter = new async_1.Limiter(10);
            return pfs.readdir(root)
                .then(extensionsFolders => Promise.all(extensionsFolders.map(extensionFolder => limiter.queue(() => this.scanExtension(extensionFolder, root, type)))))
                .then(extensions => extensions.filter(e => e && e.identifier));
        }
        scanExtension(folderName, root, type) {
            if (type === 1 /* User */ && folderName.indexOf('.') === 0) { // Do not consider user extension folder starting with `.`
                return Promise.resolve(null);
            }
            const extensionPath = path.join(root, folderName);
            return pfs.readdir(extensionPath)
                .then(children => readManifest(extensionPath)
                .then(({ manifest, metadata }) => {
                const readme = children.filter(child => /^readme(\.txt|\.md|)$/i.test(child))[0];
                const readmeUrl = readme ? uri_1.URI.file(path.join(extensionPath, readme)) : null;
                const changelog = children.filter(child => /^changelog(\.txt|\.md|)$/i.test(child))[0];
                const changelogUrl = changelog ? uri_1.URI.file(path.join(extensionPath, changelog)) : null;
                const identifier = { id: extensionManagementUtil_1.getGalleryExtensionId(manifest.publisher, manifest.name), uuid: metadata ? metadata.id : null };
                return { type, identifier, manifest, metadata, location: uri_1.URI.file(extensionPath), readmeUrl, changelogUrl };
            }))
                .then(undefined, () => null);
        }
        removeDeprecatedExtensions() {
            return this.removeUninstalledExtensions()
                .then(() => this.removeOutdatedExtensions());
        }
        removeUninstalledExtensions() {
            return this.getUninstalledExtensions()
                .then(uninstalled => this.scanExtensions(this.extensionsPath, 1 /* User */) // All user extensions
                .then(extensions => {
                const toRemove = extensions.filter(e => uninstalled[new extensions_1.ExtensionIdentifierWithVersion(e.identifier, e.manifest.version).key()]);
                return Promise.all(toRemove.map(e => this.extensionLifecycle.postUninstall(e).then(() => this.removeUninstalledExtension(e))));
            })).then(() => undefined);
        }
        removeOutdatedExtensions() {
            return this.scanExtensions(this.extensionsPath, 1 /* User */) // All user extensions
                .then(extensions => {
                const toRemove = [];
                // Outdated extensions
                const byExtension = extensionManagementUtil_1.groupByExtension(extensions, e => e.identifier);
                toRemove.push(...arrays_1.flatten(byExtension.map(p => p.sort((a, b) => semver.rcompare(a.manifest.version, b.manifest.version)).slice(1))));
                return Promise.all(toRemove.map(extension => this.removeExtension(extension, 'outdated')));
            }).then(() => undefined);
        }
        removeUninstalledExtension(extension) {
            return this.removeExtension(extension, 'uninstalled')
                .then(() => this.withUninstalledExtensions(uninstalled => delete uninstalled[new extensions_1.ExtensionIdentifierWithVersion(extension.identifier, extension.manifest.version).key()]))
                .then(() => undefined);
        }
        removeExtension(extension, type) {
            this.logService.trace(`Deleting ${type} extension from disk`, extension.identifier.id, extension.location.fsPath);
            return pfs.rimraf(extension.location.fsPath).then(() => this.logService.info('Deleted from disk', extension.identifier.id, extension.location.fsPath));
        }
        isUninstalled(identfier) {
            return this.filterUninstalled(identfier).then(uninstalled => uninstalled.length === 1);
        }
        filterUninstalled(...identifiers) {
            return this.withUninstalledExtensions(allUninstalled => {
                const uninstalled = [];
                for (const identifier of identifiers) {
                    if (!!allUninstalled[identifier.key()]) {
                        uninstalled.push(identifier.key());
                    }
                }
                return uninstalled;
            });
        }
        setUninstalled(...extensions) {
            const ids = extensions.map(e => new extensions_1.ExtensionIdentifierWithVersion(e.identifier, e.manifest.version));
            return this.withUninstalledExtensions(uninstalled => objects_1.assign(uninstalled, ids.reduce((result, id) => { result[id.key()] = true; return result; }, {})));
        }
        unsetUninstalled(extensionIdentifier) {
            return this.withUninstalledExtensions(uninstalled => delete uninstalled[extensionIdentifier.key()]);
        }
        getUninstalledExtensions() {
            return this.withUninstalledExtensions(uninstalled => uninstalled);
        }
        withUninstalledExtensions(fn) {
            return __awaiter(this, void 0, void 0, function* () {
                return yield this.uninstalledFileLimiter.queue(() => {
                    let result = null;
                    return pfs.readFile(this.uninstalledPath, 'utf8')
                        .then(undefined, err => err.code === 'ENOENT' ? Promise.resolve('{}') : Promise.reject(err))
                        .then(raw => { try {
                        return JSON.parse(raw);
                    }
                    catch (e) {
                        return {};
                    } })
                        .then(uninstalled => { result = fn(uninstalled); return uninstalled; })
                        .then(uninstalled => {
                        if (Object.keys(uninstalled).length === 0) {
                            return pfs.rimraf(this.uninstalledPath);
                        }
                        else {
                            const raw = JSON.stringify(uninstalled);
                            return pfs.writeFile(this.uninstalledPath, raw);
                        }
                    })
                        .then(() => result);
                });
            });
        }
        getExtensionsReport() {
            const now = new Date().getTime();
            if (!this.reportedExtensions || now - this.lastReportTimestamp > 1000 * 60 * 5) { // 5 minute cache freshness
                this.reportedExtensions = this.updateReportCache();
                this.lastReportTimestamp = now;
            }
            return this.reportedExtensions;
        }
        updateReportCache() {
            this.logService.trace('ExtensionManagementService.refreshReportedCache');
            return this.galleryService.getExtensionsReport()
                .then(result => {
                this.logService.trace(`ExtensionManagementService.refreshReportedCache - got ${result.length} reported extensions from service`);
                return result;
            }, err => {
                this.logService.trace('ExtensionManagementService.refreshReportedCache - failed to get extension report');
                return [];
            });
        }
        get devSystemExtensionsPath() {
            if (!this._devSystemExtensionsPath) {
                this._devSystemExtensionsPath = path.normalize(path.join(amd_1.getPathFromAmdModule(require, ''), '..', '.build', 'builtInExtensions'));
            }
            return this._devSystemExtensionsPath;
        }
        get devSystemExtensionsFilePath() {
            if (!this._devSystemExtensionsFilePath) {
                this._devSystemExtensionsFilePath = path.normalize(path.join(amd_1.getPathFromAmdModule(require, ''), '..', 'build', 'builtInExtensions.json'));
            }
            return this._devSystemExtensionsFilePath;
        }
        getDevSystemExtensionsList() {
            return pfs.readFile(this.devSystemExtensionsFilePath, 'utf8')
                .then(raw => {
                const parsed = JSON.parse(raw);
                return parsed.map(({ name }) => name);
            });
        }
        toNonCancellablePromise(promise) {
            return new Promise((c, e) => promise.then(result => c(result), error => e(error)));
        }
        reportTelemetry(eventName, extensionData, duration, error) {
            const errorcode = error ? error instanceof ExtensionManagementError ? error.code : ERROR_UNKNOWN : undefined;
            /* __GDPR__
                "extensionGallery:install" : {
                    "success": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true },
                    "duration" : { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true },
                    "errorcode": { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" },
                    "recommendationReason": { "retiredFromVersion": "1.23.0", "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
                    "${include}": [
                        "${GalleryExtensionTelemetryData}"
                    ]
                }
            */
            /* __GDPR__
                "extensionGallery:uninstall" : {
                    "success": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true },
                    "duration" : { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true },
                    "errorcode": { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" },
                    "${include}": [
                        "${GalleryExtensionTelemetryData}"
                    ]
                }
            */
            /* __GDPR__
                "extensionGallery:update" : {
                    "success": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true },
                    "duration" : { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true },
                    "errorcode": { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" },
                    "${include}": [
                        "${GalleryExtensionTelemetryData}"
                    ]
                }
            */
            this.telemetryService.publicLog(eventName, objects_1.assign(extensionData, { success: !error, duration, errorcode }));
        }
    };
    ExtensionManagementService = __decorate([
        __param(1, environment_1.IEnvironmentService),
        __param(2, configuration_1.IConfigurationService),
        __param(3, extensionManagement_1.IExtensionGalleryService),
        __param(4, log_1.ILogService),
        __param(5, instantiation_1.optional(download_1.IDownloadService)),
        __param(6, telemetry_1.ITelemetryService)
    ], ExtensionManagementService);
    exports.ExtensionManagementService = ExtensionManagementService;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/








define(__m[42/*vs/base/node/request*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/types*/,52/*url*/,29/*fs*/,7/*vs/base/common/objects*/,92/*zlib*/,25/*vs/base/common/errors*/]), function (require, exports, types_1, url_1, fs_1, objects_1, zlib_1, errors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function getNodeRequest(options) {
        return __awaiter(this, void 0, void 0, function* () {
            const endpoint = url_1.parse(options.url);
            const module = endpoint.protocol === 'https:' ? yield new Promise((resolve_1, reject_1) => { require(['https'], resolve_1, reject_1); }) : yield new Promise((resolve_2, reject_2) => { require(['http'], resolve_2, reject_2); });
            return module.request;
        });
    }
    function request(options, token) {
        let req;
        const rawRequestPromise = options.getRawRequest
            ? Promise.resolve(options.getRawRequest(options))
            : Promise.resolve(getNodeRequest(options));
        return rawRequestPromise.then(rawRequest => {
            return new Promise((c, e) => {
                const endpoint = url_1.parse(options.url);
                const opts = {
                    hostname: endpoint.hostname,
                    port: endpoint.port ? parseInt(endpoint.port) : (endpoint.protocol === 'https:' ? 443 : 80),
                    protocol: endpoint.protocol,
                    path: endpoint.path,
                    method: options.type || 'GET',
                    headers: options.headers,
                    agent: options.agent,
                    rejectUnauthorized: types_1.isBoolean(options.strictSSL) ? options.strictSSL : true
                };
                if (options.user && options.password) {
                    opts.auth = options.user + ':' + options.password;
                }
                req = rawRequest(opts, (res) => {
                    const followRedirects = types_1.isNumber(options.followRedirects) ? options.followRedirects : 3;
                    if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && followRedirects > 0 && res.headers['location']) {
                        request(objects_1.assign({}, options, {
                            url: res.headers['location'],
                            followRedirects: followRedirects - 1
                        }), token).then(c, e);
                    }
                    else {
                        let stream = res;
                        if (res.headers['content-encoding'] === 'gzip') {
                            stream = stream.pipe(zlib_1.createGunzip());
                        }
                        c({ res, stream });
                    }
                });
                req.on('error', e);
                if (options.timeout) {
                    req.setTimeout(options.timeout);
                }
                if (options.data) {
                    if (typeof options.data === 'string') {
                        req.write(options.data);
                    }
                    else {
                        options.data.pipe(req);
                        return;
                    }
                }
                req.end();
                token.onCancellationRequested(() => {
                    req.abort();
                    e(errors_1.canceled());
                });
            });
        });
    }
    exports.request = request;
    function isSuccess(context) {
        return (context.res.statusCode && context.res.statusCode >= 200 && context.res.statusCode < 300) || context.res.statusCode === 1223;
    }
    function hasNoContent(context) {
        return context.res.statusCode === 204;
    }
    function download(filePath, context) {
        return new Promise((c, e) => {
            const out = fs_1.createWriteStream(filePath);
            out.once('finish', () => c(undefined));
            context.stream.once('error', e);
            context.stream.pipe(out);
        });
    }
    exports.download = download;
    function asText(context) {
        return new Promise((c, e) => {
            if (!isSuccess(context)) {
                return e('Server returned ' + context.res.statusCode);
            }
            if (hasNoContent(context)) {
                return c(null);
            }
            const buffer = [];
            context.stream.on('data', (d) => buffer.push(d));
            context.stream.on('end', () => c(buffer.join('')));
            context.stream.on('error', e);
        });
    }
    exports.asText = asText;
    function asJson(context) {
        return new Promise((c, e) => {
            if (!isSuccess(context)) {
                return e('Server returned ' + context.res.statusCode);
            }
            if (hasNoContent(context)) {
                return c(null);
            }
            const buffer = [];
            context.stream.on('data', (d) => buffer.push(d));
            context.stream.on('end', () => {
                try {
                    c(JSON.parse(buffer.join('')));
                }
                catch (err) {
                    e(err);
                }
            });
            context.stream.on('error', e);
        });
    }
    exports.asJson = asJson;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[77/*vs/platform/extensionManagement/node/extensionGalleryService*/], __M([1/*require*/,0/*exports*/,26/*os*/,3/*vs/base/common/path*/,17/*vs/base/common/arrays*/,25/*vs/base/common/errors*/,23/*vs/platform/extensionManagement/common/extensionManagement*/,13/*vs/platform/extensionManagement/common/extensionManagementUtil*/,7/*vs/base/common/objects*/,40/*vs/platform/request/node/request*/,27/*vs/platform/telemetry/common/telemetry*/,42/*vs/base/node/request*/,21/*vs/platform/product/node/package*/,22/*vs/platform/product/node/product*/,41/*vs/platform/extensions/node/extensionValidator*/,14/*vs/platform/environment/common/environment*/,11/*vs/base/node/pfs*/,38/*vs/base/node/extfs*/,43/*vs/base/common/uuid*/,71/*vs/base/common/map*/,45/*vs/base/common/cancellation*/,5/*vs/platform/log/common/log*/]), function (require, exports, os_1, path, arrays_1, errors_1, extensionManagement_1, extensionManagementUtil_1, objects_1, request_1, telemetry_1, request_2, package_1, product_1, extensionValidator_1, environment_1, pfs_1, extfs_1, uuid_1, map_1, cancellation_1, log_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var Flags;
    (function (Flags) {
        Flags[Flags["None"] = 0] = "None";
        Flags[Flags["IncludeVersions"] = 1] = "IncludeVersions";
        Flags[Flags["IncludeFiles"] = 2] = "IncludeFiles";
        Flags[Flags["IncludeCategoryAndTags"] = 4] = "IncludeCategoryAndTags";
        Flags[Flags["IncludeSharedAccounts"] = 8] = "IncludeSharedAccounts";
        Flags[Flags["IncludeVersionProperties"] = 16] = "IncludeVersionProperties";
        Flags[Flags["ExcludeNonValidated"] = 32] = "ExcludeNonValidated";
        Flags[Flags["IncludeInstallationTargets"] = 64] = "IncludeInstallationTargets";
        Flags[Flags["IncludeAssetUri"] = 128] = "IncludeAssetUri";
        Flags[Flags["IncludeStatistics"] = 256] = "IncludeStatistics";
        Flags[Flags["IncludeLatestVersionOnly"] = 512] = "IncludeLatestVersionOnly";
        Flags[Flags["Unpublished"] = 4096] = "Unpublished";
    })(Flags || (Flags = {}));
    function flagsToString(...flags) {
        return String(flags.reduce((r, f) => r | f, 0));
    }
    var FilterType;
    (function (FilterType) {
        FilterType[FilterType["Tag"] = 1] = "Tag";
        FilterType[FilterType["ExtensionId"] = 4] = "ExtensionId";
        FilterType[FilterType["Category"] = 5] = "Category";
        FilterType[FilterType["ExtensionName"] = 7] = "ExtensionName";
        FilterType[FilterType["Target"] = 8] = "Target";
        FilterType[FilterType["Featured"] = 9] = "Featured";
        FilterType[FilterType["SearchText"] = 10] = "SearchText";
        FilterType[FilterType["ExcludeWithFlags"] = 12] = "ExcludeWithFlags";
    })(FilterType || (FilterType = {}));
    const AssetType = {
        Icon: 'Microsoft.VisualStudio.Services.Icons.Default',
        Details: 'Microsoft.VisualStudio.Services.Content.Details',
        Changelog: 'Microsoft.VisualStudio.Services.Content.Changelog',
        Manifest: 'Microsoft.VisualStudio.Code.Manifest',
        VSIX: 'Microsoft.VisualStudio.Services.VSIXPackage',
        License: 'Microsoft.VisualStudio.Services.Content.License',
        Repository: 'Microsoft.VisualStudio.Services.Links.Source'
    };
    const PropertyType = {
        Dependency: 'Microsoft.VisualStudio.Code.ExtensionDependencies',
        ExtensionPack: 'Microsoft.VisualStudio.Code.ExtensionPack',
        Engine: 'Microsoft.VisualStudio.Code.Engine',
        LocalizedLanguages: 'Microsoft.VisualStudio.Code.LocalizedLanguages'
    };
    const DefaultPageSize = 10;
    const DefaultQueryState = {
        pageNumber: 1,
        pageSize: DefaultPageSize,
        sortBy: 0 /* NoneOrRelevance */,
        sortOrder: 0 /* Default */,
        flags: Flags.None,
        criteria: [],
        assetTypes: []
    };
    class Query {
        constructor(state = DefaultQueryState) {
            this.state = state;
        }
        get pageNumber() { return this.state.pageNumber; }
        get pageSize() { return this.state.pageSize; }
        get sortBy() { return this.state.sortBy; }
        get sortOrder() { return this.state.sortOrder; }
        get flags() { return this.state.flags; }
        withPage(pageNumber, pageSize = this.state.pageSize) {
            return new Query(objects_1.assign({}, this.state, { pageNumber, pageSize }));
        }
        withFilter(filterType, ...values) {
            const criteria = [
                ...this.state.criteria,
                ...values.map(value => ({ filterType, value }))
            ];
            return new Query(objects_1.assign({}, this.state, { criteria }));
        }
        withSortBy(sortBy) {
            return new Query(objects_1.assign({}, this.state, { sortBy }));
        }
        withSortOrder(sortOrder) {
            return new Query(objects_1.assign({}, this.state, { sortOrder }));
        }
        withFlags(...flags) {
            return new Query(objects_1.assign({}, this.state, { flags: flags.reduce((r, f) => r | f, 0) }));
        }
        withAssetTypes(...assetTypes) {
            return new Query(objects_1.assign({}, this.state, { assetTypes }));
        }
        get raw() {
            const { criteria, pageNumber, pageSize, sortBy, sortOrder, flags, assetTypes } = this.state;
            const filters = [{ criteria, pageNumber, pageSize, sortBy, sortOrder }];
            return { filters, assetTypes, flags };
        }
        get searchText() {
            const criterium = this.state.criteria.filter(criterium => criterium.filterType === FilterType.SearchText)[0];
            return criterium && criterium.value ? criterium.value : '';
        }
    }
    function getStatistic(statistics, name) {
        const result = (statistics || []).filter(s => s.statisticName === name)[0];
        return result ? result.value : 0;
    }
    function getCoreTranslationAssets(version) {
        const coreTranslationAssetPrefix = 'Microsoft.VisualStudio.Code.Translation.';
        const result = version.files.filter(f => f.assetType.indexOf(coreTranslationAssetPrefix) === 0);
        return result.reduce((result, file) => {
            result[file.assetType.substring(coreTranslationAssetPrefix.length)] = getVersionAsset(version, file.assetType);
            return result;
        }, {});
    }
    function getRepositoryAsset(version) {
        if (version.properties) {
            const results = version.properties.filter(p => p.key === AssetType.Repository);
            const gitRegExp = new RegExp('((git|ssh|http(s)?)|(git@[\w\.]+))(:(//)?)([\w\.@\:/\-~]+)(\.git)(/)?');
            const uri = results.filter(r => gitRegExp.test(r.value))[0];
            return uri ? { uri: uri.value, fallbackUri: uri.value } : null;
        }
        return getVersionAsset(version, AssetType.Repository);
    }
    function getDownloadAsset(version) {
        return {
            uri: `${version.fallbackAssetUri}/${AssetType.VSIX}?redirect=true`,
            fallbackUri: `${version.fallbackAssetUri}/${AssetType.VSIX}`
        };
    }
    function getIconAsset(version) {
        const asset = getVersionAsset(version, AssetType.Icon);
        if (asset) {
            return asset;
        }
        const uri = require.toUrl('./media/defaultIcon.png');
        return { uri, fallbackUri: uri };
    }
    function getVersionAsset(version, type) {
        const result = version.files.filter(f => f.assetType === type)[0];
        return result ? { uri: `${version.assetUri}/${type}`, fallbackUri: `${version.fallbackAssetUri}/${type}` } : null;
    }
    function getExtensions(version, property) {
        const values = version.properties ? version.properties.filter(p => p.key === property) : [];
        const value = values.length > 0 && values[0].value;
        return value ? value.split(',').map(v => extensionManagementUtil_1.adoptToGalleryExtensionId(v)) : [];
    }
    function getEngine(version) {
        const values = version.properties ? version.properties.filter(p => p.key === PropertyType.Engine) : [];
        return (values.length > 0 && values[0].value) || '';
    }
    function getLocalizedLanguages(version) {
        const values = version.properties ? version.properties.filter(p => p.key === PropertyType.LocalizedLanguages) : [];
        const value = (values.length > 0 && values[0].value) || '';
        return value ? value.split(',') : [];
    }
    function getIsPreview(flags) {
        return flags.indexOf('preview') !== -1;
    }
    function toExtension(galleryExtension, version, index, query, querySource) {
        const assets = {
            manifest: getVersionAsset(version, AssetType.Manifest),
            readme: getVersionAsset(version, AssetType.Details),
            changelog: getVersionAsset(version, AssetType.Changelog),
            license: getVersionAsset(version, AssetType.License),
            repository: getRepositoryAsset(version),
            download: getDownloadAsset(version),
            icon: getIconAsset(version),
            coreTranslations: getCoreTranslationAssets(version)
        };
        return {
            identifier: {
                id: extensionManagementUtil_1.getGalleryExtensionId(galleryExtension.publisher.publisherName, galleryExtension.extensionName),
                uuid: galleryExtension.extensionId
            },
            name: galleryExtension.extensionName,
            version: version.version,
            date: version.lastUpdated,
            displayName: galleryExtension.displayName,
            publisherId: galleryExtension.publisher.publisherId,
            publisher: galleryExtension.publisher.publisherName,
            publisherDisplayName: galleryExtension.publisher.displayName,
            description: galleryExtension.shortDescription || '',
            installCount: getStatistic(galleryExtension.statistics, 'install') + getStatistic(galleryExtension.statistics, 'updateCount'),
            rating: getStatistic(galleryExtension.statistics, 'averagerating'),
            ratingCount: getStatistic(galleryExtension.statistics, 'ratingcount'),
            assets,
            properties: {
                dependencies: getExtensions(version, PropertyType.Dependency),
                extensionPack: getExtensions(version, PropertyType.ExtensionPack),
                engine: getEngine(version),
                localizedLanguages: getLocalizedLanguages(version)
            },
            /* __GDPR__FRAGMENT__
                "GalleryExtensionTelemetryData2" : {
                    "index" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
                    "searchText": { "classification": "CustomerContent", "purpose": "FeatureInsight" },
                    "querySource": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
                }
            */
            telemetryData: {
                index: ((query.pageNumber - 1) * query.pageSize) + index,
                searchText: query.searchText,
                querySource
            },
            preview: getIsPreview(galleryExtension.flags)
        };
    }
    let ExtensionGalleryService = class ExtensionGalleryService {
        constructor(requestService, logService, environmentService, telemetryService) {
            this.requestService = requestService;
            this.logService = logService;
            this.environmentService = environmentService;
            this.telemetryService = telemetryService;
            const config = product_1.default.extensionsGallery;
            this.extensionsGalleryUrl = config && config.serviceUrl;
            this.extensionsControlUrl = config && config.controlUrl;
            this.commonHeadersPromise = resolveMarketplaceHeaders(this.environmentService);
        }
        api(path = '') {
            return `${this.extensionsGalleryUrl}${path}`;
        }
        isEnabled() {
            return !!this.extensionsGalleryUrl;
        }
        getCompatibleExtension(arg1, version) {
            const extension = extensionManagement_1.isIExtensionIdentifier(arg1) ? null : arg1;
            if (extension && extension.properties.engine && extensionValidator_1.isEngineValid(extension.properties.engine)) {
                return Promise.resolve(extension);
            }
            const { id, uuid } = extension ? extension.identifier : arg1;
            let query = new Query()
                .withFlags(Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeFiles, Flags.IncludeVersionProperties, Flags.ExcludeNonValidated)
                .withPage(1, 1)
                .withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code')
                .withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished));
            if (uuid) {
                query = query.withFilter(FilterType.ExtensionId, uuid);
            }
            else {
                query = query.withFilter(FilterType.ExtensionName, id);
            }
            return this.queryGallery(query, cancellation_1.CancellationToken.None)
                .then(({ galleryExtensions }) => {
                const [rawExtension] = galleryExtensions;
                if (!rawExtension || !rawExtension.versions.length) {
                    return null;
                }
                if (version) {
                    const versionAsset = rawExtension.versions.filter(v => v.version === version)[0];
                    if (versionAsset) {
                        const extension = toExtension(rawExtension, versionAsset, 0, query);
                        if (extension.properties.engine && extensionValidator_1.isEngineValid(extension.properties.engine)) {
                            return extension;
                        }
                    }
                    return null;
                }
                return this.getLastValidExtensionVersion(rawExtension, rawExtension.versions)
                    .then(rawVersion => {
                    if (rawVersion) {
                        return toExtension(rawExtension, rawVersion, 0, query);
                    }
                    return null;
                });
            });
        }
        query(options = {}) {
            if (!this.isEnabled()) {
                return Promise.reject(new Error('No extension gallery service configured.'));
            }
            const type = options.names ? 'ids' : (options.text ? 'text' : 'all');
            let text = options.text || '';
            const pageSize = objects_1.getOrDefault(options, o => o.pageSize, 50);
            /* __GDPR__
                "galleryService:query" : {
                    "type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
                    "text": { "classification": "CustomerContent", "purpose": "FeatureInsight" }
                }
            */
            this.telemetryService.publicLog('galleryService:query', { type, text });
            let query = new Query()
                .withFlags(Flags.IncludeLatestVersionOnly, Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeFiles, Flags.IncludeVersionProperties)
                .withPage(1, pageSize)
                .withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code')
                .withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished));
            if (text) {
                // Use category filter instead of "category:themes"
                text = text.replace(/\bcategory:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedCategory, category) => {
                    query = query.withFilter(FilterType.Category, category || quotedCategory);
                    return '';
                });
                // Use tag filter instead of "tag:debuggers"
                text = text.replace(/\btag:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedTag, tag) => {
                    query = query.withFilter(FilterType.Tag, tag || quotedTag);
                    return '';
                });
                text = text.trim();
                if (text) {
                    text = text.length < 200 ? text : text.substring(0, 200);
                    query = query.withFilter(FilterType.SearchText, text);
                }
                query = query.withSortBy(0 /* NoneOrRelevance */);
            }
            else if (options.ids) {
                query = query.withFilter(FilterType.ExtensionId, ...options.ids);
            }
            else if (options.names) {
                query = query.withFilter(FilterType.ExtensionName, ...options.names);
            }
            else {
                query = query.withSortBy(4 /* InstallCount */);
            }
            if (typeof options.sortBy === 'number') {
                query = query.withSortBy(options.sortBy);
            }
            if (typeof options.sortOrder === 'number') {
                query = query.withSortOrder(options.sortOrder);
            }
            return this.queryGallery(query, cancellation_1.CancellationToken.None).then(({ galleryExtensions, total }) => {
                const extensions = galleryExtensions.map((e, index) => toExtension(e, e.versions[0], index, query, options.source));
                const pageSize = query.pageSize;
                const getPage = (pageIndex, ct) => {
                    if (ct.isCancellationRequested) {
                        return Promise.reject(errors_1.canceled());
                    }
                    const nextPageQuery = query.withPage(pageIndex + 1);
                    return this.queryGallery(nextPageQuery, ct)
                        .then(({ galleryExtensions }) => galleryExtensions.map((e, index) => toExtension(e, e.versions[0], index, nextPageQuery, options.source)));
                };
                return { firstPage: extensions, total, pageSize, getPage };
            });
        }
        queryGallery(query, token) {
            if (!this.isEnabled()) {
                return Promise.reject(new Error('No extension gallery service configured.'));
            }
            return this.commonHeadersPromise.then(commonHeaders => {
                const data = JSON.stringify(query.raw);
                const headers = objects_1.assign({}, commonHeaders, {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json;api-version=3.0-preview.1',
                    'Accept-Encoding': 'gzip',
                    'Content-Length': data.length
                });
                return this.requestService.request({
                    type: 'POST',
                    url: this.api('/extensionquery'),
                    data,
                    headers
                }, token).then(context => {
                    if (context.res.statusCode && context.res.statusCode >= 400 && context.res.statusCode < 500) {
                        return { galleryExtensions: [], total: 0 };
                    }
                    return request_2.asJson(context).then(result => {
                        if (result) {
                            const r = result.results[0];
                            const galleryExtensions = r.extensions;
                            const resultCount = r.resultMetadata && r.resultMetadata.filter(m => m.metadataType === 'ResultCount')[0];
                            const total = resultCount && resultCount.metadataItems.filter(i => i.name === 'TotalCount')[0].count || 0;
                            return { galleryExtensions, total };
                        }
                        return { galleryExtensions: [], total: 0 };
                    });
                });
            });
        }
        reportStatistic(publisher, name, version, type) {
            if (!this.isEnabled()) {
                return Promise.resolve(undefined);
            }
            return this.commonHeadersPromise.then(commonHeaders => {
                const headers = Object.assign({}, commonHeaders, { Accept: '*/*;api-version=4.0-preview.1' });
                return this.requestService.request({
                    type: 'POST',
                    url: this.api(`/publishers/${publisher}/extensions/${name}/${version}/stats?statType=${type}`),
                    headers
                }, cancellation_1.CancellationToken.None).then(undefined, () => undefined);
            });
        }
        download(extension, operation) {
            this.logService.trace('ExtensionGalleryService#download', extension.identifier.id);
            const zipPath = path.join(os_1.tmpdir(), uuid_1.generateUuid());
            const data = extensionManagementUtil_1.getGalleryExtensionTelemetryData(extension);
            const startTime = new Date().getTime();
            /* __GDPR__
                "galleryService:downloadVSIX" : {
                    "duration": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true },
                    "${include}": [
                        "${GalleryExtensionTelemetryData}"
                    ]
                }
            */
            const log = (duration) => this.telemetryService.publicLog('galleryService:downloadVSIX', objects_1.assign(data, { duration }));
            const operationParam = operation === 1 /* Install */ ? 'install' : operation === 2 /* Update */ ? 'update' : '';
            const downloadAsset = operationParam ? {
                uri: `${extension.assets.download.uri}&${operationParam}=true`,
                fallbackUri: `${extension.assets.download.fallbackUri}?${operationParam}=true`
            } : extension.assets.download;
            return this.getAsset(downloadAsset)
                .then(context => request_2.download(zipPath, context))
                .then(() => log(new Date().getTime() - startTime))
                .then(() => zipPath);
        }
        getReadme(extension, token) {
            if (extension.assets.readme) {
                return this.getAsset(extension.assets.readme, {}, token)
                    .then(context => request_2.asText(context))
                    .then(content => content || '');
            }
            return Promise.resolve('');
        }
        getManifest(extension, token) {
            if (extension.assets.manifest) {
                return this.getAsset(extension.assets.manifest, {}, token)
                    .then(request_2.asText)
                    .then(JSON.parse);
            }
            return Promise.resolve(null);
        }
        getCoreTranslation(extension, languageId) {
            const asset = extension.assets.coreTranslations[languageId.toUpperCase()];
            if (asset) {
                return this.getAsset(asset)
                    .then(request_2.asText)
                    .then(JSON.parse);
            }
            return Promise.resolve(null);
        }
        getChangelog(extension, token) {
            if (extension.assets.changelog) {
                return this.getAsset(extension.assets.changelog, {}, token)
                    .then(context => request_2.asText(context))
                    .then(content => content || '');
            }
            return Promise.resolve('');
        }
        loadAllDependencies(extensions, token) {
            return this.getDependenciesReccursively(extensions.map(e => e.id), [], token);
        }
        getAllVersions(extension, compatible) {
            let query = new Query()
                .withFlags(Flags.IncludeVersions, Flags.IncludeFiles, Flags.IncludeVersionProperties, Flags.ExcludeNonValidated)
                .withPage(1, 1)
                .withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code')
                .withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished));
            if (extension.identifier.uuid) {
                query = query.withFilter(FilterType.ExtensionId, extension.identifier.uuid);
            }
            else {
                query = query.withFilter(FilterType.ExtensionName, extension.identifier.id);
            }
            return this.queryGallery(query, cancellation_1.CancellationToken.None).then(({ galleryExtensions }) => {
                if (galleryExtensions.length) {
                    if (compatible) {
                        return Promise.all(galleryExtensions[0].versions.map(v => this.getEngine(v).then(engine => extensionValidator_1.isEngineValid(engine) ? v : null)))
                            .then(versions => versions
                            .filter(v => !!v)
                            .map(v => ({ version: v.version, date: v.lastUpdated })));
                    }
                    else {
                        return galleryExtensions[0].versions.map(v => ({ version: v.version, date: v.lastUpdated }));
                    }
                }
                return [];
            });
        }
        loadDependencies(extensionNames, token) {
            if (!extensionNames || extensionNames.length === 0) {
                return Promise.resolve([]);
            }
            let query = new Query()
                .withFlags(Flags.IncludeLatestVersionOnly, Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeFiles, Flags.IncludeVersionProperties)
                .withPage(1, extensionNames.length)
                .withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code')
                .withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished))
                .withAssetTypes(AssetType.Icon, AssetType.License, AssetType.Details, AssetType.Manifest, AssetType.VSIX)
                .withFilter(FilterType.ExtensionName, ...extensionNames);
            return this.queryGallery(query, token).then(result => {
                const dependencies = [];
                const ids = [];
                for (let index = 0; index < result.galleryExtensions.length; index++) {
                    const rawExtension = result.galleryExtensions[index];
                    if (ids.indexOf(rawExtension.extensionId) === -1) {
                        dependencies.push(toExtension(rawExtension, rawExtension.versions[0], index, query, 'dependencies'));
                        ids.push(rawExtension.extensionId);
                    }
                }
                return dependencies;
            });
        }
        getDependenciesReccursively(toGet, result, token) {
            if (!toGet || !toGet.length) {
                return Promise.resolve(result);
            }
            toGet = result.length ? toGet.filter(e => !ExtensionGalleryService.hasExtensionByName(result, e)) : toGet;
            if (!toGet.length) {
                return Promise.resolve(result);
            }
            return this.loadDependencies(toGet, token)
                .then(loadedDependencies => {
                const dependenciesSet = new Set();
                for (const dep of loadedDependencies) {
                    if (dep.properties.dependencies) {
                        dep.properties.dependencies.forEach(d => dependenciesSet.add(d));
                    }
                }
                result = arrays_1.distinct(result.concat(loadedDependencies), d => d.identifier.uuid);
                const dependencies = [];
                dependenciesSet.forEach(d => !ExtensionGalleryService.hasExtensionByName(result, d) && dependencies.push(d));
                return this.getDependenciesReccursively(dependencies, result, token);
            });
        }
        getAsset(asset, options = {}, token = cancellation_1.CancellationToken.None) {
            return this.commonHeadersPromise.then(commonHeaders => {
                const baseOptions = { type: 'GET' };
                const headers = objects_1.assign({}, commonHeaders, options.headers || {});
                options = objects_1.assign({}, options, baseOptions, { headers });
                const url = asset.uri;
                const fallbackUrl = asset.fallbackUri;
                const firstOptions = objects_1.assign({}, options, { url });
                return this.requestService.request(firstOptions, token)
                    .then(context => {
                    if (context.res.statusCode === 200) {
                        return Promise.resolve(context);
                    }
                    return request_2.asText(context)
                        .then(message => Promise.reject(new Error(`Expected 200, got back ${context.res.statusCode} instead.\n\n${message}`)));
                })
                    .then(undefined, err => {
                    if (errors_1.isPromiseCanceledError(err)) {
                        return Promise.reject(err);
                    }
                    const message = errors_1.getErrorMessage(err);
                    /* __GDPR__
                        "galleryService:requestError" : {
                            "url" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
                            "cdn": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
                            "message": { "classification": "CallstackOrException", "purpose": "FeatureInsight" }
                        }
                    */
                    this.telemetryService.publicLog('galleryService:requestError', { url, cdn: true, message });
                    /* __GDPR__
                        "galleryService:cdnFallback" : {
                            "url" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
                            "message": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
                        }
                    */
                    this.telemetryService.publicLog('galleryService:cdnFallback', { url, message });
                    const fallbackOptions = objects_1.assign({}, options, { url: fallbackUrl });
                    return this.requestService.request(fallbackOptions, token).then(undefined, err => {
                        if (errors_1.isPromiseCanceledError(err)) {
                            return Promise.reject(err);
                        }
                        const message = errors_1.getErrorMessage(err);
                        /* __GDPR__
                            "galleryService:requestError" : {
                                "url" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
                                "cdn": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
                                "message": { "classification": "CallstackOrException", "purpose": "FeatureInsight" }
                            }
                        */
                        this.telemetryService.publicLog('galleryService:requestError', { url: fallbackUrl, cdn: false, message });
                        return Promise.reject(err);
                    });
                });
            });
        }
        getLastValidExtensionVersion(extension, versions) {
            const version = this.getLastValidExtensionVersionFromProperties(extension, versions);
            if (version) {
                return version;
            }
            return this.getLastValidExtensionVersionReccursively(extension, versions);
        }
        getLastValidExtensionVersionFromProperties(extension, versions) {
            for (const version of versions) {
                const engine = getEngine(version);
                if (!engine) {
                    return null;
                }
                if (extensionValidator_1.isEngineValid(engine)) {
                    return Promise.resolve(version);
                }
            }
            return null;
        }
        getEngine(version) {
            const engine = getEngine(version);
            if (engine) {
                return Promise.resolve(engine);
            }
            const manifest = getVersionAsset(version, AssetType.Manifest);
            if (!manifest) {
                return Promise.reject('Manifest was not found');
            }
            const headers = { 'Accept-Encoding': 'gzip' };
            return this.getAsset(manifest, { headers })
                .then(context => request_2.asJson(context))
                .then(manifest => manifest ? manifest.engines.vscode : Promise.reject('Error while reading manifest'));
        }
        getLastValidExtensionVersionReccursively(extension, versions) {
            if (!versions.length) {
                return Promise.resolve(null);
            }
            const version = versions[0];
            return this.getEngine(version)
                .then(engine => {
                if (!extensionValidator_1.isEngineValid(engine)) {
                    return this.getLastValidExtensionVersionReccursively(extension, versions.slice(1));
                }
                version.properties = version.properties || [];
                version.properties.push({ key: PropertyType.Engine, value: engine });
                return version;
            });
        }
        static hasExtensionByName(extensions, name) {
            for (const extension of extensions) {
                if (`${extension.publisher}.${extension.name}` === name) {
                    return true;
                }
            }
            return false;
        }
        getExtensionsReport() {
            if (!this.isEnabled()) {
                return Promise.reject(new Error('No extension gallery service configured.'));
            }
            if (!this.extensionsControlUrl) {
                return Promise.resolve([]);
            }
            return this.requestService.request({ type: 'GET', url: this.extensionsControlUrl }, cancellation_1.CancellationToken.None).then(context => {
                if (context.res.statusCode !== 200) {
                    return Promise.reject(new Error('Could not get extensions report.'));
                }
                return request_2.asJson(context).then(result => {
                    const map = new Map();
                    if (result) {
                        for (const id of result.malicious) {
                            const ext = map.get(id) || { id: { id }, malicious: true, slow: false };
                            ext.malicious = true;
                            map.set(id, ext);
                        }
                    }
                    return Promise.resolve(map_1.values(map));
                });
            });
        }
    };
    ExtensionGalleryService = __decorate([
        __param(0, request_1.IRequestService),
        __param(1, log_1.ILogService),
        __param(2, environment_1.IEnvironmentService),
        __param(3, telemetry_1.ITelemetryService)
    ], ExtensionGalleryService);
    exports.ExtensionGalleryService = ExtensionGalleryService;
    function resolveMarketplaceHeaders(environmentService) {
        const marketplaceMachineIdFile = path.join(environmentService.userDataPath, 'machineid');
        return pfs_1.readFile(marketplaceMachineIdFile, 'utf8')
            .then(contents => uuid_1.isUUID(contents) ? contents : null, () => null /* error reading ID file */)
            .then(uuid => {
            if (!uuid) {
                uuid = uuid_1.generateUuid();
                try {
                    extfs_1.writeFileAndFlushSync(marketplaceMachineIdFile, uuid);
                }
                catch (error) {
                    //noop
                }
            }
            return {
                'X-Market-Client-Id': `VSCode ${package_1.default.version}`,
                'User-Agent': `VSCode ${package_1.default.version}`,
                'X-Market-User-Id': uuid
            };
        });
    }
    exports.resolveMarketplaceHeaders = resolveMarketplaceHeaders;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[87/*vs/platform/request/node/requestService*/], __M([1/*require*/,0/*exports*/,7/*vs/base/common/objects*/,42/*vs/base/node/request*/,51/*vs/base/node/proxy*/,12/*vs/platform/configuration/common/configuration*/,5/*vs/platform/log/common/log*/]), function (require, exports, objects_1, request_1, proxy_1, configuration_1, log_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * This service exposes the `request` API, while using the global
     * or configured proxy settings.
     */
    let RequestService = class RequestService {
        constructor(configurationService, logService) {
            this.logService = logService;
            this.disposables = [];
            this.configure(configurationService.getValue());
            configurationService.onDidChangeConfiguration(() => this.configure(configurationService.getValue()), this, this.disposables);
        }
        configure(config) {
            this.proxyUrl = config.http && config.http.proxy;
            this.strictSSL = !!(config.http && config.http.proxyStrictSSL);
            this.authorization = config.http && config.http.proxyAuthorization;
        }
        request(options, token, requestFn = request_1.request) {
            this.logService.trace('RequestService#request', options.url);
            const { proxyUrl, strictSSL } = this;
            const agentPromise = options.agent ? Promise.resolve(options.agent) : Promise.resolve(proxy_1.getProxyAgent(options.url || '', { proxyUrl, strictSSL }));
            return agentPromise.then(agent => {
                options.agent = agent;
                options.strictSSL = strictSSL;
                if (this.authorization) {
                    options.headers = objects_1.assign(options.headers || {}, { 'Proxy-Authorization': this.authorization });
                }
                return requestFn(options, token);
            });
        }
    };
    RequestService = __decorate([
        __param(0, configuration_1.IConfigurationService),
        __param(1, log_1.ILogService)
    ], RequestService);
    exports.RequestService = RequestService;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

















define(__m[95/*vs/code/node/cliProcessMain*/], __M([1/*require*/,0/*exports*/,8/*vs/nls!vs/code/node/cliProcessMain*/,22/*vs/platform/product/node/product*/,21/*vs/platform/product/node/package*/,3/*vs/base/common/path*/,86/*semver*/,36/*vs/platform/instantiation/common/serviceCollection*/,31/*vs/platform/instantiation/common/descriptors*/,2/*vs/platform/instantiation/common/instantiation*/,53/*vs/platform/instantiation/common/instantiationService*/,14/*vs/platform/environment/common/environment*/,60/*vs/platform/environment/node/environmentService*/,23/*vs/platform/extensionManagement/common/extensionManagement*/,88/*vs/platform/extensionManagement/node/extensionManagementService*/,77/*vs/platform/extensionManagement/node/extensionGalleryService*/,27/*vs/platform/telemetry/common/telemetry*/,79/*vs/platform/telemetry/common/telemetryUtils*/,78/*vs/platform/telemetry/common/telemetryService*/,82/*vs/platform/telemetry/node/commonProperties*/,40/*vs/platform/request/node/request*/,87/*vs/platform/request/node/requestService*/,12/*vs/platform/configuration/common/configuration*/,73/*vs/platform/configuration/node/configurationService*/,80/*vs/platform/telemetry/node/appInsightsAppender*/,11/*vs/base/node/pfs*/,50/*vs/base/common/labels*/,75/*vs/platform/state/common/state*/,76/*vs/platform/state/node/stateService*/,57/*vs/platform/log/node/spdlogService*/,5/*vs/platform/log/common/log*/,25/*vs/base/common/errors*/,13/*vs/platform/extensionManagement/common/extensionManagementUtil*/,20/*vs/base/common/uri*/,37/*vs/platform/extensionManagement/node/extensionManagementUtil*/,30/*vs/platform/extensions/common/extensions*/,35/*vs/platform/extensions/node/extensionsUtil*/,45/*vs/base/common/cancellation*/,65/*vs/platform/localizations/node/localizations*/]), function (require, exports, nls_1, product_1, package_1, path, semver, serviceCollection_1, descriptors_1, instantiation_1, instantiationService_1, environment_1, environmentService_1, extensionManagement_1, extensionManagementService_1, extensionGalleryService_1, telemetry_1, telemetryUtils_1, telemetryService_1, commonProperties_1, request_1, requestService_1, configuration_1, configurationService_1, appInsightsAppender_1, pfs_1, labels_1, state_1, stateService_1, spdlogService_1, log_1, errors_1, extensionManagementUtil_1, uri_1, extensionManagementUtil_2, extensions_1, extensionsUtil_1, cancellation_1, localizations_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const notFound = (id) => nls_1.localize(0, null, id);
    const notInstalled = (id) => nls_1.localize(1, null, id);
    const useId = nls_1.localize(2, null, 'ms-vscode.csharp');
    function getId(manifest, withVersion) {
        if (withVersion) {
            return `${manifest.publisher}.${manifest.name}@${manifest.version}`;
        }
        else {
            return `${manifest.publisher}.${manifest.name}`;
        }
    }
    const EXTENSION_ID_REGEX = /^([^.]+\..+)@(\d+\.\d+\.\d+(-.*)?)$/;
    function getIdAndVersion(id) {
        const matches = EXTENSION_ID_REGEX.exec(id);
        if (matches && matches[1]) {
            return [extensionManagementUtil_1.adoptToGalleryExtensionId(matches[1]), matches[2]];
        }
        return [extensionManagementUtil_1.adoptToGalleryExtensionId(id), undefined];
    }
    exports.getIdAndVersion = getIdAndVersion;
    let Main = class Main {
        constructor(remote, instantiationService, environmentService, configurationService, extensionManagementService, extensionGalleryService) {
            this.remote = remote;
            this.instantiationService = instantiationService;
            this.environmentService = environmentService;
            this.configurationService = configurationService;
            this.extensionManagementService = extensionManagementService;
            this.extensionGalleryService = extensionGalleryService;
        }
        run(argv) {
            return __awaiter(this, void 0, void 0, function* () {
                if (argv['install-source']) {
                    yield this.setInstallSource(argv['install-source']);
                }
                else if (argv['list-extensions']) {
                    yield this.listExtensions(!!argv['show-versions']);
                }
                else if (argv['install-extension']) {
                    const arg = argv['install-extension'];
                    const args = typeof arg === 'string' ? [arg] : arg;
                    yield this.installExtensions(args, argv['force']);
                }
                else if (argv['uninstall-extension']) {
                    const arg = argv['uninstall-extension'];
                    const ids = typeof arg === 'string' ? [arg] : arg;
                    yield this.uninstallExtension(ids);
                }
            });
        }
        setInstallSource(installSource) {
            return pfs_1.writeFile(this.environmentService.installSourcePath, installSource.slice(0, 30));
        }
        listExtensions(showVersions) {
            return __awaiter(this, void 0, void 0, function* () {
                const extensions = yield this.extensionManagementService.getInstalled(1 /* User */);
                extensions.forEach(e => console.log(getId(e.manifest, showVersions)));
            });
        }
        installExtensions(extensions, force) {
            return __awaiter(this, void 0, void 0, function* () {
                const failed = [];
                const installedExtensionsManifests = [];
                for (const extension of extensions) {
                    try {
                        const manifest = yield this.installExtension(extension, force);
                        if (manifest) {
                            installedExtensionsManifests.push(manifest);
                        }
                    }
                    catch (err) {
                        console.error(err.message || err.stack || err);
                        failed.push(extension);
                    }
                }
                if (installedExtensionsManifests.some(manifest => extensions_1.isLanguagePackExtension(manifest))) {
                    yield this.updateLocalizationsCache();
                }
                return failed.length ? Promise.reject(nls_1.localize(3, null, failed.join(', '))) : Promise.resolve();
            });
        }
        installExtension(extension, force) {
            return __awaiter(this, void 0, void 0, function* () {
                if (/\.vsix$/i.test(extension)) {
                    extension = path.isAbsolute(extension) ? extension : path.join(process.cwd(), extension);
                    const manifest = yield extensionManagementUtil_2.getManifest(extension);
                    if (this.remote && (!extensions_1.isLanguagePackExtension(manifest) && extensionsUtil_1.isUIExtension(manifest, [], this.configurationService))) {
                        console.log(nls_1.localize(4, null, labels_1.getBaseLabel(extension)));
                        return null;
                    }
                    const valid = yield this.validate(manifest, force);
                    if (valid) {
                        return this.extensionManagementService.install(uri_1.URI.file(extension)).then(id => {
                            console.log(nls_1.localize(5, null, labels_1.getBaseLabel(extension)));
                            return manifest;
                        }, error => {
                            if (errors_1.isPromiseCanceledError(error)) {
                                console.log(nls_1.localize(6, null, labels_1.getBaseLabel(extension)));
                                return null;
                            }
                            else {
                                return Promise.reject(error);
                            }
                        });
                    }
                    return null;
                }
                const [id, version] = getIdAndVersion(extension);
                return this.extensionManagementService.getInstalled(1 /* User */)
                    .then(installed => this.extensionGalleryService.getCompatibleExtension({ id }, version)
                    .then(null, err => {
                    if (err.responseText) {
                        try {
                            const response = JSON.parse(err.responseText);
                            return Promise.reject(response.message);
                        }
                        catch (e) {
                            // noop
                        }
                    }
                    return Promise.reject(err);
                })
                    .then((extension) => __awaiter(this, void 0, void 0, function* () {
                    if (!extension) {
                        return Promise.reject(new Error(`${notFound(version ? `${id}@${version}` : id)}\n${useId}`));
                    }
                    const manifest = yield this.extensionGalleryService.getManifest(extension, cancellation_1.CancellationToken.None);
                    if (this.remote && manifest && (!extensions_1.isLanguagePackExtension(manifest) && extensionsUtil_1.isUIExtension(manifest, [], this.configurationService))) {
                        console.log(nls_1.localize(7, null, extension.identifier.id));
                        return null;
                    }
                    const [installedExtension] = installed.filter(e => extensionManagementUtil_1.areSameExtensions(e.identifier, { id }));
                    if (installedExtension) {
                        if (extension.version === installedExtension.manifest.version) {
                            console.log(nls_1.localize(8, null, version ? `${id}@${version}` : id));
                            return Promise.resolve(null);
                        }
                        if (!version && !force) {
                            console.log(nls_1.localize(9, null, id, installedExtension.manifest.version, extension.version));
                            return Promise.resolve(null);
                        }
                        console.log(nls_1.localize(10, null, id, extension.version));
                    }
                    else {
                        console.log(nls_1.localize(11, null, id));
                    }
                    yield this.installFromGallery(id, extension);
                    return manifest;
                })));
            });
        }
        validate(manifest, force) {
            return __awaiter(this, void 0, void 0, function* () {
                if (!manifest) {
                    throw new Error('Invalid vsix');
                }
                const extensionIdentifier = { id: extensionManagementUtil_1.getGalleryExtensionId(manifest.publisher, manifest.name) };
                const installedExtensions = yield this.extensionManagementService.getInstalled(1 /* User */);
                const newer = installedExtensions.filter(local => extensionManagementUtil_1.areSameExtensions(extensionIdentifier, local.identifier) && semver.gt(local.manifest.version, manifest.version))[0];
                if (newer && !force) {
                    console.log(nls_1.localize(12, null, newer.identifier.id, newer.manifest.version, manifest.version));
                    return false;
                }
                return true;
            });
        }
        installFromGallery(id, extension) {
            return __awaiter(this, void 0, void 0, function* () {
                console.log(nls_1.localize(13, null));
                try {
                    yield this.extensionManagementService.installFromGallery(extension);
                    console.log(nls_1.localize(14, null, id, extension.version));
                }
                catch (error) {
                    if (errors_1.isPromiseCanceledError(error)) {
                        console.log(nls_1.localize(15, null, id));
                    }
                    else {
                        throw error;
                    }
                }
            });
        }
        uninstallExtension(extensions) {
            return __awaiter(this, void 0, void 0, function* () {
                function getExtensionId(extensionDescription) {
                    return __awaiter(this, void 0, void 0, function* () {
                        if (!/\.vsix$/i.test(extensionDescription)) {
                            return extensionDescription;
                        }
                        const zipPath = path.isAbsolute(extensionDescription) ? extensionDescription : path.join(process.cwd(), extensionDescription);
                        const manifest = yield extensionManagementUtil_2.getManifest(zipPath);
                        return getId(manifest);
                    });
                }
                const uninstalledExtensions = [];
                for (const extension of extensions) {
                    const id = yield getExtensionId(extension);
                    const installed = yield this.extensionManagementService.getInstalled(1 /* User */);
                    const [extensionToUninstall] = installed.filter(e => extensionManagementUtil_1.areSameExtensions(e.identifier, { id }));
                    if (!extensionToUninstall) {
                        return Promise.reject(new Error(`${notInstalled(id)}\n${useId}`));
                    }
                    console.log(nls_1.localize(16, null, id));
                    yield this.extensionManagementService.uninstall(extensionToUninstall, true);
                    uninstalledExtensions.push(extensionToUninstall);
                    console.log(nls_1.localize(17, null, id));
                }
                if (uninstalledExtensions.some(e => extensions_1.isLanguagePackExtension(e.manifest))) {
                    yield this.updateLocalizationsCache();
                }
            });
        }
        updateLocalizationsCache() {
            return __awaiter(this, void 0, void 0, function* () {
                const localizationService = this.instantiationService.createInstance(localizations_1.LocalizationsService);
                yield localizationService.update();
                localizationService.dispose();
            });
        }
    };
    Main = __decorate([
        __param(1, instantiation_1.IInstantiationService),
        __param(2, environment_1.IEnvironmentService),
        __param(3, configuration_1.IConfigurationService),
        __param(4, extensionManagement_1.IExtensionManagementService),
        __param(5, extensionManagement_1.IExtensionGalleryService)
    ], Main);
    exports.Main = Main;
    const eventPrefix = 'monacoworkbench';
    function main(argv) {
        const services = new serviceCollection_1.ServiceCollection();
        const environmentService = new environmentService_1.EnvironmentService(argv, process.execPath);
        const logService = spdlogService_1.createSpdLogService('cli', log_1.getLogLevel(environmentService), environmentService.logsPath);
        process.once('exit', () => logService.dispose());
        logService.info('main', argv);
        services.set(environment_1.IEnvironmentService, environmentService);
        services.set(log_1.ILogService, logService);
        services.set(state_1.IStateService, new descriptors_1.SyncDescriptor(stateService_1.StateService));
        const instantiationService = new instantiationService_1.InstantiationService(services);
        return instantiationService.invokeFunction(accessor => {
            const envService = accessor.get(environment_1.IEnvironmentService);
            const stateService = accessor.get(state_1.IStateService);
            return Promise.all([envService.appSettingsHome, envService.extensionsPath].map(p => pfs_1.mkdirp(p))).then(() => {
                const { appRoot, extensionsPath, extensionDevelopmentLocationURI, isBuilt, installSourcePath } = envService;
                const services = new serviceCollection_1.ServiceCollection();
                services.set(configuration_1.IConfigurationService, new descriptors_1.SyncDescriptor(configurationService_1.ConfigurationService));
                services.set(request_1.IRequestService, new descriptors_1.SyncDescriptor(requestService_1.RequestService));
                services.set(extensionManagement_1.IExtensionManagementService, new descriptors_1.SyncDescriptor(extensionManagementService_1.ExtensionManagementService, [false]));
                services.set(extensionManagement_1.IExtensionGalleryService, new descriptors_1.SyncDescriptor(extensionGalleryService_1.ExtensionGalleryService));
                const appenders = [];
                if (isBuilt && !extensionDevelopmentLocationURI && !envService.args['disable-telemetry'] && product_1.default.enableTelemetry) {
                    if (product_1.default.aiConfig && product_1.default.aiConfig.asimovKey) {
                        appenders.push(new appInsightsAppender_1.AppInsightsAppender(eventPrefix, null, product_1.default.aiConfig.asimovKey, logService));
                    }
                    const config = {
                        appender: telemetryUtils_1.combinedAppender(...appenders),
                        commonProperties: commonProperties_1.resolveCommonProperties(product_1.default.commit, package_1.default.version, stateService.getItem('telemetry.machineId'), installSourcePath),
                        piiPaths: [appRoot, extensionsPath]
                    };
                    services.set(telemetry_1.ITelemetryService, new descriptors_1.SyncDescriptor(telemetryService_1.TelemetryService, [config]));
                }
                else {
                    services.set(telemetry_1.ITelemetryService, telemetryUtils_1.NullTelemetryService);
                }
                const instantiationService2 = instantiationService.createChild(services);
                const main = instantiationService2.createInstance(Main, false);
                return main.run(argv).then(() => {
                    // Dispose the AI adapter so that remaining data gets flushed.
                    return telemetryUtils_1.combinedAppender(...appenders).dispose();
                });
            });
        });
    }
    exports.main = main;
});

}).call(this);
//# sourceMappingURL=cliProcessMain.js.map
