/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */

var extendStatics = function(d, b) {
    extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
    return extendStatics(d, b);
};

export function __extends(d, b) {
    if (typeof b !== "function" && b !== null)
        throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
    extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

export var __assign = function() {
    __assign = Object.assign || function __assign(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
        }
        return t;
    }
    return __assign.apply(this, arguments);
}

export function __rest(s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
}

export function __decorate(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;
}

export function __param(paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
}

export function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.unshift(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.unshift(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};

export function __runInitializers(thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};

export function __propKey(x) {
    return typeof x === "symbol" ? x : "".concat(x);
};

export function __setFunctionName(f, name, prefix) {
    if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
    return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};

export function __metadata(metadataKey, metadataValue) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}

export function __awaiter(thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    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) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
}

export function __generator(thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
}

export var __createBinding = Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
});

export function __exportStar(m, o) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
}

export function __values(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}

export function __read(o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
}

/** @deprecated */
export function __spread() {
    for (var ar = [], i = 0; i < arguments.length; i++)
        ar = ar.concat(__read(arguments[i]));
    return ar;
}

/** @deprecated */
export function __spreadArrays() {
    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
    for (var r = Array(s), k = 0, i = 0; i < il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
            r[k] = a[j];
    return r;
}

export function __spreadArray(to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
}

export function __await(v) {
    return this instanceof __await ? (this.v = v, this) : new __await(v);
}

export function __asyncGenerator(thisArg, _arguments, generator) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var g = generator.apply(thisArg, _arguments || []), i, q = [];
    return i = {}, verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
    function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
    function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
    function fulfill(value) { resume("next", value); }
    function reject(value) { resume("throw", value); }
    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}

export function __asyncDelegator(o) {
    var i, p;
    return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
    function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
}

export function __asyncValues(o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}

export function __makeTemplateObject(cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};

var __setModuleDefault = Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
};

export function __importStar(mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
}

export function __importDefault(mod) {
    return (mod && mod.__esModule) ? mod : { default: mod };
}

export function __classPrivateFieldGet(receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}

export function __classPrivateFieldSet(receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}

export function __classPrivateFieldIn(state, receiver) {
    if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
    return typeof state === "function" ? receiver === state : state.has(receiver);
}

export function __addDisposableResource(env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;

}

var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};

export function __disposeResources(env) {
    function fail(e) {
        env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
        env.hasError = true;
    }
    function next() {
        while (env.stack.length) {
            var rec = env.stack.pop();
            try {
                var result = rec.dispose && rec.dispose.call(rec.value);
                if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
            }
            catch (e) {
                fail(e);
            }
        }
        if (env.hasError) throw env.error;
    }
    return next();
}

export default {
    __extends: __extends,
    __assign: __assign,
    __rest: __rest,
    __decorate: __decorate,
    __param: __param,
    __metadata: __metadata,
    __awaiter: __awaiter,
    __generator: __generator,
    __createBinding: __createBinding,
    __exportStar: __exportStar,
    __values: __values,
    __read: __read,
    __spread: __spread,
    __spreadArrays: __spreadArrays,
    __spreadArray: __spreadArray,
    __await: __await,
    __asyncGenerator: __asyncGenerator,
    __asyncDelegator: __asyncDelegator,
    __asyncValues: __asyncValues,
    __makeTemplateObject: __makeTemplateObject,
    __importStar: __importStar,
    __importDefault: __importDefault,
    __classPrivateFieldGet: __classPrivateFieldGet,
    __classPrivateFieldSet: __classPrivateFieldSet,
    __classPrivateFieldIn: __classPrivateFieldIn,
    __addDisposableResource: __addDisposableResource,
    __disposeResources: __disposeResources,
};


// out-build/vs/nls.messages.js
function $f() {
  return globalThis._VSCODE_NLS_MESSAGES;
}
function $g() {
  return globalThis._VSCODE_NLS_LANGUAGE;
}

// out-build/vs/nls.js
var isPseudo = $g() === "pseudo" || typeof document !== "undefined" && document.location && typeof document.location.hash === "string" && document.location.hash.indexOf("pseudo=true") >= 0;
function _format(message, args) {
  let result;
  if (args.length === 0) {
    result = message;
  } else {
    result = message.replace(/\{(\d+)\}/g, (match, rest) => {
      const index = rest[0];
      const arg = args[index];
      let result2 = match;
      if (typeof arg === "string") {
        result2 = arg;
      } else if (typeof arg === "number" || typeof arg === "boolean" || arg === void 0 || arg === null) {
        result2 = String(arg);
      }
      return result2;
    });
  }
  if (isPseudo) {
    result = "\uFF3B" + result.replace(/[aouei]/g, "$&$&") + "\uFF3D";
  }
  return result;
}
function localize(data, message, ...args) {
  if (typeof data === "number") {
    return _format(lookupMessage(data, message), args);
  }
  return _format(message, args);
}
function lookupMessage(index, fallback) {
  const message = $f()?.[index];
  if (typeof message !== "string") {
    if (typeof fallback === "string") {
      return fallback;
    }
    throw new Error(`!!! NLS MISSING: ${index} !!!`);
  }
  return message;
}
function localize2(data, originalMessage, ...args) {
  let message;
  if (typeof data === "number") {
    message = lookupMessage(data, originalMessage);
  } else {
    message = originalMessage;
  }
  const value = _format(message, args);
  return {
    value,
    original: originalMessage === message ? value : _format(originalMessage, args)
  };
}

// out-build/vs/base/common/platform.js
var $j = "en";
var _isWindows = false;
var _isMacintosh = false;
var _isLinux = false;
var _isLinuxSnap = false;
var _isNative = false;
var _isWeb = false;
var _isElectron = false;
var _isIOS = false;
var _isCI = false;
var _isMobile = false;
var _locale = void 0;
var _language = $j;
var _platformLocale = $j;
var _translationsConfigFile = void 0;
var _userAgent = void 0;
var $globalThis = globalThis;
var nodeProcess = void 0;
if (typeof $globalThis.vscode !== "undefined" && typeof $globalThis.vscode.process !== "undefined") {
  nodeProcess = $globalThis.vscode.process;
} else if (typeof process !== "undefined" && typeof process?.versions?.node === "string") {
  nodeProcess = process;
}
var isElectronProcess = typeof nodeProcess?.versions?.electron === "string";
var isElectronRenderer = isElectronProcess && nodeProcess?.type === "renderer";
if (typeof nodeProcess === "object") {
  _isWindows = nodeProcess.platform === "win32";
  _isMacintosh = nodeProcess.platform === "darwin";
  _isLinux = nodeProcess.platform === "linux";
  _isLinuxSnap = _isLinux && !!nodeProcess.env["SNAP"] && !!nodeProcess.env["SNAP_REVISION"];
  _isElectron = isElectronProcess;
  _isCI = !!nodeProcess.env["CI"] || !!nodeProcess.env["BUILD_ARTIFACTSTAGINGDIRECTORY"];
  _locale = $j;
  _language = $j;
  const rawNlsConfig = nodeProcess.env["VSCODE_NLS_CONFIG"];
  if (rawNlsConfig) {
    try {
      const nlsConfig = JSON.parse(rawNlsConfig);
      _locale = nlsConfig.userLocale;
      _platformLocale = nlsConfig.osLocale;
      _language = nlsConfig.resolvedLanguage || $j;
      _translationsConfigFile = nlsConfig.languagePack?.translationsConfigFile;
    } catch (e) {
    }
  }
  _isNative = true;
} else if (typeof navigator === "object" && !isElectronRenderer) {
  _userAgent = navigator.userAgent;
  _isWindows = _userAgent.indexOf("Windows") >= 0;
  _isMacintosh = _userAgent.indexOf("Macintosh") >= 0;
  _isIOS = (_userAgent.indexOf("Macintosh") >= 0 || _userAgent.indexOf("iPad") >= 0 || _userAgent.indexOf("iPhone") >= 0) && !!navigator.maxTouchPoints && navigator.maxTouchPoints > 0;
  _isLinux = _userAgent.indexOf("Linux") >= 0;
  _isMobile = _userAgent?.indexOf("Mobi") >= 0;
  _isWeb = true;
  _language = $g() || $j;
  _locale = navigator.language.toLowerCase();
  _platformLocale = _locale;
} else {
  console.error("Unable to resolve platform.");
}
var Platform;
(function(Platform2) {
  Platform2[Platform2["Web"] = 0] = "Web";
  Platform2[Platform2["Mac"] = 1] = "Mac";
  Platform2[Platform2["Linux"] = 2] = "Linux";
  Platform2[Platform2["Windows"] = 3] = "Windows";
})(Platform || (Platform = {}));
function $k(platform2) {
  switch (platform2) {
    case 0:
      return "Web";
    case 1:
      return "Mac";
    case 2:
      return "Linux";
    case 3:
      return "Windows";
  }
}
var _platform = 0;
if (_isMacintosh) {
  _platform = 1;
} else if (_isWindows) {
  _platform = 3;
} else if (_isLinux) {
  _platform = 2;
}
var $l = _isWindows;
var $m = _isMacintosh;
var $n = _isLinux;
var $o = _isLinuxSnap;
var $p = _isNative;
var $r = _isWeb;
var $s = _isWeb && typeof $globalThis.importScripts === "function";
var $t = $s ? $globalThis.origin : void 0;
var $w = _isCI;
var $x = _platform;
var $y = _userAgent;
var $z = _language;
var Language;
(function(Language2) {
  function value() {
    return $z;
  }
  Language2.value = value;
  function isDefaultVariant() {
    if ($z.length === 2) {
      return $z === "en";
    } else if ($z.length >= 3) {
      return $z[0] === "e" && $z[1] === "n" && $z[2] === "-";
    } else {
      return false;
    }
  }
  Language2.isDefaultVariant = isDefaultVariant;
  function isDefault() {
    return $z === "en";
  }
  Language2.isDefault = isDefault;
})(Language || (Language = {}));
var $C = _translationsConfigFile;
var $D = typeof $globalThis.postMessage === "function" && !$globalThis.importScripts;
var $E = (() => {
  if ($D) {
    const pending = [];
    $globalThis.addEventListener("message", (e) => {
      if (e.data && e.data.vscodeScheduleAsyncWork) {
        for (let i = 0, len = pending.length; i < len; i++) {
          const candidate = pending[i];
          if (candidate.id === e.data.vscodeScheduleAsyncWork) {
            pending.splice(i, 1);
            candidate.callback();
            return;
          }
        }
      }
    });
    let lastId = 0;
    return (callback) => {
      const myId = ++lastId;
      pending.push({
        id: myId,
        callback
      });
      $globalThis.postMessage({ vscodeScheduleAsyncWork: myId }, "*");
    };
  }
  return (callback) => setTimeout(callback);
})();
var OperatingSystem;
(function(OperatingSystem2) {
  OperatingSystem2[OperatingSystem2["Windows"] = 1] = "Windows";
  OperatingSystem2[OperatingSystem2["Macintosh"] = 2] = "Macintosh";
  OperatingSystem2[OperatingSystem2["Linux"] = 3] = "Linux";
})(OperatingSystem || (OperatingSystem = {}));
var OS = _isMacintosh || _isIOS ? 2 : _isWindows ? 1 : 3;
var $H = !!($y && $y.indexOf("Chrome") >= 0);
var $I = !!($y && $y.indexOf("Firefox") >= 0);
var $J = !!(!$H && ($y && $y.indexOf("Safari") >= 0));
var $K = !!($y && $y.indexOf("Edg/") >= 0);
var $L = !!($y && $y.indexOf("Android") >= 0);
function $M(osVersion) {
  return parseFloat(osVersion) >= 20;
}

// out-build/vs/base/common/arraysFind.js
function $ub(array, predicate, startIdx = 0, endIdxEx = array.length) {
  let i = startIdx;
  let j = endIdxEx;
  while (i < j) {
    const k = Math.floor((i + j) / 2);
    if (predicate(array[k])) {
      i = k + 1;
    } else {
      j = k;
    }
  }
  return i - 1;
}
function $wb(array, predicate, startIdx = 0, endIdxEx = array.length) {
  let i = startIdx;
  let j = endIdxEx;
  while (i < j) {
    const k = Math.floor((i + j) / 2);
    if (predicate(array[k])) {
      j = k;
    } else {
      i = k + 1;
    }
  }
  return i;
}
var $yb = class _$yb {
  static {
    this.assertInvariants = false;
  }
  constructor(e) {
    this.e = e;
    this.c = 0;
  }
  /**
   * The predicate must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`!
   * For subsequent calls, current predicate must be weaker than (or equal to) the previous predicate, i.e. more entries must be `true`.
   */
  findLastMonotonous(predicate) {
    if (_$yb.assertInvariants) {
      if (this.d) {
        for (const item of this.e) {
          if (this.d(item) && !predicate(item)) {
            throw new Error("MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.");
          }
        }
      }
      this.d = predicate;
    }
    const idx = $ub(this.e, predicate, this.c);
    this.c = idx + 1;
    return idx === -1 ? void 0 : this.e[idx];
  }
};

// out-build/vs/base/common/errors.js
var $8 = class {
  constructor() {
    this.b = [];
    this.a = function(e) {
      setTimeout(() => {
        if (e.stack) {
          if ($ob.isErrorNoTelemetry(e)) {
            throw new $ob(e.message + "\n\n" + e.stack);
          }
          throw new Error(e.message + "\n\n" + e.stack);
        }
        throw e;
      }, 0);
    };
  }
  addListener(listener) {
    this.b.push(listener);
    return () => {
      this.d(listener);
    };
  }
  c(e) {
    this.b.forEach((listener) => {
      listener(e);
    });
  }
  d(listener) {
    this.b.splice(this.b.indexOf(listener), 1);
  }
  setUnexpectedErrorHandler(newUnexpectedErrorHandler) {
    this.a = newUnexpectedErrorHandler;
  }
  getUnexpectedErrorHandler() {
    return this.a;
  }
  onUnexpectedError(e) {
    this.a(e);
    this.c(e);
  }
  // For external errors, we don't want the listeners to be called
  onUnexpectedExternalError(e) {
    this.a(e);
  }
};
var $9 = new $8();
function setUnexpectedErrorHandler(newUnexpectedErrorHandler) {
  $9.setUnexpectedErrorHandler(newUnexpectedErrorHandler);
}
function $$(e) {
  if (!e || typeof e !== "object") {
    return false;
  }
  const cast = e;
  return cast.code === "EPIPE" && cast.syscall?.toUpperCase() === "WRITE";
}
function $ab(e) {
  if (!$eb(e)) {
    $9.onUnexpectedError(e);
  }
  return void 0;
}
var canceledName = "Canceled";
function $eb(error) {
  if (error instanceof $fb) {
    return true;
  }
  return error instanceof Error && error.name === canceledName && error.message === canceledName;
}
var $fb = class extends Error {
  constructor() {
    super(canceledName);
    this.name = this.message;
  }
};
function $gb() {
  const error = new Error(canceledName);
  error.name = error.message;
  return error;
}
function $ib(name) {
  if (name) {
    return new Error(`Illegal state: ${name}`);
  } else {
    return new Error("Illegal state");
  }
}
function $kb(err) {
  if (!err) {
    return "Error";
  }
  if (err.message) {
    return err.message;
  }
  if (err.stack) {
    return err.stack.split("\n")[0];
  }
  return String(err);
}
var $nb = class extends Error {
  constructor() {
    super(...arguments);
    this.isExpected = true;
  }
};
var $ob = class _$ob extends Error {
  constructor(msg) {
    super(msg);
    this.name = "CodeExpectedError";
  }
  static fromError(err) {
    if (err instanceof _$ob) {
      return err;
    }
    const result = new _$ob();
    result.message = err.message;
    result.stack = err.stack;
    return result;
  }
  static isErrorNoTelemetry(err) {
    return err.name === "CodeExpectedError";
  }
};

// out-build/vs/base/common/arrays.js
function $Hb(one, other, itemEquals = (a, b) => a === b) {
  if (one === other) {
    return true;
  }
  if (!one || !other) {
    return false;
  }
  if (one.length !== other.length) {
    return false;
  }
  for (let i = 0, len = one.length; i < len; i++) {
    if (!itemEquals(one[i], other[i])) {
      return false;
    }
  }
  return true;
}
function top(array, compare3, n) {
  if (n === 0) {
    return [];
  }
  const result = array.slice(0, n).sort(compare3);
  topStep(array, compare3, result, n, array.length);
  return result;
}
function topStep(array, compare3, result, i, m) {
  for (const n = result.length; i < m; i++) {
    const element = array[i];
    if (compare3(element, result[n - 1]) < 0) {
      result.pop();
      const j = $wb(result, (e) => compare3(element, e) < 0);
      result.splice(j, 0, element);
    }
  }
}
function $Ub(array) {
  return array.filter((e) => !!e);
}
function $Zb(array, keyFn = (value) => value) {
  const seen = /* @__PURE__ */ new Set();
  return array.filter((element) => {
    const key = keyFn(element);
    if (seen.has(key)) {
      return false;
    }
    seen.add(key);
    return true;
  });
}
function $5b(array, element) {
  array.push(element);
  return () => $6b(array, element);
}
function $6b(array, element) {
  const index = array.indexOf(element);
  if (index > -1) {
    array.splice(index, 1);
    return element;
  }
  return void 0;
}
function $8b(array, _seed) {
  let rand;
  if (typeof _seed === "number") {
    let seed = _seed;
    rand = () => {
      const x = Math.sin(seed++) * 179426549;
      return x - Math.floor(x);
    };
  } else {
    rand = Math.random;
  }
  for (let i = array.length - 1; i > 0; i -= 1) {
    const j = Math.floor(rand() * (i + 1));
    const temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
}
function $bc(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}
var CompareResult;
(function(CompareResult2) {
  function isLessThan(result) {
    return result < 0;
  }
  CompareResult2.isLessThan = isLessThan;
  function isLessThanOrEqual(result) {
    return result <= 0;
  }
  CompareResult2.isLessThanOrEqual = isLessThanOrEqual;
  function isGreaterThan(result) {
    return result > 0;
  }
  CompareResult2.isGreaterThan = isGreaterThan;
  function isNeitherLessOrGreaterThan(result) {
    return result === 0;
  }
  CompareResult2.isNeitherLessOrGreaterThan = isNeitherLessOrGreaterThan;
  CompareResult2.greaterThan = 1;
  CompareResult2.lessThan = -1;
  CompareResult2.neitherLessOrGreaterThan = 0;
})(CompareResult || (CompareResult = {}));
function $ec(selector, comparator) {
  return (a, b) => comparator(selector(a), selector(b));
}
var $gc = (a, b) => a - b;
var $kc = class _$kc {
  static {
    this.empty = new _$kc((_callback) => {
    });
  }
  constructor(iterate) {
    this.iterate = iterate;
  }
  forEach(handler) {
    this.iterate((item) => {
      handler(item);
      return true;
    });
  }
  toArray() {
    const result = [];
    this.iterate((item) => {
      result.push(item);
      return true;
    });
    return result;
  }
  filter(predicate) {
    return new _$kc((cb) => this.iterate((item) => predicate(item) ? cb(item) : true));
  }
  map(mapFn) {
    return new _$kc((cb) => this.iterate((item) => cb(mapFn(item))));
  }
  some(predicate) {
    let result = false;
    this.iterate((item) => {
      result = predicate(item);
      return !result;
    });
    return result;
  }
  findFirst(predicate) {
    let result;
    this.iterate((item) => {
      if (predicate(item)) {
        result = item;
        return false;
      }
      return true;
    });
    return result;
  }
  findLast(predicate) {
    let result;
    this.iterate((item) => {
      if (predicate(item)) {
        result = item;
      }
      return true;
    });
    return result;
  }
  findLastMaxBy(comparator) {
    let result;
    let first = true;
    this.iterate((item) => {
      if (first || CompareResult.isGreaterThan(comparator(item, result))) {
        first = false;
        result = item;
      }
      return true;
    });
    return result;
  }
};

// out-build/vs/base/common/collections.js
var _a;
function $a(data, groupFn) {
  const result = /* @__PURE__ */ 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;
}
var $e = class {
  static {
    _a = Symbol.toStringTag;
  }
  constructor(values, b) {
    this.b = b;
    this.a = /* @__PURE__ */ new Map();
    this[_a] = "SetWithKey";
    for (const value of values) {
      this.add(value);
    }
  }
  get size() {
    return this.a.size;
  }
  add(value) {
    const key = this.b(value);
    this.a.set(key, value);
    return this;
  }
  delete(value) {
    return this.a.delete(this.b(value));
  }
  has(value) {
    return this.a.has(this.b(value));
  }
  *entries() {
    for (const entry of this.a.values()) {
      yield [entry, entry];
    }
  }
  keys() {
    return this.values();
  }
  *values() {
    for (const entry of this.a.values()) {
      yield entry;
    }
  }
  clear() {
    this.a.clear();
  }
  forEach(callbackfn, thisArg) {
    this.a.forEach((entry) => callbackfn.call(thisArg, entry, entry, this));
  }
  [Symbol.iterator]() {
    return this.values();
  }
};

// out-build/vs/base/common/functional.js
function $qb(fn, fnDidRunCallback) {
  const _this = this;
  let didCall = false;
  let result;
  return function() {
    if (didCall) {
      return result;
    }
    didCall = true;
    if (fnDidRunCallback) {
      try {
        result = fn.apply(_this, arguments);
      } finally {
        fnDidRunCallback();
      }
    } else {
      result = fn.apply(_this, arguments);
    }
    return result;
  };
}

// out-build/vs/base/common/map.js
var _a2;
var _b;
var _c;
function $Kc(map) {
  const entries = [];
  map.forEach((value, key) => {
    entries.push(`${key} => ${value}`);
  });
  return `Map(${map.size}) {${entries.join(", ")}}`;
}
function $Lc(set) {
  const entries = [];
  set.forEach((value) => {
    entries.push(value);
  });
  return `Set(${set.size}) {${entries.join(", ")}}`;
}
var ResourceMapEntry = class {
  constructor(uri, value) {
    this.uri = uri;
    this.value = value;
  }
};
function isEntries(arg) {
  return Array.isArray(arg);
}
var $Mc = class _$Mc {
  static {
    this.c = (resource) => resource.toString();
  }
  constructor(arg, toKey) {
    this[_a2] = "ResourceMap";
    if (arg instanceof _$Mc) {
      this.d = new Map(arg.d);
      this.e = toKey ?? _$Mc.c;
    } else if (isEntries(arg)) {
      this.d = /* @__PURE__ */ new Map();
      this.e = toKey ?? _$Mc.c;
      for (const [resource, value] of arg) {
        this.set(resource, value);
      }
    } else {
      this.d = /* @__PURE__ */ new Map();
      this.e = arg ?? _$Mc.c;
    }
  }
  set(resource, value) {
    this.d.set(this.e(resource), new ResourceMapEntry(resource, value));
    return this;
  }
  get(resource) {
    return this.d.get(this.e(resource))?.value;
  }
  has(resource) {
    return this.d.has(this.e(resource));
  }
  get size() {
    return this.d.size;
  }
  clear() {
    this.d.clear();
  }
  delete(resource) {
    return this.d.delete(this.e(resource));
  }
  forEach(clb, thisArg) {
    if (typeof thisArg !== "undefined") {
      clb = clb.bind(thisArg);
    }
    for (const [_, entry] of this.d) {
      clb(entry.value, entry.uri, this);
    }
  }
  *values() {
    for (const entry of this.d.values()) {
      yield entry.value;
    }
  }
  *keys() {
    for (const entry of this.d.values()) {
      yield entry.uri;
    }
  }
  *entries() {
    for (const entry of this.d.values()) {
      yield [entry.uri, entry.value];
    }
  }
  *[(_a2 = Symbol.toStringTag, Symbol.iterator)]() {
    for (const [, entry] of this.d) {
      yield [entry.uri, entry.value];
    }
  }
};
var $Nc = class {
  constructor(entriesOrKey, toKey) {
    this[_b] = "ResourceSet";
    if (!entriesOrKey || typeof entriesOrKey === "function") {
      this.c = new $Mc(entriesOrKey);
    } else {
      this.c = new $Mc(toKey);
      entriesOrKey.forEach(this.add, this);
    }
  }
  get size() {
    return this.c.size;
  }
  add(value) {
    this.c.set(value, value);
    return this;
  }
  clear() {
    this.c.clear();
  }
  delete(value) {
    return this.c.delete(value);
  }
  forEach(callbackfn, thisArg) {
    this.c.forEach((_value, key) => callbackfn.call(thisArg, key, key, this));
  }
  has(value) {
    return this.c.has(value);
  }
  entries() {
    return this.c.entries();
  }
  keys() {
    return this.c.keys();
  }
  values() {
    return this.c.keys();
  }
  [(_b = Symbol.toStringTag, Symbol.iterator)]() {
    return this.keys();
  }
};
var Touch;
(function(Touch2) {
  Touch2[Touch2["None"] = 0] = "None";
  Touch2[Touch2["AsOld"] = 1] = "AsOld";
  Touch2[Touch2["AsNew"] = 2] = "AsNew";
})(Touch || (Touch = {}));
var $Oc = class {
  constructor() {
    this[_c] = "LinkedMap";
    this.c = /* @__PURE__ */ new Map();
    this.d = void 0;
    this.e = void 0;
    this.f = 0;
    this.g = 0;
  }
  clear() {
    this.c.clear();
    this.d = void 0;
    this.e = void 0;
    this.f = 0;
    this.g++;
  }
  isEmpty() {
    return !this.d && !this.e;
  }
  get size() {
    return this.f;
  }
  get first() {
    return this.d?.value;
  }
  get last() {
    return this.e?.value;
  }
  has(key) {
    return this.c.has(key);
  }
  get(key, touch = 0) {
    const item = this.c.get(key);
    if (!item) {
      return void 0;
    }
    if (touch !== 0) {
      this.m(item, touch);
    }
    return item.value;
  }
  set(key, value, touch = 0) {
    let item = this.c.get(key);
    if (item) {
      item.value = value;
      if (touch !== 0) {
        this.m(item, touch);
      }
    } else {
      item = { key, value, next: void 0, previous: void 0 };
      switch (touch) {
        case 0:
          this.k(item);
          break;
        case 1:
          this.j(item);
          break;
        case 2:
          this.k(item);
          break;
        default:
          this.k(item);
          break;
      }
      this.c.set(key, item);
      this.f++;
    }
    return this;
  }
  delete(key) {
    return !!this.remove(key);
  }
  remove(key) {
    const item = this.c.get(key);
    if (!item) {
      return void 0;
    }
    this.c.delete(key);
    this.l(item);
    this.f--;
    return item.value;
  }
  shift() {
    if (!this.d && !this.e) {
      return void 0;
    }
    if (!this.d || !this.e) {
      throw new Error("Invalid list");
    }
    const item = this.d;
    this.c.delete(item.key);
    this.l(item);
    this.f--;
    return item.value;
  }
  forEach(callbackfn, thisArg) {
    const state = this.g;
    let current = this.d;
    while (current) {
      if (thisArg) {
        callbackfn.bind(thisArg)(current.value, current.key, this);
      } else {
        callbackfn(current.value, current.key, this);
      }
      if (this.g !== state) {
        throw new Error(`LinkedMap got modified during iteration.`);
      }
      current = current.next;
    }
  }
  keys() {
    const map = this;
    const state = this.g;
    let current = this.d;
    const iterator = {
      [Symbol.iterator]() {
        return iterator;
      },
      next() {
        if (map.g !== state) {
          throw new Error(`LinkedMap got modified during iteration.`);
        }
        if (current) {
          const result = { value: current.key, done: false };
          current = current.next;
          return result;
        } else {
          return { value: void 0, done: true };
        }
      }
    };
    return iterator;
  }
  values() {
    const map = this;
    const state = this.g;
    let current = this.d;
    const iterator = {
      [Symbol.iterator]() {
        return iterator;
      },
      next() {
        if (map.g !== state) {
          throw new Error(`LinkedMap got modified during iteration.`);
        }
        if (current) {
          const result = { value: current.value, done: false };
          current = current.next;
          return result;
        } else {
          return { value: void 0, done: true };
        }
      }
    };
    return iterator;
  }
  entries() {
    const map = this;
    const state = this.g;
    let current = this.d;
    const iterator = {
      [Symbol.iterator]() {
        return iterator;
      },
      next() {
        if (map.g !== state) {
          throw new Error(`LinkedMap got modified during iteration.`);
        }
        if (current) {
          const result = { value: [current.key, current.value], done: false };
          current = current.next;
          return result;
        } else {
          return { value: void 0, done: true };
        }
      }
    };
    return iterator;
  }
  [(_c = Symbol.toStringTag, Symbol.iterator)]() {
    return this.entries();
  }
  h(newSize) {
    if (newSize >= this.size) {
      return;
    }
    if (newSize === 0) {
      this.clear();
      return;
    }
    let current = this.d;
    let currentSize = this.size;
    while (current && currentSize > newSize) {
      this.c.delete(current.key);
      current = current.next;
      currentSize--;
    }
    this.d = current;
    this.f = currentSize;
    if (current) {
      current.previous = void 0;
    }
    this.g++;
  }
  i(newSize) {
    if (newSize >= this.size) {
      return;
    }
    if (newSize === 0) {
      this.clear();
      return;
    }
    let current = this.e;
    let currentSize = this.size;
    while (current && currentSize > newSize) {
      this.c.delete(current.key);
      current = current.previous;
      currentSize--;
    }
    this.e = current;
    this.f = currentSize;
    if (current) {
      current.next = void 0;
    }
    this.g++;
  }
  j(item) {
    if (!this.d && !this.e) {
      this.e = item;
    } else if (!this.d) {
      throw new Error("Invalid list");
    } else {
      item.next = this.d;
      this.d.previous = item;
    }
    this.d = item;
    this.g++;
  }
  k(item) {
    if (!this.d && !this.e) {
      this.d = item;
    } else if (!this.e) {
      throw new Error("Invalid list");
    } else {
      item.previous = this.e;
      this.e.next = item;
    }
    this.e = item;
    this.g++;
  }
  l(item) {
    if (item === this.d && item === this.e) {
      this.d = void 0;
      this.e = void 0;
    } else if (item === this.d) {
      if (!item.next) {
        throw new Error("Invalid list");
      }
      item.next.previous = void 0;
      this.d = item.next;
    } else if (item === this.e) {
      if (!item.previous) {
        throw new Error("Invalid list");
      }
      item.previous.next = void 0;
      this.e = item.previous;
    } else {
      const next = item.next;
      const previous = item.previous;
      if (!next || !previous) {
        throw new Error("Invalid list");
      }
      next.previous = previous;
      previous.next = next;
    }
    item.next = void 0;
    item.previous = void 0;
    this.g++;
  }
  m(item, touch) {
    if (!this.d || !this.e) {
      throw new Error("Invalid list");
    }
    if (touch !== 1 && touch !== 2) {
      return;
    }
    if (touch === 1) {
      if (item === this.d) {
        return;
      }
      const next = item.next;
      const previous = item.previous;
      if (item === this.e) {
        previous.next = void 0;
        this.e = previous;
      } else {
        next.previous = previous;
        previous.next = next;
      }
      item.previous = void 0;
      item.next = this.d;
      this.d.previous = item;
      this.d = item;
      this.g++;
    } else if (touch === 2) {
      if (item === this.e) {
        return;
      }
      const next = item.next;
      const previous = item.previous;
      if (item === this.d) {
        next.previous = void 0;
        this.d = next;
      } else {
        next.previous = previous;
        previous.next = next;
      }
      item.next = void 0;
      item.previous = this.e;
      this.e.next = item;
      this.e = item;
      this.g++;
    }
  }
  toJSON() {
    const data = [];
    this.forEach((value, key) => {
      data.push([key, value]);
    });
    return data;
  }
  fromJSON(data) {
    this.clear();
    for (const [key, value] of data) {
      this.set(key, value);
    }
  }
};
var Cache = class extends $Oc {
  constructor(limit, ratio = 1) {
    super();
    this.n = limit;
    this.o = Math.min(Math.max(0, ratio), 1);
  }
  get limit() {
    return this.n;
  }
  set limit(limit) {
    this.n = limit;
    this.p();
  }
  get ratio() {
    return this.o;
  }
  set ratio(ratio) {
    this.o = Math.min(Math.max(0, ratio), 1);
    this.p();
  }
  get(key, touch = 2) {
    return super.get(key, touch);
  }
  peek(key) {
    return super.get(
      key,
      0
      /* Touch.None */
    );
  }
  set(key, value) {
    super.set(
      key,
      value,
      2
      /* Touch.AsNew */
    );
    return this;
  }
  p() {
    if (this.size > this.n) {
      this.q(Math.round(this.n * this.o));
    }
  }
};
var $Pc = class extends Cache {
  constructor(limit, ratio = 1) {
    super(limit, ratio);
  }
  q(newSize) {
    this.h(newSize);
  }
  set(key, value) {
    super.set(key, value);
    this.p();
    return this;
  }
};
var $Tc = class {
  constructor() {
    this.c = /* @__PURE__ */ new Map();
  }
  add(key, value) {
    let values = this.c.get(key);
    if (!values) {
      values = /* @__PURE__ */ new Set();
      this.c.set(key, values);
    }
    values.add(value);
  }
  delete(key, value) {
    const values = this.c.get(key);
    if (!values) {
      return;
    }
    values.delete(value);
    if (values.size === 0) {
      this.c.delete(key);
    }
  }
  forEach(key, fn) {
    const values = this.c.get(key);
    if (!values) {
      return;
    }
    values.forEach(fn);
  }
  get(key) {
    const values = this.c.get(key);
    if (!values) {
      return /* @__PURE__ */ new Set();
    }
    return values;
  }
};

// out-build/vs/base/common/iterator.js
var Iterable;
(function(Iterable2) {
  function is(thing) {
    return thing && typeof thing === "object" && typeof thing[Symbol.iterator] === "function";
  }
  Iterable2.is = is;
  const _empty2 = Object.freeze([]);
  function empty() {
    return _empty2;
  }
  Iterable2.empty = empty;
  function* single(element) {
    yield element;
  }
  Iterable2.single = single;
  function wrap(iterableOrElement) {
    if (is(iterableOrElement)) {
      return iterableOrElement;
    } else {
      return single(iterableOrElement);
    }
  }
  Iterable2.wrap = wrap;
  function from(iterable) {
    return iterable || _empty2;
  }
  Iterable2.from = from;
  function* reverse(array) {
    for (let i = array.length - 1; i >= 0; i--) {
      yield array[i];
    }
  }
  Iterable2.reverse = reverse;
  function isEmpty(iterable) {
    return !iterable || iterable[Symbol.iterator]().next().done === true;
  }
  Iterable2.isEmpty = isEmpty;
  function first(iterable) {
    return iterable[Symbol.iterator]().next().value;
  }
  Iterable2.first = first;
  function some(iterable, predicate) {
    let i = 0;
    for (const element of iterable) {
      if (predicate(element, i++)) {
        return true;
      }
    }
    return false;
  }
  Iterable2.some = some;
  function find(iterable, predicate) {
    for (const element of iterable) {
      if (predicate(element)) {
        return element;
      }
    }
    return void 0;
  }
  Iterable2.find = find;
  function* filter(iterable, predicate) {
    for (const element of iterable) {
      if (predicate(element)) {
        yield element;
      }
    }
  }
  Iterable2.filter = filter;
  function* map(iterable, fn) {
    let index = 0;
    for (const element of iterable) {
      yield fn(element, index++);
    }
  }
  Iterable2.map = map;
  function* flatMap(iterable, fn) {
    let index = 0;
    for (const element of iterable) {
      yield* fn(element, index++);
    }
  }
  Iterable2.flatMap = flatMap;
  function* concat(...iterables) {
    for (const iterable of iterables) {
      yield* iterable;
    }
  }
  Iterable2.concat = concat;
  function reduce(iterable, reducer, initialValue) {
    let value = initialValue;
    for (const element of iterable) {
      value = reducer(value, element);
    }
    return value;
  }
  Iterable2.reduce = reduce;
  function* slice(arr, from2, to = arr.length) {
    if (from2 < 0) {
      from2 += arr.length;
    }
    if (to < 0) {
      to += arr.length;
    } else if (to > arr.length) {
      to = arr.length;
    }
    for (; from2 < to; from2++) {
      yield arr[from2];
    }
  }
  Iterable2.slice = slice;
  function consume(iterable, atMost = Number.POSITIVE_INFINITY) {
    const consumed = [];
    if (atMost === 0) {
      return [consumed, iterable];
    }
    const iterator = iterable[Symbol.iterator]();
    for (let i = 0; i < atMost; i++) {
      const next = iterator.next();
      if (next.done) {
        return [consumed, Iterable2.empty()];
      }
      consumed.push(next.value);
    }
    return [consumed, { [Symbol.iterator]() {
      return iterator;
    } }];
  }
  Iterable2.consume = consume;
  async function asyncToArray(iterable) {
    const result = [];
    for await (const item of iterable) {
      result.push(item);
    }
    return Promise.resolve(result);
  }
  Iterable2.asyncToArray = asyncToArray;
})(Iterable || (Iterable = {}));

// out-build/vs/base/common/lifecycle.js
var TRACK_DISPOSABLES = false;
var disposableTracker = null;
var $Yc = class _$Yc {
  constructor() {
    this.b = /* @__PURE__ */ new Map();
  }
  static {
    this.a = 0;
  }
  c(d) {
    let val = this.b.get(d);
    if (!val) {
      val = { parent: null, source: null, isSingleton: false, value: d, idx: _$Yc.a++ };
      this.b.set(d, val);
    }
    return val;
  }
  trackDisposable(d) {
    const data = this.c(d);
    if (!data.source) {
      data.source = new Error().stack;
    }
  }
  setParent(child, parent) {
    const data = this.c(child);
    data.parent = parent;
  }
  markAsDisposed(x) {
    this.b.delete(x);
  }
  markAsSingleton(disposable) {
    this.c(disposable).isSingleton = true;
  }
  f(data, cache2) {
    const cacheValue = cache2.get(data);
    if (cacheValue) {
      return cacheValue;
    }
    const result = data.parent ? this.f(this.c(data.parent), cache2) : data;
    cache2.set(data, result);
    return result;
  }
  getTrackedDisposables() {
    const rootParentCache = /* @__PURE__ */ new Map();
    const leaking = [...this.b.entries()].filter(([, v]) => v.source !== null && !this.f(v, rootParentCache).isSingleton).flatMap(([k]) => k);
    return leaking;
  }
  computeLeakingDisposables(maxReported = 10, preComputedLeaks) {
    let uncoveredLeakingObjs;
    if (preComputedLeaks) {
      uncoveredLeakingObjs = preComputedLeaks;
    } else {
      const rootParentCache = /* @__PURE__ */ new Map();
      const leakingObjects = [...this.b.values()].filter((info) => info.source !== null && !this.f(info, rootParentCache).isSingleton);
      if (leakingObjects.length === 0) {
        return;
      }
      const leakingObjsSet = new Set(leakingObjects.map((o) => o.value));
      uncoveredLeakingObjs = leakingObjects.filter((l) => {
        return !(l.parent && leakingObjsSet.has(l.parent));
      });
      if (uncoveredLeakingObjs.length === 0) {
        throw new Error("There are cyclic diposable chains!");
      }
    }
    if (!uncoveredLeakingObjs) {
      return void 0;
    }
    function getStackTracePath(leaking) {
      function removePrefix(array, linesToRemove) {
        while (array.length > 0 && linesToRemove.some((regexp) => typeof regexp === "string" ? regexp === array[0] : array[0].match(regexp))) {
          array.shift();
        }
      }
      const lines = leaking.source.split("\n").map((p) => p.trim().replace("at ", "")).filter((l) => l !== "");
      removePrefix(lines, ["Error", /^trackDisposable \(.*\)$/, /^DisposableTracker.trackDisposable \(.*\)$/]);
      return lines.reverse();
    }
    const stackTraceStarts = new $Tc();
    for (const leaking of uncoveredLeakingObjs) {
      const stackTracePath = getStackTracePath(leaking);
      for (let i2 = 0; i2 <= stackTracePath.length; i2++) {
        stackTraceStarts.add(stackTracePath.slice(0, i2).join("\n"), leaking);
      }
    }
    uncoveredLeakingObjs.sort($ec((l) => l.idx, $gc));
    let message = "";
    let i = 0;
    for (const leaking of uncoveredLeakingObjs.slice(0, maxReported)) {
      i++;
      const stackTracePath = getStackTracePath(leaking);
      const stackTraceFormattedLines = [];
      for (let i2 = 0; i2 < stackTracePath.length; i2++) {
        let line = stackTracePath[i2];
        const starts = stackTraceStarts.get(stackTracePath.slice(0, i2 + 1).join("\n"));
        line = `(shared with ${starts.size}/${uncoveredLeakingObjs.length} leaks) at ${line}`;
        const prevStarts = stackTraceStarts.get(stackTracePath.slice(0, i2).join("\n"));
        const continuations = $a([...prevStarts].map((d) => getStackTracePath(d)[i2]), (v) => v);
        delete continuations[stackTracePath[i2]];
        for (const [cont, set] of Object.entries(continuations)) {
          stackTraceFormattedLines.unshift(`    - stacktraces of ${set.length} other leaks continue with ${cont}`);
        }
        stackTraceFormattedLines.unshift(line);
      }
      message += `


==================== Leaking disposable ${i}/${uncoveredLeakingObjs.length}: ${leaking.value.constructor.name} ====================
${stackTraceFormattedLines.join("\n")}
============================================================

`;
    }
    if (uncoveredLeakingObjs.length > maxReported) {
      message += `


... and ${uncoveredLeakingObjs.length - maxReported} more leaking disposables

`;
    }
    return { leaks: uncoveredLeakingObjs, details: message };
  }
};
function $Zc(tracker) {
  disposableTracker = tracker;
}
if (TRACK_DISPOSABLES) {
  const __is_disposable_tracked__ = "__is_disposable_tracked__";
  $Zc(new class {
    trackDisposable(x) {
      const stack = new Error("Potentially leaked disposable").stack;
      setTimeout(() => {
        if (!x[__is_disposable_tracked__]) {
          console.log(stack);
        }
      }, 3e3);
    }
    setParent(child, parent) {
      if (child && child !== $0c.None) {
        try {
          child[__is_disposable_tracked__] = true;
        } catch {
        }
      }
    }
    markAsDisposed(disposable) {
      if (disposable && disposable !== $0c.None) {
        try {
          disposable[__is_disposable_tracked__] = true;
        } catch {
        }
      }
    }
    markAsSingleton(disposable) {
    }
  }());
}
function $1c(x) {
  disposableTracker?.trackDisposable(x);
  return x;
}
function $2c(disposable) {
  disposableTracker?.markAsDisposed(disposable);
}
function setParentOfDisposable(child, parent) {
  disposableTracker?.setParent(child, parent);
}
function setParentOfDisposables(children, parent) {
  if (!disposableTracker) {
    return;
  }
  for (const child of children) {
    disposableTracker.setParent(child, parent);
  }
}
function $4c(thing) {
  return typeof thing === "object" && thing !== null && typeof thing.dispose === "function" && thing.dispose.length === 0;
}
function $5c(arg) {
  if (Iterable.is(arg)) {
    const errors = [];
    for (const d of arg) {
      if (d) {
        try {
          d.dispose();
        } catch (e) {
          errors.push(e);
        }
      }
    }
    if (errors.length === 1) {
      throw errors[0];
    } else if (errors.length > 1) {
      throw new AggregateError(errors, "Encountered errors while disposing of store");
    }
    return Array.isArray(arg) ? [] : arg;
  } else if (arg) {
    arg.dispose();
    return arg;
  }
}
function $7c(...disposables) {
  const parent = $8c(() => $5c(disposables));
  setParentOfDisposables(disposables, parent);
  return parent;
}
function $8c(fn) {
  const self2 = $1c({
    dispose: $qb(() => {
      $2c(self2);
      fn();
    })
  });
  return self2;
}
var $9c = class _$9c {
  static {
    this.DISABLE_DISPOSED_WARNING = false;
  }
  constructor() {
    this.f = /* @__PURE__ */ new Set();
    this.g = false;
    $1c(this);
  }
  /**
   * Dispose of all registered disposables and mark this object as disposed.
   *
   * Any future disposables added to this object will be disposed of on `add`.
   */
  dispose() {
    if (this.g) {
      return;
    }
    $2c(this);
    this.g = true;
    this.clear();
  }
  /**
   * @return `true` if this object has been disposed of.
   */
  get isDisposed() {
    return this.g;
  }
  /**
   * Dispose of all registered disposables but do not mark this object as disposed.
   */
  clear() {
    if (this.f.size === 0) {
      return;
    }
    try {
      $5c(this.f);
    } finally {
      this.f.clear();
    }
  }
  /**
   * Add a new {@link IDisposable disposable} to the collection.
   */
  add(o) {
    if (!o) {
      return o;
    }
    if (o === this) {
      throw new Error("Cannot register a disposable on itself!");
    }
    setParentOfDisposable(o, this);
    if (this.g) {
      if (!_$9c.DISABLE_DISPOSED_WARNING) {
        console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack);
      }
    } else {
      this.f.add(o);
    }
    return o;
  }
  /**
   * Deletes a disposable from store and disposes of it. This will not throw or warn and proceed to dispose the
   * disposable even when the disposable is not part in the store.
   */
  delete(o) {
    if (!o) {
      return;
    }
    if (o === this) {
      throw new Error("Cannot dispose a disposable on itself!");
    }
    this.f.delete(o);
    o.dispose();
  }
  /**
   * Deletes the value from the store, but does not dispose it.
   */
  deleteAndLeak(o) {
    if (!o) {
      return;
    }
    if (this.f.has(o)) {
      this.f.delete(o);
      setParentOfDisposable(o, null);
    }
  }
};
var $0c = class {
  static {
    this.None = Object.freeze({ dispose() {
    } });
  }
  constructor() {
    this.q = new $9c();
    $1c(this);
    setParentOfDisposable(this.q, this);
  }
  dispose() {
    $2c(this);
    this.q.dispose();
  }
  /**
   * Adds `o` to the collection of disposables managed by this object.
   */
  B(o) {
    if (o === this) {
      throw new Error("Cannot register a disposable on itself!");
    }
    return this.q.add(o);
  }
};
var $$c = class {
  constructor() {
    this.b = false;
    $1c(this);
  }
  get value() {
    return this.b ? void 0 : this.a;
  }
  set value(value) {
    if (this.b || value === this.a) {
      return;
    }
    this.a?.dispose();
    if (value) {
      setParentOfDisposable(value, this);
    }
    this.a = value;
  }
  /**
   * Resets the stored value and disposed of the previously stored value.
   */
  clear() {
    this.value = void 0;
  }
  dispose() {
    this.b = true;
    $2c(this);
    this.a?.dispose();
    this.a = void 0;
  }
  /**
   * Clears the value, but does not dispose it.
   * The old value is returned.
  */
  clearAndLeak() {
    const oldValue = this.a;
    this.a = void 0;
    if (oldValue) {
      setParentOfDisposable(oldValue, null);
    }
    return oldValue;
  }
};
var $gd = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
    this.b = false;
    $1c(this);
  }
  /**
   * Disposes of all stored values and mark this object as disposed.
   *
   * Trying to use this object after it has been disposed of is an error.
   */
  dispose() {
    $2c(this);
    this.b = true;
    this.clearAndDisposeAll();
  }
  /**
   * Disposes of all stored values and clear the map, but DO NOT mark this object as disposed.
   */
  clearAndDisposeAll() {
    if (!this.a.size) {
      return;
    }
    try {
      $5c(this.a.values());
    } finally {
      this.a.clear();
    }
  }
  has(key) {
    return this.a.has(key);
  }
  get size() {
    return this.a.size;
  }
  get(key) {
    return this.a.get(key);
  }
  set(key, value, skipDisposeOnOverwrite = false) {
    if (this.b) {
      console.warn(new Error("Trying to add a disposable to a DisposableMap that has already been disposed of. The added object will be leaked!").stack);
    }
    if (!skipDisposeOnOverwrite) {
      this.a.get(key)?.dispose();
    }
    this.a.set(key, value);
  }
  /**
   * Delete the value stored for `key` from this map and also dispose of it.
   */
  deleteAndDispose(key) {
    this.a.get(key)?.dispose();
    this.a.delete(key);
  }
  /**
   * Delete the value stored for `key` from this map but return it. The caller is
   * responsible for disposing of the value.
   */
  deleteAndLeak(key) {
    const value = this.a.get(key);
    this.a.delete(key);
    return value;
  }
  keys() {
    return this.a.keys();
  }
  values() {
    return this.a.values();
  }
  [Symbol.iterator]() {
    return this.a[Symbol.iterator]();
  }
};

// out-build/vs/base/common/linkedList.js
var Node = class _Node {
  static {
    this.Undefined = new _Node(void 0);
  }
  constructor(element) {
    this.element = element;
    this.next = _Node.Undefined;
    this.prev = _Node.Undefined;
  }
};
var $hd = class {
  constructor() {
    this.a = Node.Undefined;
    this.b = Node.Undefined;
    this.c = 0;
  }
  get size() {
    return this.c;
  }
  isEmpty() {
    return this.a === Node.Undefined;
  }
  clear() {
    let node = this.a;
    while (node !== Node.Undefined) {
      const next = node.next;
      node.prev = Node.Undefined;
      node.next = Node.Undefined;
      node = next;
    }
    this.a = Node.Undefined;
    this.b = Node.Undefined;
    this.c = 0;
  }
  unshift(element) {
    return this.d(element, false);
  }
  push(element) {
    return this.d(element, true);
  }
  d(element, atTheEnd) {
    const newNode = new Node(element);
    if (this.a === Node.Undefined) {
      this.a = newNode;
      this.b = newNode;
    } else if (atTheEnd) {
      const oldLast = this.b;
      this.b = newNode;
      newNode.prev = oldLast;
      oldLast.next = newNode;
    } else {
      const oldFirst = this.a;
      this.a = newNode;
      newNode.next = oldFirst;
      oldFirst.prev = newNode;
    }
    this.c += 1;
    let didRemove = false;
    return () => {
      if (!didRemove) {
        didRemove = true;
        this.e(newNode);
      }
    };
  }
  shift() {
    if (this.a === Node.Undefined) {
      return void 0;
    } else {
      const res = this.a.element;
      this.e(this.a);
      return res;
    }
  }
  pop() {
    if (this.b === Node.Undefined) {
      return void 0;
    } else {
      const res = this.b.element;
      this.e(this.b);
      return res;
    }
  }
  e(node) {
    if (node.prev !== Node.Undefined && node.next !== Node.Undefined) {
      const anchor = node.prev;
      anchor.next = node.next;
      node.next.prev = anchor;
    } else if (node.prev === Node.Undefined && node.next === Node.Undefined) {
      this.a = Node.Undefined;
      this.b = Node.Undefined;
    } else if (node.next === Node.Undefined) {
      this.b = this.b.prev;
      this.b.next = Node.Undefined;
    } else if (node.prev === Node.Undefined) {
      this.a = this.a.next;
      this.a.prev = Node.Undefined;
    }
    this.c -= 1;
  }
  *[Symbol.iterator]() {
    let node = this.a;
    while (node !== Node.Undefined) {
      yield node.element;
      node = node.next;
    }
  }
};

// out-build/vs/base/common/stopwatch.js
var hasPerformanceNow = globalThis.performance && typeof globalThis.performance.now === "function";
var $xe = class _$xe {
  static create(highResolution) {
    return new _$xe(highResolution);
  }
  constructor(highResolution) {
    this.c = hasPerformanceNow && highResolution === false ? Date.now : globalThis.performance.now.bind(globalThis.performance);
    this.a = this.c();
    this.b = -1;
  }
  stop() {
    this.b = this.c();
  }
  reset() {
    this.a = this.c();
    this.b = -1;
  }
  elapsed() {
    if (this.b !== -1) {
      return this.b - this.a;
    }
    return this.c() - this.a;
  }
};

// out-build/vs/base/common/event.js
var _enableListenerGCedWarning = false;
var _enableDisposeWithListenerWarning = false;
var _enableSnapshotPotentialLeakWarning = false;
var Event;
(function(Event2) {
  Event2.None = () => $0c.None;
  function _addLeakageTraceLogic(options) {
    if (_enableSnapshotPotentialLeakWarning) {
      const { onDidAddListener: origListenerDidAdd } = options;
      const stack = Stacktrace.create();
      let count = 0;
      options.onDidAddListener = () => {
        if (++count === 2) {
          console.warn("snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here");
          stack.print();
        }
        origListenerDidAdd?.();
      };
    }
  }
  function defer(event, disposable) {
    return debounce(event, () => void 0, 0, void 0, true, void 0, disposable);
  }
  Event2.defer = defer;
  function once(event) {
    return (listener, thisArgs = null, disposables) => {
      let didFire = false;
      let result = void 0;
      result = event((e) => {
        if (didFire) {
          return;
        } else if (result) {
          result.dispose();
        } else {
          didFire = true;
        }
        return listener.call(thisArgs, e);
      }, null, disposables);
      if (didFire) {
        result.dispose();
      }
      return result;
    };
  }
  Event2.once = once;
  function onceIf(event, condition) {
    return Event2.once(Event2.filter(event, condition));
  }
  Event2.onceIf = onceIf;
  function map(event, map2, disposable) {
    return snapshot((listener, thisArgs = null, disposables) => event((i) => listener.call(thisArgs, map2(i)), null, disposables), disposable);
  }
  Event2.map = map;
  function forEach(event, each, disposable) {
    return snapshot((listener, thisArgs = null, disposables) => event((i) => {
      each(i);
      listener.call(thisArgs, i);
    }, null, disposables), disposable);
  }
  Event2.forEach = forEach;
  function filter(event, filter2, disposable) {
    return snapshot((listener, thisArgs = null, disposables) => event((e) => filter2(e) && listener.call(thisArgs, e), null, disposables), disposable);
  }
  Event2.filter = filter;
  function signal(event) {
    return event;
  }
  Event2.signal = signal;
  function any(...events) {
    return (listener, thisArgs = null, disposables) => {
      const disposable = $7c(...events.map((event) => event((e) => listener.call(thisArgs, e))));
      return addAndReturnDisposable(disposable, disposables);
    };
  }
  Event2.any = any;
  function reduce(event, merge, initial, disposable) {
    let output = initial;
    return map(event, (e) => {
      output = merge(output, e);
      return output;
    }, disposable);
  }
  Event2.reduce = reduce;
  function snapshot(event, disposable) {
    let listener;
    const options = {
      onWillAddFirstListener() {
        listener = event(emitter.fire, emitter);
      },
      onDidRemoveLastListener() {
        listener?.dispose();
      }
    };
    if (!disposable) {
      _addLeakageTraceLogic(options);
    }
    const emitter = new $De(options);
    disposable?.add(emitter);
    return emitter.event;
  }
  function addAndReturnDisposable(d, store) {
    if (store instanceof Array) {
      store.push(d);
    } else if (store) {
      store.add(d);
    }
    return d;
  }
  function debounce(event, merge, delay = 100, leading = false, flushOnListenerRemove = false, leakWarningThreshold, disposable) {
    let subscription;
    let output = void 0;
    let handle = void 0;
    let numDebouncedCalls = 0;
    let doFire;
    const options = {
      leakWarningThreshold,
      onWillAddFirstListener() {
        subscription = event((cur) => {
          numDebouncedCalls++;
          output = merge(output, cur);
          if (leading && !handle) {
            emitter.fire(output);
            output = void 0;
          }
          doFire = () => {
            const _output = output;
            output = void 0;
            handle = void 0;
            if (!leading || numDebouncedCalls > 1) {
              emitter.fire(_output);
            }
            numDebouncedCalls = 0;
          };
          if (typeof delay === "number") {
            clearTimeout(handle);
            handle = setTimeout(doFire, delay);
          } else {
            if (handle === void 0) {
              handle = 0;
              queueMicrotask(doFire);
            }
          }
        });
      },
      onWillRemoveListener() {
        if (flushOnListenerRemove && numDebouncedCalls > 0) {
          doFire?.();
        }
      },
      onDidRemoveLastListener() {
        doFire = void 0;
        subscription.dispose();
      }
    };
    if (!disposable) {
      _addLeakageTraceLogic(options);
    }
    const emitter = new $De(options);
    disposable?.add(emitter);
    return emitter.event;
  }
  Event2.debounce = debounce;
  function accumulate(event, delay = 0, disposable) {
    return Event2.debounce(event, (last, e) => {
      if (!last) {
        return [e];
      }
      last.push(e);
      return last;
    }, delay, void 0, true, void 0, disposable);
  }
  Event2.accumulate = accumulate;
  function latch(event, equals = (a, b) => a === b, disposable) {
    let firstCall = true;
    let cache2;
    return filter(event, (value) => {
      const shouldEmit = firstCall || !equals(value, cache2);
      firstCall = false;
      cache2 = value;
      return shouldEmit;
    }, disposable);
  }
  Event2.latch = latch;
  function split(event, isT, disposable) {
    return [
      Event2.filter(event, isT, disposable),
      Event2.filter(event, (e) => !isT(e), disposable)
    ];
  }
  Event2.split = split;
  function buffer(event, flushAfterTimeout = false, _buffer = [], disposable) {
    let buffer2 = _buffer.slice();
    let listener = event((e) => {
      if (buffer2) {
        buffer2.push(e);
      } else {
        emitter.fire(e);
      }
    });
    if (disposable) {
      disposable.add(listener);
    }
    const flush = () => {
      buffer2?.forEach((e) => emitter.fire(e));
      buffer2 = null;
    };
    const emitter = new $De({
      onWillAddFirstListener() {
        if (!listener) {
          listener = event((e) => emitter.fire(e));
          if (disposable) {
            disposable.add(listener);
          }
        }
      },
      onDidAddFirstListener() {
        if (buffer2) {
          if (flushAfterTimeout) {
            setTimeout(flush);
          } else {
            flush();
          }
        }
      },
      onDidRemoveLastListener() {
        if (listener) {
          listener.dispose();
        }
        listener = null;
      }
    });
    if (disposable) {
      disposable.add(emitter);
    }
    return emitter.event;
  }
  Event2.buffer = buffer;
  function chain(event, sythensize) {
    const fn = (listener, thisArgs, disposables) => {
      const cs = sythensize(new ChainableSynthesis());
      return event(function(value) {
        const result = cs.evaluate(value);
        if (result !== HaltChainable) {
          listener.call(thisArgs, result);
        }
      }, void 0, disposables);
    };
    return fn;
  }
  Event2.chain = chain;
  const HaltChainable = Symbol("HaltChainable");
  class ChainableSynthesis {
    constructor() {
      this.f = [];
    }
    map(fn) {
      this.f.push(fn);
      return this;
    }
    forEach(fn) {
      this.f.push((v) => {
        fn(v);
        return v;
      });
      return this;
    }
    filter(fn) {
      this.f.push((v) => fn(v) ? v : HaltChainable);
      return this;
    }
    reduce(merge, initial) {
      let last = initial;
      this.f.push((v) => {
        last = merge(last, v);
        return last;
      });
      return this;
    }
    latch(equals = (a, b) => a === b) {
      let firstCall = true;
      let cache2;
      this.f.push((value) => {
        const shouldEmit = firstCall || !equals(value, cache2);
        firstCall = false;
        cache2 = value;
        return shouldEmit ? value : HaltChainable;
      });
      return this;
    }
    evaluate(value) {
      for (const step of this.f) {
        value = step(value);
        if (value === HaltChainable) {
          break;
        }
      }
      return value;
    }
  }
  function fromNodeEventEmitter(emitter, eventName, map2 = (id2) => id2) {
    const fn = (...args) => result.fire(map2(...args));
    const onFirstListenerAdd = () => emitter.on(eventName, fn);
    const onLastListenerRemove = () => emitter.removeListener(eventName, fn);
    const result = new $De({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove });
    return result.event;
  }
  Event2.fromNodeEventEmitter = fromNodeEventEmitter;
  function fromDOMEventEmitter(emitter, eventName, map2 = (id2) => id2) {
    const fn = (...args) => result.fire(map2(...args));
    const onFirstListenerAdd = () => emitter.addEventListener(eventName, fn);
    const onLastListenerRemove = () => emitter.removeEventListener(eventName, fn);
    const result = new $De({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove });
    return result.event;
  }
  Event2.fromDOMEventEmitter = fromDOMEventEmitter;
  function toPromise(event) {
    return new Promise((resolve2) => once(event)(resolve2));
  }
  Event2.toPromise = toPromise;
  function fromPromise(promise) {
    const result = new $De();
    promise.then((res) => {
      result.fire(res);
    }, () => {
      result.fire(void 0);
    }).finally(() => {
      result.dispose();
    });
    return result.event;
  }
  Event2.fromPromise = fromPromise;
  function forward(from, to) {
    return from((e) => to.fire(e));
  }
  Event2.forward = forward;
  function runAndSubscribe(event, handler, initial) {
    handler(initial);
    return event((e) => handler(e));
  }
  Event2.runAndSubscribe = runAndSubscribe;
  class EmitterObserver {
    constructor(_observable, store) {
      this._observable = _observable;
      this.f = 0;
      this.g = false;
      const options = {
        onWillAddFirstListener: () => {
          _observable.addObserver(this);
          this._observable.reportChanges();
        },
        onDidRemoveLastListener: () => {
          _observable.removeObserver(this);
        }
      };
      if (!store) {
        _addLeakageTraceLogic(options);
      }
      this.emitter = new $De(options);
      if (store) {
        store.add(this.emitter);
      }
    }
    beginUpdate(_observable) {
      this.f++;
    }
    handlePossibleChange(_observable) {
    }
    handleChange(_observable, _change) {
      this.g = true;
    }
    endUpdate(_observable) {
      this.f--;
      if (this.f === 0) {
        this._observable.reportChanges();
        if (this.g) {
          this.g = false;
          this.emitter.fire(this._observable.get());
        }
      }
    }
  }
  function fromObservable(obs, store) {
    const observer = new EmitterObserver(obs, store);
    return observer.emitter.event;
  }
  Event2.fromObservable = fromObservable;
  function fromObservableLight(observable) {
    return (listener, thisArgs, disposables) => {
      let count = 0;
      let didChange = false;
      const observer = {
        beginUpdate() {
          count++;
        },
        endUpdate() {
          count--;
          if (count === 0) {
            observable.reportChanges();
            if (didChange) {
              didChange = false;
              listener.call(thisArgs);
            }
          }
        },
        handlePossibleChange() {
        },
        handleChange() {
          didChange = true;
        }
      };
      observable.addObserver(observer);
      observable.reportChanges();
      const disposable = {
        dispose() {
          observable.removeObserver(observer);
        }
      };
      if (disposables instanceof $9c) {
        disposables.add(disposable);
      } else if (Array.isArray(disposables)) {
        disposables.push(disposable);
      }
      return disposable;
    };
  }
  Event2.fromObservableLight = fromObservableLight;
})(Event || (Event = {}));
var $ze = class _$ze {
  static {
    this.all = /* @__PURE__ */ new Set();
  }
  static {
    this.f = 0;
  }
  constructor(name) {
    this.listenerCount = 0;
    this.invocationCount = 0;
    this.elapsedOverall = 0;
    this.durations = [];
    this.name = `${name}_${_$ze.f++}`;
    _$ze.all.add(this);
  }
  start(listenerCount) {
    this.g = new $xe();
    this.listenerCount = listenerCount;
  }
  stop() {
    if (this.g) {
      const elapsed = this.g.elapsed();
      this.durations.push(elapsed);
      this.elapsedOverall += elapsed;
      this.invocationCount += 1;
      this.g = void 0;
    }
  }
};
var _globalLeakWarningThreshold = -1;
var LeakageMonitor = class _LeakageMonitor {
  static {
    this.f = 1;
  }
  constructor(j, threshold, name = (_LeakageMonitor.f++).toString(16).padStart(3, "0")) {
    this.j = j;
    this.threshold = threshold;
    this.name = name;
    this.h = 0;
  }
  dispose() {
    this.g?.clear();
  }
  check(stack, listenerCount) {
    const threshold = this.threshold;
    if (threshold <= 0 || listenerCount < threshold) {
      return void 0;
    }
    if (!this.g) {
      this.g = /* @__PURE__ */ new Map();
    }
    const count = this.g.get(stack.value) || 0;
    this.g.set(stack.value, count + 1);
    this.h -= 1;
    if (this.h <= 0) {
      this.h = threshold * 0.5;
      const [topStack, topCount] = this.getMostFrequentStack();
      const message = `[${this.name}] potential listener LEAK detected, having ${listenerCount} listeners already. MOST frequent listener (${topCount}):`;
      console.warn(message);
      console.warn(topStack);
      const error = new $Be(message, topStack);
      this.j(error);
    }
    return () => {
      const count2 = this.g.get(stack.value) || 0;
      this.g.set(stack.value, count2 - 1);
    };
  }
  getMostFrequentStack() {
    if (!this.g) {
      return void 0;
    }
    let topStack;
    let topCount = 0;
    for (const [stack, count] of this.g) {
      if (!topStack || topCount < count) {
        topStack = [stack, count];
        topCount = count;
      }
    }
    return topStack;
  }
};
var Stacktrace = class _Stacktrace {
  static create() {
    const err = new Error();
    return new _Stacktrace(err.stack ?? "");
  }
  constructor(value) {
    this.value = value;
  }
  print() {
    console.warn(this.value.split("\n").slice(2).join("\n"));
  }
};
var $Be = class extends Error {
  constructor(message, stack) {
    super(message);
    this.name = "ListenerLeakError";
    this.stack = stack;
  }
};
var $Ce = class extends Error {
  constructor(message, stack) {
    super(message);
    this.name = "ListenerRefusalError";
    this.stack = stack;
  }
};
var id = 0;
var UniqueContainer = class {
  constructor(value) {
    this.value = value;
    this.id = id++;
  }
};
var compactionThreshold = 2;
var forEachListener = (listeners, fn) => {
  if (listeners instanceof UniqueContainer) {
    fn(listeners);
  } else {
    for (let i = 0; i < listeners.length; i++) {
      const l = listeners[i];
      if (l) {
        fn(l);
      }
    }
  }
};
var _listenerFinalizers;
if (_enableListenerGCedWarning) {
  const leaks = [];
  setInterval(() => {
    if (leaks.length === 0) {
      return;
    }
    console.warn("[LEAKING LISTENERS] GC'ed these listeners that were NOT yet disposed:");
    console.warn(leaks.join("\n"));
    leaks.length = 0;
  }, 3e3);
  _listenerFinalizers = new FinalizationRegistry((heldValue) => {
    if (typeof heldValue === "string") {
      leaks.push(heldValue);
    }
  });
}
var $De = class {
  constructor(options) {
    this.z = 0;
    this.f = options;
    this.g = _globalLeakWarningThreshold > 0 || this.f?.leakWarningThreshold ? new LeakageMonitor(options?.onListenerError ?? $ab, this.f?.leakWarningThreshold ?? _globalLeakWarningThreshold) : void 0;
    this.j = this.f?._profName ? new $ze(this.f._profName) : void 0;
    this.w = this.f?.deliveryQueue;
  }
  dispose() {
    if (!this.m) {
      this.m = true;
      if (this.w?.current === this) {
        this.w.reset();
      }
      if (this.u) {
        if (_enableDisposeWithListenerWarning) {
          const listeners = this.u;
          queueMicrotask(() => {
            forEachListener(listeners, (l) => l.stack?.print());
          });
        }
        this.u = void 0;
        this.z = 0;
      }
      this.f?.onDidRemoveLastListener?.();
      this.g?.dispose();
    }
  }
  /**
   * For the public to allow to subscribe
   * to events from this Emitter
   */
  get event() {
    this.q ??= (callback, thisArgs, disposables) => {
      if (this.g && this.z > this.g.threshold ** 2) {
        const message = `[${this.g.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this.z} vs ${this.g.threshold})`;
        console.warn(message);
        const tuple = this.g.getMostFrequentStack() ?? ["UNKNOWN stack", -1];
        const error = new $Ce(`${message}. HINT: Stack shows most frequent listener (${tuple[1]}-times)`, tuple[0]);
        const errorHandler = this.f?.onListenerError || $ab;
        errorHandler(error);
        return $0c.None;
      }
      if (this.m) {
        return $0c.None;
      }
      if (thisArgs) {
        callback = callback.bind(thisArgs);
      }
      const contained = new UniqueContainer(callback);
      let removeMonitor;
      let stack;
      if (this.g && this.z >= Math.ceil(this.g.threshold * 0.2)) {
        contained.stack = Stacktrace.create();
        removeMonitor = this.g.check(contained.stack, this.z + 1);
      }
      if (_enableDisposeWithListenerWarning) {
        contained.stack = stack ?? Stacktrace.create();
      }
      if (!this.u) {
        this.f?.onWillAddFirstListener?.(this);
        this.u = contained;
        this.f?.onDidAddFirstListener?.(this);
      } else if (this.u instanceof UniqueContainer) {
        this.w ??= new EventDeliveryQueuePrivate();
        this.u = [this.u, contained];
      } else {
        this.u.push(contained);
      }
      this.z++;
      const result = $8c(() => {
        _listenerFinalizers?.unregister(result);
        removeMonitor?.();
        this.A(contained);
      });
      if (disposables instanceof $9c) {
        disposables.add(result);
      } else if (Array.isArray(disposables)) {
        disposables.push(result);
      }
      if (_listenerFinalizers) {
        const stack2 = new Error().stack.split("\n").slice(2, 3).join("\n").trim();
        const match = /(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(stack2);
        _listenerFinalizers.register(result, match?.[2] ?? stack2, result);
      }
      return result;
    };
    return this.q;
  }
  A(listener) {
    this.f?.onWillRemoveListener?.(this);
    if (!this.u) {
      return;
    }
    if (this.z === 1) {
      this.u = void 0;
      this.f?.onDidRemoveLastListener?.(this);
      this.z = 0;
      return;
    }
    const listeners = this.u;
    const index = listeners.indexOf(listener);
    if (index === -1) {
      console.log("disposed?", this.m);
      console.log("size?", this.z);
      console.log("arr?", JSON.stringify(this.u));
      throw new Error("Attempted to dispose unknown listener");
    }
    this.z--;
    listeners[index] = void 0;
    const adjustDeliveryQueue = this.w.current === this;
    if (this.z * compactionThreshold <= listeners.length) {
      let n = 0;
      for (let i = 0; i < listeners.length; i++) {
        if (listeners[i]) {
          listeners[n++] = listeners[i];
        } else if (adjustDeliveryQueue) {
          this.w.end--;
          if (n < this.w.i) {
            this.w.i--;
          }
        }
      }
      listeners.length = n;
    }
  }
  B(listener, value) {
    if (!listener) {
      return;
    }
    const errorHandler = this.f?.onListenerError || $ab;
    if (!errorHandler) {
      listener.value(value);
      return;
    }
    try {
      listener.value(value);
    } catch (e) {
      errorHandler(e);
    }
  }
  /** Delivers items in the queue. Assumes the queue is ready to go. */
  C(dq) {
    const listeners = dq.current.u;
    while (dq.i < dq.end) {
      this.B(listeners[dq.i++], dq.value);
    }
    dq.reset();
  }
  /**
   * To be kept private to fire an event to
   * subscribers
   */
  fire(event) {
    if (this.w?.current) {
      this.C(this.w);
      this.j?.stop();
    }
    this.j?.start(this.z);
    if (!this.u) {
    } else if (this.u instanceof UniqueContainer) {
      this.B(this.u, event);
    } else {
      const dq = this.w;
      dq.enqueue(this, event, this.u.length);
      this.C(dq);
    }
    this.j?.stop();
  }
  hasListeners() {
    return this.z > 0;
  }
};
var EventDeliveryQueuePrivate = class {
  constructor() {
    this.i = -1;
    this.end = 0;
  }
  enqueue(emitter, value, end) {
    this.i = 0;
    this.end = end;
    this.current = emitter;
    this.value = value;
  }
  reset() {
    this.i = this.end;
    this.current = void 0;
    this.value = void 0;
  }
};
var $Ge = class extends $De {
  get isPaused() {
    return this.h !== 0;
  }
  constructor(options) {
    super(options);
    this.h = 0;
    this.s = new $hd();
    this.t = options?.merge;
  }
  pause() {
    this.h++;
  }
  resume() {
    if (this.h !== 0 && --this.h === 0) {
      if (this.t) {
        if (this.s.size > 0) {
          const events = Array.from(this.s);
          this.s.clear();
          super.fire(this.t(events));
        }
      } else {
        while (!this.h && this.s.size !== 0) {
          super.fire(this.s.shift());
        }
      }
    }
  }
  fire(event) {
    if (this.z) {
      if (this.h !== 0) {
        this.s.push(event);
      } else {
        super.fire(event);
      }
    }
  }
};
var $Je = class {
  constructor() {
    this.g = false;
    this.h = [];
    this.f = new $De({
      onWillAddFirstListener: () => this.j(),
      onDidRemoveLastListener: () => this.k()
    });
  }
  get event() {
    return this.f.event;
  }
  add(event) {
    const e = { event, listener: null };
    this.h.push(e);
    if (this.g) {
      this.m(e);
    }
    const dispose2 = () => {
      if (this.g) {
        this.o(e);
      }
      const idx = this.h.indexOf(e);
      this.h.splice(idx, 1);
    };
    return $8c($qb(dispose2));
  }
  j() {
    this.g = true;
    this.h.forEach((e) => this.m(e));
  }
  k() {
    this.g = false;
    this.h.forEach((e) => this.o(e));
  }
  m(e) {
    e.listener = e.event((r) => this.f.fire(r));
  }
  o(e) {
    e.listener?.dispose();
    e.listener = null;
  }
  dispose() {
    this.f.dispose();
    for (const e of this.h) {
      e.listener?.dispose();
    }
    this.h = [];
  }
};
var $Me = class {
  constructor() {
    this.f = false;
    this.g = Event.None;
    this.h = $0c.None;
    this.j = new $De({
      onDidAddFirstListener: () => {
        this.f = true;
        this.h = this.g(this.j.fire, this.j);
      },
      onDidRemoveLastListener: () => {
        this.f = false;
        this.h.dispose();
      }
    });
    this.event = this.j.event;
  }
  set input(event) {
    this.g = event;
    if (this.f) {
      this.h.dispose();
      this.h = event(this.j.fire, this.j);
    }
  }
  dispose() {
    this.h.dispose();
    this.j.dispose();
  }
};

// out-build/vs/base/common/types.js
function $yg(str) {
  return typeof str === "string";
}
function $Ag(obj) {
  return typeof obj === "object" && obj !== null && !Array.isArray(obj) && !(obj instanceof RegExp) && !(obj instanceof Date);
}
function $Bg(obj) {
  const TypedArray = Object.getPrototypeOf(Uint8Array);
  return typeof obj === "object" && obj instanceof TypedArray;
}
function $Cg(obj) {
  return typeof obj === "number" && !isNaN(obj);
}
function $Eg(obj) {
  return obj === true || obj === false;
}
function $Fg(obj) {
  return typeof obj === "undefined";
}
function $Hg(obj) {
  return $Fg(obj) || obj === null;
}
function $Ig(condition, type4) {
  if (!condition) {
    throw new Error(type4 ? `Unexpected type, expected '${type4}'` : "Unexpected type");
  }
}
function $Jg(arg) {
  if ($Hg(arg)) {
    throw new Error("Assertion Failed: argument is undefined or null");
  }
  return arg;
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
function $Lg(obj) {
  if (!$Ag(obj)) {
    return false;
  }
  for (const key in obj) {
    if (hasOwnProperty.call(obj, key)) {
      return false;
    }
  }
  return true;
}
function $Mg(obj) {
  return typeof obj === "function";
}
function $Qg(x) {
  return x;
}

// out-build/vs/base/common/process.js
var safeProcess;
var vscodeGlobal = globalThis.vscode;
if (typeof vscodeGlobal !== "undefined" && typeof vscodeGlobal.process !== "undefined") {
  const sandboxProcess = vscodeGlobal.process;
  safeProcess = {
    get platform() {
      return sandboxProcess.platform;
    },
    get arch() {
      return sandboxProcess.arch;
    },
    get env() {
      return sandboxProcess.env;
    },
    cwd() {
      return sandboxProcess.cwd();
    }
  };
} else if (typeof process !== "undefined" && typeof process?.versions?.node === "string") {
  safeProcess = {
    get platform() {
      return process.platform;
    },
    get arch() {
      return process.arch;
    },
    get env() {
      return process.env;
    },
    cwd() {
      return process.env["VSCODE_CWD"] || process.cwd();
    }
  };
} else {
  safeProcess = {
    // Supported
    get platform() {
      return $l ? "win32" : $m ? "darwin" : "linux";
    },
    get arch() {
      return void 0;
    },
    // Unsupported
    get env() {
      return {};
    },
    cwd() {
      return "/";
    }
  };
}
var cwd = safeProcess.cwd;
var env = safeProcess.env;
var $pc = safeProcess.platform;
var $qc = safeProcess.arch;

// out-build/vs/base/common/path.js
var CHAR_UPPERCASE_A = 65;
var CHAR_LOWERCASE_A = 97;
var CHAR_UPPERCASE_Z = 90;
var CHAR_LOWERCASE_Z = 122;
var CHAR_DOT = 46;
var CHAR_FORWARD_SLASH = 47;
var CHAR_BACKWARD_SLASH = 92;
var CHAR_COLON = 58;
var CHAR_QUESTION_MARK = 63;
var ErrorInvalidArgType = class extends Error {
  constructor(name, expected, actual) {
    let determiner;
    if (typeof expected === "string" && expected.indexOf("not ") === 0) {
      determiner = "must not be";
      expected = expected.replace(/^not /, "");
    } else {
      determiner = "must be";
    }
    const type4 = name.indexOf(".") !== -1 ? "property" : "argument";
    let msg = `The "${name}" ${type4} ${determiner} of type ${expected}`;
    msg += `. Received type ${typeof actual}`;
    super(msg);
    this.code = "ERR_INVALID_ARG_TYPE";
  }
};
function validateObject(pathObject, name) {
  if (pathObject === null || typeof pathObject !== "object") {
    throw new ErrorInvalidArgType(name, "Object", pathObject);
  }
}
function validateString(value, name) {
  if (typeof value !== "string") {
    throw new ErrorInvalidArgType(name, "string", value);
  }
}
var platformIsWin32 = $pc === "win32";
function isPathSeparator(code2) {
  return code2 === CHAR_FORWARD_SLASH || code2 === CHAR_BACKWARD_SLASH;
}
function isPosixPathSeparator(code2) {
  return code2 === CHAR_FORWARD_SLASH;
}
function isWindowsDeviceRoot(code2) {
  return code2 >= CHAR_UPPERCASE_A && code2 <= CHAR_UPPERCASE_Z || code2 >= CHAR_LOWERCASE_A && code2 <= CHAR_LOWERCASE_Z;
}
function normalizeString(path3, allowAboveRoot, separator, isPathSeparator2) {
  let res = "";
  let lastSegmentLength = 0;
  let lastSlash = -1;
  let dots = 0;
  let code2 = 0;
  for (let i = 0; i <= path3.length; ++i) {
    if (i < path3.length) {
      code2 = path3.charCodeAt(i);
    } else if (isPathSeparator2(code2)) {
      break;
    } else {
      code2 = CHAR_FORWARD_SLASH;
    }
    if (isPathSeparator2(code2)) {
      if (lastSlash === i - 1 || dots === 1) {
      } else if (dots === 2) {
        if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT || res.charCodeAt(res.length - 2) !== CHAR_DOT) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator);
            if (lastSlashIndex === -1) {
              res = "";
              lastSegmentLength = 0;
            } else {
              res = res.slice(0, lastSlashIndex);
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator);
            }
            lastSlash = i;
            dots = 0;
            continue;
          } else if (res.length !== 0) {
            res = "";
            lastSegmentLength = 0;
            lastSlash = i;
            dots = 0;
            continue;
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : "..";
          lastSegmentLength = 2;
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path3.slice(lastSlash + 1, i)}`;
        } else {
          res = path3.slice(lastSlash + 1, i);
        }
        lastSegmentLength = i - lastSlash - 1;
      }
      lastSlash = i;
      dots = 0;
    } else if (code2 === CHAR_DOT && dots !== -1) {
      ++dots;
    } else {
      dots = -1;
    }
  }
  return res;
}
function formatExt(ext) {
  return ext ? `${ext[0] === "." ? "" : "."}${ext}` : "";
}
function _format2(sep2, pathObject) {
  validateObject(pathObject, "pathObject");
  const dir = pathObject.dir || pathObject.root;
  const base = pathObject.base || `${pathObject.name || ""}${formatExt(pathObject.ext)}`;
  if (!dir) {
    return base;
  }
  return dir === pathObject.root ? `${dir}${base}` : `${dir}${sep2}${base}`;
}
var $rc = {
  // path.resolve([from ...], to)
  resolve(...pathSegments) {
    let resolvedDevice = "";
    let resolvedTail = "";
    let resolvedAbsolute = false;
    for (let i = pathSegments.length - 1; i >= -1; i--) {
      let path3;
      if (i >= 0) {
        path3 = pathSegments[i];
        validateString(path3, `paths[${i}]`);
        if (path3.length === 0) {
          continue;
        }
      } else if (resolvedDevice.length === 0) {
        path3 = cwd();
      } else {
        path3 = env[`=${resolvedDevice}`] || cwd();
        if (path3 === void 0 || path3.slice(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && path3.charCodeAt(2) === CHAR_BACKWARD_SLASH) {
          path3 = `${resolvedDevice}\\`;
        }
      }
      const len = path3.length;
      let rootEnd = 0;
      let device = "";
      let isAbsolute = false;
      const code2 = path3.charCodeAt(0);
      if (len === 1) {
        if (isPathSeparator(code2)) {
          rootEnd = 1;
          isAbsolute = true;
        }
      } else if (isPathSeparator(code2)) {
        isAbsolute = true;
        if (isPathSeparator(path3.charCodeAt(1))) {
          let j = 2;
          let last = j;
          while (j < len && !isPathSeparator(path3.charCodeAt(j))) {
            j++;
          }
          if (j < len && j !== last) {
            const firstPart = path3.slice(last, j);
            last = j;
            while (j < len && isPathSeparator(path3.charCodeAt(j))) {
              j++;
            }
            if (j < len && j !== last) {
              last = j;
              while (j < len && !isPathSeparator(path3.charCodeAt(j))) {
                j++;
              }
              if (j === len || j !== last) {
                device = `\\\\${firstPart}\\${path3.slice(last, j)}`;
                rootEnd = j;
              }
            }
          }
        } else {
          rootEnd = 1;
        }
      } else if (isWindowsDeviceRoot(code2) && path3.charCodeAt(1) === CHAR_COLON) {
        device = path3.slice(0, 2);
        rootEnd = 2;
        if (len > 2 && isPathSeparator(path3.charCodeAt(2))) {
          isAbsolute = true;
          rootEnd = 3;
        }
      }
      if (device.length > 0) {
        if (resolvedDevice.length > 0) {
          if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
            continue;
          }
        } else {
          resolvedDevice = device;
        }
      }
      if (resolvedAbsolute) {
        if (resolvedDevice.length > 0) {
          break;
        }
      } else {
        resolvedTail = `${path3.slice(rootEnd)}\\${resolvedTail}`;
        resolvedAbsolute = isAbsolute;
        if (isAbsolute && resolvedDevice.length > 0) {
          break;
        }
      }
    }
    resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, "\\", isPathSeparator);
    return resolvedAbsolute ? `${resolvedDevice}\\${resolvedTail}` : `${resolvedDevice}${resolvedTail}` || ".";
  },
  normalize(path3) {
    validateString(path3, "path");
    const len = path3.length;
    if (len === 0) {
      return ".";
    }
    let rootEnd = 0;
    let device;
    let isAbsolute = false;
    const code2 = path3.charCodeAt(0);
    if (len === 1) {
      return isPosixPathSeparator(code2) ? "\\" : path3;
    }
    if (isPathSeparator(code2)) {
      isAbsolute = true;
      if (isPathSeparator(path3.charCodeAt(1))) {
        let j = 2;
        let last = j;
        while (j < len && !isPathSeparator(path3.charCodeAt(j))) {
          j++;
        }
        if (j < len && j !== last) {
          const firstPart = path3.slice(last, j);
          last = j;
          while (j < len && isPathSeparator(path3.charCodeAt(j))) {
            j++;
          }
          if (j < len && j !== last) {
            last = j;
            while (j < len && !isPathSeparator(path3.charCodeAt(j))) {
              j++;
            }
            if (j === len) {
              return `\\\\${firstPart}\\${path3.slice(last)}\\`;
            }
            if (j !== last) {
              device = `\\\\${firstPart}\\${path3.slice(last, j)}`;
              rootEnd = j;
            }
          }
        }
      } else {
        rootEnd = 1;
      }
    } else if (isWindowsDeviceRoot(code2) && path3.charCodeAt(1) === CHAR_COLON) {
      device = path3.slice(0, 2);
      rootEnd = 2;
      if (len > 2 && isPathSeparator(path3.charCodeAt(2))) {
        isAbsolute = true;
        rootEnd = 3;
      }
    }
    let tail = rootEnd < len ? normalizeString(path3.slice(rootEnd), !isAbsolute, "\\", isPathSeparator) : "";
    if (tail.length === 0 && !isAbsolute) {
      tail = ".";
    }
    if (tail.length > 0 && isPathSeparator(path3.charCodeAt(len - 1))) {
      tail += "\\";
    }
    if (device === void 0) {
      return isAbsolute ? `\\${tail}` : tail;
    }
    return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`;
  },
  isAbsolute(path3) {
    validateString(path3, "path");
    const len = path3.length;
    if (len === 0) {
      return false;
    }
    const code2 = path3.charCodeAt(0);
    return isPathSeparator(code2) || // Possible device root
    len > 2 && isWindowsDeviceRoot(code2) && path3.charCodeAt(1) === CHAR_COLON && isPathSeparator(path3.charCodeAt(2));
  },
  join(...paths) {
    if (paths.length === 0) {
      return ".";
    }
    let joined;
    let firstPart;
    for (let i = 0; i < paths.length; ++i) {
      const arg = paths[i];
      validateString(arg, "path");
      if (arg.length > 0) {
        if (joined === void 0) {
          joined = firstPart = arg;
        } else {
          joined += `\\${arg}`;
        }
      }
    }
    if (joined === void 0) {
      return ".";
    }
    let needsReplace = true;
    let slashCount = 0;
    if (typeof firstPart === "string" && isPathSeparator(firstPart.charCodeAt(0))) {
      ++slashCount;
      const firstLen = firstPart.length;
      if (firstLen > 1 && isPathSeparator(firstPart.charCodeAt(1))) {
        ++slashCount;
        if (firstLen > 2) {
          if (isPathSeparator(firstPart.charCodeAt(2))) {
            ++slashCount;
          } else {
            needsReplace = false;
          }
        }
      }
    }
    if (needsReplace) {
      while (slashCount < joined.length && isPathSeparator(joined.charCodeAt(slashCount))) {
        slashCount++;
      }
      if (slashCount >= 2) {
        joined = `\\${joined.slice(slashCount)}`;
      }
    }
    return $rc.normalize(joined);
  },
  // It will solve the relative path from `from` to `to`, for instance:
  //  from = 'C:\\orandea\\test\\aaa'
  //  to = 'C:\\orandea\\impl\\bbb'
  // The output of the function should be: '..\\..\\impl\\bbb'
  relative(from, to) {
    validateString(from, "from");
    validateString(to, "to");
    if (from === to) {
      return "";
    }
    const fromOrig = $rc.resolve(from);
    const toOrig = $rc.resolve(to);
    if (fromOrig === toOrig) {
      return "";
    }
    from = fromOrig.toLowerCase();
    to = toOrig.toLowerCase();
    if (from === to) {
      return "";
    }
    let fromStart = 0;
    while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
      fromStart++;
    }
    let fromEnd = from.length;
    while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
      fromEnd--;
    }
    const fromLen = fromEnd - fromStart;
    let toStart = 0;
    while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
      toStart++;
    }
    let toEnd = to.length;
    while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
      toEnd--;
    }
    const toLen = toEnd - toStart;
    const length = fromLen < toLen ? fromLen : toLen;
    let lastCommonSep = -1;
    let i = 0;
    for (; i < length; i++) {
      const fromCode = from.charCodeAt(fromStart + i);
      if (fromCode !== to.charCodeAt(toStart + i)) {
        break;
      } else if (fromCode === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i;
      }
    }
    if (i !== length) {
      if (lastCommonSep === -1) {
        return toOrig;
      }
    } else {
      if (toLen > length) {
        if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
          return toOrig.slice(toStart + i + 1);
        }
        if (i === 2) {
          return toOrig.slice(toStart + i);
        }
      }
      if (fromLen > length) {
        if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
          lastCommonSep = i;
        } else if (i === 2) {
          lastCommonSep = 3;
        }
      }
      if (lastCommonSep === -1) {
        lastCommonSep = 0;
      }
    }
    let out = "";
    for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
      if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
        out += out.length === 0 ? ".." : "\\..";
      }
    }
    toStart += lastCommonSep;
    if (out.length > 0) {
      return `${out}${toOrig.slice(toStart, toEnd)}`;
    }
    if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
      ++toStart;
    }
    return toOrig.slice(toStart, toEnd);
  },
  toNamespacedPath(path3) {
    if (typeof path3 !== "string" || path3.length === 0) {
      return path3;
    }
    const resolvedPath = $rc.resolve(path3);
    if (resolvedPath.length <= 2) {
      return path3;
    }
    if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
      if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
        const code2 = resolvedPath.charCodeAt(2);
        if (code2 !== CHAR_QUESTION_MARK && code2 !== CHAR_DOT) {
          return `\\\\?\\UNC\\${resolvedPath.slice(2)}`;
        }
      }
    } else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) && resolvedPath.charCodeAt(1) === CHAR_COLON && resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH) {
      return `\\\\?\\${resolvedPath}`;
    }
    return path3;
  },
  dirname(path3) {
    validateString(path3, "path");
    const len = path3.length;
    if (len === 0) {
      return ".";
    }
    let rootEnd = -1;
    let offset = 0;
    const code2 = path3.charCodeAt(0);
    if (len === 1) {
      return isPathSeparator(code2) ? path3 : ".";
    }
    if (isPathSeparator(code2)) {
      rootEnd = offset = 1;
      if (isPathSeparator(path3.charCodeAt(1))) {
        let j = 2;
        let last = j;
        while (j < len && !isPathSeparator(path3.charCodeAt(j))) {
          j++;
        }
        if (j < len && j !== last) {
          last = j;
          while (j < len && isPathSeparator(path3.charCodeAt(j))) {
            j++;
          }
          if (j < len && j !== last) {
            last = j;
            while (j < len && !isPathSeparator(path3.charCodeAt(j))) {
              j++;
            }
            if (j === len) {
              return path3;
            }
            if (j !== last) {
              rootEnd = offset = j + 1;
            }
          }
        }
      }
    } else if (isWindowsDeviceRoot(code2) && path3.charCodeAt(1) === CHAR_COLON) {
      rootEnd = len > 2 && isPathSeparator(path3.charCodeAt(2)) ? 3 : 2;
      offset = rootEnd;
    }
    let end = -1;
    let matchedSlash = true;
    for (let i = len - 1; i >= offset; --i) {
      if (isPathSeparator(path3.charCodeAt(i))) {
        if (!matchedSlash) {
          end = i;
          break;
        }
      } else {
        matchedSlash = false;
      }
    }
    if (end === -1) {
      if (rootEnd === -1) {
        return ".";
      }
      end = rootEnd;
    }
    return path3.slice(0, end);
  },
  basename(path3, suffix) {
    if (suffix !== void 0) {
      validateString(suffix, "suffix");
    }
    validateString(path3, "path");
    let start = 0;
    let end = -1;
    let matchedSlash = true;
    let i;
    if (path3.length >= 2 && isWindowsDeviceRoot(path3.charCodeAt(0)) && path3.charCodeAt(1) === CHAR_COLON) {
      start = 2;
    }
    if (suffix !== void 0 && suffix.length > 0 && suffix.length <= path3.length) {
      if (suffix === path3) {
        return "";
      }
      let extIdx = suffix.length - 1;
      let firstNonSlashEnd = -1;
      for (i = path3.length - 1; i >= start; --i) {
        const code2 = path3.charCodeAt(i);
        if (isPathSeparator(code2)) {
          if (!matchedSlash) {
            start = i + 1;
            break;
          }
        } else {
          if (firstNonSlashEnd === -1) {
            matchedSlash = false;
            firstNonSlashEnd = i + 1;
          }
          if (extIdx >= 0) {
            if (code2 === suffix.charCodeAt(extIdx)) {
              if (--extIdx === -1) {
                end = i;
              }
            } else {
              extIdx = -1;
              end = firstNonSlashEnd;
            }
          }
        }
      }
      if (start === end) {
        end = firstNonSlashEnd;
      } else if (end === -1) {
        end = path3.length;
      }
      return path3.slice(start, end);
    }
    for (i = path3.length - 1; i >= start; --i) {
      if (isPathSeparator(path3.charCodeAt(i))) {
        if (!matchedSlash) {
          start = i + 1;
          break;
        }
      } else if (end === -1) {
        matchedSlash = false;
        end = i + 1;
      }
    }
    if (end === -1) {
      return "";
    }
    return path3.slice(start, end);
  },
  extname(path3) {
    validateString(path3, "path");
    let start = 0;
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let preDotState = 0;
    if (path3.length >= 2 && path3.charCodeAt(1) === CHAR_COLON && isWindowsDeviceRoot(path3.charCodeAt(0))) {
      start = startPart = 2;
    }
    for (let i = path3.length - 1; i >= start; --i) {
      const code2 = path3.charCodeAt(i);
      if (isPathSeparator(code2)) {
        if (!matchedSlash) {
          startPart = i + 1;
          break;
        }
        continue;
      }
      if (end === -1) {
        matchedSlash = false;
        end = i + 1;
      }
      if (code2 === CHAR_DOT) {
        if (startDot === -1) {
          startDot = i;
        } else if (preDotState !== 1) {
          preDotState = 1;
        }
      } else if (startDot !== -1) {
        preDotState = -1;
      }
    }
    if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot
    preDotState === 0 || // The (right-most) trimmed path component is exactly '..'
    preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
      return "";
    }
    return path3.slice(startDot, end);
  },
  format: _format2.bind(null, "\\"),
  parse(path3) {
    validateString(path3, "path");
    const ret = { root: "", dir: "", base: "", ext: "", name: "" };
    if (path3.length === 0) {
      return ret;
    }
    const len = path3.length;
    let rootEnd = 0;
    let code2 = path3.charCodeAt(0);
    if (len === 1) {
      if (isPathSeparator(code2)) {
        ret.root = ret.dir = path3;
        return ret;
      }
      ret.base = ret.name = path3;
      return ret;
    }
    if (isPathSeparator(code2)) {
      rootEnd = 1;
      if (isPathSeparator(path3.charCodeAt(1))) {
        let j = 2;
        let last = j;
        while (j < len && !isPathSeparator(path3.charCodeAt(j))) {
          j++;
        }
        if (j < len && j !== last) {
          last = j;
          while (j < len && isPathSeparator(path3.charCodeAt(j))) {
            j++;
          }
          if (j < len && j !== last) {
            last = j;
            while (j < len && !isPathSeparator(path3.charCodeAt(j))) {
              j++;
            }
            if (j === len) {
              rootEnd = j;
            } else if (j !== last) {
              rootEnd = j + 1;
            }
          }
        }
      }
    } else if (isWindowsDeviceRoot(code2) && path3.charCodeAt(1) === CHAR_COLON) {
      if (len <= 2) {
        ret.root = ret.dir = path3;
        return ret;
      }
      rootEnd = 2;
      if (isPathSeparator(path3.charCodeAt(2))) {
        if (len === 3) {
          ret.root = ret.dir = path3;
          return ret;
        }
        rootEnd = 3;
      }
    }
    if (rootEnd > 0) {
      ret.root = path3.slice(0, rootEnd);
    }
    let startDot = -1;
    let startPart = rootEnd;
    let end = -1;
    let matchedSlash = true;
    let i = path3.length - 1;
    let preDotState = 0;
    for (; i >= rootEnd; --i) {
      code2 = path3.charCodeAt(i);
      if (isPathSeparator(code2)) {
        if (!matchedSlash) {
          startPart = i + 1;
          break;
        }
        continue;
      }
      if (end === -1) {
        matchedSlash = false;
        end = i + 1;
      }
      if (code2 === CHAR_DOT) {
        if (startDot === -1) {
          startDot = i;
        } else if (preDotState !== 1) {
          preDotState = 1;
        }
      } else if (startDot !== -1) {
        preDotState = -1;
      }
    }
    if (end !== -1) {
      if (startDot === -1 || // We saw a non-dot character immediately before the dot
      preDotState === 0 || // The (right-most) trimmed path component is exactly '..'
      preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
        ret.base = ret.name = path3.slice(startPart, end);
      } else {
        ret.name = path3.slice(startPart, startDot);
        ret.base = path3.slice(startPart, end);
        ret.ext = path3.slice(startDot, end);
      }
    }
    if (startPart > 0 && startPart !== rootEnd) {
      ret.dir = path3.slice(0, startPart - 1);
    } else {
      ret.dir = ret.root;
    }
    return ret;
  },
  sep: "\\",
  delimiter: ";",
  win32: null,
  posix: null
};
var posixCwd = (() => {
  if (platformIsWin32) {
    const regexp = /\\/g;
    return () => {
      const cwd2 = cwd().replace(regexp, "/");
      return cwd2.slice(cwd2.indexOf("/"));
    };
  }
  return () => cwd();
})();
var $sc = {
  // path.resolve([from ...], to)
  resolve(...pathSegments) {
    let resolvedPath = "";
    let resolvedAbsolute = false;
    for (let i = pathSegments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
      const path3 = i >= 0 ? pathSegments[i] : posixCwd();
      validateString(path3, `paths[${i}]`);
      if (path3.length === 0) {
        continue;
      }
      resolvedPath = `${path3}/${resolvedPath}`;
      resolvedAbsolute = path3.charCodeAt(0) === CHAR_FORWARD_SLASH;
    }
    resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, "/", isPosixPathSeparator);
    if (resolvedAbsolute) {
      return `/${resolvedPath}`;
    }
    return resolvedPath.length > 0 ? resolvedPath : ".";
  },
  normalize(path3) {
    validateString(path3, "path");
    if (path3.length === 0) {
      return ".";
    }
    const isAbsolute = path3.charCodeAt(0) === CHAR_FORWARD_SLASH;
    const trailingSeparator = path3.charCodeAt(path3.length - 1) === CHAR_FORWARD_SLASH;
    path3 = normalizeString(path3, !isAbsolute, "/", isPosixPathSeparator);
    if (path3.length === 0) {
      if (isAbsolute) {
        return "/";
      }
      return trailingSeparator ? "./" : ".";
    }
    if (trailingSeparator) {
      path3 += "/";
    }
    return isAbsolute ? `/${path3}` : path3;
  },
  isAbsolute(path3) {
    validateString(path3, "path");
    return path3.length > 0 && path3.charCodeAt(0) === CHAR_FORWARD_SLASH;
  },
  join(...paths) {
    if (paths.length === 0) {
      return ".";
    }
    let joined;
    for (let i = 0; i < paths.length; ++i) {
      const arg = paths[i];
      validateString(arg, "path");
      if (arg.length > 0) {
        if (joined === void 0) {
          joined = arg;
        } else {
          joined += `/${arg}`;
        }
      }
    }
    if (joined === void 0) {
      return ".";
    }
    return $sc.normalize(joined);
  },
  relative(from, to) {
    validateString(from, "from");
    validateString(to, "to");
    if (from === to) {
      return "";
    }
    from = $sc.resolve(from);
    to = $sc.resolve(to);
    if (from === to) {
      return "";
    }
    const fromStart = 1;
    const fromEnd = from.length;
    const fromLen = fromEnd - fromStart;
    const toStart = 1;
    const toLen = to.length - toStart;
    const length = fromLen < toLen ? fromLen : toLen;
    let lastCommonSep = -1;
    let i = 0;
    for (; i < length; i++) {
      const fromCode = from.charCodeAt(fromStart + i);
      if (fromCode !== to.charCodeAt(toStart + i)) {
        break;
      } else if (fromCode === CHAR_FORWARD_SLASH) {
        lastCommonSep = i;
      }
    }
    if (i === length) {
      if (toLen > length) {
        if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
          return to.slice(toStart + i + 1);
        }
        if (i === 0) {
          return to.slice(toStart + i);
        }
      } else if (fromLen > length) {
        if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
          lastCommonSep = i;
        } else if (i === 0) {
          lastCommonSep = 0;
        }
      }
    }
    let out = "";
    for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
      if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
        out += out.length === 0 ? ".." : "/..";
      }
    }
    return `${out}${to.slice(toStart + lastCommonSep)}`;
  },
  toNamespacedPath(path3) {
    return path3;
  },
  dirname(path3) {
    validateString(path3, "path");
    if (path3.length === 0) {
      return ".";
    }
    const hasRoot = path3.charCodeAt(0) === CHAR_FORWARD_SLASH;
    let end = -1;
    let matchedSlash = true;
    for (let i = path3.length - 1; i >= 1; --i) {
      if (path3.charCodeAt(i) === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          end = i;
          break;
        }
      } else {
        matchedSlash = false;
      }
    }
    if (end === -1) {
      return hasRoot ? "/" : ".";
    }
    if (hasRoot && end === 1) {
      return "//";
    }
    return path3.slice(0, end);
  },
  basename(path3, suffix) {
    if (suffix !== void 0) {
      validateString(suffix, "ext");
    }
    validateString(path3, "path");
    let start = 0;
    let end = -1;
    let matchedSlash = true;
    let i;
    if (suffix !== void 0 && suffix.length > 0 && suffix.length <= path3.length) {
      if (suffix === path3) {
        return "";
      }
      let extIdx = suffix.length - 1;
      let firstNonSlashEnd = -1;
      for (i = path3.length - 1; i >= 0; --i) {
        const code2 = path3.charCodeAt(i);
        if (code2 === CHAR_FORWARD_SLASH) {
          if (!matchedSlash) {
            start = i + 1;
            break;
          }
        } else {
          if (firstNonSlashEnd === -1) {
            matchedSlash = false;
            firstNonSlashEnd = i + 1;
          }
          if (extIdx >= 0) {
            if (code2 === suffix.charCodeAt(extIdx)) {
              if (--extIdx === -1) {
                end = i;
              }
            } else {
              extIdx = -1;
              end = firstNonSlashEnd;
            }
          }
        }
      }
      if (start === end) {
        end = firstNonSlashEnd;
      } else if (end === -1) {
        end = path3.length;
      }
      return path3.slice(start, end);
    }
    for (i = path3.length - 1; i >= 0; --i) {
      if (path3.charCodeAt(i) === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1;
          break;
        }
      } else if (end === -1) {
        matchedSlash = false;
        end = i + 1;
      }
    }
    if (end === -1) {
      return "";
    }
    return path3.slice(start, end);
  },
  extname(path3) {
    validateString(path3, "path");
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let preDotState = 0;
    for (let i = path3.length - 1; i >= 0; --i) {
      const code2 = path3.charCodeAt(i);
      if (code2 === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          startPart = i + 1;
          break;
        }
        continue;
      }
      if (end === -1) {
        matchedSlash = false;
        end = i + 1;
      }
      if (code2 === CHAR_DOT) {
        if (startDot === -1) {
          startDot = i;
        } else if (preDotState !== 1) {
          preDotState = 1;
        }
      } else if (startDot !== -1) {
        preDotState = -1;
      }
    }
    if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot
    preDotState === 0 || // The (right-most) trimmed path component is exactly '..'
    preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
      return "";
    }
    return path3.slice(startDot, end);
  },
  format: _format2.bind(null, "/"),
  parse(path3) {
    validateString(path3, "path");
    const ret = { root: "", dir: "", base: "", ext: "", name: "" };
    if (path3.length === 0) {
      return ret;
    }
    const isAbsolute = path3.charCodeAt(0) === CHAR_FORWARD_SLASH;
    let start;
    if (isAbsolute) {
      ret.root = "/";
      start = 1;
    } else {
      start = 0;
    }
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let i = path3.length - 1;
    let preDotState = 0;
    for (; i >= start; --i) {
      const code2 = path3.charCodeAt(i);
      if (code2 === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          startPart = i + 1;
          break;
        }
        continue;
      }
      if (end === -1) {
        matchedSlash = false;
        end = i + 1;
      }
      if (code2 === CHAR_DOT) {
        if (startDot === -1) {
          startDot = i;
        } else if (preDotState !== 1) {
          preDotState = 1;
        }
      } else if (startDot !== -1) {
        preDotState = -1;
      }
    }
    if (end !== -1) {
      const start2 = startPart === 0 && isAbsolute ? 1 : startPart;
      if (startDot === -1 || // We saw a non-dot character immediately before the dot
      preDotState === 0 || // The (right-most) trimmed path component is exactly '..'
      preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
        ret.base = ret.name = path3.slice(start2, end);
      } else {
        ret.name = path3.slice(start2, startDot);
        ret.base = path3.slice(start2, end);
        ret.ext = path3.slice(startDot, end);
      }
    }
    if (startPart > 0) {
      ret.dir = path3.slice(0, startPart - 1);
    } else if (isAbsolute) {
      ret.dir = "/";
    }
    return ret;
  },
  sep: "/",
  delimiter: ":",
  win32: null,
  posix: null
};
$sc.win32 = $rc.win32 = $rc;
$sc.posix = $rc.posix = $sc;
var $tc = platformIsWin32 ? $rc.normalize : $sc.normalize;
var $uc = platformIsWin32 ? $rc.isAbsolute : $sc.isAbsolute;
var $vc = platformIsWin32 ? $rc.join : $sc.join;
var $wc = platformIsWin32 ? $rc.resolve : $sc.resolve;
var $xc = platformIsWin32 ? $rc.relative : $sc.relative;
var $yc = platformIsWin32 ? $rc.dirname : $sc.dirname;
var $zc = platformIsWin32 ? $rc.basename : $sc.basename;
var $Ac = platformIsWin32 ? $rc.extname : $sc.extname;
var $Bc = platformIsWin32 ? $rc.format : $sc.format;
var $Cc = platformIsWin32 ? $rc.parse : $sc.parse;
var $Dc = platformIsWin32 ? $rc.toNamespacedPath : $sc.toNamespacedPath;
var sep = platformIsWin32 ? $rc.sep : $sc.sep;
var $Fc = platformIsWin32 ? $rc.delimiter : $sc.delimiter;

// out-build/vs/base/common/uri.js
var _schemePattern = /^\w[\w\d+.-]*$/;
var _singleSlashStart = /^\//;
var _doubleSlashStart = /^\/\//;
function _validateUri(ret, _strict) {
  if (!ret.scheme && _strict) {
    throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${ret.authority}", path: "${ret.path}", query: "${ret.query}", fragment: "${ret.fragment}"}`);
  }
  if (ret.scheme && !_schemePattern.test(ret.scheme)) {
    throw new Error("[UriError]: Scheme contains illegal characters.");
  }
  if (ret.path) {
    if (ret.authority) {
      if (!_singleSlashStart.test(ret.path)) {
        throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character');
      }
    } else {
      if (_doubleSlashStart.test(ret.path)) {
        throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")');
      }
    }
  }
}
function _schemeFix(scheme, _strict) {
  if (!scheme && !_strict) {
    return "file";
  }
  return scheme;
}
function _referenceResolution(scheme, path3) {
  switch (scheme) {
    case "https":
    case "http":
    case "file":
      if (!path3) {
        path3 = _slash;
      } else if (path3[0] !== _slash) {
        path3 = _slash + path3;
      }
      break;
  }
  return path3;
}
var _empty = "";
var _slash = "/";
var _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
var URI = class _URI {
  static isUri(thing) {
    if (thing instanceof _URI) {
      return true;
    }
    if (!thing) {
      return false;
    }
    return typeof thing.authority === "string" && typeof thing.fragment === "string" && typeof thing.path === "string" && typeof thing.query === "string" && typeof thing.scheme === "string" && typeof thing.fsPath === "string" && typeof thing.with === "function" && typeof thing.toString === "function";
  }
  /**
   * @internal
   */
  constructor(schemeOrData, authority, path3, query, fragment, _strict = false) {
    if (typeof schemeOrData === "object") {
      this.scheme = schemeOrData.scheme || _empty;
      this.authority = schemeOrData.authority || _empty;
      this.path = schemeOrData.path || _empty;
      this.query = schemeOrData.query || _empty;
      this.fragment = schemeOrData.fragment || _empty;
    } else {
      this.scheme = _schemeFix(schemeOrData, _strict);
      this.authority = authority || _empty;
      this.path = _referenceResolution(this.scheme, path3 || _empty);
      this.query = query || _empty;
      this.fragment = fragment || _empty;
      _validateUri(this, _strict);
    }
  }
  // ---- filesystem path -----------------------
  /**
   * Returns a string representing the corresponding file system path of this URI.
   * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the
   * platform specific path separator.
   *
   * * Will *not* validate the path for invalid characters and semantics.
   * * Will *not* look at the scheme of this URI.
   * * The result shall *not* be used for display purposes but for accessing a file on disk.
   *
   *
   * The *difference* to `URI#path` is the use of the platform specific separator and the handling
   * of UNC paths. See the below sample of a file-uri with an authority (UNC path).
   *
   * ```ts
      const u = URI.parse('file://server/c$/folder/file.txt')
      u.authority === 'server'
      u.path === '/shares/c$/file.txt'
      u.fsPath === '\\server\c$\folder\file.txt'
  ```
   *
   * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path,
   * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working
   * with URIs that represent files on disk (`file` scheme).
   */
  get fsPath() {
    return $Ic(this, false);
  }
  // ---- modify to new -------------------------
  with(change) {
    if (!change) {
      return this;
    }
    let { scheme, authority, path: path3, query, fragment } = change;
    if (scheme === void 0) {
      scheme = this.scheme;
    } else if (scheme === null) {
      scheme = _empty;
    }
    if (authority === void 0) {
      authority = this.authority;
    } else if (authority === null) {
      authority = _empty;
    }
    if (path3 === void 0) {
      path3 = this.path;
    } else if (path3 === null) {
      path3 = _empty;
    }
    if (query === void 0) {
      query = this.query;
    } else if (query === null) {
      query = _empty;
    }
    if (fragment === void 0) {
      fragment = this.fragment;
    } else if (fragment === null) {
      fragment = _empty;
    }
    if (scheme === this.scheme && authority === this.authority && path3 === this.path && query === this.query && fragment === this.fragment) {
      return this;
    }
    return new Uri(scheme, authority, path3, query, fragment);
  }
  // ---- parse & validate ------------------------
  /**
   * Creates a new URI from a string, e.g. `http://www.example.com/some/path`,
   * `file:///usr/home`, or `scheme:with/path`.
   *
   * @param value A string which represents an URI (see `URI#toString`).
   */
  static parse(value, _strict = false) {
    const match = _regexp.exec(value);
    if (!match) {
      return new Uri(_empty, _empty, _empty, _empty, _empty);
    }
    return new Uri(match[2] || _empty, percentDecode(match[4] || _empty), percentDecode(match[5] || _empty), percentDecode(match[7] || _empty), percentDecode(match[9] || _empty), _strict);
  }
  /**
   * Creates a new URI from a file system path, e.g. `c:\my\files`,
   * `/usr/home`, or `\\server\share\some\path`.
   *
   * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument
   * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as**
   * `URI.parse('file://' + path)` because the path might contain characters that are
   * interpreted (# and ?). See the following sample:
   * ```ts
  const good = URI.file('/coding/c#/project1');
  good.scheme === 'file';
  good.path === '/coding/c#/project1';
  good.fragment === '';
  const bad = URI.parse('file://' + '/coding/c#/project1');
  bad.scheme === 'file';
  bad.path === '/coding/c'; // path is now broken
  bad.fragment === '/project1';
  ```
   *
   * @param path A file system path (see `URI#fsPath`)
   */
  static file(path3) {
    let authority = _empty;
    if ($l) {
      path3 = path3.replace(/\\/g, _slash);
    }
    if (path3[0] === _slash && path3[1] === _slash) {
      const idx = path3.indexOf(_slash, 2);
      if (idx === -1) {
        authority = path3.substring(2);
        path3 = _slash;
      } else {
        authority = path3.substring(2, idx);
        path3 = path3.substring(idx) || _slash;
      }
    }
    return new Uri("file", authority, path3, _empty, _empty);
  }
  /**
   * Creates new URI from uri components.
   *
   * Unless `strict` is `true` the scheme is defaults to be `file`. This function performs
   * validation and should be used for untrusted uri components retrieved from storage,
   * user input, command arguments etc
   */
  static from(components, strict) {
    const result = new Uri(components.scheme, components.authority, components.path, components.query, components.fragment, strict);
    return result;
  }
  /**
   * Join a URI path with path fragments and normalizes the resulting path.
   *
   * @param uri The input URI.
   * @param pathFragment The path fragment to add to the URI path.
   * @returns The resulting URI.
   */
  static joinPath(uri, ...pathFragment) {
    if (!uri.path) {
      throw new Error(`[UriError]: cannot call joinPath on URI without path`);
    }
    let newPath;
    if ($l && uri.scheme === "file") {
      newPath = _URI.file($rc.join($Ic(uri, true), ...pathFragment)).path;
    } else {
      newPath = $sc.join(uri.path, ...pathFragment);
    }
    return uri.with({ path: newPath });
  }
  // ---- printing/externalize ---------------------------
  /**
   * Creates a string representation for this URI. It's guaranteed that calling
   * `URI.parse` with the result of this function creates an URI which is equal
   * to this URI.
   *
   * * The result shall *not* be used for display purposes but for externalization or transport.
   * * The result will be encoded using the percentage encoding and encoding happens mostly
   * ignore the scheme-specific encoding rules.
   *
   * @param skipEncoding Do not encode the result, default is `false`
   */
  toString(skipEncoding = false) {
    return _asFormatted(this, skipEncoding);
  }
  toJSON() {
    return this;
  }
  static revive(data) {
    if (!data) {
      return data;
    } else if (data instanceof _URI) {
      return data;
    } else {
      const result = new Uri(data);
      result._formatted = data.external ?? null;
      result._fsPath = data._sep === _pathSepMarker ? data.fsPath ?? null : null;
      return result;
    }
  }
  [Symbol.for("debug.description")]() {
    return `URI(${this.toString()})`;
  }
};
var _pathSepMarker = $l ? 1 : void 0;
var Uri = class extends URI {
  constructor() {
    super(...arguments);
    this._formatted = null;
    this._fsPath = null;
  }
  get fsPath() {
    if (!this._fsPath) {
      this._fsPath = $Ic(this, false);
    }
    return this._fsPath;
  }
  toString(skipEncoding = false) {
    if (!skipEncoding) {
      if (!this._formatted) {
        this._formatted = _asFormatted(this, false);
      }
      return this._formatted;
    } else {
      return _asFormatted(this, true);
    }
  }
  toJSON() {
    const res = {
      $mid: 1
      /* MarshalledId.Uri */
    };
    if (this._fsPath) {
      res.fsPath = this._fsPath;
      res._sep = _pathSepMarker;
    }
    if (this._formatted) {
      res.external = this._formatted;
    }
    if (this.path) {
      res.path = this.path;
    }
    if (this.scheme) {
      res.scheme = this.scheme;
    }
    if (this.authority) {
      res.authority = this.authority;
    }
    if (this.query) {
      res.query = this.query;
    }
    if (this.fragment) {
      res.fragment = this.fragment;
    }
    return res;
  }
};
var encodeTable = {
  [
    58
    /* CharCode.Colon */
  ]: "%3A",
  // gen-delims
  [
    47
    /* CharCode.Slash */
  ]: "%2F",
  [
    63
    /* CharCode.QuestionMark */
  ]: "%3F",
  [
    35
    /* CharCode.Hash */
  ]: "%23",
  [
    91
    /* CharCode.OpenSquareBracket */
  ]: "%5B",
  [
    93
    /* CharCode.CloseSquareBracket */
  ]: "%5D",
  [
    64
    /* CharCode.AtSign */
  ]: "%40",
  [
    33
    /* CharCode.ExclamationMark */
  ]: "%21",
  // sub-delims
  [
    36
    /* CharCode.DollarSign */
  ]: "%24",
  [
    38
    /* CharCode.Ampersand */
  ]: "%26",
  [
    39
    /* CharCode.SingleQuote */
  ]: "%27",
  [
    40
    /* CharCode.OpenParen */
  ]: "%28",
  [
    41
    /* CharCode.CloseParen */
  ]: "%29",
  [
    42
    /* CharCode.Asterisk */
  ]: "%2A",
  [
    43
    /* CharCode.Plus */
  ]: "%2B",
  [
    44
    /* CharCode.Comma */
  ]: "%2C",
  [
    59
    /* CharCode.Semicolon */
  ]: "%3B",
  [
    61
    /* CharCode.Equals */
  ]: "%3D",
  [
    32
    /* CharCode.Space */
  ]: "%20"
};
function encodeURIComponentFast(uriComponent, isPath, isAuthority) {
  let res = void 0;
  let nativeEncodePos = -1;
  for (let pos = 0; pos < uriComponent.length; pos++) {
    const code2 = uriComponent.charCodeAt(pos);
    if (code2 >= 97 && code2 <= 122 || code2 >= 65 && code2 <= 90 || code2 >= 48 && code2 <= 57 || code2 === 45 || code2 === 46 || code2 === 95 || code2 === 126 || isPath && code2 === 47 || isAuthority && code2 === 91 || isAuthority && code2 === 93 || isAuthority && code2 === 58) {
      if (nativeEncodePos !== -1) {
        res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
        nativeEncodePos = -1;
      }
      if (res !== void 0) {
        res += uriComponent.charAt(pos);
      }
    } else {
      if (res === void 0) {
        res = uriComponent.substr(0, pos);
      }
      const escaped = encodeTable[code2];
      if (escaped !== void 0) {
        if (nativeEncodePos !== -1) {
          res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
          nativeEncodePos = -1;
        }
        res += escaped;
      } else if (nativeEncodePos === -1) {
        nativeEncodePos = pos;
      }
    }
  }
  if (nativeEncodePos !== -1) {
    res += encodeURIComponent(uriComponent.substring(nativeEncodePos));
  }
  return res !== void 0 ? res : uriComponent;
}
function encodeURIComponentMinimal(path3) {
  let res = void 0;
  for (let pos = 0; pos < path3.length; pos++) {
    const code2 = path3.charCodeAt(pos);
    if (code2 === 35 || code2 === 63) {
      if (res === void 0) {
        res = path3.substr(0, pos);
      }
      res += encodeTable[code2];
    } else {
      if (res !== void 0) {
        res += path3[pos];
      }
    }
  }
  return res !== void 0 ? res : path3;
}
function $Ic(uri, keepDriveLetterCasing) {
  let value;
  if (uri.authority && uri.path.length > 1 && uri.scheme === "file") {
    value = `//${uri.authority}${uri.path}`;
  } else if (uri.path.charCodeAt(0) === 47 && (uri.path.charCodeAt(1) >= 65 && uri.path.charCodeAt(1) <= 90 || uri.path.charCodeAt(1) >= 97 && uri.path.charCodeAt(1) <= 122) && uri.path.charCodeAt(2) === 58) {
    if (!keepDriveLetterCasing) {
      value = uri.path[1].toLowerCase() + uri.path.substr(2);
    } else {
      value = uri.path.substr(1);
    }
  } else {
    value = uri.path;
  }
  if ($l) {
    value = value.replace(/\//g, "\\");
  }
  return value;
}
function _asFormatted(uri, skipEncoding) {
  const encoder = !skipEncoding ? encodeURIComponentFast : encodeURIComponentMinimal;
  let res = "";
  let { scheme, authority, path: path3, query, fragment } = uri;
  if (scheme) {
    res += scheme;
    res += ":";
  }
  if (authority || scheme === "file") {
    res += _slash;
    res += _slash;
  }
  if (authority) {
    let idx = authority.indexOf("@");
    if (idx !== -1) {
      const userinfo = authority.substr(0, idx);
      authority = authority.substr(idx + 1);
      idx = userinfo.lastIndexOf(":");
      if (idx === -1) {
        res += encoder(userinfo, false, false);
      } else {
        res += encoder(userinfo.substr(0, idx), false, false);
        res += ":";
        res += encoder(userinfo.substr(idx + 1), false, true);
      }
      res += "@";
    }
    authority = authority.toLowerCase();
    idx = authority.lastIndexOf(":");
    if (idx === -1) {
      res += encoder(authority, false, true);
    } else {
      res += encoder(authority.substr(0, idx), false, true);
      res += authority.substr(idx);
    }
  }
  if (path3) {
    if (path3.length >= 3 && path3.charCodeAt(0) === 47 && path3.charCodeAt(2) === 58) {
      const code2 = path3.charCodeAt(1);
      if (code2 >= 65 && code2 <= 90) {
        path3 = `/${String.fromCharCode(code2 + 32)}:${path3.substr(3)}`;
      }
    } else if (path3.length >= 2 && path3.charCodeAt(1) === 58) {
      const code2 = path3.charCodeAt(0);
      if (code2 >= 65 && code2 <= 90) {
        path3 = `${String.fromCharCode(code2 + 32)}:${path3.substr(2)}`;
      }
    }
    res += encoder(path3, true, false);
  }
  if (query) {
    res += "?";
    res += encoder(query, false, false);
  }
  if (fragment) {
    res += "#";
    res += !skipEncoding ? encodeURIComponentFast(fragment, false, false) : fragment;
  }
  return res;
}
function decodeURIComponentGraceful(str) {
  try {
    return decodeURIComponent(str);
  } catch {
    if (str.length > 3) {
      return str.substr(0, 3) + decodeURIComponentGraceful(str.substr(3));
    } else {
      return str;
    }
  }
}
var _rEncodedAsHex = /(%[0-9A-Za-z][0-9A-Za-z])+/g;
function percentDecode(str) {
  if (!str.match(_rEncodedAsHex)) {
    return str;
  }
  return str.replace(_rEncodedAsHex, (match) => decodeURIComponentGraceful(match));
}

// out-build/vs/platform/instantiation/common/instantiation.js
var _util;
(function(_util2) {
  _util2.serviceIds = /* @__PURE__ */ new Map();
  _util2.DI_TARGET = "$di$target";
  _util2.DI_DEPENDENCIES = "$di$dependencies";
  function getServiceDependencies(ctor) {
    return ctor[_util2.DI_DEPENDENCIES] || [];
  }
  _util2.getServiceDependencies = getServiceDependencies;
})(_util || (_util = {}));
var $Yi = $Zi("instantiationService");
function storeServiceDependency(id2, target, index) {
  if (target[_util.DI_TARGET] === target) {
    target[_util.DI_DEPENDENCIES].push({ id: id2, index });
  } else {
    target[_util.DI_DEPENDENCIES] = [{ id: id2, index }];
    target[_util.DI_TARGET] = target;
  }
}
function $Zi(serviceId) {
  if (_util.serviceIds.has(serviceId)) {
    return _util.serviceIds.get(serviceId);
  }
  const id2 = function(target, key, index) {
    if (arguments.length !== 3) {
      throw new Error("@IServiceName-decorator can only be used to decorate a parameter");
    }
    storeServiceDependency(id2, target, index);
  };
  id2.toString = () => serviceId;
  _util.serviceIds.set(serviceId, id2);
  return id2;
}
function $1i(serviceIdentifier) {
  return serviceIdentifier;
}

// out-build/vs/platform/configuration/common/configuration.js
var $tj = $Zi("configurationService");
function $uj(thing) {
  return thing && typeof thing === "object" && (!thing.overrideIdentifier || typeof thing.overrideIdentifier === "string") && (!thing.resource || thing.resource instanceof URI);
}
function $vj(thing) {
  return thing && typeof thing === "object" && (!thing.overrideIdentifiers || Array.isArray(thing.overrideIdentifiers)) && !thing.overrideIdentifier && (!thing.resource || thing.resource instanceof URI);
}
var ConfigurationTarget;
(function(ConfigurationTarget2) {
  ConfigurationTarget2[ConfigurationTarget2["APPLICATION"] = 1] = "APPLICATION";
  ConfigurationTarget2[ConfigurationTarget2["USER"] = 2] = "USER";
  ConfigurationTarget2[ConfigurationTarget2["USER_LOCAL"] = 3] = "USER_LOCAL";
  ConfigurationTarget2[ConfigurationTarget2["USER_REMOTE"] = 4] = "USER_REMOTE";
  ConfigurationTarget2[ConfigurationTarget2["WORKSPACE"] = 5] = "WORKSPACE";
  ConfigurationTarget2[ConfigurationTarget2["WORKSPACE_FOLDER"] = 6] = "WORKSPACE_FOLDER";
  ConfigurationTarget2[ConfigurationTarget2["DEFAULT"] = 7] = "DEFAULT";
  ConfigurationTarget2[ConfigurationTarget2["MEMORY"] = 8] = "MEMORY";
})(ConfigurationTarget || (ConfigurationTarget = {}));
function $yj(properties, conflictReporter) {
  const root = /* @__PURE__ */ Object.create(null);
  for (const key in properties) {
    $zj(root, key, properties[key], conflictReporter);
  }
  return root;
}
function $zj(settingsTreeRoot, key, value, conflictReporter) {
  const segments = key.split(".");
  const last = segments.pop();
  let curr = settingsTreeRoot;
  for (let i = 0; i < segments.length; i++) {
    const s = segments[i];
    let obj = curr[s];
    switch (typeof obj) {
      case "undefined":
        obj = curr[s] = /* @__PURE__ */ Object.create(null);
        break;
      case "object":
        if (obj === null) {
          conflictReporter(`Ignoring ${key} as ${segments.slice(0, i + 1).join(".")} is null`);
          return;
        }
        break;
      default:
        conflictReporter(`Ignoring ${key} as ${segments.slice(0, i + 1).join(".")} is ${JSON.stringify(obj)}`);
        return;
    }
    curr = obj;
  }
  if (typeof curr === "object" && curr !== null) {
    try {
      curr[last] = value;
    } catch (e) {
      conflictReporter(`Ignoring ${key} as ${segments.join(".")} is ${JSON.stringify(curr)}`);
    }
  } else {
    conflictReporter(`Ignoring ${key} as ${segments.join(".")} is ${JSON.stringify(curr)}`);
  }
}
function $Aj(valueTree, key) {
  const segments = key.split(".");
  doRemoveFromValueTree(valueTree, segments);
}
function doRemoveFromValueTree(valueTree, segments) {
  const first = segments.shift();
  if (segments.length === 0) {
    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];
      }
    }
  }
}
function $Bj(config, settingPath, defaultValue) {
  function accessSetting(config2, path4) {
    let current = config2;
    for (const component of path4) {
      if (typeof current !== "object" || current === null) {
        return void 0;
      }
      current = current[component];
    }
    return current;
  }
  const path3 = settingPath.split(".");
  const result = accessSetting(config, path3);
  return typeof result === "undefined" ? defaultValue : result;
}
function $Dj(settingKey) {
  return settingKey.replace(/[\[\]]/g, "");
}

// out-build/vs/base/common/jsonSchema.js
function $pk(schema) {
  let hasDups = false;
  const equalsByString = /* @__PURE__ */ new Map();
  const nodeToEquals = /* @__PURE__ */ new Map();
  const visitSchemas = (next) => {
    if (schema === next) {
      return true;
    }
    const val = JSON.stringify(next);
    if (val.length < 30) {
      return true;
    }
    const eq2 = equalsByString.get(val);
    if (!eq2) {
      const newEq = { schemas: [next] };
      equalsByString.set(val, newEq);
      nodeToEquals.set(next, newEq);
      return true;
    }
    eq2.schemas.push(next);
    nodeToEquals.set(next, eq2);
    hasDups = true;
    return false;
  };
  traverseNodes(schema, visitSchemas);
  equalsByString.clear();
  if (!hasDups) {
    return JSON.stringify(schema);
  }
  let defNodeName = "$defs";
  while (schema.hasOwnProperty(defNodeName)) {
    defNodeName += "_";
  }
  const definitions = [];
  function stringify(root) {
    return JSON.stringify(root, (_key, value) => {
      if (value !== root) {
        const eq2 = nodeToEquals.get(value);
        if (eq2 && eq2.schemas.length > 1) {
          if (!eq2.id) {
            eq2.id = `_${definitions.length}`;
            definitions.push(eq2.schemas[0]);
          }
          return { $ref: `#/${defNodeName}/${eq2.id}` };
        }
      }
      return value;
    });
  }
  const str = stringify(schema);
  const defStrings = [];
  for (let i = 0; i < definitions.length; i++) {
    defStrings.push(`"_${i}":${stringify(definitions[i])}`);
  }
  if (defStrings.length) {
    return `${str.substring(0, str.length - 1)},"${defNodeName}":{${defStrings.join(",")}}}`;
  }
  return str;
}
function isObject(thing) {
  return typeof thing === "object" && thing !== null;
}
function traverseNodes(root, visit) {
  if (!root || typeof root !== "object") {
    return;
  }
  const collectEntries = (...entries) => {
    for (const entry of entries) {
      if (isObject(entry)) {
        toWalk.push(entry);
      }
    }
  };
  const collectMapEntries = (...maps) => {
    for (const map of maps) {
      if (isObject(map)) {
        for (const key in map) {
          const entry = map[key];
          if (isObject(entry)) {
            toWalk.push(entry);
          }
        }
      }
    }
  };
  const collectArrayEntries = (...arrays) => {
    for (const array of arrays) {
      if (Array.isArray(array)) {
        for (const entry of array) {
          if (isObject(entry)) {
            toWalk.push(entry);
          }
        }
      }
    }
  };
  const collectEntryOrArrayEntries = (items) => {
    if (Array.isArray(items)) {
      for (const entry of items) {
        if (isObject(entry)) {
          toWalk.push(entry);
        }
      }
    } else if (isObject(items)) {
      toWalk.push(items);
    }
  };
  const toWalk = [root];
  let next = toWalk.pop();
  while (next) {
    const visitChildern = visit(next);
    if (visitChildern) {
      collectEntries(next.additionalItems, next.additionalProperties, next.not, next.contains, next.propertyNames, next.if, next.then, next.else, next.unevaluatedItems, next.unevaluatedProperties);
      collectMapEntries(next.definitions, next.$defs, next.properties, next.patternProperties, next.dependencies, next.dependentSchemas);
      collectArrayEntries(next.anyOf, next.allOf, next.oneOf, next.prefixItems);
      collectEntryOrArrayEntries(next.items);
    }
    next = toWalk.pop();
  }
}

// out-build/vs/base/common/assert.js
function ok(value, message) {
  if (!value) {
    throw new Error(message ? `Assertion failed (${message})` : "Assertion Failed");
  }
}

// out-build/vs/platform/registry/common/platform.js
var RegistryImpl = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  add(id2, data) {
    ok($yg(id2));
    ok($Ag(data));
    ok(!this.a.has(id2), "There is already an extension with this id");
    this.a.set(id2, data);
  }
  knows(id2) {
    return this.a.has(id2);
  }
  as(id2) {
    return this.a.get(id2) || null;
  }
};
var $Mo = new RegistryImpl();

// out-build/vs/platform/jsonschemas/common/jsonContributionRegistry.js
var $No = {
  JSONContribution: "base.contributions.json"
};
function normalizeId(id2) {
  if (id2.length > 0 && id2.charAt(id2.length - 1) === "#") {
    return id2.substring(0, id2.length - 1);
  }
  return id2;
}
var JSONContributionRegistry = class {
  constructor() {
    this.b = new $De();
    this.onDidChangeSchema = this.b.event;
    this.a = {};
  }
  registerSchema(uri, unresolvedSchemaContent) {
    this.a[normalizeId(uri)] = unresolvedSchemaContent;
    this.b.fire(uri);
  }
  notifySchemaChanged(uri) {
    this.b.fire(uri);
  }
  getSchemaContributions() {
    return {
      schemas: this.a
    };
  }
  getSchemaContent(uri) {
    const schema = this.a[uri];
    return schema ? $pk(schema) : void 0;
  }
  hasSchemaContent(uri) {
    return !!this.a[uri];
  }
};
var jsonContributionRegistry = new JSONContributionRegistry();
$Mo.add($No.JSONContribution, jsonContributionRegistry);

// out-build/vs/platform/configuration/common/configurationRegistry.js
var EditPresentationTypes;
(function(EditPresentationTypes2) {
  EditPresentationTypes2["Multiline"] = "multilineText";
  EditPresentationTypes2["Singleline"] = "singlelineText";
})(EditPresentationTypes || (EditPresentationTypes = {}));
var $Ro = {
  Configuration: "base.contributions.configuration"
};
var ConfigurationScope;
(function(ConfigurationScope2) {
  ConfigurationScope2[ConfigurationScope2["APPLICATION"] = 1] = "APPLICATION";
  ConfigurationScope2[ConfigurationScope2["MACHINE"] = 2] = "MACHINE";
  ConfigurationScope2[ConfigurationScope2["WINDOW"] = 3] = "WINDOW";
  ConfigurationScope2[ConfigurationScope2["RESOURCE"] = 4] = "RESOURCE";
  ConfigurationScope2[ConfigurationScope2["LANGUAGE_OVERRIDABLE"] = 5] = "LANGUAGE_OVERRIDABLE";
  ConfigurationScope2[ConfigurationScope2["MACHINE_OVERRIDABLE"] = 6] = "MACHINE_OVERRIDABLE";
})(ConfigurationScope || (ConfigurationScope = {}));
var $So = { properties: {}, patternProperties: {} };
var $To = { properties: {}, patternProperties: {} };
var $Uo = { properties: {}, patternProperties: {} };
var $Vo = { properties: {}, patternProperties: {} };
var $Wo = { properties: {}, patternProperties: {} };
var $Xo = { properties: {}, patternProperties: {} };
var $Yo = "vscode://schemas/settings/resourceLanguage";
var contributionRegistry = $Mo.as($No.JSONContribution);
var ConfigurationRegistry = class {
  constructor() {
    this.a = [];
    this.i = /* @__PURE__ */ new Set();
    this.j = new $De();
    this.onDidSchemaChange = this.j.event;
    this.k = new $De();
    this.onDidUpdateConfiguration = this.k.event;
    this.b = /* @__PURE__ */ new Map();
    this.c = {
      id: "defaultOverrides",
      title: localize(1672, null),
      properties: {}
    };
    this.d = [this.c];
    this.h = {
      properties: {},
      patternProperties: {},
      additionalProperties: true,
      allowTrailingCommas: true,
      allowComments: true
    };
    this.e = {};
    this.f = /* @__PURE__ */ new Map();
    this.g = {};
    contributionRegistry.registerSchema($Yo, this.h);
    this.z();
  }
  registerConfiguration(configuration, validate = true) {
    this.registerConfigurations([configuration], validate);
  }
  registerConfigurations(configurations, validate = true) {
    const properties = /* @__PURE__ */ new Set();
    this.r(configurations, validate, properties);
    contributionRegistry.registerSchema($Yo, this.h);
    this.j.fire();
    this.k.fire({ properties });
  }
  deregisterConfigurations(configurations) {
    const properties = /* @__PURE__ */ new Set();
    this.s(configurations, properties);
    contributionRegistry.registerSchema($Yo, this.h);
    this.j.fire();
    this.k.fire({ properties });
  }
  updateConfigurations({ add, remove }) {
    const properties = /* @__PURE__ */ new Set();
    this.s(remove, properties);
    this.r(add, false, properties);
    contributionRegistry.registerSchema($Yo, this.h);
    this.j.fire();
    this.k.fire({ properties });
  }
  registerDefaultConfigurations(configurationDefaults) {
    const properties = /* @__PURE__ */ new Set();
    this.l(configurationDefaults, properties);
    this.j.fire();
    this.k.fire({ properties, defaultsOverrides: true });
  }
  l(configurationDefaults, bucket) {
    this.a.push(...configurationDefaults);
    const overrideIdentifiers = [];
    for (const { overrides, source } of configurationDefaults) {
      for (const key in overrides) {
        bucket.add(key);
        const configurationDefaultOverridesForKey = this.b.get(key) ?? this.b.set(key, { configurationDefaultOverrides: [] }).get(key);
        const value = overrides[key];
        configurationDefaultOverridesForKey.configurationDefaultOverrides.push({ value, source });
        if ($2o.test(key)) {
          const newDefaultOverride = this.o(key, value, source, configurationDefaultOverridesForKey.configurationDefaultOverrideValue);
          if (!newDefaultOverride) {
            continue;
          }
          configurationDefaultOverridesForKey.configurationDefaultOverrideValue = newDefaultOverride;
          this.n(key, newDefaultOverride, source);
          overrideIdentifiers.push(...$3o(key));
        } else {
          const newDefaultOverride = this.p(key, value, source, configurationDefaultOverridesForKey.configurationDefaultOverrideValue);
          if (!newDefaultOverride) {
            continue;
          }
          configurationDefaultOverridesForKey.configurationDefaultOverrideValue = newDefaultOverride;
          const property = this.e[key];
          if (property) {
            this.A(key, property);
            this.w(key, property);
          }
        }
      }
    }
    this.q(overrideIdentifiers);
  }
  deregisterDefaultConfigurations(defaultConfigurations) {
    const properties = /* @__PURE__ */ new Set();
    this.m(defaultConfigurations, properties);
    this.j.fire();
    this.k.fire({ properties, defaultsOverrides: true });
  }
  m(defaultConfigurations, bucket) {
    for (const defaultConfiguration of defaultConfigurations) {
      const index = this.a.indexOf(defaultConfiguration);
      if (index !== -1) {
        this.a.splice(index, 1);
      }
    }
    for (const { overrides, source } of defaultConfigurations) {
      for (const key in overrides) {
        const configurationDefaultOverridesForKey = this.b.get(key);
        if (!configurationDefaultOverridesForKey) {
          continue;
        }
        const index = configurationDefaultOverridesForKey.configurationDefaultOverrides.findIndex((configurationDefaultOverride) => source ? configurationDefaultOverride.source?.id === source.id : configurationDefaultOverride.value === overrides[key]);
        if (index === -1) {
          continue;
        }
        configurationDefaultOverridesForKey.configurationDefaultOverrides.splice(index, 1);
        if (configurationDefaultOverridesForKey.configurationDefaultOverrides.length === 0) {
          this.b.delete(key);
        }
        if ($2o.test(key)) {
          let configurationDefaultOverrideValue;
          for (const configurationDefaultOverride of configurationDefaultOverridesForKey.configurationDefaultOverrides) {
            configurationDefaultOverrideValue = this.o(key, configurationDefaultOverride.value, configurationDefaultOverride.source, configurationDefaultOverrideValue);
          }
          if (configurationDefaultOverrideValue && !$Lg(configurationDefaultOverrideValue.value)) {
            configurationDefaultOverridesForKey.configurationDefaultOverrideValue = configurationDefaultOverrideValue;
            this.n(key, configurationDefaultOverrideValue, source);
          } else {
            this.b.delete(key);
            delete this.e[key];
            delete this.c.properties[key];
          }
        } else {
          let configurationDefaultOverrideValue;
          for (const configurationDefaultOverride of configurationDefaultOverridesForKey.configurationDefaultOverrides) {
            configurationDefaultOverrideValue = this.p(key, configurationDefaultOverride.value, configurationDefaultOverride.source, configurationDefaultOverrideValue);
          }
          configurationDefaultOverridesForKey.configurationDefaultOverrideValue = configurationDefaultOverrideValue;
          const property = this.e[key];
          if (property) {
            this.A(key, property);
            this.w(key, property);
          }
        }
        bucket.add(key);
      }
    }
    this.y();
  }
  n(key, newDefaultOverride, source) {
    const property = {
      type: "object",
      default: newDefaultOverride.value,
      description: localize(1673, null, $Dj(key)),
      $ref: $Yo,
      defaultDefaultValue: newDefaultOverride.value,
      source,
      defaultValueSource: source
    };
    this.e[key] = property;
    this.c.properties[key] = property;
  }
  o(overrideIdentifier, configurationValueObject, valueSource, existingDefaultOverride) {
    const defaultValue = existingDefaultOverride?.value || {};
    const source = existingDefaultOverride?.source ?? /* @__PURE__ */ new Map();
    if (!(source instanceof Map)) {
      console.error("objectConfigurationSources is not a Map");
      return void 0;
    }
    for (const propertyKey of Object.keys(configurationValueObject)) {
      const propertyDefaultValue = configurationValueObject[propertyKey];
      const isObjectSetting = $Ag(propertyDefaultValue) && ($Fg(defaultValue[propertyKey]) || $Ag(defaultValue[propertyKey]));
      if (isObjectSetting) {
        defaultValue[propertyKey] = { ...defaultValue[propertyKey] ?? {}, ...propertyDefaultValue };
        if (valueSource) {
          for (const objectKey in propertyDefaultValue) {
            source.set(`${propertyKey}.${objectKey}`, valueSource);
          }
        }
      } else {
        defaultValue[propertyKey] = propertyDefaultValue;
        if (valueSource) {
          source.set(propertyKey, valueSource);
        } else {
          source.delete(propertyKey);
        }
      }
    }
    return { value: defaultValue, source };
  }
  p(propertyKey, value, valuesSource, existingDefaultOverride) {
    const property = this.e[propertyKey];
    const existingDefaultValue = existingDefaultOverride?.value ?? property?.defaultDefaultValue;
    let source = valuesSource;
    const isObjectSetting = $Ag(value) && (property !== void 0 && property.type === "object" || property === void 0 && ($Fg(existingDefaultValue) || $Ag(existingDefaultValue)));
    if (isObjectSetting) {
      source = existingDefaultOverride?.source ?? /* @__PURE__ */ new Map();
      if (!(source instanceof Map)) {
        console.error("defaultValueSource is not a Map");
        return void 0;
      }
      for (const objectKey in value) {
        if (valuesSource) {
          source.set(`${propertyKey}.${objectKey}`, valuesSource);
        }
      }
      value = { ...$Ag(existingDefaultValue) ? existingDefaultValue : {}, ...value };
    }
    return { value, source };
  }
  deltaConfiguration(delta) {
    let defaultsOverrides = false;
    const properties = /* @__PURE__ */ new Set();
    if (delta.removedDefaults) {
      this.m(delta.removedDefaults, properties);
      defaultsOverrides = true;
    }
    if (delta.addedDefaults) {
      this.l(delta.addedDefaults, properties);
      defaultsOverrides = true;
    }
    if (delta.removedConfigurations) {
      this.s(delta.removedConfigurations, properties);
    }
    if (delta.addedConfigurations) {
      this.r(delta.addedConfigurations, false, properties);
    }
    this.j.fire();
    this.k.fire({ properties, defaultsOverrides });
  }
  notifyConfigurationSchemaUpdated(...configurations) {
    this.j.fire();
  }
  registerOverrideIdentifiers(overrideIdentifiers) {
    this.q(overrideIdentifiers);
    this.j.fire();
  }
  q(overrideIdentifiers) {
    for (const overrideIdentifier of overrideIdentifiers) {
      this.i.add(overrideIdentifier);
    }
    this.y();
  }
  r(configurations, validate, bucket) {
    configurations.forEach((configuration) => {
      this.u(configuration, validate, configuration.extensionInfo, configuration.restrictedProperties, void 0, bucket);
      this.d.push(configuration);
      this.v(configuration);
    });
  }
  s(configurations, bucket) {
    const deregisterConfiguration = (configuration) => {
      if (configuration.properties) {
        for (const key in configuration.properties) {
          bucket.add(key);
          const property = this.e[key];
          if (property?.policy?.name) {
            this.f.delete(property.policy.name);
          }
          delete this.e[key];
          this.x(key, configuration.properties[key]);
        }
      }
      configuration.allOf?.forEach((node) => deregisterConfiguration(node));
    };
    for (const configuration of configurations) {
      deregisterConfiguration(configuration);
      const index = this.d.indexOf(configuration);
      if (index !== -1) {
        this.d.splice(index, 1);
      }
    }
  }
  u(configuration, validate = true, extensionInfo, restrictedProperties, scope = 3, bucket) {
    scope = $Hg(configuration.scope) ? scope : configuration.scope;
    const properties = configuration.properties;
    if (properties) {
      for (const key in properties) {
        const property = properties[key];
        if (validate && $6o(key, property)) {
          delete properties[key];
          continue;
        }
        property.source = extensionInfo;
        property.defaultDefaultValue = properties[key].default;
        this.A(key, property);
        if ($2o.test(key)) {
          property.scope = void 0;
        } else {
          property.scope = $Hg(property.scope) ? scope : property.scope;
          property.restricted = $Hg(property.restricted) ? !!restrictedProperties?.includes(key) : property.restricted;
        }
        if (properties[key].hasOwnProperty("included") && !properties[key].included) {
          this.g[key] = properties[key];
          delete properties[key];
          continue;
        } else {
          this.e[key] = properties[key];
          if (properties[key].policy?.name) {
            this.f.set(properties[key].policy.name, key);
          }
        }
        if (!properties[key].deprecationMessage && properties[key].markdownDeprecationMessage) {
          properties[key].deprecationMessage = properties[key].markdownDeprecationMessage;
        }
        bucket.add(key);
      }
    }
    const subNodes = configuration.allOf;
    if (subNodes) {
      for (const node of subNodes) {
        this.u(node, validate, extensionInfo, restrictedProperties, scope, bucket);
      }
    }
  }
  // TODO: @sandy081 - Remove this method and include required info in getConfigurationProperties
  getConfigurations() {
    return this.d;
  }
  getConfigurationProperties() {
    return this.e;
  }
  getPolicyConfigurations() {
    return this.f;
  }
  getExcludedConfigurationProperties() {
    return this.g;
  }
  getRegisteredDefaultConfigurations() {
    return [...this.a];
  }
  getConfigurationDefaultsOverrides() {
    const configurationDefaultsOverrides = /* @__PURE__ */ new Map();
    for (const [key, value] of this.b) {
      if (value.configurationDefaultOverrideValue) {
        configurationDefaultsOverrides.set(key, value.configurationDefaultOverrideValue);
      }
    }
    return configurationDefaultsOverrides;
  }
  v(configuration) {
    const register = (configuration2) => {
      const properties = configuration2.properties;
      if (properties) {
        for (const key in properties) {
          this.w(key, properties[key]);
        }
      }
      const subNodes = configuration2.allOf;
      subNodes?.forEach(register);
    };
    register(configuration);
  }
  w(key, property) {
    $So.properties[key] = property;
    switch (property.scope) {
      case 1:
        $To.properties[key] = property;
        break;
      case 2:
        $Uo.properties[key] = property;
        break;
      case 6:
        $Vo.properties[key] = property;
        break;
      case 3:
        $Wo.properties[key] = property;
        break;
      case 4:
        $Xo.properties[key] = property;
        break;
      case 5:
        $Xo.properties[key] = property;
        this.h.properties[key] = property;
        break;
    }
  }
  x(key, property) {
    delete $So.properties[key];
    switch (property.scope) {
      case 1:
        delete $To.properties[key];
        break;
      case 2:
        delete $Uo.properties[key];
        break;
      case 6:
        delete $Vo.properties[key];
        break;
      case 3:
        delete $Wo.properties[key];
        break;
      case 4:
      case 5:
        delete $Xo.properties[key];
        delete this.h.properties[key];
        break;
    }
  }
  y() {
    for (const overrideIdentifier of this.i.values()) {
      const overrideIdentifierProperty = `[${overrideIdentifier}]`;
      const resourceLanguagePropertiesSchema = {
        type: "object",
        description: localize(1674, null),
        errorMessage: localize(1675, null),
        $ref: $Yo
      };
      this.A(overrideIdentifierProperty, resourceLanguagePropertiesSchema);
      $So.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
      $To.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
      $Uo.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
      $Vo.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
      $Wo.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
      $Xo.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
    }
  }
  z() {
    const resourceLanguagePropertiesSchema = {
      type: "object",
      description: localize(1676, null),
      errorMessage: localize(1677, null),
      $ref: $Yo
    };
    $So.patternProperties[$1o] = resourceLanguagePropertiesSchema;
    $To.patternProperties[$1o] = resourceLanguagePropertiesSchema;
    $Uo.patternProperties[$1o] = resourceLanguagePropertiesSchema;
    $Vo.patternProperties[$1o] = resourceLanguagePropertiesSchema;
    $Wo.patternProperties[$1o] = resourceLanguagePropertiesSchema;
    $Xo.patternProperties[$1o] = resourceLanguagePropertiesSchema;
    this.j.fire();
  }
  A(key, property) {
    const configurationdefaultOverride = this.b.get(key)?.configurationDefaultOverrideValue;
    let defaultValue = void 0;
    let defaultSource = void 0;
    if (configurationdefaultOverride && (!property.disallowConfigurationDefault || !configurationdefaultOverride.source)) {
      defaultValue = configurationdefaultOverride.value;
      defaultSource = configurationdefaultOverride.source;
    }
    if ($Fg(defaultValue)) {
      defaultValue = property.defaultDefaultValue;
      defaultSource = void 0;
    }
    if ($Fg(defaultValue)) {
      defaultValue = $5o(property.type);
    }
    property.default = defaultValue;
    property.defaultValueSource = defaultSource;
  }
};
var OVERRIDE_IDENTIFIER_PATTERN = `\\[([^\\]]+)\\]`;
var OVERRIDE_IDENTIFIER_REGEX = new RegExp(OVERRIDE_IDENTIFIER_PATTERN, "g");
var $1o = `^(${OVERRIDE_IDENTIFIER_PATTERN})+$`;
var $2o = new RegExp($1o);
function $3o(key) {
  const identifiers = [];
  if ($2o.test(key)) {
    let matches = OVERRIDE_IDENTIFIER_REGEX.exec(key);
    while (matches?.length) {
      const identifier = matches[1].trim();
      if (identifier) {
        identifiers.push(identifier);
      }
      matches = OVERRIDE_IDENTIFIER_REGEX.exec(key);
    }
  }
  return $Zb(identifiers);
}
function $4o(overrideIdentifiers) {
  return overrideIdentifiers.reduce((result, overrideIdentifier) => `${result}[${overrideIdentifier}]`, "");
}
function $5o(type4) {
  const t = Array.isArray(type4) ? type4[0] : type4;
  switch (t) {
    case "boolean":
      return false;
    case "integer":
    case "number":
      return 0;
    case "string":
      return "";
    case "array":
      return [];
    case "object":
      return {};
    default:
      return null;
  }
}
var configurationRegistry = new ConfigurationRegistry();
$Mo.add($Ro.Configuration, configurationRegistry);
function $6o(property, schema) {
  if (!property.trim()) {
    return localize(1678, null);
  }
  if ($2o.test(property)) {
    return localize(1679, null, property);
  }
  if (configurationRegistry.getConfigurationProperties()[property] !== void 0) {
    return localize(1680, null, property);
  }
  if (schema.policy?.name && configurationRegistry.getPolicyConfigurations().get(schema.policy?.name) !== void 0) {
    return localize(1681, null, property, schema.policy?.name, configurationRegistry.getPolicyConfigurations().get(schema.policy?.name));
  }
  return null;
}

// out-build/vs/platform/update/common/update.config.contribution.js
var configurationRegistry2 = $Mo.as($Ro.Configuration);
configurationRegistry2.registerConfiguration({
  id: "update",
  order: 15,
  title: localize(2445, null),
  type: "object",
  properties: {
    "update.mode": {
      type: "string",
      enum: ["none", "manual", "start", "default"],
      default: "default",
      scope: 1,
      description: localize(2446, null),
      tags: ["usesOnlineServices"],
      enumDescriptions: [
        localize(2447, null),
        localize(2448, null),
        localize(2449, null),
        localize(2450, null)
      ],
      policy: {
        name: "UpdateMode",
        minimumVersion: "1.67"
      }
    },
    "update.channel": {
      type: "string",
      default: "default",
      scope: 1,
      description: localize(2451, null),
      deprecationMessage: localize(2452, null, "update.mode")
    },
    "update.enableWindowsBackgroundUpdates": {
      type: "boolean",
      default: true,
      scope: 1,
      title: localize(2453, null),
      description: localize(2454, null),
      included: $l && !$r
    },
    "update.showReleaseNotes": {
      type: "boolean",
      default: true,
      scope: 1,
      description: localize(2455, null),
      tags: ["usesOnlineServices"]
    }
  }
});

// out-build/vs/code/electron-main/main.js
import { app as app13, dialog } from "electron";
import { unlinkSync as unlinkSync2, promises as promises15 } from "fs";

// out-build/vs/base/common/cancellation.js
var shortcutEvent = Object.freeze(function(callback, context) {
  const handle = setTimeout(callback.bind(context), 0);
  return { dispose() {
    clearTimeout(handle);
  } };
});
var CancellationToken;
(function(CancellationToken2) {
  function isCancellationToken(thing) {
    if (thing === CancellationToken2.None || thing === CancellationToken2.Cancelled) {
      return true;
    }
    if (thing instanceof MutableToken) {
      return true;
    }
    if (!thing || typeof thing !== "object") {
      return false;
    }
    return typeof thing.isCancellationRequested === "boolean" && typeof thing.onCancellationRequested === "function";
  }
  CancellationToken2.isCancellationToken = isCancellationToken;
  CancellationToken2.None = Object.freeze({
    isCancellationRequested: false,
    onCancellationRequested: Event.None
  });
  CancellationToken2.Cancelled = Object.freeze({
    isCancellationRequested: true,
    onCancellationRequested: shortcutEvent
  });
})(CancellationToken || (CancellationToken = {}));
var MutableToken = class {
  constructor() {
    this.a = false;
    this.b = null;
  }
  cancel() {
    if (!this.a) {
      this.a = true;
      if (this.b) {
        this.b.fire(void 0);
        this.dispose();
      }
    }
  }
  get isCancellationRequested() {
    return this.a;
  }
  get onCancellationRequested() {
    if (this.a) {
      return shortcutEvent;
    }
    if (!this.b) {
      this.b = new $De();
    }
    return this.b.event;
  }
  dispose() {
    if (this.b) {
      this.b.dispose();
      this.b = null;
    }
  }
};
var $Pe = class {
  constructor(parent) {
    this.f = void 0;
    this.g = void 0;
    this.g = parent && parent.onCancellationRequested(this.cancel, this);
  }
  get token() {
    if (!this.f) {
      this.f = new MutableToken();
    }
    return this.f;
  }
  cancel() {
    if (!this.f) {
      this.f = CancellationToken.Cancelled;
    } else if (this.f instanceof MutableToken) {
      this.f.cancel();
    }
  }
  dispose(cancel = false) {
    if (cancel) {
      this.cancel();
    }
    this.g?.dispose();
    if (!this.f) {
      this.f = CancellationToken.None;
    } else if (this.f instanceof MutableToken) {
      this.f.dispose();
    }
  }
};

// out-build/vs/base/common/cache.js
function $qf(t) {
  return t;
}
var $rf = class {
  constructor(arg1, arg2) {
    this.a = void 0;
    this.b = void 0;
    if (typeof arg1 === "function") {
      this.c = arg1;
      this.d = $qf;
    } else {
      this.c = arg2;
      this.d = arg1.getCacheKey;
    }
  }
  get(arg) {
    const key = this.d(arg);
    if (this.b !== key) {
      this.b = key;
      this.a = this.c(arg);
    }
    return this.a;
  }
};

// out-build/vs/base/common/lazy.js
var $7 = class {
  constructor(d) {
    this.d = d;
    this.a = false;
  }
  /**
   * True if the lazy value has been resolved.
   */
  get hasValue() {
    return this.a;
  }
  /**
   * Get the wrapped value.
   *
   * This will force evaluation of the lazy value if it has not been resolved yet. Lazy values are only
   * resolved once. `getValue` will re-throw exceptions that are hit while resolving the value
   */
  get value() {
    if (!this.a) {
      try {
        this.b = this.d();
      } catch (err) {
        this.c = err;
      } finally {
        this.a = true;
      }
    }
    if (this.c) {
      throw this.c;
    }
    return this.b;
  }
  /**
   * Get the wrapped value without forcing evaluation.
   */
  get rawValue() {
    return this.b;
  }
};

// out-build/vs/base/common/strings.js
function $vf(str) {
  if (!str || typeof str !== "string") {
    return true;
  }
  return str.trim().length === 0;
}
function $Af(value) {
  return value.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g, "\\$&");
}
function $Ef(haystack, needle = " ") {
  const trimmed = $Ff(haystack, needle);
  return $Gf(trimmed, needle);
}
function $Ff(haystack, needle) {
  if (!haystack || !needle) {
    return haystack;
  }
  const needleLen = needle.length;
  if (needleLen === 0 || haystack.length === 0) {
    return haystack;
  }
  let offset = 0;
  while (haystack.indexOf(needle, offset) === offset) {
    offset = offset + needleLen;
  }
  return haystack.substring(offset);
}
function $Gf(haystack, needle) {
  if (!haystack || !needle) {
    return haystack;
  }
  const needleLen = needle.length, haystackLen = haystack.length;
  if (needleLen === 0 || haystackLen === 0) {
    return haystack;
  }
  let offset = haystackLen, idx = -1;
  while (true) {
    idx = haystack.lastIndexOf(needle, offset - 1);
    if (idx === -1 || idx + needleLen !== offset) {
      break;
    }
    if (idx === 0) {
      return "";
    }
    offset = idx;
  }
  return haystack.substring(0, offset);
}
function $Sf(a, b) {
  if (a < b) {
    return -1;
  } else if (a > b) {
    return 1;
  } else {
    return 0;
  }
}
function $Tf(a, b, aStart = 0, aEnd = a.length, bStart = 0, bEnd = b.length) {
  for (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) {
    const codeA = a.charCodeAt(aStart);
    const codeB = b.charCodeAt(bStart);
    if (codeA < codeB) {
      return -1;
    } else if (codeA > codeB) {
      return 1;
    }
  }
  const aLen = aEnd - aStart;
  const bLen = bEnd - bStart;
  if (aLen < bLen) {
    return -1;
  } else if (aLen > bLen) {
    return 1;
  }
  return 0;
}
function $Uf(a, b) {
  return $Vf(a, b, 0, a.length, 0, b.length);
}
function $Vf(a, b, aStart = 0, aEnd = a.length, bStart = 0, bEnd = b.length) {
  for (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) {
    let codeA = a.charCodeAt(aStart);
    let codeB = b.charCodeAt(bStart);
    if (codeA === codeB) {
      continue;
    }
    if (codeA >= 128 || codeB >= 128) {
      return $Tf(a.toLowerCase(), b.toLowerCase(), aStart, aEnd, bStart, bEnd);
    }
    if ($Xf(codeA)) {
      codeA -= 32;
    }
    if ($Xf(codeB)) {
      codeB -= 32;
    }
    const diff2 = codeA - codeB;
    if (diff2 === 0) {
      continue;
    }
    return diff2;
  }
  const aLen = aEnd - aStart;
  const bLen = bEnd - bStart;
  if (aLen < bLen) {
    return -1;
  } else if (aLen > bLen) {
    return 1;
  }
  return 0;
}
function $Xf(code2) {
  return code2 >= 97 && code2 <= 122;
}
function $Yf(code2) {
  return code2 >= 65 && code2 <= 90;
}
function $Zf(a, b) {
  return a.length === b.length && $Vf(a, b) === 0;
}
function $1f(str, candidate) {
  const candidateLength = candidate.length;
  if (candidate.length > str.length) {
    return false;
  }
  return $Vf(str, candidate, 0, candidateLength) === 0;
}
function $4f(charCode) {
  return 55296 <= charCode && charCode <= 56319;
}
function $5f(charCode) {
  return 56320 <= charCode && charCode <= 57343;
}
function $6f(highSurrogate, lowSurrogate) {
  return (highSurrogate - 55296 << 10) + (lowSurrogate - 56320) + 65536;
}
var $lg = String.fromCharCode(
  65279
  /* CharCode.UTF8_BOM */
);
var GraphemeBreakType;
(function(GraphemeBreakType2) {
  GraphemeBreakType2[GraphemeBreakType2["Other"] = 0] = "Other";
  GraphemeBreakType2[GraphemeBreakType2["Prepend"] = 1] = "Prepend";
  GraphemeBreakType2[GraphemeBreakType2["CR"] = 2] = "CR";
  GraphemeBreakType2[GraphemeBreakType2["LF"] = 3] = "LF";
  GraphemeBreakType2[GraphemeBreakType2["Control"] = 4] = "Control";
  GraphemeBreakType2[GraphemeBreakType2["Extend"] = 5] = "Extend";
  GraphemeBreakType2[GraphemeBreakType2["Regional_Indicator"] = 6] = "Regional_Indicator";
  GraphemeBreakType2[GraphemeBreakType2["SpacingMark"] = 7] = "SpacingMark";
  GraphemeBreakType2[GraphemeBreakType2["L"] = 8] = "L";
  GraphemeBreakType2[GraphemeBreakType2["V"] = 9] = "V";
  GraphemeBreakType2[GraphemeBreakType2["T"] = 10] = "T";
  GraphemeBreakType2[GraphemeBreakType2["LV"] = 11] = "LV";
  GraphemeBreakType2[GraphemeBreakType2["LVT"] = 12] = "LVT";
  GraphemeBreakType2[GraphemeBreakType2["ZWJ"] = 13] = "ZWJ";
  GraphemeBreakType2[GraphemeBreakType2["Extended_Pictographic"] = 14] = "Extended_Pictographic";
})(GraphemeBreakType || (GraphemeBreakType = {}));
var GraphemeBreakTree = class _GraphemeBreakTree {
  static {
    this.c = null;
  }
  static getInstance() {
    if (!_GraphemeBreakTree.c) {
      _GraphemeBreakTree.c = new _GraphemeBreakTree();
    }
    return _GraphemeBreakTree.c;
  }
  constructor() {
    this.d = getGraphemeBreakRawData();
  }
  getGraphemeBreakType(codePoint) {
    if (codePoint < 32) {
      if (codePoint === 10) {
        return 3;
      }
      if (codePoint === 13) {
        return 2;
      }
      return 4;
    }
    if (codePoint < 127) {
      return 0;
    }
    const data = this.d;
    const nodeCount = data.length / 3;
    let nodeIndex = 1;
    while (nodeIndex <= nodeCount) {
      if (codePoint < data[3 * nodeIndex]) {
        nodeIndex = 2 * nodeIndex;
      } else if (codePoint > data[3 * nodeIndex + 1]) {
        nodeIndex = 2 * nodeIndex + 1;
      } else {
        return data[3 * nodeIndex + 2];
      }
    }
    return 0;
  }
};
function getGraphemeBreakRawData() {
  return JSON.parse("[0,0,0,51229,51255,12,44061,44087,12,127462,127487,6,7083,7085,5,47645,47671,12,54813,54839,12,128678,128678,14,3270,3270,5,9919,9923,14,45853,45879,12,49437,49463,12,53021,53047,12,71216,71218,7,128398,128399,14,129360,129374,14,2519,2519,5,4448,4519,9,9742,9742,14,12336,12336,14,44957,44983,12,46749,46775,12,48541,48567,12,50333,50359,12,52125,52151,12,53917,53943,12,69888,69890,5,73018,73018,5,127990,127990,14,128558,128559,14,128759,128760,14,129653,129655,14,2027,2035,5,2891,2892,7,3761,3761,5,6683,6683,5,8293,8293,4,9825,9826,14,9999,9999,14,43452,43453,5,44509,44535,12,45405,45431,12,46301,46327,12,47197,47223,12,48093,48119,12,48989,49015,12,49885,49911,12,50781,50807,12,51677,51703,12,52573,52599,12,53469,53495,12,54365,54391,12,65279,65279,4,70471,70472,7,72145,72147,7,119173,119179,5,127799,127818,14,128240,128244,14,128512,128512,14,128652,128652,14,128721,128722,14,129292,129292,14,129445,129450,14,129734,129743,14,1476,1477,5,2366,2368,7,2750,2752,7,3076,3076,5,3415,3415,5,4141,4144,5,6109,6109,5,6964,6964,5,7394,7400,5,9197,9198,14,9770,9770,14,9877,9877,14,9968,9969,14,10084,10084,14,43052,43052,5,43713,43713,5,44285,44311,12,44733,44759,12,45181,45207,12,45629,45655,12,46077,46103,12,46525,46551,12,46973,46999,12,47421,47447,12,47869,47895,12,48317,48343,12,48765,48791,12,49213,49239,12,49661,49687,12,50109,50135,12,50557,50583,12,51005,51031,12,51453,51479,12,51901,51927,12,52349,52375,12,52797,52823,12,53245,53271,12,53693,53719,12,54141,54167,12,54589,54615,12,55037,55063,12,69506,69509,5,70191,70193,5,70841,70841,7,71463,71467,5,72330,72342,5,94031,94031,5,123628,123631,5,127763,127765,14,127941,127941,14,128043,128062,14,128302,128317,14,128465,128467,14,128539,128539,14,128640,128640,14,128662,128662,14,128703,128703,14,128745,128745,14,129004,129007,14,129329,129330,14,129402,129402,14,129483,129483,14,129686,129704,14,130048,131069,14,173,173,4,1757,1757,1,2200,2207,5,2434,2435,7,2631,2632,5,2817,2817,5,3008,3008,5,3201,3201,5,3387,3388,5,3542,3542,5,3902,3903,7,4190,4192,5,6002,6003,5,6439,6440,5,6765,6770,7,7019,7027,5,7154,7155,7,8205,8205,13,8505,8505,14,9654,9654,14,9757,9757,14,9792,9792,14,9852,9853,14,9890,9894,14,9937,9937,14,9981,9981,14,10035,10036,14,11035,11036,14,42654,42655,5,43346,43347,7,43587,43587,5,44006,44007,7,44173,44199,12,44397,44423,12,44621,44647,12,44845,44871,12,45069,45095,12,45293,45319,12,45517,45543,12,45741,45767,12,45965,45991,12,46189,46215,12,46413,46439,12,46637,46663,12,46861,46887,12,47085,47111,12,47309,47335,12,47533,47559,12,47757,47783,12,47981,48007,12,48205,48231,12,48429,48455,12,48653,48679,12,48877,48903,12,49101,49127,12,49325,49351,12,49549,49575,12,49773,49799,12,49997,50023,12,50221,50247,12,50445,50471,12,50669,50695,12,50893,50919,12,51117,51143,12,51341,51367,12,51565,51591,12,51789,51815,12,52013,52039,12,52237,52263,12,52461,52487,12,52685,52711,12,52909,52935,12,53133,53159,12,53357,53383,12,53581,53607,12,53805,53831,12,54029,54055,12,54253,54279,12,54477,54503,12,54701,54727,12,54925,54951,12,55149,55175,12,68101,68102,5,69762,69762,7,70067,70069,7,70371,70378,5,70720,70721,7,71087,71087,5,71341,71341,5,71995,71996,5,72249,72249,7,72850,72871,5,73109,73109,5,118576,118598,5,121505,121519,5,127245,127247,14,127568,127569,14,127777,127777,14,127872,127891,14,127956,127967,14,128015,128016,14,128110,128172,14,128259,128259,14,128367,128368,14,128424,128424,14,128488,128488,14,128530,128532,14,128550,128551,14,128566,128566,14,128647,128647,14,128656,128656,14,128667,128673,14,128691,128693,14,128715,128715,14,128728,128732,14,128752,128752,14,128765,128767,14,129096,129103,14,129311,129311,14,129344,129349,14,129394,129394,14,129413,129425,14,129466,129471,14,129511,129535,14,129664,129666,14,129719,129722,14,129760,129767,14,917536,917631,5,13,13,2,1160,1161,5,1564,1564,4,1807,1807,1,2085,2087,5,2307,2307,7,2382,2383,7,2497,2500,5,2563,2563,7,2677,2677,5,2763,2764,7,2879,2879,5,2914,2915,5,3021,3021,5,3142,3144,5,3263,3263,5,3285,3286,5,3398,3400,7,3530,3530,5,3633,3633,5,3864,3865,5,3974,3975,5,4155,4156,7,4229,4230,5,5909,5909,7,6078,6085,7,6277,6278,5,6451,6456,7,6744,6750,5,6846,6846,5,6972,6972,5,7074,7077,5,7146,7148,7,7222,7223,5,7416,7417,5,8234,8238,4,8417,8417,5,9000,9000,14,9203,9203,14,9730,9731,14,9748,9749,14,9762,9763,14,9776,9783,14,9800,9811,14,9831,9831,14,9872,9873,14,9882,9882,14,9900,9903,14,9929,9933,14,9941,9960,14,9974,9974,14,9989,9989,14,10006,10006,14,10062,10062,14,10160,10160,14,11647,11647,5,12953,12953,14,43019,43019,5,43232,43249,5,43443,43443,5,43567,43568,7,43696,43696,5,43765,43765,7,44013,44013,5,44117,44143,12,44229,44255,12,44341,44367,12,44453,44479,12,44565,44591,12,44677,44703,12,44789,44815,12,44901,44927,12,45013,45039,12,45125,45151,12,45237,45263,12,45349,45375,12,45461,45487,12,45573,45599,12,45685,45711,12,45797,45823,12,45909,45935,12,46021,46047,12,46133,46159,12,46245,46271,12,46357,46383,12,46469,46495,12,46581,46607,12,46693,46719,12,46805,46831,12,46917,46943,12,47029,47055,12,47141,47167,12,47253,47279,12,47365,47391,12,47477,47503,12,47589,47615,12,47701,47727,12,47813,47839,12,47925,47951,12,48037,48063,12,48149,48175,12,48261,48287,12,48373,48399,12,48485,48511,12,48597,48623,12,48709,48735,12,48821,48847,12,48933,48959,12,49045,49071,12,49157,49183,12,49269,49295,12,49381,49407,12,49493,49519,12,49605,49631,12,49717,49743,12,49829,49855,12,49941,49967,12,50053,50079,12,50165,50191,12,50277,50303,12,50389,50415,12,50501,50527,12,50613,50639,12,50725,50751,12,50837,50863,12,50949,50975,12,51061,51087,12,51173,51199,12,51285,51311,12,51397,51423,12,51509,51535,12,51621,51647,12,51733,51759,12,51845,51871,12,51957,51983,12,52069,52095,12,52181,52207,12,52293,52319,12,52405,52431,12,52517,52543,12,52629,52655,12,52741,52767,12,52853,52879,12,52965,52991,12,53077,53103,12,53189,53215,12,53301,53327,12,53413,53439,12,53525,53551,12,53637,53663,12,53749,53775,12,53861,53887,12,53973,53999,12,54085,54111,12,54197,54223,12,54309,54335,12,54421,54447,12,54533,54559,12,54645,54671,12,54757,54783,12,54869,54895,12,54981,55007,12,55093,55119,12,55243,55291,10,66045,66045,5,68325,68326,5,69688,69702,5,69817,69818,5,69957,69958,7,70089,70092,5,70198,70199,5,70462,70462,5,70502,70508,5,70750,70750,5,70846,70846,7,71100,71101,5,71230,71230,7,71351,71351,5,71737,71738,5,72000,72000,7,72160,72160,5,72273,72278,5,72752,72758,5,72882,72883,5,73031,73031,5,73461,73462,7,94192,94193,7,119149,119149,7,121403,121452,5,122915,122916,5,126980,126980,14,127358,127359,14,127535,127535,14,127759,127759,14,127771,127771,14,127792,127793,14,127825,127867,14,127897,127899,14,127945,127945,14,127985,127986,14,128000,128007,14,128021,128021,14,128066,128100,14,128184,128235,14,128249,128252,14,128266,128276,14,128335,128335,14,128379,128390,14,128407,128419,14,128444,128444,14,128481,128481,14,128499,128499,14,128526,128526,14,128536,128536,14,128543,128543,14,128556,128556,14,128564,128564,14,128577,128580,14,128643,128645,14,128649,128649,14,128654,128654,14,128660,128660,14,128664,128664,14,128675,128675,14,128686,128689,14,128695,128696,14,128705,128709,14,128717,128719,14,128725,128725,14,128736,128741,14,128747,128748,14,128755,128755,14,128762,128762,14,128981,128991,14,129009,129023,14,129160,129167,14,129296,129304,14,129320,129327,14,129340,129342,14,129356,129356,14,129388,129392,14,129399,129400,14,129404,129407,14,129432,129442,14,129454,129455,14,129473,129474,14,129485,129487,14,129648,129651,14,129659,129660,14,129671,129679,14,129709,129711,14,129728,129730,14,129751,129753,14,129776,129782,14,917505,917505,4,917760,917999,5,10,10,3,127,159,4,768,879,5,1471,1471,5,1536,1541,1,1648,1648,5,1767,1768,5,1840,1866,5,2070,2073,5,2137,2139,5,2274,2274,1,2363,2363,7,2377,2380,7,2402,2403,5,2494,2494,5,2507,2508,7,2558,2558,5,2622,2624,7,2641,2641,5,2691,2691,7,2759,2760,5,2786,2787,5,2876,2876,5,2881,2884,5,2901,2902,5,3006,3006,5,3014,3016,7,3072,3072,5,3134,3136,5,3157,3158,5,3260,3260,5,3266,3266,5,3274,3275,7,3328,3329,5,3391,3392,7,3405,3405,5,3457,3457,5,3536,3537,7,3551,3551,5,3636,3642,5,3764,3772,5,3895,3895,5,3967,3967,7,3993,4028,5,4146,4151,5,4182,4183,7,4226,4226,5,4253,4253,5,4957,4959,5,5940,5940,7,6070,6070,7,6087,6088,7,6158,6158,4,6432,6434,5,6448,6449,7,6679,6680,5,6742,6742,5,6754,6754,5,6783,6783,5,6912,6915,5,6966,6970,5,6978,6978,5,7042,7042,7,7080,7081,5,7143,7143,7,7150,7150,7,7212,7219,5,7380,7392,5,7412,7412,5,8203,8203,4,8232,8232,4,8265,8265,14,8400,8412,5,8421,8432,5,8617,8618,14,9167,9167,14,9200,9200,14,9410,9410,14,9723,9726,14,9733,9733,14,9745,9745,14,9752,9752,14,9760,9760,14,9766,9766,14,9774,9774,14,9786,9786,14,9794,9794,14,9823,9823,14,9828,9828,14,9833,9850,14,9855,9855,14,9875,9875,14,9880,9880,14,9885,9887,14,9896,9897,14,9906,9916,14,9926,9927,14,9935,9935,14,9939,9939,14,9962,9962,14,9972,9972,14,9978,9978,14,9986,9986,14,9997,9997,14,10002,10002,14,10017,10017,14,10055,10055,14,10071,10071,14,10133,10135,14,10548,10549,14,11093,11093,14,12330,12333,5,12441,12442,5,42608,42610,5,43010,43010,5,43045,43046,5,43188,43203,7,43302,43309,5,43392,43394,5,43446,43449,5,43493,43493,5,43571,43572,7,43597,43597,7,43703,43704,5,43756,43757,5,44003,44004,7,44009,44010,7,44033,44059,12,44089,44115,12,44145,44171,12,44201,44227,12,44257,44283,12,44313,44339,12,44369,44395,12,44425,44451,12,44481,44507,12,44537,44563,12,44593,44619,12,44649,44675,12,44705,44731,12,44761,44787,12,44817,44843,12,44873,44899,12,44929,44955,12,44985,45011,12,45041,45067,12,45097,45123,12,45153,45179,12,45209,45235,12,45265,45291,12,45321,45347,12,45377,45403,12,45433,45459,12,45489,45515,12,45545,45571,12,45601,45627,12,45657,45683,12,45713,45739,12,45769,45795,12,45825,45851,12,45881,45907,12,45937,45963,12,45993,46019,12,46049,46075,12,46105,46131,12,46161,46187,12,46217,46243,12,46273,46299,12,46329,46355,12,46385,46411,12,46441,46467,12,46497,46523,12,46553,46579,12,46609,46635,12,46665,46691,12,46721,46747,12,46777,46803,12,46833,46859,12,46889,46915,12,46945,46971,12,47001,47027,12,47057,47083,12,47113,47139,12,47169,47195,12,47225,47251,12,47281,47307,12,47337,47363,12,47393,47419,12,47449,47475,12,47505,47531,12,47561,47587,12,47617,47643,12,47673,47699,12,47729,47755,12,47785,47811,12,47841,47867,12,47897,47923,12,47953,47979,12,48009,48035,12,48065,48091,12,48121,48147,12,48177,48203,12,48233,48259,12,48289,48315,12,48345,48371,12,48401,48427,12,48457,48483,12,48513,48539,12,48569,48595,12,48625,48651,12,48681,48707,12,48737,48763,12,48793,48819,12,48849,48875,12,48905,48931,12,48961,48987,12,49017,49043,12,49073,49099,12,49129,49155,12,49185,49211,12,49241,49267,12,49297,49323,12,49353,49379,12,49409,49435,12,49465,49491,12,49521,49547,12,49577,49603,12,49633,49659,12,49689,49715,12,49745,49771,12,49801,49827,12,49857,49883,12,49913,49939,12,49969,49995,12,50025,50051,12,50081,50107,12,50137,50163,12,50193,50219,12,50249,50275,12,50305,50331,12,50361,50387,12,50417,50443,12,50473,50499,12,50529,50555,12,50585,50611,12,50641,50667,12,50697,50723,12,50753,50779,12,50809,50835,12,50865,50891,12,50921,50947,12,50977,51003,12,51033,51059,12,51089,51115,12,51145,51171,12,51201,51227,12,51257,51283,12,51313,51339,12,51369,51395,12,51425,51451,12,51481,51507,12,51537,51563,12,51593,51619,12,51649,51675,12,51705,51731,12,51761,51787,12,51817,51843,12,51873,51899,12,51929,51955,12,51985,52011,12,52041,52067,12,52097,52123,12,52153,52179,12,52209,52235,12,52265,52291,12,52321,52347,12,52377,52403,12,52433,52459,12,52489,52515,12,52545,52571,12,52601,52627,12,52657,52683,12,52713,52739,12,52769,52795,12,52825,52851,12,52881,52907,12,52937,52963,12,52993,53019,12,53049,53075,12,53105,53131,12,53161,53187,12,53217,53243,12,53273,53299,12,53329,53355,12,53385,53411,12,53441,53467,12,53497,53523,12,53553,53579,12,53609,53635,12,53665,53691,12,53721,53747,12,53777,53803,12,53833,53859,12,53889,53915,12,53945,53971,12,54001,54027,12,54057,54083,12,54113,54139,12,54169,54195,12,54225,54251,12,54281,54307,12,54337,54363,12,54393,54419,12,54449,54475,12,54505,54531,12,54561,54587,12,54617,54643,12,54673,54699,12,54729,54755,12,54785,54811,12,54841,54867,12,54897,54923,12,54953,54979,12,55009,55035,12,55065,55091,12,55121,55147,12,55177,55203,12,65024,65039,5,65520,65528,4,66422,66426,5,68152,68154,5,69291,69292,5,69633,69633,5,69747,69748,5,69811,69814,5,69826,69826,5,69932,69932,7,70016,70017,5,70079,70080,7,70095,70095,5,70196,70196,5,70367,70367,5,70402,70403,7,70464,70464,5,70487,70487,5,70709,70711,7,70725,70725,7,70833,70834,7,70843,70844,7,70849,70849,7,71090,71093,5,71103,71104,5,71227,71228,7,71339,71339,5,71344,71349,5,71458,71461,5,71727,71735,5,71985,71989,7,71998,71998,5,72002,72002,7,72154,72155,5,72193,72202,5,72251,72254,5,72281,72283,5,72344,72345,5,72766,72766,7,72874,72880,5,72885,72886,5,73023,73029,5,73104,73105,5,73111,73111,5,92912,92916,5,94095,94098,5,113824,113827,4,119142,119142,7,119155,119162,4,119362,119364,5,121476,121476,5,122888,122904,5,123184,123190,5,125252,125258,5,127183,127183,14,127340,127343,14,127377,127386,14,127491,127503,14,127548,127551,14,127744,127756,14,127761,127761,14,127769,127769,14,127773,127774,14,127780,127788,14,127796,127797,14,127820,127823,14,127869,127869,14,127894,127895,14,127902,127903,14,127943,127943,14,127947,127950,14,127972,127972,14,127988,127988,14,127992,127994,14,128009,128011,14,128019,128019,14,128023,128041,14,128064,128064,14,128102,128107,14,128174,128181,14,128238,128238,14,128246,128247,14,128254,128254,14,128264,128264,14,128278,128299,14,128329,128330,14,128348,128359,14,128371,128377,14,128392,128393,14,128401,128404,14,128421,128421,14,128433,128434,14,128450,128452,14,128476,128478,14,128483,128483,14,128495,128495,14,128506,128506,14,128519,128520,14,128528,128528,14,128534,128534,14,128538,128538,14,128540,128542,14,128544,128549,14,128552,128555,14,128557,128557,14,128560,128563,14,128565,128565,14,128567,128576,14,128581,128591,14,128641,128642,14,128646,128646,14,128648,128648,14,128650,128651,14,128653,128653,14,128655,128655,14,128657,128659,14,128661,128661,14,128663,128663,14,128665,128666,14,128674,128674,14,128676,128677,14,128679,128685,14,128690,128690,14,128694,128694,14,128697,128702,14,128704,128704,14,128710,128714,14,128716,128716,14,128720,128720,14,128723,128724,14,128726,128727,14,128733,128735,14,128742,128744,14,128746,128746,14,128749,128751,14,128753,128754,14,128756,128758,14,128761,128761,14,128763,128764,14,128884,128895,14,128992,129003,14,129008,129008,14,129036,129039,14,129114,129119,14,129198,129279,14,129293,129295,14,129305,129310,14,129312,129319,14,129328,129328,14,129331,129338,14,129343,129343,14,129351,129355,14,129357,129359,14,129375,129387,14,129393,129393,14,129395,129398,14,129401,129401,14,129403,129403,14,129408,129412,14,129426,129431,14,129443,129444,14,129451,129453,14,129456,129465,14,129472,129472,14,129475,129482,14,129484,129484,14,129488,129510,14,129536,129647,14,129652,129652,14,129656,129658,14,129661,129663,14,129667,129670,14,129680,129685,14,129705,129708,14,129712,129718,14,129723,129727,14,129731,129733,14,129744,129750,14,129754,129759,14,129768,129775,14,129783,129791,14,917504,917504,4,917506,917535,4,917632,917759,4,918000,921599,4,0,9,4,11,12,4,14,31,4,169,169,14,174,174,14,1155,1159,5,1425,1469,5,1473,1474,5,1479,1479,5,1552,1562,5,1611,1631,5,1750,1756,5,1759,1764,5,1770,1773,5,1809,1809,5,1958,1968,5,2045,2045,5,2075,2083,5,2089,2093,5,2192,2193,1,2250,2273,5,2275,2306,5,2362,2362,5,2364,2364,5,2369,2376,5,2381,2381,5,2385,2391,5,2433,2433,5,2492,2492,5,2495,2496,7,2503,2504,7,2509,2509,5,2530,2531,5,2561,2562,5,2620,2620,5,2625,2626,5,2635,2637,5,2672,2673,5,2689,2690,5,2748,2748,5,2753,2757,5,2761,2761,7,2765,2765,5,2810,2815,5,2818,2819,7,2878,2878,5,2880,2880,7,2887,2888,7,2893,2893,5,2903,2903,5,2946,2946,5,3007,3007,7,3009,3010,7,3018,3020,7,3031,3031,5,3073,3075,7,3132,3132,5,3137,3140,7,3146,3149,5,3170,3171,5,3202,3203,7,3262,3262,7,3264,3265,7,3267,3268,7,3271,3272,7,3276,3277,5,3298,3299,5,3330,3331,7,3390,3390,5,3393,3396,5,3402,3404,7,3406,3406,1,3426,3427,5,3458,3459,7,3535,3535,5,3538,3540,5,3544,3550,7,3570,3571,7,3635,3635,7,3655,3662,5,3763,3763,7,3784,3789,5,3893,3893,5,3897,3897,5,3953,3966,5,3968,3972,5,3981,3991,5,4038,4038,5,4145,4145,7,4153,4154,5,4157,4158,5,4184,4185,5,4209,4212,5,4228,4228,7,4237,4237,5,4352,4447,8,4520,4607,10,5906,5908,5,5938,5939,5,5970,5971,5,6068,6069,5,6071,6077,5,6086,6086,5,6089,6099,5,6155,6157,5,6159,6159,5,6313,6313,5,6435,6438,7,6441,6443,7,6450,6450,5,6457,6459,5,6681,6682,7,6741,6741,7,6743,6743,7,6752,6752,5,6757,6764,5,6771,6780,5,6832,6845,5,6847,6862,5,6916,6916,7,6965,6965,5,6971,6971,7,6973,6977,7,6979,6980,7,7040,7041,5,7073,7073,7,7078,7079,7,7082,7082,7,7142,7142,5,7144,7145,5,7149,7149,5,7151,7153,5,7204,7211,7,7220,7221,7,7376,7378,5,7393,7393,7,7405,7405,5,7415,7415,7,7616,7679,5,8204,8204,5,8206,8207,4,8233,8233,4,8252,8252,14,8288,8292,4,8294,8303,4,8413,8416,5,8418,8420,5,8482,8482,14,8596,8601,14,8986,8987,14,9096,9096,14,9193,9196,14,9199,9199,14,9201,9202,14,9208,9210,14,9642,9643,14,9664,9664,14,9728,9729,14,9732,9732,14,9735,9741,14,9743,9744,14,9746,9746,14,9750,9751,14,9753,9756,14,9758,9759,14,9761,9761,14,9764,9765,14,9767,9769,14,9771,9773,14,9775,9775,14,9784,9785,14,9787,9791,14,9793,9793,14,9795,9799,14,9812,9822,14,9824,9824,14,9827,9827,14,9829,9830,14,9832,9832,14,9851,9851,14,9854,9854,14,9856,9861,14,9874,9874,14,9876,9876,14,9878,9879,14,9881,9881,14,9883,9884,14,9888,9889,14,9895,9895,14,9898,9899,14,9904,9905,14,9917,9918,14,9924,9925,14,9928,9928,14,9934,9934,14,9936,9936,14,9938,9938,14,9940,9940,14,9961,9961,14,9963,9967,14,9970,9971,14,9973,9973,14,9975,9977,14,9979,9980,14,9982,9985,14,9987,9988,14,9992,9996,14,9998,9998,14,10000,10001,14,10004,10004,14,10013,10013,14,10024,10024,14,10052,10052,14,10060,10060,14,10067,10069,14,10083,10083,14,10085,10087,14,10145,10145,14,10175,10175,14,11013,11015,14,11088,11088,14,11503,11505,5,11744,11775,5,12334,12335,5,12349,12349,14,12951,12951,14,42607,42607,5,42612,42621,5,42736,42737,5,43014,43014,5,43043,43044,7,43047,43047,7,43136,43137,7,43204,43205,5,43263,43263,5,43335,43345,5,43360,43388,8,43395,43395,7,43444,43445,7,43450,43451,7,43454,43456,7,43561,43566,5,43569,43570,5,43573,43574,5,43596,43596,5,43644,43644,5,43698,43700,5,43710,43711,5,43755,43755,7,43758,43759,7,43766,43766,5,44005,44005,5,44008,44008,5,44012,44012,7,44032,44032,11,44060,44060,11,44088,44088,11,44116,44116,11,44144,44144,11,44172,44172,11,44200,44200,11,44228,44228,11,44256,44256,11,44284,44284,11,44312,44312,11,44340,44340,11,44368,44368,11,44396,44396,11,44424,44424,11,44452,44452,11,44480,44480,11,44508,44508,11,44536,44536,11,44564,44564,11,44592,44592,11,44620,44620,11,44648,44648,11,44676,44676,11,44704,44704,11,44732,44732,11,44760,44760,11,44788,44788,11,44816,44816,11,44844,44844,11,44872,44872,11,44900,44900,11,44928,44928,11,44956,44956,11,44984,44984,11,45012,45012,11,45040,45040,11,45068,45068,11,45096,45096,11,45124,45124,11,45152,45152,11,45180,45180,11,45208,45208,11,45236,45236,11,45264,45264,11,45292,45292,11,45320,45320,11,45348,45348,11,45376,45376,11,45404,45404,11,45432,45432,11,45460,45460,11,45488,45488,11,45516,45516,11,45544,45544,11,45572,45572,11,45600,45600,11,45628,45628,11,45656,45656,11,45684,45684,11,45712,45712,11,45740,45740,11,45768,45768,11,45796,45796,11,45824,45824,11,45852,45852,11,45880,45880,11,45908,45908,11,45936,45936,11,45964,45964,11,45992,45992,11,46020,46020,11,46048,46048,11,46076,46076,11,46104,46104,11,46132,46132,11,46160,46160,11,46188,46188,11,46216,46216,11,46244,46244,11,46272,46272,11,46300,46300,11,46328,46328,11,46356,46356,11,46384,46384,11,46412,46412,11,46440,46440,11,46468,46468,11,46496,46496,11,46524,46524,11,46552,46552,11,46580,46580,11,46608,46608,11,46636,46636,11,46664,46664,11,46692,46692,11,46720,46720,11,46748,46748,11,46776,46776,11,46804,46804,11,46832,46832,11,46860,46860,11,46888,46888,11,46916,46916,11,46944,46944,11,46972,46972,11,47000,47000,11,47028,47028,11,47056,47056,11,47084,47084,11,47112,47112,11,47140,47140,11,47168,47168,11,47196,47196,11,47224,47224,11,47252,47252,11,47280,47280,11,47308,47308,11,47336,47336,11,47364,47364,11,47392,47392,11,47420,47420,11,47448,47448,11,47476,47476,11,47504,47504,11,47532,47532,11,47560,47560,11,47588,47588,11,47616,47616,11,47644,47644,11,47672,47672,11,47700,47700,11,47728,47728,11,47756,47756,11,47784,47784,11,47812,47812,11,47840,47840,11,47868,47868,11,47896,47896,11,47924,47924,11,47952,47952,11,47980,47980,11,48008,48008,11,48036,48036,11,48064,48064,11,48092,48092,11,48120,48120,11,48148,48148,11,48176,48176,11,48204,48204,11,48232,48232,11,48260,48260,11,48288,48288,11,48316,48316,11,48344,48344,11,48372,48372,11,48400,48400,11,48428,48428,11,48456,48456,11,48484,48484,11,48512,48512,11,48540,48540,11,48568,48568,11,48596,48596,11,48624,48624,11,48652,48652,11,48680,48680,11,48708,48708,11,48736,48736,11,48764,48764,11,48792,48792,11,48820,48820,11,48848,48848,11,48876,48876,11,48904,48904,11,48932,48932,11,48960,48960,11,48988,48988,11,49016,49016,11,49044,49044,11,49072,49072,11,49100,49100,11,49128,49128,11,49156,49156,11,49184,49184,11,49212,49212,11,49240,49240,11,49268,49268,11,49296,49296,11,49324,49324,11,49352,49352,11,49380,49380,11,49408,49408,11,49436,49436,11,49464,49464,11,49492,49492,11,49520,49520,11,49548,49548,11,49576,49576,11,49604,49604,11,49632,49632,11,49660,49660,11,49688,49688,11,49716,49716,11,49744,49744,11,49772,49772,11,49800,49800,11,49828,49828,11,49856,49856,11,49884,49884,11,49912,49912,11,49940,49940,11,49968,49968,11,49996,49996,11,50024,50024,11,50052,50052,11,50080,50080,11,50108,50108,11,50136,50136,11,50164,50164,11,50192,50192,11,50220,50220,11,50248,50248,11,50276,50276,11,50304,50304,11,50332,50332,11,50360,50360,11,50388,50388,11,50416,50416,11,50444,50444,11,50472,50472,11,50500,50500,11,50528,50528,11,50556,50556,11,50584,50584,11,50612,50612,11,50640,50640,11,50668,50668,11,50696,50696,11,50724,50724,11,50752,50752,11,50780,50780,11,50808,50808,11,50836,50836,11,50864,50864,11,50892,50892,11,50920,50920,11,50948,50948,11,50976,50976,11,51004,51004,11,51032,51032,11,51060,51060,11,51088,51088,11,51116,51116,11,51144,51144,11,51172,51172,11,51200,51200,11,51228,51228,11,51256,51256,11,51284,51284,11,51312,51312,11,51340,51340,11,51368,51368,11,51396,51396,11,51424,51424,11,51452,51452,11,51480,51480,11,51508,51508,11,51536,51536,11,51564,51564,11,51592,51592,11,51620,51620,11,51648,51648,11,51676,51676,11,51704,51704,11,51732,51732,11,51760,51760,11,51788,51788,11,51816,51816,11,51844,51844,11,51872,51872,11,51900,51900,11,51928,51928,11,51956,51956,11,51984,51984,11,52012,52012,11,52040,52040,11,52068,52068,11,52096,52096,11,52124,52124,11,52152,52152,11,52180,52180,11,52208,52208,11,52236,52236,11,52264,52264,11,52292,52292,11,52320,52320,11,52348,52348,11,52376,52376,11,52404,52404,11,52432,52432,11,52460,52460,11,52488,52488,11,52516,52516,11,52544,52544,11,52572,52572,11,52600,52600,11,52628,52628,11,52656,52656,11,52684,52684,11,52712,52712,11,52740,52740,11,52768,52768,11,52796,52796,11,52824,52824,11,52852,52852,11,52880,52880,11,52908,52908,11,52936,52936,11,52964,52964,11,52992,52992,11,53020,53020,11,53048,53048,11,53076,53076,11,53104,53104,11,53132,53132,11,53160,53160,11,53188,53188,11,53216,53216,11,53244,53244,11,53272,53272,11,53300,53300,11,53328,53328,11,53356,53356,11,53384,53384,11,53412,53412,11,53440,53440,11,53468,53468,11,53496,53496,11,53524,53524,11,53552,53552,11,53580,53580,11,53608,53608,11,53636,53636,11,53664,53664,11,53692,53692,11,53720,53720,11,53748,53748,11,53776,53776,11,53804,53804,11,53832,53832,11,53860,53860,11,53888,53888,11,53916,53916,11,53944,53944,11,53972,53972,11,54000,54000,11,54028,54028,11,54056,54056,11,54084,54084,11,54112,54112,11,54140,54140,11,54168,54168,11,54196,54196,11,54224,54224,11,54252,54252,11,54280,54280,11,54308,54308,11,54336,54336,11,54364,54364,11,54392,54392,11,54420,54420,11,54448,54448,11,54476,54476,11,54504,54504,11,54532,54532,11,54560,54560,11,54588,54588,11,54616,54616,11,54644,54644,11,54672,54672,11,54700,54700,11,54728,54728,11,54756,54756,11,54784,54784,11,54812,54812,11,54840,54840,11,54868,54868,11,54896,54896,11,54924,54924,11,54952,54952,11,54980,54980,11,55008,55008,11,55036,55036,11,55064,55064,11,55092,55092,11,55120,55120,11,55148,55148,11,55176,55176,11,55216,55238,9,64286,64286,5,65056,65071,5,65438,65439,5,65529,65531,4,66272,66272,5,68097,68099,5,68108,68111,5,68159,68159,5,68900,68903,5,69446,69456,5,69632,69632,7,69634,69634,7,69744,69744,5,69759,69761,5,69808,69810,7,69815,69816,7,69821,69821,1,69837,69837,1,69927,69931,5,69933,69940,5,70003,70003,5,70018,70018,7,70070,70078,5,70082,70083,1,70094,70094,7,70188,70190,7,70194,70195,7,70197,70197,7,70206,70206,5,70368,70370,7,70400,70401,5,70459,70460,5,70463,70463,7,70465,70468,7,70475,70477,7,70498,70499,7,70512,70516,5,70712,70719,5,70722,70724,5,70726,70726,5,70832,70832,5,70835,70840,5,70842,70842,5,70845,70845,5,70847,70848,5,70850,70851,5,71088,71089,7,71096,71099,7,71102,71102,7,71132,71133,5,71219,71226,5,71229,71229,5,71231,71232,5,71340,71340,7,71342,71343,7,71350,71350,7,71453,71455,5,71462,71462,7,71724,71726,7,71736,71736,7,71984,71984,5,71991,71992,7,71997,71997,7,71999,71999,1,72001,72001,1,72003,72003,5,72148,72151,5,72156,72159,7,72164,72164,7,72243,72248,5,72250,72250,1,72263,72263,5,72279,72280,7,72324,72329,1,72343,72343,7,72751,72751,7,72760,72765,5,72767,72767,5,72873,72873,7,72881,72881,7,72884,72884,7,73009,73014,5,73020,73021,5,73030,73030,1,73098,73102,7,73107,73108,7,73110,73110,7,73459,73460,5,78896,78904,4,92976,92982,5,94033,94087,7,94180,94180,5,113821,113822,5,118528,118573,5,119141,119141,5,119143,119145,5,119150,119154,5,119163,119170,5,119210,119213,5,121344,121398,5,121461,121461,5,121499,121503,5,122880,122886,5,122907,122913,5,122918,122922,5,123566,123566,5,125136,125142,5,126976,126979,14,126981,127182,14,127184,127231,14,127279,127279,14,127344,127345,14,127374,127374,14,127405,127461,14,127489,127490,14,127514,127514,14,127538,127546,14,127561,127567,14,127570,127743,14,127757,127758,14,127760,127760,14,127762,127762,14,127766,127768,14,127770,127770,14,127772,127772,14,127775,127776,14,127778,127779,14,127789,127791,14,127794,127795,14,127798,127798,14,127819,127819,14,127824,127824,14,127868,127868,14,127870,127871,14,127892,127893,14,127896,127896,14,127900,127901,14,127904,127940,14,127942,127942,14,127944,127944,14,127946,127946,14,127951,127955,14,127968,127971,14,127973,127984,14,127987,127987,14,127989,127989,14,127991,127991,14,127995,127999,5,128008,128008,14,128012,128014,14,128017,128018,14,128020,128020,14,128022,128022,14,128042,128042,14,128063,128063,14,128065,128065,14,128101,128101,14,128108,128109,14,128173,128173,14,128182,128183,14,128236,128237,14,128239,128239,14,128245,128245,14,128248,128248,14,128253,128253,14,128255,128258,14,128260,128263,14,128265,128265,14,128277,128277,14,128300,128301,14,128326,128328,14,128331,128334,14,128336,128347,14,128360,128366,14,128369,128370,14,128378,128378,14,128391,128391,14,128394,128397,14,128400,128400,14,128405,128406,14,128420,128420,14,128422,128423,14,128425,128432,14,128435,128443,14,128445,128449,14,128453,128464,14,128468,128475,14,128479,128480,14,128482,128482,14,128484,128487,14,128489,128494,14,128496,128498,14,128500,128505,14,128507,128511,14,128513,128518,14,128521,128525,14,128527,128527,14,128529,128529,14,128533,128533,14,128535,128535,14,128537,128537,14]");
}
var CodePoint;
(function(CodePoint2) {
  CodePoint2[CodePoint2["zwj"] = 8205] = "zwj";
  CodePoint2[CodePoint2["emojiVariantSelector"] = 65039] = "emojiVariantSelector";
  CodePoint2[CodePoint2["enclosingKeyCap"] = 8419] = "enclosingKeyCap";
})(CodePoint || (CodePoint = {}));
var $wg = class _$wg {
  static {
    this.c = new $7(() => {
      return JSON.parse('{"_common":[8232,32,8233,32,5760,32,8192,32,8193,32,8194,32,8195,32,8196,32,8197,32,8198,32,8200,32,8201,32,8202,32,8287,32,8199,32,8239,32,2042,95,65101,95,65102,95,65103,95,8208,45,8209,45,8210,45,65112,45,1748,45,8259,45,727,45,8722,45,10134,45,11450,45,1549,44,1643,44,8218,44,184,44,42233,44,894,59,2307,58,2691,58,1417,58,1795,58,1796,58,5868,58,65072,58,6147,58,6153,58,8282,58,1475,58,760,58,42889,58,8758,58,720,58,42237,58,451,33,11601,33,660,63,577,63,2429,63,5038,63,42731,63,119149,46,8228,46,1793,46,1794,46,42510,46,68176,46,1632,46,1776,46,42232,46,1373,96,65287,96,8219,96,8242,96,1370,96,1523,96,8175,96,65344,96,900,96,8189,96,8125,96,8127,96,8190,96,697,96,884,96,712,96,714,96,715,96,756,96,699,96,701,96,700,96,702,96,42892,96,1497,96,2036,96,2037,96,5194,96,5836,96,94033,96,94034,96,65339,91,10088,40,10098,40,12308,40,64830,40,65341,93,10089,41,10099,41,12309,41,64831,41,10100,123,119060,123,10101,125,65342,94,8270,42,1645,42,8727,42,66335,42,5941,47,8257,47,8725,47,8260,47,9585,47,10187,47,10744,47,119354,47,12755,47,12339,47,11462,47,20031,47,12035,47,65340,92,65128,92,8726,92,10189,92,10741,92,10745,92,119311,92,119355,92,12756,92,20022,92,12034,92,42872,38,708,94,710,94,5869,43,10133,43,66203,43,8249,60,10094,60,706,60,119350,60,5176,60,5810,60,5120,61,11840,61,12448,61,42239,61,8250,62,10095,62,707,62,119351,62,5171,62,94015,62,8275,126,732,126,8128,126,8764,126,65372,124,65293,45,120784,50,120794,50,120804,50,120814,50,120824,50,130034,50,42842,50,423,50,1000,50,42564,50,5311,50,42735,50,119302,51,120785,51,120795,51,120805,51,120815,51,120825,51,130035,51,42923,51,540,51,439,51,42858,51,11468,51,1248,51,94011,51,71882,51,120786,52,120796,52,120806,52,120816,52,120826,52,130036,52,5070,52,71855,52,120787,53,120797,53,120807,53,120817,53,120827,53,130037,53,444,53,71867,53,120788,54,120798,54,120808,54,120818,54,120828,54,130038,54,11474,54,5102,54,71893,54,119314,55,120789,55,120799,55,120809,55,120819,55,120829,55,130039,55,66770,55,71878,55,2819,56,2538,56,2666,56,125131,56,120790,56,120800,56,120810,56,120820,56,120830,56,130040,56,547,56,546,56,66330,56,2663,57,2920,57,2541,57,3437,57,120791,57,120801,57,120811,57,120821,57,120831,57,130041,57,42862,57,11466,57,71884,57,71852,57,71894,57,9082,97,65345,97,119834,97,119886,97,119938,97,119990,97,120042,97,120094,97,120146,97,120198,97,120250,97,120302,97,120354,97,120406,97,120458,97,593,97,945,97,120514,97,120572,97,120630,97,120688,97,120746,97,65313,65,119808,65,119860,65,119912,65,119964,65,120016,65,120068,65,120120,65,120172,65,120224,65,120276,65,120328,65,120380,65,120432,65,913,65,120488,65,120546,65,120604,65,120662,65,120720,65,5034,65,5573,65,42222,65,94016,65,66208,65,119835,98,119887,98,119939,98,119991,98,120043,98,120095,98,120147,98,120199,98,120251,98,120303,98,120355,98,120407,98,120459,98,388,98,5071,98,5234,98,5551,98,65314,66,8492,66,119809,66,119861,66,119913,66,120017,66,120069,66,120121,66,120173,66,120225,66,120277,66,120329,66,120381,66,120433,66,42932,66,914,66,120489,66,120547,66,120605,66,120663,66,120721,66,5108,66,5623,66,42192,66,66178,66,66209,66,66305,66,65347,99,8573,99,119836,99,119888,99,119940,99,119992,99,120044,99,120096,99,120148,99,120200,99,120252,99,120304,99,120356,99,120408,99,120460,99,7428,99,1010,99,11429,99,43951,99,66621,99,128844,67,71922,67,71913,67,65315,67,8557,67,8450,67,8493,67,119810,67,119862,67,119914,67,119966,67,120018,67,120174,67,120226,67,120278,67,120330,67,120382,67,120434,67,1017,67,11428,67,5087,67,42202,67,66210,67,66306,67,66581,67,66844,67,8574,100,8518,100,119837,100,119889,100,119941,100,119993,100,120045,100,120097,100,120149,100,120201,100,120253,100,120305,100,120357,100,120409,100,120461,100,1281,100,5095,100,5231,100,42194,100,8558,68,8517,68,119811,68,119863,68,119915,68,119967,68,120019,68,120071,68,120123,68,120175,68,120227,68,120279,68,120331,68,120383,68,120435,68,5024,68,5598,68,5610,68,42195,68,8494,101,65349,101,8495,101,8519,101,119838,101,119890,101,119942,101,120046,101,120098,101,120150,101,120202,101,120254,101,120306,101,120358,101,120410,101,120462,101,43826,101,1213,101,8959,69,65317,69,8496,69,119812,69,119864,69,119916,69,120020,69,120072,69,120124,69,120176,69,120228,69,120280,69,120332,69,120384,69,120436,69,917,69,120492,69,120550,69,120608,69,120666,69,120724,69,11577,69,5036,69,42224,69,71846,69,71854,69,66182,69,119839,102,119891,102,119943,102,119995,102,120047,102,120099,102,120151,102,120203,102,120255,102,120307,102,120359,102,120411,102,120463,102,43829,102,42905,102,383,102,7837,102,1412,102,119315,70,8497,70,119813,70,119865,70,119917,70,120021,70,120073,70,120125,70,120177,70,120229,70,120281,70,120333,70,120385,70,120437,70,42904,70,988,70,120778,70,5556,70,42205,70,71874,70,71842,70,66183,70,66213,70,66853,70,65351,103,8458,103,119840,103,119892,103,119944,103,120048,103,120100,103,120152,103,120204,103,120256,103,120308,103,120360,103,120412,103,120464,103,609,103,7555,103,397,103,1409,103,119814,71,119866,71,119918,71,119970,71,120022,71,120074,71,120126,71,120178,71,120230,71,120282,71,120334,71,120386,71,120438,71,1292,71,5056,71,5107,71,42198,71,65352,104,8462,104,119841,104,119945,104,119997,104,120049,104,120101,104,120153,104,120205,104,120257,104,120309,104,120361,104,120413,104,120465,104,1211,104,1392,104,5058,104,65320,72,8459,72,8460,72,8461,72,119815,72,119867,72,119919,72,120023,72,120179,72,120231,72,120283,72,120335,72,120387,72,120439,72,919,72,120494,72,120552,72,120610,72,120668,72,120726,72,11406,72,5051,72,5500,72,42215,72,66255,72,731,105,9075,105,65353,105,8560,105,8505,105,8520,105,119842,105,119894,105,119946,105,119998,105,120050,105,120102,105,120154,105,120206,105,120258,105,120310,105,120362,105,120414,105,120466,105,120484,105,618,105,617,105,953,105,8126,105,890,105,120522,105,120580,105,120638,105,120696,105,120754,105,1110,105,42567,105,1231,105,43893,105,5029,105,71875,105,65354,106,8521,106,119843,106,119895,106,119947,106,119999,106,120051,106,120103,106,120155,106,120207,106,120259,106,120311,106,120363,106,120415,106,120467,106,1011,106,1112,106,65322,74,119817,74,119869,74,119921,74,119973,74,120025,74,120077,74,120129,74,120181,74,120233,74,120285,74,120337,74,120389,74,120441,74,42930,74,895,74,1032,74,5035,74,5261,74,42201,74,119844,107,119896,107,119948,107,120000,107,120052,107,120104,107,120156,107,120208,107,120260,107,120312,107,120364,107,120416,107,120468,107,8490,75,65323,75,119818,75,119870,75,119922,75,119974,75,120026,75,120078,75,120130,75,120182,75,120234,75,120286,75,120338,75,120390,75,120442,75,922,75,120497,75,120555,75,120613,75,120671,75,120729,75,11412,75,5094,75,5845,75,42199,75,66840,75,1472,108,8739,73,9213,73,65512,73,1633,108,1777,73,66336,108,125127,108,120783,73,120793,73,120803,73,120813,73,120823,73,130033,73,65321,73,8544,73,8464,73,8465,73,119816,73,119868,73,119920,73,120024,73,120128,73,120180,73,120232,73,120284,73,120336,73,120388,73,120440,73,65356,108,8572,73,8467,108,119845,108,119897,108,119949,108,120001,108,120053,108,120105,73,120157,73,120209,73,120261,73,120313,73,120365,73,120417,73,120469,73,448,73,120496,73,120554,73,120612,73,120670,73,120728,73,11410,73,1030,73,1216,73,1493,108,1503,108,1575,108,126464,108,126592,108,65166,108,65165,108,1994,108,11599,73,5825,73,42226,73,93992,73,66186,124,66313,124,119338,76,8556,76,8466,76,119819,76,119871,76,119923,76,120027,76,120079,76,120131,76,120183,76,120235,76,120287,76,120339,76,120391,76,120443,76,11472,76,5086,76,5290,76,42209,76,93974,76,71843,76,71858,76,66587,76,66854,76,65325,77,8559,77,8499,77,119820,77,119872,77,119924,77,120028,77,120080,77,120132,77,120184,77,120236,77,120288,77,120340,77,120392,77,120444,77,924,77,120499,77,120557,77,120615,77,120673,77,120731,77,1018,77,11416,77,5047,77,5616,77,5846,77,42207,77,66224,77,66321,77,119847,110,119899,110,119951,110,120003,110,120055,110,120107,110,120159,110,120211,110,120263,110,120315,110,120367,110,120419,110,120471,110,1400,110,1404,110,65326,78,8469,78,119821,78,119873,78,119925,78,119977,78,120029,78,120081,78,120185,78,120237,78,120289,78,120341,78,120393,78,120445,78,925,78,120500,78,120558,78,120616,78,120674,78,120732,78,11418,78,42208,78,66835,78,3074,111,3202,111,3330,111,3458,111,2406,111,2662,111,2790,111,3046,111,3174,111,3302,111,3430,111,3664,111,3792,111,4160,111,1637,111,1781,111,65359,111,8500,111,119848,111,119900,111,119952,111,120056,111,120108,111,120160,111,120212,111,120264,111,120316,111,120368,111,120420,111,120472,111,7439,111,7441,111,43837,111,959,111,120528,111,120586,111,120644,111,120702,111,120760,111,963,111,120532,111,120590,111,120648,111,120706,111,120764,111,11423,111,4351,111,1413,111,1505,111,1607,111,126500,111,126564,111,126596,111,65259,111,65260,111,65258,111,65257,111,1726,111,64428,111,64429,111,64427,111,64426,111,1729,111,64424,111,64425,111,64423,111,64422,111,1749,111,3360,111,4125,111,66794,111,71880,111,71895,111,66604,111,1984,79,2534,79,2918,79,12295,79,70864,79,71904,79,120782,79,120792,79,120802,79,120812,79,120822,79,130032,79,65327,79,119822,79,119874,79,119926,79,119978,79,120030,79,120082,79,120134,79,120186,79,120238,79,120290,79,120342,79,120394,79,120446,79,927,79,120502,79,120560,79,120618,79,120676,79,120734,79,11422,79,1365,79,11604,79,4816,79,2848,79,66754,79,42227,79,71861,79,66194,79,66219,79,66564,79,66838,79,9076,112,65360,112,119849,112,119901,112,119953,112,120005,112,120057,112,120109,112,120161,112,120213,112,120265,112,120317,112,120369,112,120421,112,120473,112,961,112,120530,112,120544,112,120588,112,120602,112,120646,112,120660,112,120704,112,120718,112,120762,112,120776,112,11427,112,65328,80,8473,80,119823,80,119875,80,119927,80,119979,80,120031,80,120083,80,120187,80,120239,80,120291,80,120343,80,120395,80,120447,80,929,80,120504,80,120562,80,120620,80,120678,80,120736,80,11426,80,5090,80,5229,80,42193,80,66197,80,119850,113,119902,113,119954,113,120006,113,120058,113,120110,113,120162,113,120214,113,120266,113,120318,113,120370,113,120422,113,120474,113,1307,113,1379,113,1382,113,8474,81,119824,81,119876,81,119928,81,119980,81,120032,81,120084,81,120188,81,120240,81,120292,81,120344,81,120396,81,120448,81,11605,81,119851,114,119903,114,119955,114,120007,114,120059,114,120111,114,120163,114,120215,114,120267,114,120319,114,120371,114,120423,114,120475,114,43847,114,43848,114,7462,114,11397,114,43905,114,119318,82,8475,82,8476,82,8477,82,119825,82,119877,82,119929,82,120033,82,120189,82,120241,82,120293,82,120345,82,120397,82,120449,82,422,82,5025,82,5074,82,66740,82,5511,82,42211,82,94005,82,65363,115,119852,115,119904,115,119956,115,120008,115,120060,115,120112,115,120164,115,120216,115,120268,115,120320,115,120372,115,120424,115,120476,115,42801,115,445,115,1109,115,43946,115,71873,115,66632,115,65331,83,119826,83,119878,83,119930,83,119982,83,120034,83,120086,83,120138,83,120190,83,120242,83,120294,83,120346,83,120398,83,120450,83,1029,83,1359,83,5077,83,5082,83,42210,83,94010,83,66198,83,66592,83,119853,116,119905,116,119957,116,120009,116,120061,116,120113,116,120165,116,120217,116,120269,116,120321,116,120373,116,120425,116,120477,116,8868,84,10201,84,128872,84,65332,84,119827,84,119879,84,119931,84,119983,84,120035,84,120087,84,120139,84,120191,84,120243,84,120295,84,120347,84,120399,84,120451,84,932,84,120507,84,120565,84,120623,84,120681,84,120739,84,11430,84,5026,84,42196,84,93962,84,71868,84,66199,84,66225,84,66325,84,119854,117,119906,117,119958,117,120010,117,120062,117,120114,117,120166,117,120218,117,120270,117,120322,117,120374,117,120426,117,120478,117,42911,117,7452,117,43854,117,43858,117,651,117,965,117,120534,117,120592,117,120650,117,120708,117,120766,117,1405,117,66806,117,71896,117,8746,85,8899,85,119828,85,119880,85,119932,85,119984,85,120036,85,120088,85,120140,85,120192,85,120244,85,120296,85,120348,85,120400,85,120452,85,1357,85,4608,85,66766,85,5196,85,42228,85,94018,85,71864,85,8744,118,8897,118,65366,118,8564,118,119855,118,119907,118,119959,118,120011,118,120063,118,120115,118,120167,118,120219,118,120271,118,120323,118,120375,118,120427,118,120479,118,7456,118,957,118,120526,118,120584,118,120642,118,120700,118,120758,118,1141,118,1496,118,71430,118,43945,118,71872,118,119309,86,1639,86,1783,86,8548,86,119829,86,119881,86,119933,86,119985,86,120037,86,120089,86,120141,86,120193,86,120245,86,120297,86,120349,86,120401,86,120453,86,1140,86,11576,86,5081,86,5167,86,42719,86,42214,86,93960,86,71840,86,66845,86,623,119,119856,119,119908,119,119960,119,120012,119,120064,119,120116,119,120168,119,120220,119,120272,119,120324,119,120376,119,120428,119,120480,119,7457,119,1121,119,1309,119,1377,119,71434,119,71438,119,71439,119,43907,119,71919,87,71910,87,119830,87,119882,87,119934,87,119986,87,120038,87,120090,87,120142,87,120194,87,120246,87,120298,87,120350,87,120402,87,120454,87,1308,87,5043,87,5076,87,42218,87,5742,120,10539,120,10540,120,10799,120,65368,120,8569,120,119857,120,119909,120,119961,120,120013,120,120065,120,120117,120,120169,120,120221,120,120273,120,120325,120,120377,120,120429,120,120481,120,5441,120,5501,120,5741,88,9587,88,66338,88,71916,88,65336,88,8553,88,119831,88,119883,88,119935,88,119987,88,120039,88,120091,88,120143,88,120195,88,120247,88,120299,88,120351,88,120403,88,120455,88,42931,88,935,88,120510,88,120568,88,120626,88,120684,88,120742,88,11436,88,11613,88,5815,88,42219,88,66192,88,66228,88,66327,88,66855,88,611,121,7564,121,65369,121,119858,121,119910,121,119962,121,120014,121,120066,121,120118,121,120170,121,120222,121,120274,121,120326,121,120378,121,120430,121,120482,121,655,121,7935,121,43866,121,947,121,8509,121,120516,121,120574,121,120632,121,120690,121,120748,121,1199,121,4327,121,71900,121,65337,89,119832,89,119884,89,119936,89,119988,89,120040,89,120092,89,120144,89,120196,89,120248,89,120300,89,120352,89,120404,89,120456,89,933,89,978,89,120508,89,120566,89,120624,89,120682,89,120740,89,11432,89,1198,89,5033,89,5053,89,42220,89,94019,89,71844,89,66226,89,119859,122,119911,122,119963,122,120015,122,120067,122,120119,122,120171,122,120223,122,120275,122,120327,122,120379,122,120431,122,120483,122,7458,122,43923,122,71876,122,66293,90,71909,90,65338,90,8484,90,8488,90,119833,90,119885,90,119937,90,119989,90,120041,90,120197,90,120249,90,120301,90,120353,90,120405,90,120457,90,918,90,120493,90,120551,90,120609,90,120667,90,120725,90,5059,90,42204,90,71849,90,65282,34,65284,36,65285,37,65286,38,65290,42,65291,43,65294,46,65295,47,65296,48,65297,49,65298,50,65299,51,65300,52,65301,53,65302,54,65303,55,65304,56,65305,57,65308,60,65309,61,65310,62,65312,64,65316,68,65318,70,65319,71,65324,76,65329,81,65330,82,65333,85,65334,86,65335,87,65343,95,65346,98,65348,100,65350,102,65355,107,65357,109,65358,110,65361,113,65362,114,65364,116,65365,117,65367,119,65370,122,65371,123,65373,125,119846,109],"_default":[160,32,8211,45,65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"cs":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"de":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"es":[8211,45,65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"fr":[65374,126,65306,58,65281,33,8216,96,8245,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"it":[160,32,8211,45,65374,126,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"ja":[8211,45,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65292,44,65307,59],"ko":[8211,45,65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"pl":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"pt-BR":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"qps-ploc":[160,32,8211,45,65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"ru":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,305,105,921,73,1009,112,215,120,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"tr":[160,32,8211,45,65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"zh-hans":[65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41],"zh-hant":[8211,45,65374,126,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65307,59]}');
    });
  }
  static {
    this.d = new $rf({ getCacheKey: JSON.stringify }, (locales) => {
      function arrayToMap(arr) {
        const result = /* @__PURE__ */ new Map();
        for (let i = 0; i < arr.length; i += 2) {
          result.set(arr[i], arr[i + 1]);
        }
        return result;
      }
      function mergeMaps(map1, map2) {
        const result = new Map(map1);
        for (const [key, value] of map2) {
          result.set(key, value);
        }
        return result;
      }
      function intersectMaps(map1, map2) {
        if (!map1) {
          return map2;
        }
        const result = /* @__PURE__ */ new Map();
        for (const [key, value] of map1) {
          if (map2.has(key)) {
            result.set(key, value);
          }
        }
        return result;
      }
      const data = this.c.value;
      let filteredLocales = locales.filter((l) => !l.startsWith("_") && l in data);
      if (filteredLocales.length === 0) {
        filteredLocales = ["_default"];
      }
      let languageSpecificMap = void 0;
      for (const locale of filteredLocales) {
        const map2 = arrayToMap(data[locale]);
        languageSpecificMap = intersectMaps(languageSpecificMap, map2);
      }
      const commonMap = arrayToMap(data["_common"]);
      const map = mergeMaps(commonMap, languageSpecificMap);
      return new _$wg(map);
    });
  }
  static getInstance(locales) {
    return _$wg.d.get(Array.from(locales));
  }
  static {
    this.e = new $7(() => Object.keys(_$wg.c.value).filter((k) => !k.startsWith("_")));
  }
  static getLocales() {
    return _$wg.e.value;
  }
  constructor(f) {
    this.f = f;
  }
  isAmbiguous(codePoint) {
    return this.f.has(codePoint);
  }
  containsAmbiguousCharacter(str) {
    for (let i = 0; i < str.length; i++) {
      const codePoint = str.codePointAt(i);
      if (typeof codePoint === "number" && this.isAmbiguous(codePoint)) {
        return true;
      }
    }
    return false;
  }
  /**
   * Returns the non basic ASCII code point that the given code point can be confused,
   * or undefined if such code point does note exist.
   */
  getPrimaryConfusable(codePoint) {
    return this.f.get(codePoint);
  }
  getConfusableCodePoints() {
    return new Set(this.f.keys());
  }
};
var $xg = class _$xg {
  static c() {
    return JSON.parse("[9,10,11,12,13,32,127,160,173,847,1564,4447,4448,6068,6069,6155,6156,6157,6158,7355,7356,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8203,8204,8205,8206,8207,8234,8235,8236,8237,8238,8239,8287,8288,8289,8290,8291,8292,8293,8294,8295,8296,8297,8298,8299,8300,8301,8302,8303,10240,12288,12644,65024,65025,65026,65027,65028,65029,65030,65031,65032,65033,65034,65035,65036,65037,65038,65039,65279,65440,65520,65521,65522,65523,65524,65525,65526,65527,65528,65532,78844,119155,119156,119157,119158,119159,119160,119161,119162,917504,917505,917506,917507,917508,917509,917510,917511,917512,917513,917514,917515,917516,917517,917518,917519,917520,917521,917522,917523,917524,917525,917526,917527,917528,917529,917530,917531,917532,917533,917534,917535,917536,917537,917538,917539,917540,917541,917542,917543,917544,917545,917546,917547,917548,917549,917550,917551,917552,917553,917554,917555,917556,917557,917558,917559,917560,917561,917562,917563,917564,917565,917566,917567,917568,917569,917570,917571,917572,917573,917574,917575,917576,917577,917578,917579,917580,917581,917582,917583,917584,917585,917586,917587,917588,917589,917590,917591,917592,917593,917594,917595,917596,917597,917598,917599,917600,917601,917602,917603,917604,917605,917606,917607,917608,917609,917610,917611,917612,917613,917614,917615,917616,917617,917618,917619,917620,917621,917622,917623,917624,917625,917626,917627,917628,917629,917630,917631,917760,917761,917762,917763,917764,917765,917766,917767,917768,917769,917770,917771,917772,917773,917774,917775,917776,917777,917778,917779,917780,917781,917782,917783,917784,917785,917786,917787,917788,917789,917790,917791,917792,917793,917794,917795,917796,917797,917798,917799,917800,917801,917802,917803,917804,917805,917806,917807,917808,917809,917810,917811,917812,917813,917814,917815,917816,917817,917818,917819,917820,917821,917822,917823,917824,917825,917826,917827,917828,917829,917830,917831,917832,917833,917834,917835,917836,917837,917838,917839,917840,917841,917842,917843,917844,917845,917846,917847,917848,917849,917850,917851,917852,917853,917854,917855,917856,917857,917858,917859,917860,917861,917862,917863,917864,917865,917866,917867,917868,917869,917870,917871,917872,917873,917874,917875,917876,917877,917878,917879,917880,917881,917882,917883,917884,917885,917886,917887,917888,917889,917890,917891,917892,917893,917894,917895,917896,917897,917898,917899,917900,917901,917902,917903,917904,917905,917906,917907,917908,917909,917910,917911,917912,917913,917914,917915,917916,917917,917918,917919,917920,917921,917922,917923,917924,917925,917926,917927,917928,917929,917930,917931,917932,917933,917934,917935,917936,917937,917938,917939,917940,917941,917942,917943,917944,917945,917946,917947,917948,917949,917950,917951,917952,917953,917954,917955,917956,917957,917958,917959,917960,917961,917962,917963,917964,917965,917966,917967,917968,917969,917970,917971,917972,917973,917974,917975,917976,917977,917978,917979,917980,917981,917982,917983,917984,917985,917986,917987,917988,917989,917990,917991,917992,917993,917994,917995,917996,917997,917998,917999]");
  }
  static {
    this.d = void 0;
  }
  static e() {
    if (!this.d) {
      this.d = new Set(_$xg.c());
    }
    return this.d;
  }
  static isInvisibleCharacter(codePoint) {
    return _$xg.e().has(codePoint);
  }
  static containsInvisibleCharacter(str) {
    for (let i = 0; i < str.length; i++) {
      const codePoint = str.codePointAt(i);
      if (typeof codePoint === "number" && _$xg.isInvisibleCharacter(codePoint)) {
        return true;
      }
    }
    return false;
  }
  static get codePoints() {
    return _$xg.e();
  }
};

// out-build/vs/base/common/extpath.js
function $Rg(code2) {
  return code2 === 47 || code2 === 92;
}
function $Sg(osPath) {
  return osPath.replace(/[\\/]/g, $sc.sep);
}
function $Tg(osPath) {
  if (osPath.indexOf("/") === -1) {
    osPath = $Sg(osPath);
  }
  if (/^[a-zA-Z]:(\/|$)/.test(osPath)) {
    osPath = "/" + osPath;
  }
  return osPath;
}
function $Ug(path3, sep2 = $sc.sep) {
  if (!path3) {
    return "";
  }
  const len = path3.length;
  const firstLetter = path3.charCodeAt(0);
  if ($Rg(firstLetter)) {
    if ($Rg(path3.charCodeAt(1))) {
      if (!$Rg(path3.charCodeAt(2))) {
        let pos2 = 3;
        const start = pos2;
        for (; pos2 < len; pos2++) {
          if ($Rg(path3.charCodeAt(pos2))) {
            break;
          }
        }
        if (start !== pos2 && !$Rg(path3.charCodeAt(pos2 + 1))) {
          pos2 += 1;
          for (; pos2 < len; pos2++) {
            if ($Rg(path3.charCodeAt(pos2))) {
              return path3.slice(0, pos2 + 1).replace(/[\\/]/g, sep2);
            }
          }
        }
      }
    }
    return sep2;
  } else if ($Zg(firstLetter)) {
    if (path3.charCodeAt(1) === 58) {
      if ($Rg(path3.charCodeAt(2))) {
        return path3.slice(0, 2) + sep2;
      } else {
        return path3.slice(0, 2);
      }
    }
  }
  let pos = path3.indexOf("://");
  if (pos !== -1) {
    pos += 3;
    for (; pos < len; pos++) {
      if ($Rg(path3.charCodeAt(pos))) {
        return path3.slice(0, pos + 1);
      }
    }
  }
  return "";
}
function $Vg(path3) {
  if (!$l) {
    return false;
  }
  if (!path3 || path3.length < 5) {
    return false;
  }
  let code2 = path3.charCodeAt(0);
  if (code2 !== 92) {
    return false;
  }
  code2 = path3.charCodeAt(1);
  if (code2 !== 92) {
    return false;
  }
  let pos = 2;
  const start = pos;
  for (; pos < path3.length; pos++) {
    code2 = path3.charCodeAt(pos);
    if (code2 === 92) {
      break;
    }
  }
  if (start === pos) {
    return false;
  }
  code2 = path3.charCodeAt(pos + 1);
  if (isNaN(code2) || code2 === 92) {
    return false;
  }
  return true;
}
var WINDOWS_INVALID_FILE_CHARS = /[\\/:\*\?"<>\|]/g;
var UNIX_INVALID_FILE_CHARS = /[/]/g;
var WINDOWS_FORBIDDEN_NAMES = /^(con|prn|aux|clock\$|nul|lpt[0-9]|com[0-9])(\.(.*?))?$/i;
function $Wg(name, isWindowsOS = $l) {
  const invalidFileChars = isWindowsOS ? WINDOWS_INVALID_FILE_CHARS : UNIX_INVALID_FILE_CHARS;
  if (!name || name.length === 0 || /^\s+$/.test(name)) {
    return false;
  }
  invalidFileChars.lastIndex = 0;
  if (invalidFileChars.test(name)) {
    return false;
  }
  if (isWindowsOS && WINDOWS_FORBIDDEN_NAMES.test(name)) {
    return false;
  }
  if (name === "." || name === "..") {
    return false;
  }
  if (isWindowsOS && name[name.length - 1] === ".") {
    return false;
  }
  if (isWindowsOS && name.length !== name.trim().length) {
    return false;
  }
  if (name.length > 255) {
    return false;
  }
  return true;
}
function $Xg(pathA, pathB, ignoreCase) {
  const identityEquals = pathA === pathB;
  if (!ignoreCase || identityEquals) {
    return identityEquals;
  }
  if (!pathA || !pathB) {
    return false;
  }
  return $Zf(pathA, pathB);
}
function $Yg(base, parentCandidate, ignoreCase, separator = sep) {
  if (base === parentCandidate) {
    return true;
  }
  if (!base || !parentCandidate) {
    return false;
  }
  if (parentCandidate.length > base.length) {
    return false;
  }
  if (ignoreCase) {
    const beginsWith = $1f(base, parentCandidate);
    if (!beginsWith) {
      return false;
    }
    if (parentCandidate.length === base.length) {
      return true;
    }
    let sepOffset = parentCandidate.length;
    if (parentCandidate.charAt(parentCandidate.length - 1) === separator) {
      sepOffset--;
    }
    return base.charAt(sepOffset) === separator;
  }
  if (parentCandidate.charAt(parentCandidate.length - 1) !== separator) {
    parentCandidate += separator;
  }
  return base.indexOf(parentCandidate) === 0;
}
function $Zg(char0) {
  return char0 >= 65 && char0 <= 90 || char0 >= 97 && char0 <= 122;
}
function $1g(candidate, cwd2) {
  if ($l && candidate.endsWith(":")) {
    candidate += sep;
  }
  if (!$uc(candidate)) {
    candidate = $vc(cwd2, candidate);
  }
  candidate = $tc(candidate);
  return $2g(candidate);
}
function $2g(candidate) {
  if ($l) {
    candidate = $Gf(candidate, sep);
    if (candidate.endsWith(":")) {
      candidate += sep;
    }
  } else {
    candidate = $Gf(candidate, sep);
    if (!candidate) {
      candidate = sep;
    }
  }
  return candidate;
}
function $3g(path3) {
  const pathNormalized = $tc(path3);
  if ($l) {
    if (path3.length > 3) {
      return false;
    }
    return $4g(pathNormalized) && (path3.length === 2 || pathNormalized.charCodeAt(2) === 92);
  }
  return pathNormalized === $sc.sep;
}
function $4g(path3, isWindowsOS = $l) {
  if (isWindowsOS) {
    return $Zg(path3.charCodeAt(0)) && path3.charCodeAt(1) === 58;
  }
  return false;
}
function $7g(rawPath) {
  const segments = rawPath.split(":");
  let path3 = void 0;
  let line = void 0;
  let column = void 0;
  for (const segment of segments) {
    const segmentAsNumber = Number(segment);
    if (!$Cg(segmentAsNumber)) {
      path3 = !!path3 ? [path3, segment].join(":") : segment;
    } else if (line === void 0) {
      line = segmentAsNumber;
    } else if (column === void 0) {
      column = segmentAsNumber;
    }
  }
  if (!path3) {
    throw new Error("Format for `--goto` should be: `FILE:LINE(:COLUMN)`");
  }
  return {
    path: path3,
    line: line !== void 0 ? line : void 0,
    column: column !== void 0 ? column : line !== void 0 ? 1 : void 0
    // if we have a line, make sure column is also set
  };
}
var pathChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var windowsSafePathFirstChars = "BDEFGHIJKMOQRSTUVWXYZbdefghijkmoqrstuvwxyz0123456789";
function $8g(parent, prefix, randomLength = 8) {
  let suffix = "";
  for (let i = 0; i < randomLength; i++) {
    let pathCharsTouse;
    if (i === 0 && $l && !prefix && (randomLength === 3 || randomLength === 4)) {
      pathCharsTouse = windowsSafePathFirstChars;
    } else {
      pathCharsTouse = pathChars;
    }
    suffix += pathCharsTouse.charAt(Math.floor(Math.random() * pathCharsTouse.length));
  }
  let randomFileName;
  if (prefix) {
    randomFileName = `${prefix}-${suffix}`;
  } else {
    randomFileName = suffix;
  }
  if (parent) {
    return $vc(parent, randomFileName);
  }
  return randomFileName;
}

// out-build/vs/base/common/network.js
var Schemas;
(function(Schemas2) {
  Schemas2.inMemory = "inmemory";
  Schemas2.vscode = "vscode";
  Schemas2.internal = "private";
  Schemas2.walkThrough = "walkThrough";
  Schemas2.walkThroughSnippet = "walkThroughSnippet";
  Schemas2.http = "http";
  Schemas2.https = "https";
  Schemas2.file = "file";
  Schemas2.mailto = "mailto";
  Schemas2.untitled = "untitled";
  Schemas2.data = "data";
  Schemas2.command = "command";
  Schemas2.vscodeRemote = "vscode-remote";
  Schemas2.vscodeRemoteResource = "vscode-remote-resource";
  Schemas2.vscodeManagedRemoteResource = "vscode-managed-remote-resource";
  Schemas2.vscodeUserData = "vscode-userdata";
  Schemas2.vscodeCustomEditor = "vscode-custom-editor";
  Schemas2.vscodeNotebookCell = "vscode-notebook-cell";
  Schemas2.vscodeNotebookCellMetadata = "vscode-notebook-cell-metadata";
  Schemas2.vscodeNotebookCellMetadataDiff = "vscode-notebook-cell-metadata-diff";
  Schemas2.vscodeNotebookCellOutput = "vscode-notebook-cell-output";
  Schemas2.vscodeNotebookCellOutputDiff = "vscode-notebook-cell-output-diff";
  Schemas2.vscodeNotebookMetadata = "vscode-notebook-metadata";
  Schemas2.vscodeInteractiveInput = "vscode-interactive-input";
  Schemas2.vscodeSettings = "vscode-settings";
  Schemas2.vscodeWorkspaceTrust = "vscode-workspace-trust";
  Schemas2.vscodeTerminal = "vscode-terminal";
  Schemas2.vscodeChatCodeBlock = "vscode-chat-code-block";
  Schemas2.vscodeChatCodeCompareBlock = "vscode-chat-code-compare-block";
  Schemas2.vscodeChatSesssion = "vscode-chat-editor";
  Schemas2.webviewPanel = "webview-panel";
  Schemas2.vscodeWebview = "vscode-webview";
  Schemas2.extension = "extension";
  Schemas2.vscodeFileResource = "vscode-file";
  Schemas2.tmp = "tmp";
  Schemas2.vsls = "vsls";
  Schemas2.vscodeSourceControl = "vscode-scm";
  Schemas2.commentsInput = "comment";
  Schemas2.codeSetting = "code-setting";
  Schemas2.outputChannel = "output";
})(Schemas || (Schemas = {}));
function $9g(target, scheme) {
  if (URI.isUri(target)) {
    return $Zf(target.scheme, scheme);
  } else {
    return $1f(target, scheme + ":");
  }
}
function $0g(target, ...schemes) {
  return schemes.some((scheme) => $9g(target, scheme));
}
var $_g = "tkn";
var RemoteAuthoritiesImpl = class {
  constructor() {
    this.a = /* @__PURE__ */ Object.create(null);
    this.b = /* @__PURE__ */ Object.create(null);
    this.c = /* @__PURE__ */ Object.create(null);
    this.d = "http";
    this.e = null;
    this.f = "/";
  }
  setPreferredWebSchema(schema) {
    this.d = schema;
  }
  setDelegate(delegate) {
    this.e = delegate;
  }
  setServerRootPath(product2, serverBasePath) {
    this.f = $bh(product2, serverBasePath);
  }
  getServerRootPath() {
    return this.f;
  }
  get g() {
    return $sc.join(this.f, Schemas.vscodeRemoteResource);
  }
  set(authority, host, port) {
    this.a[authority] = host;
    this.b[authority] = port;
  }
  setConnectionToken(authority, connectionToken) {
    this.c[authority] = connectionToken;
  }
  getPreferredWebSchema() {
    return this.d;
  }
  rewrite(uri) {
    if (this.e) {
      try {
        return this.e(uri);
      } catch (err) {
        $ab(err);
        return uri;
      }
    }
    const authority = uri.authority;
    let host = this.a[authority];
    if (host && host.indexOf(":") !== -1 && host.indexOf("[") === -1) {
      host = `[${host}]`;
    }
    const port = this.b[authority];
    const connectionToken = this.c[authority];
    let query = `path=${encodeURIComponent(uri.path)}`;
    if (typeof connectionToken === "string") {
      query += `&${$_g}=${encodeURIComponent(connectionToken)}`;
    }
    return URI.from({
      scheme: $r ? this.d : Schemas.vscodeRemoteResource,
      authority: `${host}:${port}`,
      path: this.g,
      query
    });
  }
};
var $ah = new RemoteAuthoritiesImpl();
function $bh(product2, basePath) {
  return $sc.join(basePath ?? "/", `${product2.quality ?? "oss"}-${product2.commit ?? "dev"}`);
}
var $dh = "vs/../../node_modules";
var $eh = "vs/../../node_modules.asar";
var $gh = "vscode-app";
var FileAccessImpl = class _FileAccessImpl {
  static {
    this.a = $gh;
  }
  /**
   * Returns a URI to use in contexts where the browser is responsible
   * for loading (e.g. fetch()) or when used within the DOM.
   *
   * **Note:** use `dom.ts#asCSSUrl` whenever the URL is to be used in CSS context.
   */
  asBrowserUri(resourcePath) {
    const uri = this.b(resourcePath);
    return this.uriToBrowserUri(uri);
  }
  /**
   * Returns a URI to use in contexts where the browser is responsible
   * for loading (e.g. fetch()) or when used within the DOM.
   *
   * **Note:** use `dom.ts#asCSSUrl` whenever the URL is to be used in CSS context.
   */
  uriToBrowserUri(uri) {
    if (uri.scheme === Schemas.vscodeRemote) {
      return $ah.rewrite(uri);
    }
    if (
      // ...only ever for `file` resources
      uri.scheme === Schemas.file && // ...and we run in native environments
      ($p || // ...or web worker extensions on desktop
      $t === `${Schemas.vscodeFileResource}://${_FileAccessImpl.a}`)
    ) {
      return uri.with({
        scheme: Schemas.vscodeFileResource,
        // We need to provide an authority here so that it can serve
        // as origin for network and loading matters in chromium.
        // If the URI is not coming with an authority already, we
        // add our own
        authority: uri.authority || _FileAccessImpl.a,
        query: null,
        fragment: null
      });
    }
    return uri;
  }
  /**
   * Returns the `file` URI to use in contexts where node.js
   * is responsible for loading.
   */
  asFileUri(resourcePath) {
    const uri = this.b(resourcePath);
    return this.uriToFileUri(uri);
  }
  /**
   * Returns the `file` URI to use in contexts where node.js
   * is responsible for loading.
   */
  uriToFileUri(uri) {
    if (uri.scheme === Schemas.vscodeFileResource) {
      return uri.with({
        scheme: Schemas.file,
        // Only preserve the `authority` if it is different from
        // our fallback authority. This ensures we properly preserve
        // Windows UNC paths that come with their own authority.
        authority: uri.authority !== _FileAccessImpl.a ? uri.authority : null,
        query: null,
        fragment: null
      });
    }
    return uri;
  }
  b(uriOrModule, moduleIdToUrl) {
    if (URI.isUri(uriOrModule)) {
      return uriOrModule;
    }
    if (globalThis._VSCODE_FILE_ROOT) {
      const rootUriOrPath = globalThis._VSCODE_FILE_ROOT;
      if (/^\w[\w\d+.-]*:\/\//.test(rootUriOrPath)) {
        return URI.joinPath(URI.parse(rootUriOrPath, true), uriOrModule);
      }
      const modulePath = $vc(rootUriOrPath, uriOrModule);
      return URI.file(modulePath);
    }
    return URI.parse(moduleIdToUrl.toUrl(uriOrModule));
  }
};
var $hh = new FileAccessImpl();
var COI;
(function(COI2) {
  const coiHeaders = /* @__PURE__ */ new Map([
    ["1", { "Cross-Origin-Opener-Policy": "same-origin" }],
    ["2", { "Cross-Origin-Embedder-Policy": "require-corp" }],
    ["3", { "Cross-Origin-Opener-Policy": "same-origin", "Cross-Origin-Embedder-Policy": "require-corp" }]
  ]);
  COI2.CoopAndCoep = Object.freeze(coiHeaders.get("3"));
  const coiSearchParamName = "vscode-coi";
  function getHeadersFromQuery(url) {
    let params;
    if (typeof url === "string") {
      params = new URL(url).searchParams;
    } else if (url instanceof URL) {
      params = url.searchParams;
    } else if (URI.isUri(url)) {
      params = new URL(url.toString(true)).searchParams;
    }
    const value = params?.get(coiSearchParamName);
    if (!value) {
      return void 0;
    }
    return coiHeaders.get(value);
  }
  COI2.getHeadersFromQuery = getHeadersFromQuery;
  function addSearchParam(urlOrSearch, coop, coep) {
    if (!globalThis.crossOriginIsolated) {
      return;
    }
    const value = coop && coep ? "3" : coep ? "2" : "1";
    if (urlOrSearch instanceof URLSearchParams) {
      urlOrSearch.set(coiSearchParamName, value);
    } else {
      urlOrSearch[coiSearchParamName] = value;
    }
  }
  COI2.addSearchParam = addSearchParam;
})(COI || (COI = {}));

// out-build/vs/base/common/resources.js
function $oh(uri) {
  return $Ic(uri, true);
}
var $ph = class {
  constructor(a) {
    this.a = a;
  }
  compare(uri1, uri2, ignoreFragment = false) {
    if (uri1 === uri2) {
      return 0;
    }
    return $Sf(this.getComparisonKey(uri1, ignoreFragment), this.getComparisonKey(uri2, ignoreFragment));
  }
  isEqual(uri1, uri2, ignoreFragment = false) {
    if (uri1 === uri2) {
      return true;
    }
    if (!uri1 || !uri2) {
      return false;
    }
    return this.getComparisonKey(uri1, ignoreFragment) === this.getComparisonKey(uri2, ignoreFragment);
  }
  getComparisonKey(uri, ignoreFragment = false) {
    return uri.with({
      path: this.a(uri) ? uri.path.toLowerCase() : void 0,
      fragment: ignoreFragment ? null : void 0
    }).toString();
  }
  ignorePathCasing(uri) {
    return this.a(uri);
  }
  isEqualOrParent(base, parentCandidate, ignoreFragment = false) {
    if (base.scheme === parentCandidate.scheme) {
      if (base.scheme === Schemas.file) {
        return $Yg($oh(base), $oh(parentCandidate), this.a(base)) && base.query === parentCandidate.query && (ignoreFragment || base.fragment === parentCandidate.fragment);
      }
      if ($Fh(base.authority, parentCandidate.authority)) {
        return $Yg(base.path, parentCandidate.path, this.a(base), "/") && base.query === parentCandidate.query && (ignoreFragment || base.fragment === parentCandidate.fragment);
      }
    }
    return false;
  }
  // --- path math
  joinPath(resource, ...pathFragment) {
    return URI.joinPath(resource, ...pathFragment);
  }
  basenameOrAuthority(resource) {
    return $xh(resource) || resource.authority;
  }
  basename(resource) {
    return $sc.basename(resource.path);
  }
  extname(resource) {
    return $sc.extname(resource.path);
  }
  dirname(resource) {
    if (resource.path.length === 0) {
      return resource;
    }
    let dirname2;
    if (resource.scheme === Schemas.file) {
      dirname2 = URI.file($yc($oh(resource))).path;
    } else {
      dirname2 = $sc.dirname(resource.path);
      if (resource.authority && dirname2.length && dirname2.charCodeAt(0) !== 47) {
        console.error(`dirname("${resource.toString})) resulted in a relative path`);
        dirname2 = "/";
      }
    }
    return resource.with({
      path: dirname2
    });
  }
  normalizePath(resource) {
    if (!resource.path.length) {
      return resource;
    }
    let normalizedPath;
    if (resource.scheme === Schemas.file) {
      normalizedPath = URI.file($tc($oh(resource))).path;
    } else {
      normalizedPath = $sc.normalize(resource.path);
    }
    return resource.with({
      path: normalizedPath
    });
  }
  relativePath(from, to) {
    if (from.scheme !== to.scheme || !$Fh(from.authority, to.authority)) {
      return void 0;
    }
    if (from.scheme === Schemas.file) {
      const relativePath = $xc($oh(from), $oh(to));
      return $l ? $Sg(relativePath) : relativePath;
    }
    let fromPath = from.path || "/";
    const toPath = to.path || "/";
    if (this.a(from)) {
      let i = 0;
      for (const len = Math.min(fromPath.length, toPath.length); i < len; i++) {
        if (fromPath.charCodeAt(i) !== toPath.charCodeAt(i)) {
          if (fromPath.charAt(i).toLowerCase() !== toPath.charAt(i).toLowerCase()) {
            break;
          }
        }
      }
      fromPath = toPath.substr(0, i) + fromPath.substr(i);
    }
    return $sc.relative(fromPath, toPath);
  }
  resolvePath(base, path3) {
    if (base.scheme === Schemas.file) {
      const newURI = URI.file($wc($oh(base), path3));
      return base.with({
        authority: newURI.authority,
        path: newURI.path
      });
    }
    path3 = $Tg(path3);
    return base.with({
      path: $sc.resolve(base.path, path3)
    });
  }
  // --- misc
  isAbsolutePath(resource) {
    return !!resource.path && resource.path[0] === "/";
  }
  isEqualAuthority(a1, a2) {
    return a1 === a2 || a1 !== void 0 && a2 !== void 0 && $Zf(a1, a2);
  }
  hasTrailingPathSeparator(resource, sep2 = sep) {
    if (resource.scheme === Schemas.file) {
      const fsp = $oh(resource);
      return fsp.length > $Ug(fsp).length && fsp[fsp.length - 1] === sep2;
    } else {
      const p = resource.path;
      return p.length > 1 && p.charCodeAt(p.length - 1) === 47 && !/^[a-zA-Z]:(\/$|\\$)/.test(resource.fsPath);
    }
  }
  removeTrailingPathSeparator(resource, sep2 = sep) {
    if ($Gh(resource, sep2)) {
      return resource.with({ path: resource.path.substr(0, resource.path.length - 1) });
    }
    return resource;
  }
  addTrailingPathSeparator(resource, sep2 = sep) {
    let isRootSep = false;
    if (resource.scheme === Schemas.file) {
      const fsp = $oh(resource);
      isRootSep = fsp !== void 0 && fsp.length === $Ug(fsp).length && fsp[fsp.length - 1] === sep2;
    } else {
      sep2 = "/";
      const p = resource.path;
      isRootSep = p.length === 1 && p.charCodeAt(p.length - 1) === 47;
    }
    if (!isRootSep && !$Gh(resource, sep2)) {
      return resource.with({ path: resource.path + "/" });
    }
    return resource;
  }
};
var $qh = new $ph(() => false);
var $rh = new $ph((uri) => {
  return uri.scheme === Schemas.file ? !$n : true;
});
var $sh = new $ph((_) => true);
var $th = $qh.isEqual.bind($qh);
var $uh = $qh.isEqualOrParent.bind($qh);
var $vh = $qh.getComparisonKey.bind($qh);
var $wh = $qh.basenameOrAuthority.bind($qh);
var $xh = $qh.basename.bind($qh);
var $yh = $qh.extname.bind($qh);
var $zh = $qh.dirname.bind($qh);
var $Ah = $qh.joinPath.bind($qh);
var $Bh = $qh.normalizePath.bind($qh);
var $Ch = $qh.relativePath.bind($qh);
var $Dh = $qh.resolvePath.bind($qh);
var $Eh = $qh.isAbsolutePath.bind($qh);
var $Fh = $qh.isEqualAuthority.bind($qh);
var $Gh = $qh.hasTrailingPathSeparator.bind($qh);
var $Hh = $qh.removeTrailingPathSeparator.bind($qh);
var $Ih = $qh.addTrailingPathSeparator.bind($qh);
var DataUri;
(function(DataUri2) {
  DataUri2.META_DATA_LABEL = "label";
  DataUri2.META_DATA_DESCRIPTION = "description";
  DataUri2.META_DATA_SIZE = "size";
  DataUri2.META_DATA_MIME = "mime";
  function parseMetaData(dataUri) {
    const metadata = /* @__PURE__ */ new Map();
    const meta = dataUri.path.substring(dataUri.path.indexOf(";") + 1, dataUri.path.lastIndexOf(";"));
    meta.split(";").forEach((property) => {
      const [key, value] = property.split(":");
      if (key && value) {
        metadata.set(key, value);
      }
    });
    const mime = dataUri.path.substring(0, dataUri.path.indexOf(";"));
    if (mime) {
      metadata.set(DataUri2.META_DATA_MIME, mime);
    }
    return metadata;
  }
  DataUri2.parseMetaData = parseMetaData;
})(DataUri || (DataUri = {}));

// out-build/vs/base/common/symbols.js
var $ye = Symbol("MicrotaskDelay");

// out-build/vs/base/common/async.js
function $Lh(obj) {
  return !!obj && typeof obj.then === "function";
}
function $Mh(callback) {
  const source = new $Pe();
  const thenable = callback(source.token);
  const promise = new Promise((resolve2, reject) => {
    const subscription = source.token.onCancellationRequested(() => {
      subscription.dispose();
      reject(new $fb());
    });
    Promise.resolve(thenable).then((value) => {
      subscription.dispose();
      source.dispose();
      resolve2(value);
    }, (err) => {
      subscription.dispose();
      source.dispose();
      reject(err);
    });
  });
  return new class {
    cancel() {
      source.cancel();
      source.dispose();
    }
    then(resolve2, reject) {
      return promise.then(resolve2, reject);
    }
    catch(reject) {
      return this.then(void 0, reject);
    }
    finally(onfinally) {
      return promise.finally(onfinally);
    }
  }();
}
function $Qh(promise, timeout, onTimeout) {
  let promiseResolve = void 0;
  const timer = setTimeout(() => {
    promiseResolve?.(void 0);
    onTimeout?.();
  }, timeout);
  return Promise.race([
    promise.finally(() => clearTimeout(timer)),
    new Promise((resolve2) => promiseResolve = resolve2)
  ]);
}
function $Sh() {
  let resolve2;
  let reject;
  const promise = new Promise((res, rej) => {
    resolve2 = res;
    reject = rej;
  });
  return { promise, resolve: resolve2, reject };
}
var $Th = class {
  constructor() {
    this.f = false;
    this.a = null;
    this.b = null;
    this.d = null;
  }
  queue(promiseFactory) {
    if (this.f) {
      return Promise.reject(new Error("Throttler is disposed"));
    }
    if (this.a) {
      this.d = promiseFactory;
      if (!this.b) {
        const onComplete = () => {
          this.b = null;
          if (this.f) {
            return;
          }
          const result = this.queue(this.d);
          this.d = null;
          return result;
        };
        this.b = new Promise((resolve2) => {
          this.a.then(onComplete, onComplete).then(resolve2);
        });
      }
      return new Promise((resolve2, reject) => {
        this.b.then(resolve2, reject);
      });
    }
    this.a = promiseFactory();
    return new Promise((resolve2, reject) => {
      this.a.then((result) => {
        this.a = null;
        resolve2(result);
      }, (err) => {
        this.a = null;
        reject(err);
      });
    });
  }
  dispose() {
    this.f = true;
  }
};
var timeoutDeferred = (timeout, fn) => {
  let scheduled = true;
  const handle = setTimeout(() => {
    scheduled = false;
    fn();
  }, timeout);
  return {
    isTriggered: () => scheduled,
    dispose: () => {
      clearTimeout(handle);
      scheduled = false;
    }
  };
};
var microtaskDeferred = (fn) => {
  let scheduled = true;
  queueMicrotask(() => {
    if (scheduled) {
      scheduled = false;
      fn();
    }
  });
  return {
    isTriggered: () => scheduled,
    dispose: () => {
      scheduled = false;
    }
  };
};
var $Wh = class {
  constructor(defaultDelay) {
    this.defaultDelay = defaultDelay;
    this.a = null;
    this.b = null;
    this.d = null;
    this.f = null;
    this.g = null;
  }
  trigger(task, delay = this.defaultDelay) {
    this.g = task;
    this.h();
    if (!this.b) {
      this.b = new Promise((resolve2, reject) => {
        this.d = resolve2;
        this.f = reject;
      }).then(() => {
        this.b = null;
        this.d = null;
        if (this.g) {
          const task2 = this.g;
          this.g = null;
          return task2();
        }
        return void 0;
      });
    }
    const fn = () => {
      this.a = null;
      this.d?.(null);
    };
    this.a = delay === $ye ? microtaskDeferred(fn) : timeoutDeferred(delay, fn);
    return this.b;
  }
  isTriggered() {
    return !!this.a?.isTriggered();
  }
  cancel() {
    this.h();
    if (this.b) {
      this.f?.(new $fb());
      this.b = null;
    }
  }
  h() {
    this.a?.dispose();
    this.a = null;
  }
  dispose() {
    this.cancel();
  }
};
var $Xh = class {
  constructor(defaultDelay) {
    this.a = new $Wh(defaultDelay);
    this.b = new $Th();
  }
  trigger(promiseFactory, delay) {
    return this.a.trigger(() => this.b.queue(promiseFactory), delay);
  }
  isTriggered() {
    return this.a.isTriggered();
  }
  cancel() {
    this.a.cancel();
  }
  dispose() {
    this.a.dispose();
    this.b.dispose();
  }
};
var $Yh = class {
  constructor() {
    this.a = false;
    this.b = new Promise((c, e) => {
      this.d = c;
    });
  }
  isOpen() {
    return this.a;
  }
  open() {
    this.a = true;
    this.d(true);
  }
  wait() {
    return this.b;
  }
};
function $1h(millis, token) {
  if (!token) {
    return $Mh((token2) => $1h(millis, token2));
  }
  return new Promise((resolve2, reject) => {
    const handle = setTimeout(() => {
      disposable.dispose();
      resolve2();
    }, millis);
    const disposable = token.onCancellationRequested(() => {
      clearTimeout(handle);
      disposable.dispose();
      reject(new $fb());
    });
  });
}
function $2h(handler, timeout = 0, store) {
  const timer = setTimeout(() => {
    handler();
    if (store) {
      disposable.dispose();
    }
  }, timeout);
  const disposable = $8c(() => {
    clearTimeout(timer);
    store?.deleteAndLeak(disposable);
  });
  store?.add(disposable);
  return disposable;
}
function $4h(promiseFactories, shouldStop = (t) => !!t, defaultValue = null) {
  let index = 0;
  const len = promiseFactories.length;
  const loop = () => {
    if (index >= len) {
      return Promise.resolve(defaultValue);
    }
    const factory = promiseFactories[index++];
    const promise = Promise.resolve(factory());
    return promise.then((result) => {
      if (shouldStop(result)) {
        return Promise.resolve(result);
      }
      return loop();
    });
  };
  return loop();
}
var $6h = class {
  constructor(maxDegreeOfParalellism) {
    this.a = 0;
    this.b = false;
    this.f = maxDegreeOfParalellism;
    this.g = [];
    this.d = 0;
    this.h = new $De();
  }
  /**
   *
   * @returns A promise that resolved when all work is done (onDrained) or when
   * there is nothing to do
   */
  whenIdle() {
    return this.size > 0 ? Event.toPromise(this.onDrained) : Promise.resolve();
  }
  get onDrained() {
    return this.h.event;
  }
  get size() {
    return this.a;
  }
  queue(factory) {
    if (this.b) {
      throw new Error("Object has been disposed");
    }
    this.a++;
    return new Promise((c, e) => {
      this.g.push({ factory, c, e });
      this.j();
    });
  }
  j() {
    while (this.g.length && this.d < this.f) {
      const iLimitedTask = this.g.shift();
      this.d++;
      const promise = iLimitedTask.factory();
      promise.then(iLimitedTask.c, iLimitedTask.e);
      promise.then(() => this.k(), () => this.k());
    }
  }
  k() {
    if (this.b) {
      return;
    }
    this.d--;
    if (--this.a === 0) {
      this.h.fire();
    }
    if (this.g.length > 0) {
      this.j();
    }
  }
  clear() {
    if (this.b) {
      throw new Error("Object has been disposed");
    }
    this.g.length = 0;
    this.a = this.d;
  }
  dispose() {
    this.b = true;
    this.g.length = 0;
    this.a = 0;
    this.h.dispose();
  }
};
var $7h = class extends $6h {
  constructor() {
    super(1);
  }
};
var $9h = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Set();
    this.d = void 0;
    this.f = 0;
  }
  async whenDrained() {
    if (this.g()) {
      return;
    }
    const promise = new $ki();
    this.b.add(promise);
    return promise.p;
  }
  g() {
    for (const [, queue] of this.a) {
      if (queue.size > 0) {
        return false;
      }
    }
    return true;
  }
  queueSize(resource, extUri = $qh) {
    const key = extUri.getComparisonKey(resource);
    return this.a.get(key)?.size ?? 0;
  }
  queueFor(resource, factory, extUri = $qh) {
    const key = extUri.getComparisonKey(resource);
    let queue = this.a.get(key);
    if (!queue) {
      queue = new $7h();
      const drainListenerId = this.f++;
      const drainListener = Event.once(queue.onDrained)(() => {
        queue?.dispose();
        this.a.delete(key);
        this.h();
        this.d?.deleteAndDispose(drainListenerId);
        if (this.d?.size === 0) {
          this.d.dispose();
          this.d = void 0;
        }
      });
      if (!this.d) {
        this.d = new $gd();
      }
      this.d.set(drainListenerId, drainListener);
      this.a.set(key, queue);
    }
    return queue.queue(factory);
  }
  h() {
    if (!this.g()) {
      return;
    }
    this.j();
  }
  j() {
    for (const drainer of this.b) {
      drainer.complete();
    }
    this.b.clear();
  }
  dispose() {
    for (const [, queue] of this.a) {
      queue.dispose();
    }
    this.a.clear();
    this.j();
    this.d?.dispose();
  }
};
var $_h = class {
  constructor(runner, delay) {
    this.b = -1;
    this.a = runner;
    this.d = delay;
    this.f = this.g.bind(this);
  }
  /**
   * Dispose RunOnceScheduler
   */
  dispose() {
    this.cancel();
    this.a = null;
  }
  /**
   * Cancel current scheduled runner (if any).
   */
  cancel() {
    if (this.isScheduled()) {
      clearTimeout(this.b);
      this.b = -1;
    }
  }
  /**
   * Cancel previous runner (if any) & schedule a new runner.
   */
  schedule(delay = this.d) {
    this.cancel();
    this.b = setTimeout(this.f, delay);
  }
  get delay() {
    return this.d;
  }
  set delay(value) {
    this.d = value;
  }
  /**
   * Returns true if scheduled.
   */
  isScheduled() {
    return this.b !== -1;
  }
  flush() {
    if (this.isScheduled()) {
      this.cancel();
      this.h();
    }
  }
  g() {
    this.b = -1;
    if (this.a) {
      this.h();
    }
  }
  h() {
    this.a?.();
  }
};
var $bi = class extends $_h {
  constructor(runner, timeout) {
    super(runner, timeout);
    this.j = [];
  }
  work(unit) {
    this.j.push(unit);
    if (!this.isScheduled()) {
      this.schedule();
    }
  }
  h() {
    const units = this.j;
    this.j = [];
    this.a?.(units);
  }
  dispose() {
    this.j = [];
    super.dispose();
  }
};
var $ci = class extends $0c {
  constructor(g, h) {
    super();
    this.g = g;
    this.h = h;
    this.a = [];
    this.b = this.B(new $$c());
    this.f = false;
  }
  /**
   * The number of work units that are pending to be processed.
   */
  get pending() {
    return this.a.length;
  }
  /**
   * Add units to be worked on. Use `pending` to figure out
   * how many units are not yet processed after this method
   * was called.
   *
   * @returns whether the work was accepted or not. If the
   * worker is disposed, it will not accept any more work.
   * If the number of pending units would become larger
   * than `maxPendingWork`, more work will also not be accepted.
   */
  work(units) {
    if (this.f) {
      return false;
    }
    if (typeof this.g.maxBufferedWork === "number") {
      if (this.b.value) {
        if (this.pending + units.length > this.g.maxBufferedWork) {
          return false;
        }
      } else {
        if (this.pending + units.length - this.g.maxWorkChunkSize > this.g.maxBufferedWork) {
          return false;
        }
      }
    }
    for (const unit of units) {
      this.a.push(unit);
    }
    if (!this.b.value) {
      this.j();
    }
    return true;
  }
  j() {
    this.h(this.a.splice(0, this.g.maxWorkChunkSize));
    if (this.a.length > 0) {
      this.b.value = new $_h(() => {
        this.b.clear();
        this.j();
      }, this.g.throttleDelay);
      this.b.value.schedule();
    }
  }
  dispose() {
    super.dispose();
    this.f = true;
  }
};
var $di;
var $ei;
(function() {
  if (typeof globalThis.requestIdleCallback !== "function" || typeof globalThis.cancelIdleCallback !== "function") {
    $ei = (_targetWindow, runner) => {
      $E(() => {
        if (disposed) {
          return;
        }
        const end = Date.now() + 15;
        const deadline = {
          didTimeout: true,
          timeRemaining() {
            return Math.max(0, end - Date.now());
          }
        };
        runner(Object.freeze(deadline));
      });
      let disposed = false;
      return {
        dispose() {
          if (disposed) {
            return;
          }
          disposed = true;
        }
      };
    };
  } else {
    $ei = (targetWindow, runner, timeout) => {
      const handle = targetWindow.requestIdleCallback(runner, typeof timeout === "number" ? { timeout } : void 0);
      let disposed = false;
      return {
        dispose() {
          if (disposed) {
            return;
          }
          disposed = true;
          targetWindow.cancelIdleCallback(handle);
        }
      };
    };
  }
  $di = (runner) => $ei(globalThis, runner);
})();
var $fi = class {
  constructor(targetWindow, executor) {
    this.g = false;
    this.d = () => {
      try {
        this.j = executor();
      } catch (err) {
        this.l = err;
      } finally {
        this.g = true;
      }
    };
    this.f = $ei(targetWindow, () => this.d());
  }
  dispose() {
    this.f.dispose();
  }
  get value() {
    if (!this.g) {
      this.f.dispose();
      this.d();
    }
    if (this.l) {
      throw this.l;
    }
    return this.j;
  }
  get isInitialized() {
    return this.g;
  }
};
var $gi = class extends $fi {
  constructor(executor) {
    super(globalThis, executor);
  }
};
async function $hi(task, delay, retries) {
  let lastError;
  for (let i = 0; i < retries; i++) {
    try {
      return await task();
    } catch (error) {
      lastError = error;
      await $1h(delay);
    }
  }
  throw lastError;
}
var DeferredOutcome;
(function(DeferredOutcome2) {
  DeferredOutcome2[DeferredOutcome2["Resolved"] = 0] = "Resolved";
  DeferredOutcome2[DeferredOutcome2["Rejected"] = 1] = "Rejected";
})(DeferredOutcome || (DeferredOutcome = {}));
var $ki = class {
  get isRejected() {
    return this.d?.outcome === 1;
  }
  get isResolved() {
    return this.d?.outcome === 0;
  }
  get isSettled() {
    return !!this.d;
  }
  get value() {
    return this.d?.outcome === 0 ? this.d?.value : void 0;
  }
  constructor() {
    this.p = new Promise((c, e) => {
      this.a = c;
      this.b = e;
    });
  }
  complete(value) {
    return new Promise((resolve2) => {
      this.a(value);
      this.d = { outcome: 0, value };
      resolve2();
    });
  }
  error(err) {
    return new Promise((resolve2) => {
      this.b(err);
      this.d = { outcome: 1, value: err };
      resolve2();
    });
  }
  cancel() {
    return this.error(new $fb());
  }
};
var Promises;
(function(Promises3) {
  async function settled(promises16) {
    let firstError = void 0;
    const result = await Promise.all(promises16.map((promise) => promise.then((value) => value, (error) => {
      if (!firstError) {
        firstError = error;
      }
      return void 0;
    })));
    if (typeof firstError !== "undefined") {
      throw firstError;
    }
    return result;
  }
  Promises3.settled = settled;
  function withAsyncBody(bodyFn) {
    return new Promise(async (resolve2, reject) => {
      try {
        await bodyFn(resolve2, reject);
      } catch (error) {
        reject(error);
      }
    });
  }
  Promises3.withAsyncBody = withAsyncBody;
})(Promises || (Promises = {}));
var AsyncIterableSourceState;
(function(AsyncIterableSourceState2) {
  AsyncIterableSourceState2[AsyncIterableSourceState2["Initial"] = 0] = "Initial";
  AsyncIterableSourceState2[AsyncIterableSourceState2["DoneOK"] = 1] = "DoneOK";
  AsyncIterableSourceState2[AsyncIterableSourceState2["DoneError"] = 2] = "DoneError";
})(AsyncIterableSourceState || (AsyncIterableSourceState = {}));
var $ni = class _$ni {
  static fromArray(items) {
    return new _$ni((writer) => {
      writer.emitMany(items);
    });
  }
  static fromPromise(promise) {
    return new _$ni(async (emitter) => {
      emitter.emitMany(await promise);
    });
  }
  static fromPromises(promises16) {
    return new _$ni(async (emitter) => {
      await Promise.all(promises16.map(async (p) => emitter.emitOne(await p)));
    });
  }
  static merge(iterables) {
    return new _$ni(async (emitter) => {
      await Promise.all(iterables.map(async (iterable) => {
        for await (const item of iterable) {
          emitter.emitOne(item);
        }
      }));
    });
  }
  static {
    this.EMPTY = _$ni.fromArray([]);
  }
  constructor(executor, onReturn) {
    this.a = 0;
    this.b = [];
    this.d = null;
    this.f = onReturn;
    this.g = new $De();
    queueMicrotask(async () => {
      const writer = {
        emitOne: (item) => this.h(item),
        emitMany: (items) => this.j(items),
        reject: (error) => this.l(error)
      };
      try {
        await Promise.resolve(executor(writer));
        this.k();
      } catch (err) {
        this.l(err);
      } finally {
        writer.emitOne = void 0;
        writer.emitMany = void 0;
        writer.reject = void 0;
      }
    });
  }
  [Symbol.asyncIterator]() {
    let i = 0;
    return {
      next: async () => {
        do {
          if (this.a === 2) {
            throw this.d;
          }
          if (i < this.b.length) {
            return { done: false, value: this.b[i++] };
          }
          if (this.a === 1) {
            return { done: true, value: void 0 };
          }
          await Event.toPromise(this.g.event);
        } while (true);
      },
      return: async () => {
        this.f?.();
        return { done: true, value: void 0 };
      }
    };
  }
  static map(iterable, mapFn) {
    return new _$ni(async (emitter) => {
      for await (const item of iterable) {
        emitter.emitOne(mapFn(item));
      }
    });
  }
  map(mapFn) {
    return _$ni.map(this, mapFn);
  }
  static filter(iterable, filterFn) {
    return new _$ni(async (emitter) => {
      for await (const item of iterable) {
        if (filterFn(item)) {
          emitter.emitOne(item);
        }
      }
    });
  }
  filter(filterFn) {
    return _$ni.filter(this, filterFn);
  }
  static coalesce(iterable) {
    return _$ni.filter(iterable, (item) => !!item);
  }
  coalesce() {
    return _$ni.coalesce(this);
  }
  static async toPromise(iterable) {
    const result = [];
    for await (const item of iterable) {
      result.push(item);
    }
    return result;
  }
  toPromise() {
    return _$ni.toPromise(this);
  }
  /**
   * The value will be appended at the end.
   *
   * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
   */
  h(value) {
    if (this.a !== 0) {
      return;
    }
    this.b.push(value);
    this.g.fire();
  }
  /**
   * The values will be appended at the end.
   *
   * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
   */
  j(values) {
    if (this.a !== 0) {
      return;
    }
    this.b = this.b.concat(values);
    this.g.fire();
  }
  /**
   * Calling `resolve()` will mark the result array as complete.
   *
   * **NOTE** `resolve()` must be called, otherwise all consumers of this iterable will hang indefinitely, similar to a non-resolved promise.
   * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
   */
  k() {
    if (this.a !== 0) {
      return;
    }
    this.a = 1;
    this.g.fire();
  }
  /**
   * Writing an error will permanently invalidate this iterable.
   * The current users will receive an error thrown, as will all future users.
   *
   * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
   */
  l(error) {
    if (this.a !== 0) {
      return;
    }
    this.a = 2;
    this.d = error;
    this.g.fire();
  }
};

// out-build/vs/base/common/errorMessage.js
function exceptionToErrorMessage(exception, verbose) {
  if (verbose && (exception.stack || exception.stacktrace)) {
    return localize(108, null, detectSystemErrorMessage(exception), stackToString(exception.stack) || stackToString(exception.stacktrace));
  }
  return detectSystemErrorMessage(exception);
}
function stackToString(stack) {
  if (Array.isArray(stack)) {
    return stack.join("\n");
  }
  return stack;
}
function detectSystemErrorMessage(exception) {
  if (exception.code === "ERR_UNC_HOST_NOT_ALLOWED") {
    return `${exception.message}. Please update the 'security.allowedUNCHosts' setting if you want to allow this host.`;
  }
  if (typeof exception.code === "string" && typeof exception.errno === "number" && typeof exception.syscall === "string") {
    return localize(109, null, exception.message);
  }
  return exception.message || localize(110, null);
}
function $Kj(error = null, verbose = false) {
  if (!error) {
    return localize(111, null);
  }
  if (Array.isArray(error)) {
    const errors = $Ub(error);
    const msg = $Kj(errors[0], verbose);
    if (errors.length > 1) {
      return localize(112, null, msg, errors.length);
    }
    return msg;
  }
  if ($yg(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 localize(113, null);
}

// out-build/vs/base/common/labels.js
function $rx(resource, formatting) {
  const { os: os6, tildify: tildifier, relative: relatifier } = formatting;
  if (relatifier) {
    const relativePath = getRelativePathLabel(resource, relatifier, os6);
    if (typeof relativePath === "string") {
      return relativePath;
    }
  }
  let absolutePath = resource.fsPath;
  if (os6 === 1 && !$l) {
    absolutePath = absolutePath.replace(/\//g, "\\");
  } else if (os6 !== 1 && $l) {
    absolutePath = absolutePath.replace(/\\/g, "/");
  }
  if (os6 !== 1 && tildifier?.userHome) {
    const userHome = tildifier.userHome.fsPath;
    let userHomeCandidate;
    if (resource.scheme !== tildifier.userHome.scheme && resource.path[0] === $sc.sep && resource.path[1] !== $sc.sep) {
      userHomeCandidate = tildifier.userHome.with({ path: resource.path }).fsPath;
    } else {
      userHomeCandidate = absolutePath;
    }
    absolutePath = $tx(userHomeCandidate, userHome, os6);
  }
  const pathLib = os6 === 1 ? $rc : $sc;
  return pathLib.normalize($sx(
    absolutePath,
    os6 === 1
    /* OperatingSystem.Windows */
  ));
}
function getRelativePathLabel(resource, relativePathProvider, os6) {
  const pathLib = os6 === 1 ? $rc : $sc;
  const extUriLib = os6 === 3 ? $qh : $sh;
  const workspace = relativePathProvider.getWorkspace();
  const firstFolder = workspace.folders.at(0);
  if (!firstFolder) {
    return void 0;
  }
  if (resource.scheme !== firstFolder.uri.scheme && resource.path[0] === $sc.sep && resource.path[1] !== $sc.sep) {
    resource = firstFolder.uri.with({ path: resource.path });
  }
  const folder = relativePathProvider.getWorkspaceFolder(resource);
  if (!folder) {
    return void 0;
  }
  let relativePathLabel = void 0;
  if (extUriLib.isEqual(folder.uri, resource)) {
    relativePathLabel = "";
  } else {
    relativePathLabel = extUriLib.relativePath(folder.uri, resource) ?? "";
  }
  if (relativePathLabel) {
    relativePathLabel = pathLib.normalize(relativePathLabel);
  }
  if (workspace.folders.length > 1 && !relativePathProvider.noPrefix) {
    const rootName = folder.name ? folder.name : extUriLib.basenameOrAuthority(folder.uri);
    relativePathLabel = relativePathLabel ? `${rootName} \u2022 ${relativePathLabel}` : rootName;
  }
  return relativePathLabel;
}
function $sx(path3, isWindowsOS = $l) {
  if ($4g(path3, isWindowsOS)) {
    return path3.charAt(0).toUpperCase() + path3.slice(1);
  }
  return path3;
}
var normalizedUserHomeCached = /* @__PURE__ */ Object.create(null);
function $tx(path3, userHome, os6 = OS) {
  if (os6 === 1 || !path3 || !userHome) {
    return path3;
  }
  let normalizedUserHome = normalizedUserHomeCached.original === userHome ? normalizedUserHomeCached.normalized : void 0;
  if (!normalizedUserHome) {
    normalizedUserHome = userHome;
    if ($l) {
      normalizedUserHome = $Sg(normalizedUserHome);
    }
    normalizedUserHome = `${$Gf(normalizedUserHome, $sc.sep)}${$sc.sep}`;
    normalizedUserHomeCached = { original: userHome, normalized: normalizedUserHome };
  }
  let normalizedPath = path3;
  if ($l) {
    normalizedPath = $Sg(normalizedPath);
  }
  if (os6 === 3 ? normalizedPath.startsWith(normalizedUserHome) : $1f(normalizedPath, normalizedUserHome)) {
    return `~/${normalizedPath.substr(normalizedUserHome.length)}`;
  }
  return path3;
}
var Type;
(function(Type2) {
  Type2[Type2["TEXT"] = 0] = "TEXT";
  Type2[Type2["VARIABLE"] = 1] = "VARIABLE";
  Type2[Type2["SEPARATOR"] = 2] = "SEPARATOR";
})(Type || (Type = {}));
function $xx(label, forceDisableMnemonics) {
  if ($m || forceDisableMnemonics) {
    return label.replace(/\(&&\w\)|&&/g, "").replace(/&/g, $m ? "&" : "&&");
  }
  return label.replace(/&&|&/g, (m) => m === "&" ? "&&" : "&");
}
function $yx(label, forceDisableMnemonics) {
  if ($m || forceDisableMnemonics) {
    return label.replace(/\(&&\w\)|&&/g, "");
  }
  if ($l) {
    return label.replace(/&&|&/g, (m) => m === "&" ? "&&" : "&");
  }
  return label.replace(/&&/g, "_");
}
function $Ax(recentLabel) {
  if (recentLabel.endsWith("]")) {
    const lastIndexOfSquareBracket = recentLabel.lastIndexOf(" [", recentLabel.length - 2);
    if (lastIndexOfSquareBracket !== -1) {
      const split = splitName(recentLabel.substring(0, lastIndexOfSquareBracket));
      const remoteNameWithSpace = recentLabel.substring(lastIndexOfSquareBracket);
      return { name: split.name + remoteNameWithSpace, parentPath: split.parentPath };
    }
  }
  return splitName(recentLabel);
}
function splitName(fullPath) {
  const p = fullPath.indexOf("/") !== -1 ? $sc : $rc;
  const name = p.basename(fullPath);
  const parentPath = p.dirname(fullPath);
  if (name.length) {
    return { name, parentPath };
  }
  return { name: parentPath, parentPath: "" };
}

// out-build/vs/base/common/performance.js
var module = { exports: {} };
(function() {
  const isESM = true;
  function _definePolyfillMarks(timeOrigin) {
    const _data = [];
    if (typeof timeOrigin === "number") {
      _data.push("code/timeOrigin", timeOrigin);
    }
    function mark2(name) {
      _data.push(name, Date.now());
    }
    function getMarks2() {
      const result = [];
      for (let i = 0; i < _data.length; i += 2) {
        result.push({
          name: _data[i],
          startTime: _data[i + 1]
        });
      }
      return result;
    }
    return { mark: mark2, getMarks: getMarks2 };
  }
  function _define() {
    if (typeof performance === "object" && typeof performance.mark === "function" && !performance.nodeTiming) {
      if (typeof performance.timeOrigin !== "number" && !performance.timing) {
        return _definePolyfillMarks();
      } else {
        return {
          mark(name) {
            performance.mark(name);
          },
          getMarks() {
            let timeOrigin = performance.timeOrigin;
            if (typeof timeOrigin !== "number") {
              timeOrigin = performance.timing.navigationStart || performance.timing.redirectStart || performance.timing.fetchStart;
            }
            const result = [{ name: "code/timeOrigin", startTime: Math.round(timeOrigin) }];
            for (const entry of performance.getEntriesByType("mark")) {
              result.push({
                name: entry.name,
                startTime: Math.round(timeOrigin + entry.startTime)
              });
            }
            return result;
          }
        };
      }
    } else if (typeof process === "object") {
      const timeOrigin = performance?.timeOrigin;
      return _definePolyfillMarks(timeOrigin);
    } else {
      console.trace("perf-util loaded in UNKNOWN environment");
      return _definePolyfillMarks();
    }
  }
  function _factory(sharedObj2) {
    if (!sharedObj2.MonacoPerformanceMarks) {
      sharedObj2.MonacoPerformanceMarks = _define();
    }
    return sharedObj2.MonacoPerformanceMarks;
  }
  var sharedObj;
  if (typeof global === "object") {
    sharedObj = global;
  } else if (typeof self === "object") {
    sharedObj = self;
  } else {
    sharedObj = {};
  }
  if (!isESM && typeof define === "function") {
    define([], function() {
      return _factory(sharedObj);
    });
  } else if (typeof module === "object" && typeof module.exports === "object") {
    module.exports = _factory(sharedObj);
  } else {
    console.trace("perf-util defined in UNKNOWN context (neither requirejs or commonjs)");
    sharedObj.perf = _factory(sharedObj);
  }
})();
var mark = module.exports.mark;
var getMarks = module.exports.getMarks;

// out-build/vs/base/node/pfs.js
import * as fs from "fs";
import { tmpdir } from "os";
import { promisify } from "util";

// out-build/vs/base/common/normalization.js
var nfcCache = new $Pc(1e4);
function $Hm(str) {
  return normalize(str, "NFC", nfcCache);
}
var nfdCache = new $Pc(1e4);
var nonAsciiCharactersPattern = /[^\u0000-\u0080]/;
function normalize(str, form, normalizedCache) {
  if (!str) {
    return str;
  }
  const cached = normalizedCache.get(str);
  if (cached) {
    return cached;
  }
  let res;
  if (nonAsciiCharactersPattern.test(str)) {
    res = str.normalize(form);
  } else {
    res = str;
  }
  normalizedCache.set(str, res);
  return res;
}

// out-build/vs/base/node/pfs.js
var RimRafMode;
(function(RimRafMode2) {
  RimRafMode2[RimRafMode2["UNLINK"] = 0] = "UNLINK";
  RimRafMode2[RimRafMode2["MOVE"] = 1] = "MOVE";
})(RimRafMode || (RimRafMode = {}));
async function rimraf(path3, mode = RimRafMode.UNLINK, moveToPath) {
  if ($3g(path3)) {
    throw new Error("rimraf - will refuse to recursively delete root");
  }
  if (mode === RimRafMode.UNLINK) {
    return rimrafUnlink(path3);
  }
  return rimrafMove(path3, moveToPath);
}
async function rimrafMove(path3, moveToPath = $8g(tmpdir())) {
  try {
    try {
      await fs.promises.rename(path3, moveToPath);
    } catch (error) {
      if (error.code === "ENOENT") {
        return;
      }
      return rimrafUnlink(path3);
    }
    rimrafUnlink(moveToPath).catch((error) => {
    });
  } catch (error) {
    if (error.code !== "ENOENT") {
      throw error;
    }
  }
}
async function rimrafUnlink(path3) {
  return fs.promises.rm(path3, { recursive: true, force: true, maxRetries: 3 });
}
async function readdir(path3, options) {
  return handleDirectoryChildren(await (options ? safeReaddirWithFileTypes(path3) : fs.promises.readdir(path3)));
}
async function safeReaddirWithFileTypes(path3) {
  try {
    return await fs.promises.readdir(path3, { withFileTypes: true });
  } catch (error) {
    console.warn("[node.js fs] readdir with filetypes failed with error: ", error);
  }
  const result = [];
  const children = await readdir(path3);
  for (const child of children) {
    let isFile = false;
    let isDirectory = false;
    let isSymbolicLink = false;
    try {
      const lstat = await fs.promises.lstat($vc(path3, child));
      isFile = lstat.isFile();
      isDirectory = lstat.isDirectory();
      isSymbolicLink = lstat.isSymbolicLink();
    } catch (error) {
      console.warn("[node.js fs] unexpected error from lstat after readdir: ", error);
    }
    result.push({
      name: child,
      isFile: () => isFile,
      isDirectory: () => isDirectory,
      isSymbolicLink: () => isSymbolicLink
    });
  }
  return result;
}
function handleDirectoryChildren(children) {
  return children.map((child) => {
    if (typeof child === "string") {
      return $m ? $Hm(child) : child;
    }
    child.name = $m ? $Hm(child.name) : child.name;
    return child;
  });
}
async function readDirsInDir(dirPath) {
  const children = await readdir(dirPath);
  const directories = [];
  for (const child of children) {
    if (await SymlinkSupport.existsDirectory($vc(dirPath, child))) {
      directories.push(child);
    }
  }
  return directories;
}
function whenDeleted(path3, intervalMs = 1e3) {
  return new Promise((resolve2) => {
    let running = false;
    const interval = setInterval(() => {
      if (!running) {
        running = true;
        fs.access(path3, (err) => {
          running = false;
          if (err) {
            clearInterval(interval);
            resolve2(void 0);
          }
        });
      }
    }, intervalMs);
  });
}
var SymlinkSupport;
(function(SymlinkSupport2) {
  async function stat(path3) {
    let lstats;
    try {
      lstats = await fs.promises.lstat(path3);
      if (!lstats.isSymbolicLink()) {
        return { stat: lstats };
      }
    } catch (error) {
    }
    try {
      const stats = await fs.promises.stat(path3);
      return { stat: stats, symbolicLink: lstats?.isSymbolicLink() ? { dangling: false } : void 0 };
    } catch (error) {
      if (error.code === "ENOENT" && lstats) {
        return { stat: lstats, symbolicLink: { dangling: true } };
      }
      if ($l && error.code === "EACCES") {
        try {
          const stats = await fs.promises.stat(await fs.promises.readlink(path3));
          return { stat: stats, symbolicLink: { dangling: false } };
        } catch (error2) {
          if (error2.code === "ENOENT" && lstats) {
            return { stat: lstats, symbolicLink: { dangling: true } };
          }
          throw error2;
        }
      }
      throw error;
    }
  }
  SymlinkSupport2.stat = stat;
  async function existsFile(path3) {
    try {
      const { stat: stat2, symbolicLink } = await SymlinkSupport2.stat(path3);
      return stat2.isFile() && symbolicLink?.dangling !== true;
    } catch (error) {
    }
    return false;
  }
  SymlinkSupport2.existsFile = existsFile;
  async function existsDirectory(path3) {
    try {
      const { stat: stat2, symbolicLink } = await SymlinkSupport2.stat(path3);
      return stat2.isDirectory() && symbolicLink?.dangling !== true;
    } catch (error) {
    }
    return false;
  }
  SymlinkSupport2.existsDirectory = existsDirectory;
})(SymlinkSupport || (SymlinkSupport = {}));
var writeQueues = new $9h();
function writeFile2(path3, data, options) {
  return writeQueues.queueFor(URI.file(path3), () => {
    const ensuredOptions = ensureWriteOptions(options);
    return new Promise((resolve2, reject) => doWriteFileAndFlush(path3, data, ensuredOptions, (error) => error ? reject(error) : resolve2()));
  }, $rh);
}
var canFlush = true;
function configureFlushOnWrite(enabled) {
  canFlush = enabled;
}
function doWriteFileAndFlush(path3, data, options, callback) {
  if (!canFlush) {
    return fs.writeFile(path3, data, { mode: options.mode, flag: options.flag }, callback);
  }
  fs.open(path3, options.flag, options.mode, (openError, fd) => {
    if (openError) {
      return callback(openError);
    }
    fs.writeFile(fd, data, (writeError) => {
      if (writeError) {
        return fs.close(fd, () => callback(writeError));
      }
      fs.fdatasync(fd, (syncError) => {
        if (syncError) {
          console.warn("[node.js fs] fdatasync is now disabled for this session because it failed: ", syncError);
          configureFlushOnWrite(false);
        }
        return fs.close(fd, (closeError) => callback(closeError));
      });
    });
  });
}
function ensureWriteOptions(options) {
  if (!options) {
    return { mode: 438, flag: "w" };
  }
  return {
    mode: typeof options.mode === "number" ? options.mode : 438,
    flag: typeof options.flag === "string" ? options.flag : "w"
  };
}
async function rename(source, target, windowsRetryTimeout = 6e4) {
  if (source === target) {
    return;
  }
  try {
    if ($l && typeof windowsRetryTimeout === "number") {
      await renameWithRetry(source, target, Date.now(), windowsRetryTimeout);
    } else {
      await fs.promises.rename(source, target);
    }
  } catch (error) {
    if (source.toLowerCase() !== target.toLowerCase() && error.code === "EXDEV" || source.endsWith(".")) {
      await copy(source, target, {
        preserveSymlinks: false
        /* copying to another device */
      });
      await rimraf(source, RimRafMode.MOVE);
    } else {
      throw error;
    }
  }
}
async function renameWithRetry(source, target, startTime, retryTimeout, attempt = 0) {
  try {
    return await fs.promises.rename(source, target);
  } catch (error) {
    if (error.code !== "EACCES" && error.code !== "EPERM" && error.code !== "EBUSY") {
      throw error;
    }
    if (Date.now() - startTime >= retryTimeout) {
      console.error(`[node.js fs] rename failed after ${attempt} retries with error: ${error}`);
      throw error;
    }
    if (attempt === 0) {
      let abortRetry = false;
      try {
        const { stat } = await SymlinkSupport.stat(target);
        if (!stat.isFile()) {
          abortRetry = true;
        }
      } catch (error2) {
      }
      if (abortRetry) {
        throw error;
      }
    }
    await $1h(Math.min(100, attempt * 10));
    return renameWithRetry(source, target, startTime, retryTimeout, attempt + 1);
  }
}
async function copy(source, target, options) {
  return doCopy(source, target, { root: { source, target }, options, handledSourcePaths: /* @__PURE__ */ new Set() });
}
var COPY_MODE_MASK = 511;
async function doCopy(source, target, payload) {
  if (payload.handledSourcePaths.has(source)) {
    return;
  } else {
    payload.handledSourcePaths.add(source);
  }
  const { stat, symbolicLink } = await SymlinkSupport.stat(source);
  if (symbolicLink) {
    if (payload.options.preserveSymlinks) {
      try {
        return await doCopySymlink(source, target, payload);
      } catch (error) {
      }
    }
    if (symbolicLink.dangling) {
      return;
    }
  }
  if (stat.isDirectory()) {
    return doCopyDirectory(source, target, stat.mode & COPY_MODE_MASK, payload);
  } else {
    return doCopyFile(source, target, stat.mode & COPY_MODE_MASK);
  }
}
async function doCopyDirectory(source, target, mode, payload) {
  await fs.promises.mkdir(target, { recursive: true, mode });
  const files = await readdir(source);
  for (const file of files) {
    await doCopy($vc(source, file), $vc(target, file), payload);
  }
}
async function doCopyFile(source, target, mode) {
  await fs.promises.copyFile(source, target);
  await fs.promises.chmod(target, mode);
}
async function doCopySymlink(source, target, payload) {
  let linkTarget = await fs.promises.readlink(source);
  if ($Yg(linkTarget, payload.root.source, !$n)) {
    linkTarget = $vc(payload.root.target, linkTarget.substr(payload.root.source.length + 1));
  }
  await fs.promises.symlink(linkTarget, target);
}
var Promises2 = new class {
  //#region Implemented by node.js
  get read() {
    return (fd, buffer, offset, length, position) => {
      return new Promise((resolve2, reject) => {
        fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer2) => {
          if (err) {
            return reject(err);
          }
          return resolve2({ bytesRead, buffer: buffer2 });
        });
      });
    };
  }
  get write() {
    return (fd, buffer, offset, length, position) => {
      return new Promise((resolve2, reject) => {
        fs.write(fd, buffer, offset, length, position, (err, bytesWritten, buffer2) => {
          if (err) {
            return reject(err);
          }
          return resolve2({ bytesWritten, buffer: buffer2 });
        });
      });
    };
  }
  get fdatasync() {
    return promisify(fs.fdatasync);
  }
  // not exposed as API in 20.x yet
  get open() {
    return promisify(fs.open);
  }
  // changed to return `FileHandle` in promise API
  get close() {
    return promisify(fs.close);
  }
  // not exposed as API due to the `FileHandle` return type of `open`
  get realpath() {
    return promisify(fs.realpath);
  }
  // `fs.promises.realpath` will use `fs.realpath.native` which we do not want
  //#endregion
  //#region Implemented by us
  async exists(path3) {
    try {
      await fs.promises.access(path3);
      return true;
    } catch {
      return false;
    }
  }
  get readdir() {
    return readdir;
  }
  get readDirsInDir() {
    return readDirsInDir;
  }
  get writeFile() {
    return writeFile2;
  }
  get rm() {
    return rimraf;
  }
  get rename() {
    return rename;
  }
  get copy() {
    return copy;
  }
}();

// out-build/vs/base/common/stream.js
function $Se(obj) {
  const candidate = obj;
  if (!candidate) {
    return false;
  }
  return [candidate.on, candidate.pause, candidate.resume, candidate.destroy].every((fn) => typeof fn === "function");
}
function $Te(obj) {
  const candidate = obj;
  if (!candidate) {
    return false;
  }
  return $Se(candidate.stream) && Array.isArray(candidate.buffer) && typeof candidate.ended === "boolean";
}
function $Ue(reducer, options) {
  return new WriteableStreamImpl(reducer, options);
}
var WriteableStreamImpl = class {
  constructor(e, f) {
    this.e = e;
    this.f = f;
    this.a = {
      flowing: false,
      ended: false,
      destroyed: false
    };
    this.b = {
      data: [],
      error: []
    };
    this.c = {
      data: [],
      error: [],
      end: []
    };
    this.d = [];
  }
  pause() {
    if (this.a.destroyed) {
      return;
    }
    this.a.flowing = false;
  }
  resume() {
    if (this.a.destroyed) {
      return;
    }
    if (!this.a.flowing) {
      this.a.flowing = true;
      this.j();
      this.k();
      this.l();
    }
  }
  write(data) {
    if (this.a.destroyed) {
      return;
    }
    if (this.a.flowing) {
      this.g(data);
    } else {
      this.b.data.push(data);
      if (typeof this.f?.highWaterMark === "number" && this.b.data.length > this.f.highWaterMark) {
        return new Promise((resolve2) => this.d.push(resolve2));
      }
    }
  }
  error(error) {
    if (this.a.destroyed) {
      return;
    }
    if (this.a.flowing) {
      this.h(error);
    } else {
      this.b.error.push(error);
    }
  }
  end(result) {
    if (this.a.destroyed) {
      return;
    }
    if (typeof result !== "undefined") {
      this.write(result);
    }
    if (this.a.flowing) {
      this.i();
      this.destroy();
    } else {
      this.a.ended = true;
    }
  }
  g(data) {
    this.c.data.slice(0).forEach((listener) => listener(data));
  }
  h(error) {
    if (this.c.error.length === 0) {
      $ab(error);
    } else {
      this.c.error.slice(0).forEach((listener) => listener(error));
    }
  }
  i() {
    this.c.end.slice(0).forEach((listener) => listener());
  }
  on(event, callback) {
    if (this.a.destroyed) {
      return;
    }
    switch (event) {
      case "data":
        this.c.data.push(callback);
        this.resume();
        break;
      case "end":
        this.c.end.push(callback);
        if (this.a.flowing && this.l()) {
          this.destroy();
        }
        break;
      case "error":
        this.c.error.push(callback);
        if (this.a.flowing) {
          this.k();
        }
        break;
    }
  }
  removeListener(event, callback) {
    if (this.a.destroyed) {
      return;
    }
    let listeners = void 0;
    switch (event) {
      case "data":
        listeners = this.c.data;
        break;
      case "end":
        listeners = this.c.end;
        break;
      case "error":
        listeners = this.c.error;
        break;
    }
    if (listeners) {
      const index = listeners.indexOf(callback);
      if (index >= 0) {
        listeners.splice(index, 1);
      }
    }
  }
  j() {
    if (this.b.data.length > 0) {
      const fullDataBuffer = this.e(this.b.data);
      this.g(fullDataBuffer);
      this.b.data.length = 0;
      const pendingWritePromises = [...this.d];
      this.d.length = 0;
      pendingWritePromises.forEach((pendingWritePromise) => pendingWritePromise());
    }
  }
  k() {
    if (this.c.error.length > 0) {
      for (const error of this.b.error) {
        this.h(error);
      }
      this.b.error.length = 0;
    }
  }
  l() {
    if (this.a.ended) {
      this.i();
      return this.c.end.length > 0;
    }
    return false;
  }
  destroy() {
    if (!this.a.destroyed) {
      this.a.destroyed = true;
      this.a.ended = true;
      this.b.data.length = 0;
      this.b.error.length = 0;
      this.c.data.length = 0;
      this.c.error.length = 0;
      this.c.end.length = 0;
      this.d.length = 0;
    }
  }
};
function $Ve(readable, reducer) {
  const chunks = [];
  let chunk;
  while ((chunk = readable.read()) !== null) {
    chunks.push(chunk);
  }
  return reducer(chunks);
}
function $We(readable, reducer, maxChunks) {
  const chunks = [];
  let chunk = void 0;
  while ((chunk = readable.read()) !== null && chunks.length < maxChunks) {
    chunks.push(chunk);
  }
  if (chunk === null && chunks.length > 0) {
    return reducer(chunks);
  }
  return {
    read: () => {
      if (chunks.length > 0) {
        return chunks.shift();
      }
      if (typeof chunk !== "undefined") {
        const lastReadChunk = chunk;
        chunk = void 0;
        return lastReadChunk;
      }
      return readable.read();
    }
  };
}
function $Xe(stream, reducer) {
  return new Promise((resolve2, reject) => {
    const chunks = [];
    $Ye(stream, {
      onData: (chunk) => {
        if (reducer) {
          chunks.push(chunk);
        }
      },
      onError: (error) => {
        if (reducer) {
          reject(error);
        } else {
          resolve2(void 0);
        }
      },
      onEnd: () => {
        if (reducer) {
          resolve2(reducer(chunks));
        } else {
          resolve2(void 0);
        }
      }
    });
  });
}
function $Ye(stream, listener, token) {
  stream.on("error", (error) => {
    if (!token?.isCancellationRequested) {
      listener.onError(error);
    }
  });
  stream.on("end", () => {
    if (!token?.isCancellationRequested) {
      listener.onEnd();
    }
  });
  stream.on("data", (data) => {
    if (!token?.isCancellationRequested) {
      listener.onData(data);
    }
  });
}
function $Ze(stream, maxChunks) {
  return new Promise((resolve2, reject) => {
    const streamListeners = new $9c();
    const buffer = [];
    const dataListener = (chunk) => {
      buffer.push(chunk);
      if (buffer.length > maxChunks) {
        streamListeners.dispose();
        stream.pause();
        return resolve2({ stream, buffer, ended: false });
      }
    };
    const errorListener = (error) => {
      streamListeners.dispose();
      return reject(error);
    };
    const endListener = () => {
      streamListeners.dispose();
      return resolve2({ stream, buffer, ended: true });
    };
    streamListeners.add($8c(() => stream.removeListener("error", errorListener)));
    stream.on("error", errorListener);
    streamListeners.add($8c(() => stream.removeListener("end", endListener)));
    stream.on("end", endListener);
    streamListeners.add($8c(() => stream.removeListener("data", dataListener)));
    stream.on("data", dataListener);
  });
}
function $3e(t) {
  let consumed = false;
  return {
    read: () => {
      if (consumed) {
        return null;
      }
      consumed = true;
      return t;
    }
  };
}
function $4e(stream, transformer, reducer) {
  const target = $Ue(reducer);
  $Ye(stream, {
    onData: (data) => target.write(transformer.data(data)),
    onError: (error) => target.error(transformer.error ? transformer.error(error) : error),
    onEnd: () => target.end()
  });
  return target;
}

// out-build/vs/base/common/buffer.js
var hasBuffer = typeof Buffer !== "undefined";
var indexOfTable = new $7(() => new Uint8Array(256));
var textEncoder;
var textDecoder;
var $7e = class _$7e {
  /**
   * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
   * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
   */
  static alloc(byteLength) {
    if (hasBuffer) {
      return new _$7e(Buffer.allocUnsafe(byteLength));
    } else {
      return new _$7e(new Uint8Array(byteLength));
    }
  }
  /**
   * When running in a nodejs context, if `actual` is not a nodejs Buffer, the backing store for
   * the returned `VSBuffer` instance might use a nodejs Buffer allocated from node's Buffer pool,
   * which is not transferrable.
   */
  static wrap(actual) {
    if (hasBuffer && !Buffer.isBuffer(actual)) {
      actual = Buffer.from(actual.buffer, actual.byteOffset, actual.byteLength);
    }
    return new _$7e(actual);
  }
  /**
   * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
   * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
   */
  static fromString(source, options) {
    const dontUseNodeBuffer = options?.dontUseNodeBuffer || false;
    if (!dontUseNodeBuffer && hasBuffer) {
      return new _$7e(Buffer.from(source));
    } else {
      if (!textEncoder) {
        textEncoder = new TextEncoder();
      }
      return new _$7e(textEncoder.encode(source));
    }
  }
  /**
   * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
   * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
   */
  static fromByteArray(source) {
    const result = _$7e.alloc(source.length);
    for (let i = 0, len = source.length; i < len; i++) {
      result.buffer[i] = source[i];
    }
    return result;
  }
  /**
   * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
   * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
   */
  static concat(buffers, totalLength) {
    if (typeof totalLength === "undefined") {
      totalLength = 0;
      for (let i = 0, len = buffers.length; i < len; i++) {
        totalLength += buffers[i].byteLength;
      }
    }
    const ret = _$7e.alloc(totalLength);
    let offset = 0;
    for (let i = 0, len = buffers.length; i < len; i++) {
      const element = buffers[i];
      ret.set(element, offset);
      offset += element.byteLength;
    }
    return ret;
  }
  constructor(buffer) {
    this.buffer = buffer;
    this.byteLength = this.buffer.byteLength;
  }
  /**
   * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
   * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
   */
  clone() {
    const result = _$7e.alloc(this.byteLength);
    result.set(this);
    return result;
  }
  toString() {
    if (hasBuffer) {
      return this.buffer.toString();
    } else {
      if (!textDecoder) {
        textDecoder = new TextDecoder();
      }
      return textDecoder.decode(this.buffer);
    }
  }
  slice(start, end) {
    return new _$7e(this.buffer.subarray(start, end));
  }
  set(array, offset) {
    if (array instanceof _$7e) {
      this.buffer.set(array.buffer, offset);
    } else if (array instanceof Uint8Array) {
      this.buffer.set(array, offset);
    } else if (array instanceof ArrayBuffer) {
      this.buffer.set(new Uint8Array(array), offset);
    } else if (ArrayBuffer.isView(array)) {
      this.buffer.set(new Uint8Array(array.buffer, array.byteOffset, array.byteLength), offset);
    } else {
      throw new Error(`Unknown argument 'array'`);
    }
  }
  readUInt32BE(offset) {
    return $$e(this.buffer, offset);
  }
  writeUInt32BE(value, offset) {
    $_e(this.buffer, value, offset);
  }
  readUInt32LE(offset) {
    return $af(this.buffer, offset);
  }
  writeUInt32LE(value, offset) {
    $bf(this.buffer, value, offset);
  }
  readUInt8(offset) {
    return $cf(this.buffer, offset);
  }
  writeUInt8(value, offset) {
    $df(this.buffer, value, offset);
  }
  indexOf(subarray, offset = 0) {
    return $8e(this.buffer, subarray instanceof _$7e ? subarray.buffer : subarray, offset);
  }
};
function $8e(haystack, needle, offset = 0) {
  const needleLen = needle.byteLength;
  const haystackLen = haystack.byteLength;
  if (needleLen === 0) {
    return 0;
  }
  if (needleLen === 1) {
    return haystack.indexOf(needle[0]);
  }
  if (needleLen > haystackLen - offset) {
    return -1;
  }
  const table = indexOfTable.value;
  table.fill(needle.length);
  for (let i2 = 0; i2 < needle.length; i2++) {
    table[needle[i2]] = needle.length - i2 - 1;
  }
  let i = offset + needle.length - 1;
  let j = i;
  let result = -1;
  while (i < haystackLen) {
    if (haystack[i] === needle[j]) {
      if (j === 0) {
        result = i;
        break;
      }
      i--;
      j--;
    } else {
      i += Math.max(needle.length - j, table[haystack[i]]);
      j = needle.length - 1;
    }
  }
  return result;
}
function $$e(source, offset) {
  return source[offset] * 2 ** 24 + source[offset + 1] * 2 ** 16 + source[offset + 2] * 2 ** 8 + source[offset + 3];
}
function $_e(destination, value, offset) {
  destination[offset + 3] = value;
  value = value >>> 8;
  destination[offset + 2] = value;
  value = value >>> 8;
  destination[offset + 1] = value;
  value = value >>> 8;
  destination[offset] = value;
}
function $af(source, offset) {
  return source[offset + 0] << 0 >>> 0 | source[offset + 1] << 8 >>> 0 | source[offset + 2] << 16 >>> 0 | source[offset + 3] << 24 >>> 0;
}
function $bf(destination, value, offset) {
  destination[offset + 0] = value & 255;
  value = value >>> 8;
  destination[offset + 1] = value & 255;
  value = value >>> 8;
  destination[offset + 2] = value & 255;
  value = value >>> 8;
  destination[offset + 3] = value & 255;
}
function $cf(source, offset) {
  return source[offset];
}
function $df(destination, value, offset) {
  destination[offset] = value;
}
function $ef(readable) {
  return $Ve(readable, (chunks) => $7e.concat(chunks));
}
function $ff(buffer) {
  return $3e(buffer);
}
function $gf(stream) {
  return $Xe(stream, (chunks) => $7e.concat(chunks));
}
async function $hf(bufferedStream) {
  if (bufferedStream.ended) {
    return $7e.concat(bufferedStream.buffer);
  }
  return $7e.concat([
    // Include already read chunks...
    ...bufferedStream.buffer,
    // ...and all additional chunks
    await $gf(bufferedStream.stream)
  ]);
}
function $jf(stream) {
  return $4e(stream, { data: (data) => typeof data === "string" ? $7e.fromString(data) : $7e.wrap(data) }, (chunks) => $7e.concat(chunks));
}
function $kf(options) {
  return $Ue((chunks) => $7e.concat(chunks), options);
}

// out-build/vs/base/common/decorators.js
function $ri(_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];
  };
}

// out-build/vs/base/common/marshalling.js
function $ui(obj) {
  return JSON.stringify(obj, replacer);
}
function $vi(text) {
  let data = JSON.parse(text);
  data = $wi(data);
  return data;
}
function replacer(key, value) {
  if (value instanceof RegExp) {
    return {
      $mid: 2,
      source: value.source,
      flags: value.flags
    };
  }
  return value;
}
function $wi(obj, depth = 0) {
  if (!obj || depth > 200) {
    return obj;
  }
  if (typeof obj === "object") {
    switch (obj.$mid) {
      case 1:
        return URI.revive(obj);
      case 2:
        return new RegExp(obj.source, obj.flags);
      case 17:
        return new Date(obj.source);
    }
    if (obj instanceof $7e || obj instanceof Uint8Array) {
      return obj;
    }
    if (Array.isArray(obj)) {
      for (let i = 0; i < obj.length; ++i) {
        obj[i] = $wi(obj[i], depth + 1);
      }
    } else {
      for (const key in obj) {
        if (Object.hasOwnProperty.call(obj, key)) {
          obj[key] = $wi(obj[key], depth + 1);
        }
      }
    }
  }
  return obj;
}

// out-build/vs/base/parts/ipc/common/ipc.js
var RequestType;
(function(RequestType2) {
  RequestType2[RequestType2["Promise"] = 100] = "Promise";
  RequestType2[RequestType2["PromiseCancel"] = 101] = "PromiseCancel";
  RequestType2[RequestType2["EventListen"] = 102] = "EventListen";
  RequestType2[RequestType2["EventDispose"] = 103] = "EventDispose";
})(RequestType || (RequestType = {}));
function requestTypeToStr(type4) {
  switch (type4) {
    case 100:
      return "req";
    case 101:
      return "cancel";
    case 102:
      return "subscribe";
    case 103:
      return "unsubscribe";
  }
}
var ResponseType;
(function(ResponseType2) {
  ResponseType2[ResponseType2["Initialize"] = 200] = "Initialize";
  ResponseType2[ResponseType2["PromiseSuccess"] = 201] = "PromiseSuccess";
  ResponseType2[ResponseType2["PromiseError"] = 202] = "PromiseError";
  ResponseType2[ResponseType2["PromiseErrorObj"] = 203] = "PromiseErrorObj";
  ResponseType2[ResponseType2["EventFire"] = 204] = "EventFire";
})(ResponseType || (ResponseType = {}));
function responseTypeToStr(type4) {
  switch (type4) {
    case 200:
      return `init`;
    case 201:
      return `reply:`;
    case 202:
    case 203:
      return `replyErr:`;
    case 204:
      return `event:`;
  }
}
var State;
(function(State2) {
  State2[State2["Uninitialized"] = 0] = "Uninitialized";
  State2[State2["Idle"] = 1] = "Idle";
})(State || (State = {}));
function readIntVQL(reader) {
  let value = 0;
  for (let n = 0; ; n += 7) {
    const next = reader.read(1);
    value |= (next.buffer[0] & 127) << n;
    if (!(next.buffer[0] & 128)) {
      return value;
    }
  }
}
var vqlZero = createOneByteBuffer(0);
function writeInt32VQL(writer, value) {
  if (value === 0) {
    writer.write(vqlZero);
    return;
  }
  let len = 0;
  for (let v2 = value; v2 !== 0; v2 = v2 >>> 7) {
    len++;
  }
  const scratch = $7e.alloc(len);
  for (let i = 0; value !== 0; i++) {
    scratch.buffer[i] = value & 127;
    value = value >>> 7;
    if (value > 0) {
      scratch.buffer[i] |= 128;
    }
  }
  writer.write(scratch);
}
var $xi = class {
  constructor(b) {
    this.b = b;
    this.a = 0;
  }
  read(bytes) {
    const result = this.b.slice(this.a, this.a + bytes);
    this.a += result.byteLength;
    return result;
  }
};
var $yi = class {
  constructor() {
    this.a = [];
  }
  get buffer() {
    return $7e.concat(this.a);
  }
  write(buffer) {
    this.a.push(buffer);
  }
};
var DataType;
(function(DataType2) {
  DataType2[DataType2["Undefined"] = 0] = "Undefined";
  DataType2[DataType2["String"] = 1] = "String";
  DataType2[DataType2["Buffer"] = 2] = "Buffer";
  DataType2[DataType2["VSBuffer"] = 3] = "VSBuffer";
  DataType2[DataType2["Array"] = 4] = "Array";
  DataType2[DataType2["Object"] = 5] = "Object";
  DataType2[DataType2["Int"] = 6] = "Int";
})(DataType || (DataType = {}));
function createOneByteBuffer(value) {
  const result = $7e.alloc(1);
  result.writeUInt8(value, 0);
  return result;
}
var BufferPresets = {
  Undefined: createOneByteBuffer(DataType.Undefined),
  String: createOneByteBuffer(DataType.String),
  Buffer: createOneByteBuffer(DataType.Buffer),
  VSBuffer: createOneByteBuffer(DataType.VSBuffer),
  Array: createOneByteBuffer(DataType.Array),
  Object: createOneByteBuffer(DataType.Object),
  Uint: createOneByteBuffer(DataType.Int)
};
var hasBuffer2 = typeof Buffer !== "undefined";
function $zi(writer, data) {
  if (typeof data === "undefined") {
    writer.write(BufferPresets.Undefined);
  } else if (typeof data === "string") {
    const buffer = $7e.fromString(data);
    writer.write(BufferPresets.String);
    writeInt32VQL(writer, buffer.byteLength);
    writer.write(buffer);
  } else if (hasBuffer2 && Buffer.isBuffer(data)) {
    const buffer = $7e.wrap(data);
    writer.write(BufferPresets.Buffer);
    writeInt32VQL(writer, buffer.byteLength);
    writer.write(buffer);
  } else if (data instanceof $7e) {
    writer.write(BufferPresets.VSBuffer);
    writeInt32VQL(writer, data.byteLength);
    writer.write(data);
  } else if (Array.isArray(data)) {
    writer.write(BufferPresets.Array);
    writeInt32VQL(writer, data.length);
    for (const el of data) {
      $zi(writer, el);
    }
  } else if (typeof data === "number" && (data | 0) === data) {
    writer.write(BufferPresets.Uint);
    writeInt32VQL(writer, data);
  } else {
    const buffer = $7e.fromString(JSON.stringify(data));
    writer.write(BufferPresets.Object);
    writeInt32VQL(writer, buffer.byteLength);
    writer.write(buffer);
  }
}
function $Ai(reader) {
  const type4 = reader.read(1).readUInt8(0);
  switch (type4) {
    case DataType.Undefined:
      return void 0;
    case DataType.String:
      return reader.read(readIntVQL(reader)).toString();
    case DataType.Buffer:
      return reader.read(readIntVQL(reader)).buffer;
    case DataType.VSBuffer:
      return reader.read(readIntVQL(reader));
    case DataType.Array: {
      const length = readIntVQL(reader);
      const result = [];
      for (let i = 0; i < length; i++) {
        result.push($Ai(reader));
      }
      return result;
    }
    case DataType.Object:
      return JSON.parse(reader.read(readIntVQL(reader)).toString());
    case DataType.Int:
      return readIntVQL(reader);
  }
}
var $Bi = class {
  constructor(h, j, k = null, l = 1e3) {
    this.h = h;
    this.j = j;
    this.k = k;
    this.l = l;
    this.b = /* @__PURE__ */ new Map();
    this.d = /* @__PURE__ */ new Map();
    this.g = /* @__PURE__ */ new Map();
    this.f = this.h.onMessage((msg) => this.q(msg));
    this.m({
      type: 200
      /* ResponseType.Initialize */
    });
  }
  registerChannel(channelName, channel) {
    this.b.set(channelName, channel);
    setTimeout(() => this.w(channelName), 0);
  }
  m(response) {
    switch (response.type) {
      case 200: {
        const msgLength = this.o([response.type]);
        this.k?.logOutgoing(msgLength, 0, 1, responseTypeToStr(response.type));
        return;
      }
      case 201:
      case 202:
      case 204:
      case 203: {
        const msgLength = this.o([response.type, response.id], response.data);
        this.k?.logOutgoing(msgLength, response.id, 1, responseTypeToStr(response.type), response.data);
        return;
      }
    }
  }
  o(header, body = void 0) {
    const writer = new $yi();
    $zi(writer, header);
    $zi(writer, body);
    return this.p(writer.buffer);
  }
  p(message) {
    try {
      this.h.send(message);
      return message.byteLength;
    } catch (err) {
      return 0;
    }
  }
  q(message) {
    const reader = new $xi(message);
    const header = $Ai(reader);
    const body = $Ai(reader);
    const type4 = header[0];
    switch (type4) {
      case 100:
        this.k?.logIncoming(message.byteLength, header[1], 1, `${requestTypeToStr(type4)}: ${header[2]}.${header[3]}`, body);
        return this.s({ type: type4, id: header[1], channelName: header[2], name: header[3], arg: body });
      case 102:
        this.k?.logIncoming(message.byteLength, header[1], 1, `${requestTypeToStr(type4)}: ${header[2]}.${header[3]}`, body);
        return this.t({ type: type4, id: header[1], channelName: header[2], name: header[3], arg: body });
      case 101:
        this.k?.logIncoming(message.byteLength, header[1], 1, `${requestTypeToStr(type4)}`);
        return this.u({ type: type4, id: header[1] });
      case 103:
        this.k?.logIncoming(message.byteLength, header[1], 1, `${requestTypeToStr(type4)}`);
        return this.u({ type: type4, id: header[1] });
    }
  }
  s(request) {
    const channel = this.b.get(request.channelName);
    if (!channel) {
      this.v(request);
      return;
    }
    const cancellationTokenSource = new $Pe();
    let promise;
    try {
      promise = channel.call(this.j, request.name, request.arg, cancellationTokenSource.token);
    } catch (err) {
      promise = Promise.reject(err);
    }
    const id2 = request.id;
    promise.then((data) => {
      this.m({
        id: id2,
        data,
        type: 201
        /* ResponseType.PromiseSuccess */
      });
    }, (err) => {
      if (err instanceof Error) {
        this.m({
          id: id2,
          data: {
            message: err.message,
            name: err.name,
            stack: err.stack ? err.stack.split("\n") : void 0
          },
          type: 202
          /* ResponseType.PromiseError */
        });
      } else {
        this.m({
          id: id2,
          data: err,
          type: 203
          /* ResponseType.PromiseErrorObj */
        });
      }
    }).finally(() => {
      disposable.dispose();
      this.d.delete(request.id);
    });
    const disposable = $8c(() => cancellationTokenSource.cancel());
    this.d.set(request.id, disposable);
  }
  t(request) {
    const channel = this.b.get(request.channelName);
    if (!channel) {
      this.v(request);
      return;
    }
    const id2 = request.id;
    const event = channel.listen(this.j, request.name, request.arg);
    const disposable = event((data) => this.m({
      id: id2,
      data,
      type: 204
      /* ResponseType.EventFire */
    }));
    this.d.set(request.id, disposable);
  }
  u(request) {
    const disposable = this.d.get(request.id);
    if (disposable) {
      disposable.dispose();
      this.d.delete(request.id);
    }
  }
  v(request) {
    let pendingRequests = this.g.get(request.channelName);
    if (!pendingRequests) {
      pendingRequests = [];
      this.g.set(request.channelName, pendingRequests);
    }
    const timer = setTimeout(() => {
      console.error(`Unknown channel: ${request.channelName}`);
      if (request.type === 100) {
        this.m({
          id: request.id,
          data: { name: "Unknown channel", message: `Channel name '${request.channelName}' timed out after ${this.l}ms`, stack: void 0 },
          type: 202
          /* ResponseType.PromiseError */
        });
      }
    }, this.l);
    pendingRequests.push({ request, timeoutTimer: timer });
  }
  w(channelName) {
    const requests = this.g.get(channelName);
    if (requests) {
      for (const request of requests) {
        clearTimeout(request.timeoutTimer);
        switch (request.request.type) {
          case 100:
            this.s(request.request);
            break;
          case 102:
            this.t(request.request);
            break;
        }
      }
      this.g.delete(channelName);
    }
  }
  dispose() {
    if (this.f) {
      this.f.dispose();
      this.f = null;
    }
    $5c(this.d.values());
    this.d.clear();
  }
};
var RequestInitiator;
(function(RequestInitiator2) {
  RequestInitiator2[RequestInitiator2["LocalSide"] = 0] = "LocalSide";
  RequestInitiator2[RequestInitiator2["OtherSide"] = 1] = "OtherSide";
})(RequestInitiator || (RequestInitiator = {}));
var $Ci = class {
  constructor(l, logger = null) {
    this.l = l;
    this.a = false;
    this.b = State.Uninitialized;
    this.d = /* @__PURE__ */ new Set();
    this.f = /* @__PURE__ */ new Map();
    this.g = 0;
    this.k = new $De();
    this.onDidInitialize = this.k.event;
    this.h = this.l.onMessage((msg) => this.s(msg));
    this.j = logger;
  }
  getChannel(channelName) {
    const that = this;
    return {
      call(command, arg, cancellationToken) {
        if (that.a) {
          return Promise.reject(new $fb());
        }
        return that.m(channelName, command, arg, cancellationToken);
      },
      listen(event, arg) {
        if (that.a) {
          return Event.None;
        }
        return that.o(channelName, event, arg);
      }
    };
  }
  m(channelName, name, arg, cancellationToken = CancellationToken.None) {
    const id2 = this.g++;
    const type4 = 100;
    const request = { id: id2, type: type4, channelName, name, arg };
    if (cancellationToken.isCancellationRequested) {
      return Promise.reject(new $fb());
    }
    let disposable;
    const result = new Promise((c, e) => {
      if (cancellationToken.isCancellationRequested) {
        return e(new $fb());
      }
      const doRequest = () => {
        const handler = (response) => {
          switch (response.type) {
            case 201:
              this.f.delete(id2);
              c(response.data);
              break;
            case 202: {
              this.f.delete(id2);
              const error = new Error(response.data.message);
              error.stack = Array.isArray(response.data.stack) ? response.data.stack.join("\n") : response.data.stack;
              error.name = response.data.name;
              e(error);
              break;
            }
            case 203:
              this.f.delete(id2);
              e(response.data);
              break;
          }
        };
        this.f.set(id2, handler);
        this.p(request);
      };
      let uninitializedPromise = null;
      if (this.b === State.Idle) {
        doRequest();
      } else {
        uninitializedPromise = $Mh((_) => this.u());
        uninitializedPromise.then(() => {
          uninitializedPromise = null;
          doRequest();
        });
      }
      const cancel = () => {
        if (uninitializedPromise) {
          uninitializedPromise.cancel();
          uninitializedPromise = null;
        } else {
          this.p({
            id: id2,
            type: 101
            /* RequestType.PromiseCancel */
          });
        }
        e(new $fb());
      };
      const cancellationTokenListener = cancellationToken.onCancellationRequested(cancel);
      disposable = $7c($8c(cancel), cancellationTokenListener);
      this.d.add(disposable);
    });
    return result.finally(() => {
      disposable.dispose();
      this.d.delete(disposable);
    });
  }
  o(channelName, name, arg) {
    const id2 = this.g++;
    const type4 = 102;
    const request = { id: id2, type: type4, channelName, name, arg };
    let uninitializedPromise = null;
    const emitter = new $De({
      onWillAddFirstListener: () => {
        uninitializedPromise = $Mh((_) => this.u());
        uninitializedPromise.then(() => {
          uninitializedPromise = null;
          this.d.add(emitter);
          this.p(request);
        });
      },
      onDidRemoveLastListener: () => {
        if (uninitializedPromise) {
          uninitializedPromise.cancel();
          uninitializedPromise = null;
        } else {
          this.d.delete(emitter);
          this.p({
            id: id2,
            type: 103
            /* RequestType.EventDispose */
          });
        }
      }
    });
    const handler = (res) => emitter.fire(res.data);
    this.f.set(id2, handler);
    return emitter.event;
  }
  p(request) {
    switch (request.type) {
      case 100:
      case 102: {
        const msgLength = this.q([request.type, request.id, request.channelName, request.name], request.arg);
        this.j?.logOutgoing(msgLength, request.id, 0, `${requestTypeToStr(request.type)}: ${request.channelName}.${request.name}`, request.arg);
        return;
      }
      case 101:
      case 103: {
        const msgLength = this.q([request.type, request.id]);
        this.j?.logOutgoing(msgLength, request.id, 0, requestTypeToStr(request.type));
        return;
      }
    }
  }
  q(header, body = void 0) {
    const writer = new $yi();
    $zi(writer, header);
    $zi(writer, body);
    return this.r(writer.buffer);
  }
  r(message) {
    try {
      this.l.send(message);
      return message.byteLength;
    } catch (err) {
      return 0;
    }
  }
  s(message) {
    const reader = new $xi(message);
    const header = $Ai(reader);
    const body = $Ai(reader);
    const type4 = header[0];
    switch (type4) {
      case 200:
        this.j?.logIncoming(message.byteLength, 0, 0, responseTypeToStr(type4));
        return this.t({ type: header[0] });
      case 201:
      case 202:
      case 204:
      case 203:
        this.j?.logIncoming(message.byteLength, header[1], 0, responseTypeToStr(type4), body);
        return this.t({ type: header[0], id: header[1], data: body });
    }
  }
  t(response) {
    if (response.type === 200) {
      this.b = State.Idle;
      this.k.fire();
      return;
    }
    const handler = this.f.get(response.id);
    handler?.(response);
  }
  get onDidInitializePromise() {
    return Event.toPromise(this.onDidInitialize);
  }
  u() {
    if (this.b === State.Idle) {
      return Promise.resolve();
    } else {
      return this.onDidInitializePromise;
    }
  }
  dispose() {
    this.a = true;
    if (this.h) {
      this.h.dispose();
      this.h = null;
    }
    $5c(this.d.values());
    this.d.clear();
  }
};
__decorate([
  $ri
], $Ci.prototype, "onDidInitializePromise", null);
var $Di = class {
  get connections() {
    const result = [];
    this.f.forEach((ctx) => result.push(ctx));
    return result;
  }
  constructor(onDidClientConnect, ipcLogger, timeoutDelay) {
    this.a = /* @__PURE__ */ new Map();
    this.f = /* @__PURE__ */ new Set();
    this.g = new $De();
    this.onDidAddConnection = this.g.event;
    this.h = new $De();
    this.onDidRemoveConnection = this.h.event;
    this.j = new $9c();
    this.j.add(onDidClientConnect(({ protocol: protocol3, onDidClientDisconnect }) => {
      const onFirstMessage = Event.once(protocol3.onMessage);
      this.j.add(onFirstMessage((msg) => {
        const reader = new $xi(msg);
        const ctx = $Ai(reader);
        const channelServer = new $Bi(protocol3, ctx, ipcLogger, timeoutDelay);
        const channelClient = new $Ci(protocol3, ipcLogger);
        this.a.forEach((channel, name) => channelServer.registerChannel(name, channel));
        const connection = { channelServer, channelClient, ctx };
        this.f.add(connection);
        this.g.fire(connection);
        this.j.add(onDidClientDisconnect(() => {
          channelServer.dispose();
          channelClient.dispose();
          this.f.delete(connection);
          this.h.fire(connection);
        }));
      }));
    }));
  }
  getChannel(channelName, routerOrClientFilter) {
    const that = this;
    return {
      call(command, arg, cancellationToken) {
        let connectionPromise;
        if ($Mg(routerOrClientFilter)) {
          const connection = $bc(that.connections.filter(routerOrClientFilter));
          connectionPromise = connection ? Promise.resolve(connection) : Event.toPromise(Event.filter(that.onDidAddConnection, routerOrClientFilter));
        } else {
          connectionPromise = routerOrClientFilter.routeCall(that, command, arg);
        }
        const channelPromise = connectionPromise.then((connection) => connection.channelClient.getChannel(channelName));
        return $Fi(channelPromise).call(command, arg, cancellationToken);
      },
      listen(event, arg) {
        if ($Mg(routerOrClientFilter)) {
          return that.k(channelName, routerOrClientFilter, event, arg);
        }
        const channelPromise = routerOrClientFilter.routeEvent(that, event, arg).then((connection) => connection.channelClient.getChannel(channelName));
        return $Fi(channelPromise).listen(event, arg);
      }
    };
  }
  k(channelName, clientFilter, eventName, arg) {
    const that = this;
    let disposables;
    const emitter = new $De({
      onWillAddFirstListener: () => {
        disposables = new $9c();
        const eventMultiplexer = new $Je();
        const map = /* @__PURE__ */ new Map();
        const onDidAddConnection = (connection) => {
          const channel = connection.channelClient.getChannel(channelName);
          const event = channel.listen(eventName, arg);
          const disposable = eventMultiplexer.add(event);
          map.set(connection, disposable);
        };
        const onDidRemoveConnection = (connection) => {
          const disposable = map.get(connection);
          if (!disposable) {
            return;
          }
          disposable.dispose();
          map.delete(connection);
        };
        that.connections.filter(clientFilter).forEach(onDidAddConnection);
        Event.filter(that.onDidAddConnection, clientFilter)(onDidAddConnection, void 0, disposables);
        that.onDidRemoveConnection(onDidRemoveConnection, void 0, disposables);
        eventMultiplexer.event(emitter.fire, emitter, disposables);
        disposables.add(eventMultiplexer);
      },
      onDidRemoveLastListener: () => {
        disposables?.dispose();
        disposables = void 0;
      }
    });
    return emitter.event;
  }
  registerChannel(channelName, channel) {
    this.a.set(channelName, channel);
    for (const connection of this.f) {
      connection.channelServer.registerChannel(channelName, channel);
    }
  }
  dispose() {
    this.j.dispose();
    for (const connection of this.f) {
      connection.channelClient.dispose();
      connection.channelServer.dispose();
    }
    this.f.clear();
    this.a.clear();
    this.g.dispose();
    this.h.dispose();
  }
};
var $Ei = class {
  constructor(protocol3, ctx, ipcLogger = null) {
    const writer = new $yi();
    $zi(writer, ctx);
    protocol3.send(writer.buffer);
    this.a = new $Ci(protocol3, ipcLogger);
    this.d = new $Bi(protocol3, ctx, ipcLogger);
  }
  getChannel(channelName) {
    return this.a.getChannel(channelName);
  }
  registerChannel(channelName, channel) {
    this.d.registerChannel(channelName, channel);
  }
  dispose() {
    this.a.dispose();
    this.d.dispose();
  }
};
function $Fi(promise) {
  return {
    call(command, arg, cancellationToken) {
      return promise.then((c) => c.call(command, arg, cancellationToken));
    },
    listen(event, arg) {
      const relay = new $Me();
      promise.then((c) => relay.input = c.listen(event, arg));
      return relay.event;
    }
  };
}
function $Gi(channel) {
  let didTick = false;
  return {
    call(command, arg, cancellationToken) {
      if (didTick) {
        return channel.call(command, arg, cancellationToken);
      }
      return $1h(0).then(() => didTick = true).then(() => channel.call(command, arg, cancellationToken));
    },
    listen(event, arg) {
      if (didTick) {
        return channel.listen(event, arg);
      }
      const relay = new $Me();
      $1h(0).then(() => didTick = true).then(() => relay.input = channel.listen(event, arg));
      return relay.event;
    }
  };
}
var $Hi = class {
  constructor(a) {
    this.a = a;
  }
  routeCall(hub) {
    return this.b(hub);
  }
  routeEvent(hub) {
    return this.b(hub);
  }
  async b(hub) {
    for (const connection of hub.connections) {
      if (await Promise.resolve(this.a(connection.ctx))) {
        return Promise.resolve(connection);
      }
    }
    await Event.toPromise(hub.onDidAddConnection);
    return await this.b(hub);
  }
};
var ProxyChannel;
(function(ProxyChannel2) {
  function fromService(service, disposables, options) {
    const handler = service;
    const disableMarshalling = options && options.disableMarshalling;
    const mapEventNameToEvent = /* @__PURE__ */ new Map();
    for (const key in handler) {
      if (propertyIsEvent(key)) {
        mapEventNameToEvent.set(key, Event.buffer(handler[key], true, void 0, disposables));
      }
    }
    return new class {
      listen(_, event, arg) {
        const eventImpl = mapEventNameToEvent.get(event);
        if (eventImpl) {
          return eventImpl;
        }
        const target = handler[event];
        if (typeof target === "function") {
          if (propertyIsDynamicEvent(event)) {
            return target.call(handler, arg);
          }
          if (propertyIsEvent(event)) {
            mapEventNameToEvent.set(event, Event.buffer(handler[event], true, void 0, disposables));
            return mapEventNameToEvent.get(event);
          }
        }
        throw new $ob(`Event not found: ${event}`);
      }
      call(_, command, args) {
        const target = handler[command];
        if (typeof target === "function") {
          if (!disableMarshalling && Array.isArray(args)) {
            for (let i = 0; i < args.length; i++) {
              args[i] = $wi(args[i]);
            }
          }
          let res = target.apply(handler, args);
          if (!(res instanceof Promise)) {
            res = Promise.resolve(res);
          }
          return res;
        }
        throw new $ob(`Method not found: ${command}`);
      }
    }();
  }
  ProxyChannel2.fromService = fromService;
  function toService(channel, options) {
    const disableMarshalling = options && options.disableMarshalling;
    return new Proxy({}, {
      get(_target, propKey) {
        if (typeof propKey === "string") {
          if (options?.properties?.has(propKey)) {
            return options.properties.get(propKey);
          }
          if (propertyIsDynamicEvent(propKey)) {
            return function(arg) {
              return channel.listen(propKey, arg);
            };
          }
          if (propertyIsEvent(propKey)) {
            return channel.listen(propKey);
          }
          return async function(...args) {
            let methodArgs;
            if (options && !$Hg(options.context)) {
              methodArgs = [options.context, ...args];
            } else {
              methodArgs = args;
            }
            const result = await channel.call(propKey, methodArgs);
            if (!disableMarshalling) {
              return $wi(result);
            }
            return result;
          };
        }
        throw new $ob(`Property not found: ${String(propKey)}`);
      }
    });
  }
  ProxyChannel2.toService = toService;
  function propertyIsEvent(name) {
    return name[0] === "o" && name[1] === "n" && $Yf(name.charCodeAt(2));
  }
  function propertyIsDynamicEvent(name) {
    return /^onDynamic/.test(name) && $Yf(name.charCodeAt(9));
  }
})(ProxyChannel || (ProxyChannel = {}));

// out-build/vs/base/parts/ipc/node/ipc.net.js
import { createHash } from "crypto";
import { createServer, createConnection } from "net";
import { tmpdir as tmpdir2 } from "os";
import { createDeflateRaw, createInflateRaw } from "zlib";

// out-build/vs/base/common/uuid.js
var _UUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function $ih(value) {
  return _UUIDPattern.test(value);
}
var $jh = function() {
  if (typeof crypto === "object" && typeof crypto.randomUUID === "function") {
    return crypto.randomUUID.bind(crypto);
  }
  let getRandomValues;
  if (typeof crypto === "object" && typeof crypto.getRandomValues === "function") {
    getRandomValues = crypto.getRandomValues.bind(crypto);
  } else {
    getRandomValues = function(bucket) {
      for (let i = 0; i < bucket.length; i++) {
        bucket[i] = Math.floor(Math.random() * 256);
      }
      return bucket;
    };
  }
  const _data = new Uint8Array(16);
  const _hex = [];
  for (let i = 0; i < 256; i++) {
    _hex.push(i.toString(16).padStart(2, "0"));
  }
  return function generateUuid() {
    getRandomValues(_data);
    _data[6] = _data[6] & 15 | 64;
    _data[8] = _data[8] & 63 | 128;
    let i = 0;
    let result = "";
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    result += "-";
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    result += "-";
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    result += "-";
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    result += "-";
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    return result;
  };
}();

// out-build/vs/base/parts/ipc/common/ipc.net.js
var SocketDiagnosticsEventType;
(function(SocketDiagnosticsEventType2) {
  SocketDiagnosticsEventType2["Created"] = "created";
  SocketDiagnosticsEventType2["Read"] = "read";
  SocketDiagnosticsEventType2["Write"] = "write";
  SocketDiagnosticsEventType2["Open"] = "open";
  SocketDiagnosticsEventType2["Error"] = "error";
  SocketDiagnosticsEventType2["Close"] = "close";
  SocketDiagnosticsEventType2["BrowserWebSocketBlobReceived"] = "browserWebSocketBlobReceived";
  SocketDiagnosticsEventType2["NodeEndReceived"] = "nodeEndReceived";
  SocketDiagnosticsEventType2["NodeEndSent"] = "nodeEndSent";
  SocketDiagnosticsEventType2["NodeDrainBegin"] = "nodeDrainBegin";
  SocketDiagnosticsEventType2["NodeDrainEnd"] = "nodeDrainEnd";
  SocketDiagnosticsEventType2["zlibInflateError"] = "zlibInflateError";
  SocketDiagnosticsEventType2["zlibInflateData"] = "zlibInflateData";
  SocketDiagnosticsEventType2["zlibInflateInitialWrite"] = "zlibInflateInitialWrite";
  SocketDiagnosticsEventType2["zlibInflateInitialFlushFired"] = "zlibInflateInitialFlushFired";
  SocketDiagnosticsEventType2["zlibInflateWrite"] = "zlibInflateWrite";
  SocketDiagnosticsEventType2["zlibInflateFlushFired"] = "zlibInflateFlushFired";
  SocketDiagnosticsEventType2["zlibDeflateError"] = "zlibDeflateError";
  SocketDiagnosticsEventType2["zlibDeflateData"] = "zlibDeflateData";
  SocketDiagnosticsEventType2["zlibDeflateWrite"] = "zlibDeflateWrite";
  SocketDiagnosticsEventType2["zlibDeflateFlushFired"] = "zlibDeflateFlushFired";
  SocketDiagnosticsEventType2["WebSocketNodeSocketWrite"] = "webSocketNodeSocketWrite";
  SocketDiagnosticsEventType2["WebSocketNodeSocketPeekedHeader"] = "webSocketNodeSocketPeekedHeader";
  SocketDiagnosticsEventType2["WebSocketNodeSocketReadHeader"] = "webSocketNodeSocketReadHeader";
  SocketDiagnosticsEventType2["WebSocketNodeSocketReadData"] = "webSocketNodeSocketReadData";
  SocketDiagnosticsEventType2["WebSocketNodeSocketUnmaskedData"] = "webSocketNodeSocketUnmaskedData";
  SocketDiagnosticsEventType2["WebSocketNodeSocketDrainBegin"] = "webSocketNodeSocketDrainBegin";
  SocketDiagnosticsEventType2["WebSocketNodeSocketDrainEnd"] = "webSocketNodeSocketDrainEnd";
  SocketDiagnosticsEventType2["ProtocolHeaderRead"] = "protocolHeaderRead";
  SocketDiagnosticsEventType2["ProtocolMessageRead"] = "protocolMessageRead";
  SocketDiagnosticsEventType2["ProtocolHeaderWrite"] = "protocolHeaderWrite";
  SocketDiagnosticsEventType2["ProtocolMessageWrite"] = "protocolMessageWrite";
  SocketDiagnosticsEventType2["ProtocolWrite"] = "protocolWrite";
})(SocketDiagnosticsEventType || (SocketDiagnosticsEventType = {}));
var SocketDiagnostics;
(function(SocketDiagnostics2) {
  SocketDiagnostics2.enableDiagnostics = false;
  SocketDiagnostics2.records = [];
  const socketIds = /* @__PURE__ */ new WeakMap();
  let lastUsedSocketId = 0;
  function getSocketId(nativeObject, label) {
    if (!socketIds.has(nativeObject)) {
      const id2 = String(++lastUsedSocketId);
      socketIds.set(nativeObject, id2);
    }
    return socketIds.get(nativeObject);
  }
  function traceSocketEvent(nativeObject, socketDebugLabel, type4, data) {
    if (!SocketDiagnostics2.enableDiagnostics) {
      return;
    }
    const id2 = getSocketId(nativeObject, socketDebugLabel);
    if (data instanceof $7e || data instanceof Uint8Array || data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
      const copiedData = $7e.alloc(data.byteLength);
      copiedData.set(data);
      SocketDiagnostics2.records.push({ timestamp: Date.now(), id: id2, label: socketDebugLabel, type: type4, buff: copiedData });
    } else {
      SocketDiagnostics2.records.push({ timestamp: Date.now(), id: id2, label: socketDebugLabel, type: type4, data });
    }
  }
  SocketDiagnostics2.traceSocketEvent = traceSocketEvent;
})(SocketDiagnostics || (SocketDiagnostics = {}));
var SocketCloseEventType;
(function(SocketCloseEventType2) {
  SocketCloseEventType2[SocketCloseEventType2["NodeSocketCloseEvent"] = 0] = "NodeSocketCloseEvent";
  SocketCloseEventType2[SocketCloseEventType2["WebSocketCloseEvent"] = 1] = "WebSocketCloseEvent";
})(SocketCloseEventType || (SocketCloseEventType = {}));
var emptyBuffer = null;
function getEmptyBuffer() {
  if (!emptyBuffer) {
    emptyBuffer = $7e.alloc(0);
  }
  return emptyBuffer;
}
var $Ji = class {
  get byteLength() {
    return this.b;
  }
  constructor() {
    this.a = [];
    this.b = 0;
  }
  acceptChunk(buff) {
    this.a.push(buff);
    this.b += buff.byteLength;
  }
  read(byteCount) {
    return this.c(byteCount, true);
  }
  peek(byteCount) {
    return this.c(byteCount, false);
  }
  c(byteCount, advance) {
    if (byteCount === 0) {
      return getEmptyBuffer();
    }
    if (byteCount > this.b) {
      throw new Error(`Cannot read so many bytes!`);
    }
    if (this.a[0].byteLength === byteCount) {
      const result2 = this.a[0];
      if (advance) {
        this.a.shift();
        this.b -= byteCount;
      }
      return result2;
    }
    if (this.a[0].byteLength > byteCount) {
      const result2 = this.a[0].slice(0, byteCount);
      if (advance) {
        this.a[0] = this.a[0].slice(byteCount);
        this.b -= byteCount;
      }
      return result2;
    }
    const result = $7e.alloc(byteCount);
    let resultOffset = 0;
    let chunkIndex = 0;
    while (byteCount > 0) {
      const chunk = this.a[chunkIndex];
      if (chunk.byteLength > byteCount) {
        const chunkPart = chunk.slice(0, byteCount);
        result.set(chunkPart, resultOffset);
        resultOffset += byteCount;
        if (advance) {
          this.a[chunkIndex] = chunk.slice(byteCount);
          this.b -= byteCount;
        }
        byteCount -= byteCount;
      } else {
        result.set(chunk, resultOffset);
        resultOffset += chunk.byteLength;
        if (advance) {
          this.a.shift();
          this.b -= chunk.byteLength;
        } else {
          chunkIndex++;
        }
        byteCount -= chunk.byteLength;
      }
    }
    return result;
  }
};
var ProtocolMessageType;
(function(ProtocolMessageType2) {
  ProtocolMessageType2[ProtocolMessageType2["None"] = 0] = "None";
  ProtocolMessageType2[ProtocolMessageType2["Regular"] = 1] = "Regular";
  ProtocolMessageType2[ProtocolMessageType2["Control"] = 2] = "Control";
  ProtocolMessageType2[ProtocolMessageType2["Ack"] = 3] = "Ack";
  ProtocolMessageType2[ProtocolMessageType2["Disconnect"] = 5] = "Disconnect";
  ProtocolMessageType2[ProtocolMessageType2["ReplayRequest"] = 6] = "ReplayRequest";
  ProtocolMessageType2[ProtocolMessageType2["Pause"] = 7] = "Pause";
  ProtocolMessageType2[ProtocolMessageType2["Resume"] = 8] = "Resume";
  ProtocolMessageType2[ProtocolMessageType2["KeepAlive"] = 9] = "KeepAlive";
})(ProtocolMessageType || (ProtocolMessageType = {}));
function protocolMessageTypeToString(messageType) {
  switch (messageType) {
    case 0:
      return "None";
    case 1:
      return "Regular";
    case 2:
      return "Control";
    case 3:
      return "Ack";
    case 5:
      return "Disconnect";
    case 6:
      return "ReplayRequest";
    case 7:
      return "PauseWriting";
    case 8:
      return "ResumeWriting";
    case 9:
      return "KeepAlive";
  }
}
var ProtocolConstants;
(function(ProtocolConstants2) {
  ProtocolConstants2[ProtocolConstants2["HeaderLength"] = 13] = "HeaderLength";
  ProtocolConstants2[ProtocolConstants2["AcknowledgeTime"] = 2e3] = "AcknowledgeTime";
  ProtocolConstants2[ProtocolConstants2["TimeoutTime"] = 2e4] = "TimeoutTime";
  ProtocolConstants2[ProtocolConstants2["ReconnectionGraceTime"] = 108e5] = "ReconnectionGraceTime";
  ProtocolConstants2[ProtocolConstants2["ReconnectionShortGraceTime"] = 3e5] = "ReconnectionShortGraceTime";
  ProtocolConstants2[ProtocolConstants2["KeepAliveSendTime"] = 5e3] = "KeepAliveSendTime";
})(ProtocolConstants || (ProtocolConstants = {}));
var ProtocolMessage = class {
  constructor(type4, id2, ack, data) {
    this.type = type4;
    this.id = id2;
    this.ack = ack;
    this.data = data;
    this.writtenTime = 0;
  }
  get size() {
    return this.data.byteLength;
  }
};
var ProtocolReader = class extends $0c {
  constructor(socket) {
    super();
    this.f = this.B(new $De());
    this.onMessage = this.f.event;
    this.g = {
      readHead: true,
      readLen: 13,
      messageType: 0,
      id: 0,
      ack: 0
    };
    this.a = socket;
    this.b = false;
    this.c = new $Ji();
    this.B(this.a.onData((data) => this.acceptChunk(data)));
    this.lastReadTime = Date.now();
  }
  acceptChunk(data) {
    if (!data || data.byteLength === 0) {
      return;
    }
    this.lastReadTime = Date.now();
    this.c.acceptChunk(data);
    while (this.c.byteLength >= this.g.readLen) {
      const buff = this.c.read(this.g.readLen);
      if (this.g.readHead) {
        this.g.readHead = false;
        this.g.readLen = buff.readUInt32BE(9);
        this.g.messageType = buff.readUInt8(0);
        this.g.id = buff.readUInt32BE(1);
        this.g.ack = buff.readUInt32BE(5);
        this.a.traceSocketEvent("protocolHeaderRead", { messageType: protocolMessageTypeToString(this.g.messageType), id: this.g.id, ack: this.g.ack, messageSize: this.g.readLen });
      } else {
        const messageType = this.g.messageType;
        const id2 = this.g.id;
        const ack = this.g.ack;
        this.g.readHead = true;
        this.g.readLen = 13;
        this.g.messageType = 0;
        this.g.id = 0;
        this.g.ack = 0;
        this.a.traceSocketEvent("protocolMessageRead", buff);
        this.f.fire(new ProtocolMessage(messageType, id2, ack, buff));
        if (this.b) {
          break;
        }
      }
    }
  }
  readEntireBuffer() {
    return this.c.read(this.c.byteLength);
  }
  dispose() {
    this.b = true;
    super.dispose();
  }
};
var ProtocolWriter = class {
  constructor(socket) {
    this.k = null;
    this.a = false;
    this.b = false;
    this.c = socket;
    this.d = [];
    this.f = 0;
    this.lastWriteTime = 0;
  }
  dispose() {
    try {
      this.flush();
    } catch (err) {
    }
    this.a = true;
  }
  drain() {
    this.flush();
    return this.c.drain();
  }
  flush() {
    this.m();
  }
  pause() {
    this.b = true;
  }
  resume() {
    this.b = false;
    this.l();
  }
  write(msg) {
    if (this.a) {
      return;
    }
    msg.writtenTime = Date.now();
    this.lastWriteTime = Date.now();
    const header = $7e.alloc(
      13
      /* ProtocolConstants.HeaderLength */
    );
    header.writeUInt8(msg.type, 0);
    header.writeUInt32BE(msg.id, 1);
    header.writeUInt32BE(msg.ack, 5);
    header.writeUInt32BE(msg.data.byteLength, 9);
    this.c.traceSocketEvent("protocolHeaderWrite", { messageType: protocolMessageTypeToString(msg.type), id: msg.id, ack: msg.ack, messageSize: msg.data.byteLength });
    this.c.traceSocketEvent("protocolMessageWrite", msg.data);
    this.j(header, msg.data);
  }
  g(head, body) {
    const wasEmpty = this.f === 0;
    this.d.push(head, body);
    this.f += head.byteLength + body.byteLength;
    return wasEmpty;
  }
  h() {
    const ret = $7e.concat(this.d, this.f);
    this.d.length = 0;
    this.f = 0;
    return ret;
  }
  j(header, data) {
    if (this.g(header, data)) {
      this.l();
    }
  }
  l() {
    if (this.k) {
      return;
    }
    this.k = setTimeout(() => {
      this.k = null;
      this.m();
    });
  }
  m() {
    if (this.f === 0) {
      return;
    }
    if (this.b) {
      return;
    }
    const data = this.h();
    this.c.traceSocketEvent("protocolWrite", { byteLength: data.byteLength });
    this.c.write(data);
  }
};
var $Ki = class extends $0c {
  constructor(socket) {
    super();
    this.f = new $De();
    this.onMessage = this.f.event;
    this.g = new $De();
    this.onDidDispose = this.g.event;
    this.a = socket;
    this.b = this.B(new ProtocolWriter(this.a));
    this.c = this.B(new ProtocolReader(this.a));
    this.B(this.c.onMessage((msg) => {
      if (msg.type === 1) {
        this.f.fire(msg.data);
      }
    }));
    this.B(this.a.onClose(() => this.g.fire()));
  }
  drain() {
    return this.b.drain();
  }
  getSocket() {
    return this.a;
  }
  sendDisconnect() {
  }
  send(buffer) {
    this.b.write(new ProtocolMessage(1, 0, 0, buffer));
  }
};
var $Li = class _$Li extends $Ei {
  static fromSocket(socket, id2) {
    return new _$Li(new $Ki(socket), id2);
  }
  get onDidDispose() {
    return this.b.onDidDispose;
  }
  constructor(b, id2, ipcLogger = null) {
    super(b, id2, ipcLogger);
    this.b = b;
  }
  dispose() {
    super.dispose();
    const socket = this.b.getSocket();
    this.b.sendDisconnect();
    this.b.dispose();
    socket.end();
  }
};
var $Mi = class {
  constructor() {
    this.b = false;
    this.c = false;
    this.d = [];
    this.a = new $De({
      onWillAddFirstListener: () => {
        this.b = true;
        queueMicrotask(() => this.f());
      },
      onDidRemoveLastListener: () => {
        this.b = false;
      }
    });
    this.event = this.a.event;
  }
  f() {
    if (this.c) {
      return;
    }
    this.c = true;
    while (this.b && this.d.length > 0) {
      this.a.fire(this.d.shift());
    }
    this.c = false;
  }
  fire(event) {
    if (this.b) {
      if (this.d.length > 0) {
        this.d.push(event);
      } else {
        this.a.fire(event);
      }
    } else {
      this.d.push(event);
    }
  }
  flushBuffer() {
    this.d = [];
  }
};
var QueueElement = class {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
};
var Queue = class {
  constructor() {
    this.a = null;
    this.b = null;
  }
  length() {
    let result = 0;
    let current = this.a;
    while (current) {
      current = current.next;
      result++;
    }
    return result;
  }
  peek() {
    if (!this.a) {
      return null;
    }
    return this.a.data;
  }
  toArray() {
    const result = [];
    let resultLen = 0;
    let it = this.a;
    while (it) {
      result[resultLen++] = it.data;
      it = it.next;
    }
    return result;
  }
  pop() {
    if (!this.a) {
      return;
    }
    if (this.a === this.b) {
      this.a = null;
      this.b = null;
      return;
    }
    this.a = this.a.next;
  }
  push(item) {
    const element = new QueueElement(item);
    if (!this.a) {
      this.a = element;
      this.b = element;
      return;
    }
    this.b.next = element;
    this.b = element;
  }
};
var LoadEstimator = class _LoadEstimator {
  static {
    this.a = 10;
  }
  static {
    this.b = null;
  }
  static getInstance() {
    if (!_LoadEstimator.b) {
      _LoadEstimator.b = new _LoadEstimator();
    }
    return _LoadEstimator.b;
  }
  constructor() {
    this.c = [];
    const now2 = Date.now();
    for (let i = 0; i < _LoadEstimator.a; i++) {
      this.c[i] = now2 - 1e3 * i;
    }
    setInterval(() => {
      for (let i = _LoadEstimator.a; i >= 1; i--) {
        this.c[i] = this.c[i - 1];
      }
      this.c[0] = Date.now();
    }, 1e3);
  }
  /**
   * returns an estimative number, from 0 (low load) to 1 (high load)
   */
  d() {
    const now2 = Date.now();
    const historyLimit = (1 + _LoadEstimator.a) * 1e3;
    let score = 0;
    for (let i = 0; i < _LoadEstimator.a; i++) {
      if (now2 - this.c[i] <= historyLimit) {
        score++;
      }
    }
    return 1 - score / _LoadEstimator.a;
  }
  hasHighLoad() {
    return this.d() >= 0.5;
  }
};
var $Ni = class {
  get unacknowledgedCount() {
    return this.d - this.f;
  }
  constructor(opts) {
    this.v = new $Mi();
    this.onControlMessage = this.v.event;
    this.w = new $Mi();
    this.onMessage = this.w.event;
    this.x = new $Mi();
    this.onDidDispose = this.x.event;
    this.y = new $Mi();
    this.onSocketClose = this.y.event;
    this.z = new $Mi();
    this.onSocketTimeout = this.z.event;
    this.t = opts.loadEstimator ?? LoadEstimator.getInstance();
    this.u = opts.sendKeepAlive ?? true;
    this.a = false;
    this.c = new Queue();
    this.d = 0;
    this.f = 0;
    this.g = null;
    this.h = 0;
    this.j = 0;
    this.k = 0;
    this.l = null;
    this.n = 0;
    this.o = Date.now();
    this.s = new $9c();
    this.p = opts.socket;
    this.q = this.s.add(new ProtocolWriter(this.p));
    this.r = this.s.add(new ProtocolReader(this.p));
    this.s.add(this.r.onMessage((msg) => this.A(msg)));
    this.s.add(this.p.onClose((e) => this.y.fire(e)));
    if (opts.initialChunk) {
      this.r.acceptChunk(opts.initialChunk);
    }
    if (this.u) {
      this.m = setInterval(
        () => {
          this.E();
        },
        5e3
        /* ProtocolConstants.KeepAliveSendTime */
      );
    } else {
      this.m = null;
    }
  }
  dispose() {
    if (this.g) {
      clearTimeout(this.g);
      this.g = null;
    }
    if (this.l) {
      clearTimeout(this.l);
      this.l = null;
    }
    if (this.m) {
      clearInterval(this.m);
      this.m = null;
    }
    this.s.dispose();
  }
  drain() {
    return this.q.drain();
  }
  sendDisconnect() {
    if (!this.b) {
      this.b = true;
      const msg = new ProtocolMessage(5, 0, 0, getEmptyBuffer());
      this.q.write(msg);
      this.q.flush();
    }
  }
  sendPause() {
    const msg = new ProtocolMessage(7, 0, 0, getEmptyBuffer());
    this.q.write(msg);
  }
  sendResume() {
    const msg = new ProtocolMessage(8, 0, 0, getEmptyBuffer());
    this.q.write(msg);
  }
  pauseSocketWriting() {
    this.q.pause();
  }
  getSocket() {
    return this.p;
  }
  getMillisSinceLastIncomingData() {
    return Date.now() - this.r.lastReadTime;
  }
  beginAcceptReconnection(socket, initialDataChunk) {
    this.a = true;
    this.s.dispose();
    this.s = new $9c();
    this.v.flushBuffer();
    this.y.flushBuffer();
    this.z.flushBuffer();
    this.p.dispose();
    this.n = 0;
    this.o = Date.now();
    this.p = socket;
    this.q = this.s.add(new ProtocolWriter(this.p));
    this.r = this.s.add(new ProtocolReader(this.p));
    this.s.add(this.r.onMessage((msg) => this.A(msg)));
    this.s.add(this.p.onClose((e) => this.y.fire(e)));
    this.r.acceptChunk(initialDataChunk);
  }
  endAcceptReconnection() {
    this.a = false;
    this.j = this.h;
    const msg = new ProtocolMessage(3, 0, this.j, getEmptyBuffer());
    this.q.write(msg);
    const toSend = this.c.toArray();
    for (let i = 0, len = toSend.length; i < len; i++) {
      this.q.write(toSend[i]);
    }
    this.C();
  }
  acceptDisconnect() {
    this.x.fire();
  }
  A(msg) {
    if (msg.ack > this.f) {
      this.f = msg.ack;
      do {
        const first = this.c.peek();
        if (first && first.id <= msg.ack) {
          this.c.pop();
        } else {
          break;
        }
      } while (true);
    }
    switch (msg.type) {
      case 0: {
        break;
      }
      case 1: {
        if (msg.id > this.h) {
          if (msg.id !== this.h + 1) {
            const now2 = Date.now();
            if (now2 - this.n > 1e4) {
              this.n = now2;
              this.q.write(new ProtocolMessage(6, 0, 0, getEmptyBuffer()));
            }
          } else {
            this.h = msg.id;
            this.k = Date.now();
            this.B();
            this.w.fire(msg.data);
          }
        }
        break;
      }
      case 2: {
        this.v.fire(msg.data);
        break;
      }
      case 3: {
        break;
      }
      case 5: {
        this.x.fire();
        break;
      }
      case 6: {
        const toSend = this.c.toArray();
        for (let i = 0, len = toSend.length; i < len; i++) {
          this.q.write(toSend[i]);
        }
        this.C();
        break;
      }
      case 7: {
        this.q.pause();
        break;
      }
      case 8: {
        this.q.resume();
        break;
      }
      case 9: {
        break;
      }
    }
  }
  readEntireBuffer() {
    return this.r.readEntireBuffer();
  }
  flush() {
    this.q.flush();
  }
  send(buffer) {
    const myId = ++this.d;
    this.j = this.h;
    const msg = new ProtocolMessage(1, myId, this.j, buffer);
    this.c.push(msg);
    if (!this.a) {
      this.q.write(msg);
      this.C();
    }
  }
  /**
   * Send a message which will not be part of the regular acknowledge flow.
   * Use this for early control messages which are repeated in case of reconnection.
   */
  sendControl(buffer) {
    const msg = new ProtocolMessage(2, 0, 0, buffer);
    this.q.write(msg);
  }
  B() {
    if (this.h <= this.j) {
      return;
    }
    if (this.l) {
      return;
    }
    const timeSinceLastIncomingMsg = Date.now() - this.k;
    if (timeSinceLastIncomingMsg >= 2e3) {
      this.D();
      return;
    }
    this.l = setTimeout(() => {
      this.l = null;
      this.B();
    }, 2e3 - timeSinceLastIncomingMsg + 5);
  }
  C() {
    if (this.d <= this.f) {
      return;
    }
    if (this.g) {
      return;
    }
    if (this.a) {
      return;
    }
    const oldestUnacknowledgedMsg = this.c.peek();
    const timeSinceOldestUnacknowledgedMsg = Date.now() - oldestUnacknowledgedMsg.writtenTime;
    const timeSinceLastReceivedSomeData = Date.now() - this.r.lastReadTime;
    const timeSinceLastTimeout = Date.now() - this.o;
    if (timeSinceOldestUnacknowledgedMsg >= 2e4 && timeSinceLastReceivedSomeData >= 2e4 && timeSinceLastTimeout >= 2e4) {
      if (!this.t.hasHighLoad()) {
        this.o = Date.now();
        this.z.fire({
          unacknowledgedMsgCount: this.c.length(),
          timeSinceOldestUnacknowledgedMsg,
          timeSinceLastReceivedSomeData
        });
        return;
      }
    }
    const minimumTimeUntilTimeout = Math.max(2e4 - timeSinceOldestUnacknowledgedMsg, 2e4 - timeSinceLastReceivedSomeData, 2e4 - timeSinceLastTimeout, 500);
    this.g = setTimeout(() => {
      this.g = null;
      this.C();
    }, minimumTimeUntilTimeout);
  }
  D() {
    if (this.h <= this.j) {
      return;
    }
    this.j = this.h;
    const msg = new ProtocolMessage(3, 0, this.j, getEmptyBuffer());
    this.q.write(msg);
  }
  E() {
    this.j = this.h;
    const msg = new ProtocolMessage(9, 0, this.j, getEmptyBuffer());
    this.q.write(msg);
  }
};

// out-build/vs/base/parts/ipc/node/ipc.net.js
var socketEndTimeoutMs = 3e4;
var $Oi = class {
  traceSocketEvent(type4, data) {
    SocketDiagnostics.traceSocketEvent(this.socket, this.debugLabel, type4, data);
  }
  constructor(socket, debugLabel = "") {
    this.f = true;
    this.debugLabel = debugLabel;
    this.socket = socket;
    this.traceSocketEvent("created", { type: "NodeSocket" });
    this.a = (err) => {
      this.traceSocketEvent("error", { code: err?.code, message: err?.message });
      if (err) {
        if (err.code === "EPIPE") {
          return;
        }
        $ab(err);
      }
    };
    this.socket.on("error", this.a);
    let endTimeoutHandle;
    this.b = (hadError) => {
      this.traceSocketEvent("close", { hadError });
      this.f = false;
      if (endTimeoutHandle) {
        clearTimeout(endTimeoutHandle);
      }
    };
    this.socket.on("close", this.b);
    this.d = () => {
      this.traceSocketEvent(
        "nodeEndReceived"
        /* SocketDiagnosticsEventType.NodeEndReceived */
      );
      this.f = false;
      endTimeoutHandle = setTimeout(() => socket.destroy(), socketEndTimeoutMs);
    };
    this.socket.on("end", this.d);
  }
  dispose() {
    this.socket.off("error", this.a);
    this.socket.off("close", this.b);
    this.socket.off("end", this.d);
    this.socket.destroy();
  }
  onData(_listener) {
    const listener = (buff) => {
      this.traceSocketEvent("read", buff);
      _listener($7e.wrap(buff));
    };
    this.socket.on("data", listener);
    return {
      dispose: () => this.socket.off("data", listener)
    };
  }
  onClose(listener) {
    const adapter = (hadError) => {
      listener({
        type: 0,
        hadError,
        error: void 0
      });
    };
    this.socket.on("close", adapter);
    return {
      dispose: () => this.socket.off("close", adapter)
    };
  }
  onEnd(listener) {
    const adapter = () => {
      listener();
    };
    this.socket.on("end", adapter);
    return {
      dispose: () => this.socket.off("end", adapter)
    };
  }
  write(buffer) {
    if (this.socket.destroyed || !this.f) {
      return;
    }
    try {
      this.traceSocketEvent("write", buffer);
      this.socket.write(buffer.buffer, (err) => {
        if (err) {
          if (err.code === "EPIPE") {
            return;
          }
          $ab(err);
        }
      });
    } catch (err) {
      if (err.code === "EPIPE") {
        return;
      }
      $ab(err);
    }
  }
  end() {
    this.traceSocketEvent(
      "nodeEndSent"
      /* SocketDiagnosticsEventType.NodeEndSent */
    );
    this.socket.end();
  }
  drain() {
    this.traceSocketEvent(
      "nodeDrainBegin"
      /* SocketDiagnosticsEventType.NodeDrainBegin */
    );
    return new Promise((resolve2, reject) => {
      if (this.socket.bufferSize === 0) {
        this.traceSocketEvent(
          "nodeDrainEnd"
          /* SocketDiagnosticsEventType.NodeDrainEnd */
        );
        resolve2();
        return;
      }
      const finished = () => {
        this.socket.off("close", finished);
        this.socket.off("end", finished);
        this.socket.off("error", finished);
        this.socket.off("timeout", finished);
        this.socket.off("drain", finished);
        this.traceSocketEvent(
          "nodeDrainEnd"
          /* SocketDiagnosticsEventType.NodeDrainEnd */
        );
        resolve2();
      };
      this.socket.on("close", finished);
      this.socket.on("end", finished);
      this.socket.on("error", finished);
      this.socket.on("timeout", finished);
      this.socket.on("drain", finished);
    });
  }
};
var Constants;
(function(Constants4) {
  Constants4[Constants4["MinHeaderByteSize"] = 2] = "MinHeaderByteSize";
  Constants4[Constants4["MaxWebSocketMessageLength"] = 262144] = "MaxWebSocketMessageLength";
})(Constants || (Constants = {}));
var ReadState;
(function(ReadState2) {
  ReadState2[ReadState2["PeekHeader"] = 1] = "PeekHeader";
  ReadState2[ReadState2["ReadHeader"] = 2] = "ReadHeader";
  ReadState2[ReadState2["ReadBody"] = 3] = "ReadBody";
  ReadState2[ReadState2["Fin"] = 4] = "Fin";
})(ReadState || (ReadState = {}));
var $Qi = process.env["XDG_RUNTIME_DIR"];
var safeIpcPathLengths = {
  [
    2
    /* Platform.Linux */
  ]: 107,
  [
    1
    /* Platform.Mac */
  ]: 103
};
function $Si(directoryPath, type4, version) {
  const scope = createHash("sha256").update(directoryPath).digest("hex");
  const scopeForSocket = scope.substr(0, 8);
  if (process.platform === "win32") {
    return `\\\\.\\pipe\\${scopeForSocket}-${version}-${type4}-sock`;
  }
  const versionForSocket = version.substr(0, 4);
  const typeForSocket = type4.substr(0, 6);
  let result;
  if (process.platform !== "darwin" && $Qi && !process.env["VSCODE_PORTABLE"]) {
    result = $vc($Qi, `vscode-${scopeForSocket}-${versionForSocket}-${typeForSocket}.sock`);
  } else {
    result = $vc(directoryPath, `${versionForSocket}-${typeForSocket}.sock`);
  }
  validateIPCHandleLength(result);
  return result;
}
function validateIPCHandleLength(handle) {
  const limit = safeIpcPathLengths[$x];
  if (typeof limit === "number" && handle.length >= limit) {
    console.warn(`WARNING: IPC handle "${handle}" is longer than ${limit} chars, try a shorter --user-data-dir`);
  }
}
var $Ti = class _$Ti extends $Di {
  static b(server) {
    const onConnection = Event.fromNodeEventEmitter(server, "connection");
    return Event.map(onConnection, (socket) => ({
      protocol: new $Ki(new $Oi(socket, "ipc-server-connection")),
      onDidClientDisconnect: Event.once(Event.fromNodeEventEmitter(socket, "close"))
    }));
  }
  constructor(server) {
    super(_$Ti.b(server));
    this.d = server;
  }
  dispose() {
    super.dispose();
    if (this.d) {
      this.d.close();
      this.d = null;
    }
  }
};
function $Ui(hook) {
  return new Promise((c, e) => {
    const server = createServer();
    server.on("error", e);
    server.listen(hook, () => {
      server.removeListener("error", e);
      c(new $Ti(server));
    });
  });
}
function $Vi(hook, clientId) {
  return new Promise((c, e) => {
    const socket = createConnection(hook, () => {
      socket.removeListener("error", e);
      c($Li.fromSocket(new $Oi(socket, `ipc-client${clientId}`), clientId));
    });
    socket.once("error", e);
  });
}

// out-build/vs/code/electron-main/app.js
import { app as app12, BrowserWindow as BrowserWindow8, protocol as protocol2, session, systemPreferences } from "electron";

// out-build/vs/base/node/unc.js
var module2 = { exports: {} };
(function() {
  const isESM = true;
  function factory() {
    function processUNCHostAllowlist() {
      return process.uncHostAllowlist;
    }
    function toSafeStringArray(arg0) {
      const allowedUNCHosts = /* @__PURE__ */ new Set();
      if (Array.isArray(arg0)) {
        for (const host of arg0) {
          if (typeof host === "string") {
            allowedUNCHosts.add(host);
          }
        }
      }
      return Array.from(allowedUNCHosts);
    }
    function getUNCHostAllowlist2() {
      const allowlist = processUNCHostAllowlist();
      if (allowlist) {
        return Array.from(allowlist);
      }
      return [];
    }
    function addUNCHostToAllowlist2(allowedHost) {
      if (process.platform !== "win32") {
        return;
      }
      const allowlist = processUNCHostAllowlist();
      if (allowlist) {
        if (typeof allowedHost === "string") {
          allowlist.add(allowedHost.toLowerCase());
        } else {
          for (const host of toSafeStringArray(allowedHost)) {
            addUNCHostToAllowlist2(host);
          }
        }
      }
    }
    function getUNCHost2(maybeUNCPath) {
      if (typeof maybeUNCPath !== "string") {
        return void 0;
      }
      const uncRoots = [
        "\\\\.\\UNC\\",
        // DOS Device paths (https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats)
        "\\\\?\\UNC\\",
        "\\\\"
        // standard UNC path
      ];
      let host = void 0;
      for (const uncRoot of uncRoots) {
        const indexOfUNCRoot = maybeUNCPath.indexOf(uncRoot);
        if (indexOfUNCRoot !== 0) {
          continue;
        }
        const indexOfUNCPath = maybeUNCPath.indexOf("\\", uncRoot.length);
        if (indexOfUNCPath === -1) {
          continue;
        }
        const hostCandidate = maybeUNCPath.substring(uncRoot.length, indexOfUNCPath);
        if (hostCandidate) {
          host = hostCandidate;
          break;
        }
      }
      return host;
    }
    function disableUNCAccessRestrictions2() {
      if (process.platform !== "win32") {
        return;
      }
      process.restrictUNCAccess = false;
    }
    function isUNCAccessRestrictionsDisabled2() {
      if (process.platform !== "win32") {
        return true;
      }
      return process.restrictUNCAccess === false;
    }
    return {
      getUNCHostAllowlist: getUNCHostAllowlist2,
      addUNCHostToAllowlist: addUNCHostToAllowlist2,
      getUNCHost: getUNCHost2,
      disableUNCAccessRestrictions: disableUNCAccessRestrictions2,
      isUNCAccessRestrictionsDisabled: isUNCAccessRestrictionsDisabled2
    };
  }
  if (!isESM && typeof define === "function") {
    define([], function() {
      return factory();
    });
  } else if (typeof module2 === "object" && typeof module2.exports === "object") {
    module2.exports = factory();
  } else {
    console.trace("vs/base/node/unc defined in UNKNOWN context (neither requirejs or commonjs)");
  }
})();
var getUNCHost = module2.exports.getUNCHost;
var getUNCHostAllowlist = module2.exports.getUNCHostAllowlist;
var addUNCHostToAllowlist = module2.exports.addUNCHostToAllowlist;
var disableUNCAccessRestrictions = module2.exports.disableUNCAccessRestrictions;
var isUNCAccessRestrictionsDisabled = module2.exports.isUNCAccessRestrictionsDisabled;

// out-build/vs/base/parts/ipc/electron-main/ipcMain.js
import electron from "electron";
var ValidatedIpcMain = class {
  constructor() {
    this.a = /* @__PURE__ */ new WeakMap();
  }
  /**
   * Listens to `channel`, when a new message arrives `listener` would be called with
   * `listener(event, args...)`.
   */
  on(channel, listener) {
    const wrappedListener = (event, ...args) => {
      if (this.b(channel, event)) {
        listener(event, ...args);
      }
    };
    this.a.set(listener, wrappedListener);
    electron.ipcMain.on(channel, wrappedListener);
    return this;
  }
  /**
   * Adds a one time `listener` function for the event. This `listener` is invoked
   * only the next time a message is sent to `channel`, after which it is removed.
   */
  once(channel, listener) {
    electron.ipcMain.once(channel, (event, ...args) => {
      if (this.b(channel, event)) {
        listener(event, ...args);
      }
    });
    return this;
  }
  /**
   * Adds a handler for an `invoke`able IPC. This handler will be called whenever a
   * renderer calls `ipcRenderer.invoke(channel, ...args)`.
   *
   * If `listener` returns a Promise, the eventual result of the promise will be
   * returned as a reply to the remote caller. Otherwise, the return value of the
   * listener will be used as the value of the reply.
   *
   * The `event` that is passed as the first argument to the handler is the same as
   * that passed to a regular event listener. It includes information about which
   * WebContents is the source of the invoke request.
   *
   * Errors thrown through `handle` in the main process are not transparent as they
   * are serialized and only the `message` property from the original error is
   * provided to the renderer process. Please refer to #24427 for details.
   */
  handle(channel, listener) {
    electron.ipcMain.handle(channel, (event, ...args) => {
      if (this.b(channel, event)) {
        return listener(event, ...args);
      }
      return Promise.reject(`Invalid channel '${channel}' or sender for ipcMain.handle() usage.`);
    });
    return this;
  }
  /**
   * Removes any handler for `channel`, if present.
   */
  removeHandler(channel) {
    electron.ipcMain.removeHandler(channel);
    return this;
  }
  /**
   * Removes the specified `listener` from the listener array for the specified
   * `channel`.
   */
  removeListener(channel, listener) {
    const wrappedListener = this.a.get(listener);
    if (wrappedListener) {
      electron.ipcMain.removeListener(channel, wrappedListener);
      this.a.delete(listener);
    }
    return this;
  }
  b(channel, event) {
    if (!channel || !channel.startsWith("vscode:")) {
      $ab(`Refused to handle ipcMain event for channel '${channel}' because the channel is unknown.`);
      return false;
    }
    const sender = event.senderFrame;
    const url = sender.url;
    if (!url || url === "about:blank") {
      return true;
    }
    let host = "unknown";
    try {
      host = new URL(url).host;
    } catch (error) {
      $ab(`Refused to handle ipcMain event for channel '${channel}' because of a malformed URL '${url}'.`);
      return false;
    }
    if (host !== $gh) {
      $ab(`Refused to handle ipcMain event for channel '${channel}' because of a bad origin of '${host}'.`);
      return false;
    }
    if (sender.parent !== null) {
      $ab(`Refused to handle ipcMain event for channel '${channel}' because sender of origin '${host}' is not a main frame.`);
      return false;
    }
    return true;
  }
};
var $ZY = new ValidatedIpcMain();

// out-build/vs/code/electron-main/app.js
import { hostname as hostname2, release as release7 } from "os";

// out-build/vs/base/common/jsonc.js
var module3 = { exports: {} };
(function() {
  const isESM = true;
  function factory() {
    const regexp = /("[^"\\]*(?:\\.[^"\\]*)*")|('[^'\\]*(?:\\.[^'\\]*)*')|(\/\*[^\/\*]*(?:(?:\*|\/)[^\/\*]*)*?\*\/)|(\/{2,}.*?(?:(?:\r?\n)|$))|(,\s*[}\]])/g;
    function stripComments2(content) {
      return content.replace(regexp, function(match, _m1, _m2, m3, m4, m5) {
        if (m3) {
          return "";
        } else if (m4) {
          const length = m4.length;
          if (m4[length - 1] === "\n") {
            return m4[length - 2] === "\r" ? "\r\n" : "\n";
          } else {
            return "";
          }
        } else if (m5) {
          return match.substring(1);
        } else {
          return match;
        }
      });
    }
    function parse3(content) {
      const commentsStripped = stripComments2(content);
      try {
        return JSON.parse(commentsStripped);
      } catch (error) {
        const trailingCommasStriped = commentsStripped.replace(/,\s*([}\]])/g, "$1");
        return JSON.parse(trailingCommasStriped);
      }
    }
    return {
      stripComments: stripComments2,
      parse: parse3
    };
  }
  if (!isESM && typeof define === "function") {
    define([], function() {
      return factory();
    });
  } else if (typeof module3 === "object" && typeof module3.exports === "object") {
    module3.exports = factory();
  } else {
    console.trace("jsonc defined in UNKNOWN context (neither requirejs or commonjs)");
  }
})();
var stripComments = module3.exports.stripComments;
var parse = module3.exports.parse;

// out-build/vs/base/parts/contextmenu/electron-main/contextmenu.js
import { Menu, MenuItem } from "electron";

// out-build/vs/base/parts/contextmenu/common/contextmenu.js
var $XY = "vscode:contextmenu";
var $YY = "vscode:onCloseContextMenu";

// out-build/vs/base/parts/contextmenu/electron-main/contextmenu.js
function $1Y() {
  $ZY.on($XY, (event, contextMenuId, items, onClickChannel, options) => {
    const menu = createMenu(event, onClickChannel, items);
    menu.popup({
      x: options ? options.x : void 0,
      y: options ? options.y : void 0,
      positioningItem: options ? options.positioningItem : void 0,
      callback: () => {
        if (menu) {
          event.sender.send($YY, contextMenuId);
        }
      }
    });
  });
}
function createMenu(event, onClickChannel, items) {
  const menu = new Menu();
  items.forEach((item) => {
    let menuitem;
    if (item.type === "separator") {
      menuitem = new MenuItem({
        type: item.type
      });
    } else if (Array.isArray(item.submenu)) {
      menuitem = new MenuItem({
        submenu: createMenu(event, onClickChannel, item.submenu),
        label: item.label
      });
    } else {
      menuitem = new MenuItem({
        label: item.label,
        type: item.type,
        accelerator: item.accelerator,
        checked: item.checked,
        enabled: item.enabled,
        visible: item.visible,
        click: (menuItem, win, contextmenuEvent) => event.sender.send(onClickChannel, item.id, contextmenuEvent)
      });
    }
    menu.append(menuitem);
  });
  return menu;
}

// out-build/vs/base/parts/ipc/common/ipc.electron.js
var $6Y = class {
  constructor(a, onMessage) {
    this.a = a;
    this.onMessage = onMessage;
  }
  send(message) {
    try {
      this.a.send("vscode:message", message.buffer);
    } catch (e) {
    }
  }
  disconnect() {
    this.a.send("vscode:disconnect", null);
  }
};

// out-build/vs/base/parts/ipc/electron-main/ipc.electron.js
function createScopedOnMessageEvent(senderId, eventName) {
  const onMessage = Event.fromNodeEventEmitter($ZY, eventName, (event, message) => ({ event, message }));
  const onMessageFromSender = Event.filter(onMessage, ({ event }) => event.sender.id === senderId);
  return Event.map(onMessageFromSender, ({ message }) => message ? $7e.wrap(message) : message);
}
var $7Y = class _$7Y extends $Di {
  static {
    this.b = /* @__PURE__ */ new Map();
  }
  static d() {
    const onHello = Event.fromNodeEventEmitter($ZY, "vscode:hello", ({ sender }) => sender);
    return Event.map(onHello, (webContents3) => {
      const id2 = webContents3.id;
      const client = _$7Y.b.get(id2);
      client?.dispose();
      const onDidClientReconnect = new $De();
      _$7Y.b.set(id2, $8c(() => onDidClientReconnect.fire()));
      const onMessage = createScopedOnMessageEvent(id2, "vscode:message");
      const onDidClientDisconnect = Event.any(Event.signal(createScopedOnMessageEvent(id2, "vscode:disconnect")), onDidClientReconnect.event);
      const protocol3 = new $6Y(webContents3, onMessage);
      return { protocol: protocol3, onDidClientDisconnect };
    });
  }
  constructor() {
    super(_$7Y.d());
  }
};

// out-build/vs/base/parts/ipc/common/ipc.mp.js
var $3Y = class {
  constructor(a) {
    this.a = a;
    this.onMessage = Event.fromDOMEventEmitter(this.a, "message", (e) => {
      if (e.data) {
        return $7e.wrap(e.data);
      }
      return $7e.alloc(0);
    });
    a.start();
  }
  send(message) {
    this.a.postMessage(message.buffer);
  }
  disconnect() {
    this.a.close();
  }
};
var $4Y = class extends $Ei {
  constructor(port, clientId) {
    const protocol3 = new $3Y(port);
    super(protocol3, clientId);
    this.b = protocol3;
  }
  dispose() {
    this.b.disconnect();
    super.dispose();
  }
};

// out-build/vs/base/parts/ipc/electron-main/ipc.mp.js
var $8Y = class extends $4Y {
  /**
   * @param clientId a way to uniquely identify this client among
   * other clients. this is important for routing because every
   * client can also be a server
   */
  constructor(port, clientId) {
    super({
      addEventListener: (type4, listener) => port.addListener(type4, listener),
      removeEventListener: (type4, listener) => port.removeListener(type4, listener),
      postMessage: (message) => port.postMessage(message),
      start: () => port.start(),
      close: () => port.close()
    }, clientId);
  }
};

// out-build/vs/platform/native/electron-main/auth.js
import { app } from "electron";

// out-build/vs/base/common/hash.js
function $Nj(obj) {
  return $Oj(obj, 0);
}
function $Oj(obj, hashVal) {
  switch (typeof obj) {
    case "object":
      if (obj === null) {
        return $Pj(349, hashVal);
      } else if (Array.isArray(obj)) {
        return arrayHash(obj, hashVal);
      }
      return objectHash(obj, hashVal);
    case "string":
      return $Qj(obj, hashVal);
    case "boolean":
      return booleanHash(obj, hashVal);
    case "number":
      return $Pj(obj, hashVal);
    case "undefined":
      return $Pj(937, hashVal);
    default:
      return $Pj(617, hashVal);
  }
}
function $Pj(val, initialHashVal) {
  return (initialHashVal << 5) - initialHashVal + val | 0;
}
function booleanHash(b, initialHashVal) {
  return $Pj(b ? 433 : 863, initialHashVal);
}
function $Qj(s, hashVal) {
  hashVal = $Pj(149417, hashVal);
  for (let i = 0, length = s.length; i < length; i++) {
    hashVal = $Pj(s.charCodeAt(i), hashVal);
  }
  return hashVal;
}
function arrayHash(arr, initialHashVal) {
  initialHashVal = $Pj(104579, initialHashVal);
  return arr.reduce((hashVal, item) => $Oj(item, hashVal), initialHashVal);
}
function objectHash(obj, initialHashVal) {
  initialHashVal = $Pj(181387, initialHashVal);
  return Object.keys(obj).sort().reduce((hashVal, key) => {
    hashVal = $Qj(key, hashVal);
    return $Oj(obj[key], hashVal);
  }, initialHashVal);
}
var SHA1Constant;
(function(SHA1Constant2) {
  SHA1Constant2[SHA1Constant2["BLOCK_SIZE"] = 64] = "BLOCK_SIZE";
  SHA1Constant2[SHA1Constant2["UNICODE_REPLACEMENT"] = 65533] = "UNICODE_REPLACEMENT";
})(SHA1Constant || (SHA1Constant = {}));
function leftRotate(value, bits, totalBits = 32) {
  const delta = totalBits - bits;
  const mask = ~((1 << delta) - 1);
  return (value << bits | (mask & value) >>> delta) >>> 0;
}
function fill(dest, index = 0, count = dest.byteLength, value = 0) {
  for (let i = 0; i < count; i++) {
    dest[index + i] = value;
  }
}
function leftPad(value, length, char = "0") {
  while (value.length < length) {
    value = char + value;
  }
  return value;
}
function $Sj(bufferOrValue, bitsize = 32) {
  if (bufferOrValue instanceof ArrayBuffer) {
    return Array.from(new Uint8Array(bufferOrValue)).map((b) => b.toString(16).padStart(2, "0")).join("");
  }
  return leftPad((bufferOrValue >>> 0).toString(16), bitsize / 4);
}
var $Tj = class _$Tj {
  static {
    this.g = new DataView(new ArrayBuffer(320));
  }
  // 80 * 4 = 320
  constructor() {
    this.h = 1732584193;
    this.l = 4023233417;
    this.m = 2562383102;
    this.n = 271733878;
    this.o = 3285377520;
    this.p = new Uint8Array(
      64 + 3
      /* to fit any utf-8 */
    );
    this.q = new DataView(this.p.buffer);
    this.r = 0;
    this.t = 0;
    this.u = 0;
    this.v = false;
  }
  update(str) {
    const strLen = str.length;
    if (strLen === 0) {
      return;
    }
    const buff = this.p;
    let buffLen = this.r;
    let leftoverHighSurrogate = this.u;
    let charCode;
    let offset;
    if (leftoverHighSurrogate !== 0) {
      charCode = leftoverHighSurrogate;
      offset = -1;
      leftoverHighSurrogate = 0;
    } else {
      charCode = str.charCodeAt(0);
      offset = 0;
    }
    while (true) {
      let codePoint = charCode;
      if ($4f(charCode)) {
        if (offset + 1 < strLen) {
          const nextCharCode = str.charCodeAt(offset + 1);
          if ($5f(nextCharCode)) {
            offset++;
            codePoint = $6f(charCode, nextCharCode);
          } else {
            codePoint = 65533;
          }
        } else {
          leftoverHighSurrogate = charCode;
          break;
        }
      } else if ($5f(charCode)) {
        codePoint = 65533;
      }
      buffLen = this.w(buff, buffLen, codePoint);
      offset++;
      if (offset < strLen) {
        charCode = str.charCodeAt(offset);
      } else {
        break;
      }
    }
    this.r = buffLen;
    this.u = leftoverHighSurrogate;
  }
  w(buff, buffLen, codePoint) {
    if (codePoint < 128) {
      buff[buffLen++] = codePoint;
    } else if (codePoint < 2048) {
      buff[buffLen++] = 192 | (codePoint & 1984) >>> 6;
      buff[buffLen++] = 128 | (codePoint & 63) >>> 0;
    } else if (codePoint < 65536) {
      buff[buffLen++] = 224 | (codePoint & 61440) >>> 12;
      buff[buffLen++] = 128 | (codePoint & 4032) >>> 6;
      buff[buffLen++] = 128 | (codePoint & 63) >>> 0;
    } else {
      buff[buffLen++] = 240 | (codePoint & 1835008) >>> 18;
      buff[buffLen++] = 128 | (codePoint & 258048) >>> 12;
      buff[buffLen++] = 128 | (codePoint & 4032) >>> 6;
      buff[buffLen++] = 128 | (codePoint & 63) >>> 0;
    }
    if (buffLen >= 64) {
      this.y();
      buffLen -= 64;
      this.t += 64;
      buff[0] = buff[64 + 0];
      buff[1] = buff[64 + 1];
      buff[2] = buff[64 + 2];
    }
    return buffLen;
  }
  digest() {
    if (!this.v) {
      this.v = true;
      if (this.u) {
        this.u = 0;
        this.r = this.w(
          this.p,
          this.r,
          65533
          /* SHA1Constant.UNICODE_REPLACEMENT */
        );
      }
      this.t += this.r;
      this.x();
    }
    return $Sj(this.h) + $Sj(this.l) + $Sj(this.m) + $Sj(this.n) + $Sj(this.o);
  }
  x() {
    this.p[this.r++] = 128;
    fill(this.p, this.r);
    if (this.r > 56) {
      this.y();
      fill(this.p);
    }
    const ml = 8 * this.t;
    this.q.setUint32(56, Math.floor(ml / 4294967296), false);
    this.q.setUint32(60, ml % 4294967296, false);
    this.y();
  }
  y() {
    const bigBlock32 = _$Tj.g;
    const data = this.q;
    for (let j = 0; j < 64; j += 4) {
      bigBlock32.setUint32(j, data.getUint32(j, false), false);
    }
    for (let j = 64; j < 320; j += 4) {
      bigBlock32.setUint32(j, leftRotate(bigBlock32.getUint32(j - 12, false) ^ bigBlock32.getUint32(j - 32, false) ^ bigBlock32.getUint32(j - 56, false) ^ bigBlock32.getUint32(j - 64, false), 1), false);
    }
    let a = this.h;
    let b = this.l;
    let c = this.m;
    let d = this.n;
    let e = this.o;
    let f, k;
    let temp;
    for (let j = 0; j < 80; j++) {
      if (j < 20) {
        f = b & c | ~b & d;
        k = 1518500249;
      } else if (j < 40) {
        f = b ^ c ^ d;
        k = 1859775393;
      } else if (j < 60) {
        f = b & c | b & d | c & d;
        k = 2400959708;
      } else {
        f = b ^ c ^ d;
        k = 3395469782;
      }
      temp = leftRotate(a, 5) + f + e + k + bigBlock32.getUint32(j * 4, false) & 4294967295;
      e = d;
      d = c;
      c = leftRotate(b, 30);
      b = a;
      a = temp;
    }
    this.h = this.h + a & 4294967295;
    this.l = this.l + b & 4294967295;
    this.m = this.m + c & 4294967295;
    this.n = this.n + d & 4294967295;
    this.o = this.o + e & 4294967295;
  }
};

// out-build/vs/platform/encryption/common/encryptionService.js
var $HZ = $Zi("encryptionService");
var $IZ = $Zi("encryptionMainService");
var PasswordStoreCLIOption;
(function(PasswordStoreCLIOption2) {
  PasswordStoreCLIOption2["kwallet"] = "kwallet";
  PasswordStoreCLIOption2["kwallet5"] = "kwallet5";
  PasswordStoreCLIOption2["gnomeLibsecret"] = "gnome-libsecret";
  PasswordStoreCLIOption2["basic"] = "basic";
})(PasswordStoreCLIOption || (PasswordStoreCLIOption = {}));
var KnownStorageProvider;
(function(KnownStorageProvider2) {
  KnownStorageProvider2["unknown"] = "unknown";
  KnownStorageProvider2["basicText"] = "basic_text";
  KnownStorageProvider2["gnomeAny"] = "gnome_any";
  KnownStorageProvider2["gnomeLibsecret"] = "gnome_libsecret";
  KnownStorageProvider2["gnomeKeyring"] = "gnome_keyring";
  KnownStorageProvider2["kwallet"] = "kwallet";
  KnownStorageProvider2["kwallet5"] = "kwallet5";
  KnownStorageProvider2["kwallet6"] = "kwallet6";
  KnownStorageProvider2["dplib"] = "dpapi";
  KnownStorageProvider2["keychainAccess"] = "keychain_access";
})(KnownStorageProvider || (KnownStorageProvider = {}));

// out-build/vs/platform/environment/common/environment.js
var $7i = $Zi("environmentService");
var $8i = $1i($7i);

// out-build/vs/platform/environment/node/environmentService.js
import { homedir, tmpdir as tmpdir3 } from "os";

// out-build/vs/base/common/date.js
var minute = 60;
var hour = minute * 60;
var day = hour * 24;
var week = day * 7;
var month = day * 30;
var year = day * 365;
function $mn(date) {
  return date.getFullYear() + "-" + String(date.getMonth() + 1).padStart(2, "0") + "-" + String(date.getDate()).padStart(2, "0") + "T" + String(date.getHours()).padStart(2, "0") + ":" + String(date.getMinutes()).padStart(2, "0") + ":" + String(date.getSeconds()).padStart(2, "0") + "." + (date.getMilliseconds() / 1e3).toFixed(3).slice(2, 5) + "Z";
}

// out-build/vs/platform/environment/common/environmentService.js
var $nn = /^([^.]+\..+)[:=](.+)$/;
var $on = class {
  get appRoot() {
    return $yc($hh.asFileUri("").fsPath);
  }
  get userHome() {
    return URI.file(this.b.homeDir);
  }
  get userDataPath() {
    return this.b.userDataDir;
  }
  get appSettingsHome() {
    return URI.file($vc(this.userDataPath, "User"));
  }
  get tmpDir() {
    return URI.file(this.b.tmpDir);
  }
  get cacheHome() {
    return URI.file(this.userDataPath);
  }
  get stateResource() {
    return $Ah(this.appSettingsHome, "globalStorage", "storage.json");
  }
  get userRoamingDataHome() {
    return this.appSettingsHome.with({ scheme: Schemas.vscodeUserData });
  }
  get userDataSyncHome() {
    return $Ah(this.appSettingsHome, "sync");
  }
  get logsHome() {
    if (!this.args.logsPath) {
      const key = $mn(/* @__PURE__ */ new Date()).replace(/-|:|\.\d+Z$/g, "");
      this.args.logsPath = $vc(this.userDataPath, "logs", key);
    }
    return URI.file(this.args.logsPath);
  }
  get sync() {
    return this.args.sync;
  }
  get machineSettingsResource() {
    return $Ah(URI.file($vc(this.userDataPath, "Machine")), "settings.json");
  }
  get workspaceStorageHome() {
    return $Ah(this.appSettingsHome, "workspaceStorage");
  }
  get localHistoryHome() {
    return $Ah(this.appSettingsHome, "History");
  }
  get keyboardLayoutResource() {
    return $Ah(this.userRoamingDataHome, "keyboardLayout.json");
  }
  get argvResource() {
    const vscodePortable = env["VSCODE_PORTABLE"];
    if (vscodePortable) {
      return URI.file($vc(vscodePortable, "argv.json"));
    }
    return $Ah(this.userHome, this.c.dataFolderName, "argv.json");
  }
  get isExtensionDevelopment() {
    return !!this.args.extensionDevelopmentPath;
  }
  get untitledWorkspacesHome() {
    return URI.file($vc(this.userDataPath, "Workspaces"));
  }
  get builtinExtensionsPath() {
    const cliBuiltinExtensionsDir = this.args["builtin-extensions-dir"];
    if (cliBuiltinExtensionsDir) {
      return $wc(cliBuiltinExtensionsDir);
    }
    return $tc($vc($hh.asFileUri("").fsPath, "..", "extensions"));
  }
  get extensionsDownloadLocation() {
    const cliExtensionsDownloadDir = this.args["extensions-download-dir"];
    if (cliExtensionsDownloadDir) {
      return URI.file($wc(cliExtensionsDownloadDir));
    }
    return URI.file($vc(this.userDataPath, "CachedExtensionVSIXs"));
  }
  get extensionsPath() {
    const cliExtensionsDir = this.args["extensions-dir"];
    if (cliExtensionsDir) {
      return $wc(cliExtensionsDir);
    }
    const vscodeExtensions = env["VSCODE_EXTENSIONS"];
    if (vscodeExtensions) {
      return vscodeExtensions;
    }
    const vscodePortable = env["VSCODE_PORTABLE"];
    if (vscodePortable) {
      return $vc(vscodePortable, "extensions");
    }
    return $Ah(this.userHome, this.c.dataFolderName, "extensions").fsPath;
  }
  get extensionDevelopmentLocationURI() {
    const extensionDevelopmentPaths = this.args.extensionDevelopmentPath;
    if (Array.isArray(extensionDevelopmentPaths)) {
      return extensionDevelopmentPaths.map((extensionDevelopmentPath) => {
        if (/^[^:/?#]+?:\/\//.test(extensionDevelopmentPath)) {
          return URI.parse(extensionDevelopmentPath);
        }
        return URI.file($tc(extensionDevelopmentPath));
      });
    }
    return void 0;
  }
  get extensionDevelopmentKind() {
    return this.args.extensionDevelopmentKind?.map((kind) => kind === "ui" || kind === "workspace" || kind === "web" ? kind : "workspace");
  }
  get extensionTestsLocationURI() {
    const extensionTestsPath = this.args.extensionTestsPath;
    if (extensionTestsPath) {
      if (/^[^:/?#]+?:\/\//.test(extensionTestsPath)) {
        return URI.parse(extensionTestsPath);
      }
      return URI.file($tc(extensionTestsPath));
    }
    return void 0;
  }
  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 debugExtensionHost() {
    return $pn(this.args, this.isBuilt);
  }
  get debugRenderer() {
    return !!this.args.debugRenderer;
  }
  get isBuilt() {
    return !env["VSCODE_DEV"];
  }
  get verbose() {
    return !!this.args.verbose;
  }
  get logLevel() {
    return this.args.log?.find((entry) => !$nn.test(entry));
  }
  get extensionLogLevel() {
    const result = [];
    for (const entry of this.args.log || []) {
      const matches = $nn.exec(entry);
      if (matches && matches[1] && matches[2]) {
        result.push([matches[1], matches[2]]);
      }
    }
    return result.length ? result : void 0;
  }
  get serviceMachineIdResource() {
    return $Ah(URI.file(this.userDataPath), "machineid");
  }
  get crashReporterId() {
    return this.args["crash-reporter-id"];
  }
  get crashReporterDirectory() {
    return this.args["crash-reporter-directory"];
  }
  get disableTelemetry() {
    return !!this.args["disable-telemetry"];
  }
  get disableWorkspaceTrust() {
    return !!this.args["disable-workspace-trust"];
  }
  get useInMemorySecretStorage() {
    return !!this.args["use-inmemory-secretstorage"];
  }
  get policyFile() {
    if (this.args["__enable-file-policy"]) {
      const vscodePortable = env["VSCODE_PORTABLE"];
      if (vscodePortable) {
        return URI.file($vc(vscodePortable, "policy.json"));
      }
      return $Ah(this.userHome, this.c.dataFolderName, "policy.json");
    }
    return void 0;
  }
  get continueOn() {
    return this.args["continueOn"];
  }
  set continueOn(value) {
    this.args["continueOn"] = value;
  }
  get args() {
    return this.a;
  }
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.editSessionId = this.args["editSessionId"];
  }
};
__decorate([
  $ri
], $on.prototype, "appRoot", null);
__decorate([
  $ri
], $on.prototype, "userHome", null);
__decorate([
  $ri
], $on.prototype, "userDataPath", null);
__decorate([
  $ri
], $on.prototype, "appSettingsHome", null);
__decorate([
  $ri
], $on.prototype, "tmpDir", null);
__decorate([
  $ri
], $on.prototype, "cacheHome", null);
__decorate([
  $ri
], $on.prototype, "stateResource", null);
__decorate([
  $ri
], $on.prototype, "userRoamingDataHome", null);
__decorate([
  $ri
], $on.prototype, "userDataSyncHome", null);
__decorate([
  $ri
], $on.prototype, "sync", null);
__decorate([
  $ri
], $on.prototype, "machineSettingsResource", null);
__decorate([
  $ri
], $on.prototype, "workspaceStorageHome", null);
__decorate([
  $ri
], $on.prototype, "localHistoryHome", null);
__decorate([
  $ri
], $on.prototype, "keyboardLayoutResource", null);
__decorate([
  $ri
], $on.prototype, "argvResource", null);
__decorate([
  $ri
], $on.prototype, "isExtensionDevelopment", null);
__decorate([
  $ri
], $on.prototype, "untitledWorkspacesHome", null);
__decorate([
  $ri
], $on.prototype, "builtinExtensionsPath", null);
__decorate([
  $ri
], $on.prototype, "extensionsPath", null);
__decorate([
  $ri
], $on.prototype, "extensionDevelopmentLocationURI", null);
__decorate([
  $ri
], $on.prototype, "extensionDevelopmentKind", null);
__decorate([
  $ri
], $on.prototype, "extensionTestsLocationURI", null);
__decorate([
  $ri
], $on.prototype, "debugExtensionHost", null);
__decorate([
  $ri
], $on.prototype, "logLevel", null);
__decorate([
  $ri
], $on.prototype, "extensionLogLevel", null);
__decorate([
  $ri
], $on.prototype, "serviceMachineIdResource", null);
__decorate([
  $ri
], $on.prototype, "disableTelemetry", null);
__decorate([
  $ri
], $on.prototype, "disableWorkspaceTrust", null);
__decorate([
  $ri
], $on.prototype, "useInMemorySecretStorage", null);
__decorate([
  $ri
], $on.prototype, "policyFile", null);
function $pn(args, isBuilt) {
  return $qn(args["inspect-extensions"], args["inspect-brk-extensions"], 5870, isBuilt, args.debugId, args.extensionEnvironment);
}
function $qn(debugArg, debugBrkArg, defaultBuildPort, isBuilt, debugId, environmentString) {
  const portStr = debugBrkArg || debugArg;
  const port = Number(portStr) || (!isBuilt ? defaultBuildPort : null);
  const brk = port ? Boolean(!!debugBrkArg) : false;
  let env2;
  if (environmentString) {
    try {
      env2 = JSON.parse(environmentString);
    } catch {
    }
  }
  return { port, break: brk, debugId, env: env2 };
}

// out-build/vs/platform/environment/node/userDataPath.js
import * as os from "os";
import * as path from "path";
var module4 = { exports: {} };
(function() {
  const isESM = true;
  function factory(path3, os6, cwd2) {
    function getUserDataPath2(cliArgs, productName) {
      const userDataPath = doGetUserDataPath(cliArgs, productName);
      const pathsToResolve = [userDataPath];
      if (!path3.isAbsolute(userDataPath)) {
        pathsToResolve.unshift(cwd2);
      }
      return path3.resolve(...pathsToResolve);
    }
    function doGetUserDataPath(cliArgs, productName) {
      if (process.env["VSCODE_DEV"]) {
        productName = "code-oss-dev";
      }
      const portablePath = process.env["VSCODE_PORTABLE"];
      if (portablePath) {
        return path3.join(portablePath, "user-data");
      }
      let appDataPath = process.env["VSCODE_APPDATA"];
      if (appDataPath) {
        return path3.join(appDataPath, productName);
      }
      const cliPath = cliArgs["user-data-dir"];
      if (cliPath) {
        return cliPath;
      }
      switch (process.platform) {
        case "win32":
          appDataPath = process.env["APPDATA"];
          if (!appDataPath) {
            const userProfile = process.env["USERPROFILE"];
            if (typeof userProfile !== "string") {
              throw new Error("Windows: Unexpected undefined %USERPROFILE% environment variable");
            }
            appDataPath = path3.join(userProfile, "AppData", "Roaming");
          }
          break;
        case "darwin":
          appDataPath = path3.join(os6.homedir(), "Library", "Application Support");
          break;
        case "linux":
          appDataPath = process.env["XDG_CONFIG_HOME"] || path3.join(os6.homedir(), ".config");
          break;
        default:
          throw new Error("Platform not supported");
      }
      return path3.join(appDataPath, productName);
    }
    return {
      getUserDataPath: getUserDataPath2
    };
  }
  if (!isESM && typeof define === "function") {
    define(["path", "os", "vs/base/common/process"], function(path3, os6, process2) {
      return factory(path3, os6, process2.cwd());
    });
  } else if (typeof module4 === "object" && typeof module4.exports === "object") {
    module4.exports = factory(path, os, process.env["VSCODE_CWD"] || process.cwd());
  } else {
    throw new Error("Unknown context");
  }
})();
var getUserDataPath = module4.exports.getUserDataPath;

// out-build/vs/platform/environment/node/environmentService.js
var $rn = class extends $on {
  constructor(args, productService) {
    super(args, {
      homeDir: homedir(),
      tmpDir: tmpdir3(),
      userDataDir: getUserDataPath(args, productService.nameShort)
    }, productService);
  }
};
function $sn(args, isBuilt) {
  return $qn(args["inspect-ptyhost"], args["inspect-brk-ptyhost"], 5877, isBuilt, args.extensionEnvironment);
}
function $tn(args, isBuilt) {
  return $qn(args["inspect-sharedprocess"], args["inspect-brk-sharedprocess"], 5879, isBuilt, args.extensionEnvironment);
}

// out-build/vs/platform/environment/electron-main/environmentMainService.js
var $Cjc = $1i($7i);
var $Djc = class extends $rn {
  constructor() {
    super(...arguments);
    this.d = {};
  }
  get backupHome() {
    return $vc(this.userDataPath, "Backups");
  }
  get mainIPCHandle() {
    return $Si(this.userDataPath, "main", this.c.version);
  }
  get mainLockfile() {
    return $vc(this.userDataPath, "code.lock");
  }
  get disableUpdates() {
    return !!this.args["disable-updates"];
  }
  get crossOriginIsolated() {
    return !!this.args["enable-coi"];
  }
  get codeCachePath() {
    return process.env["VSCODE_CODE_CACHE_PATH"] || void 0;
  }
  get useCodeCache() {
    return !!this.codeCachePath;
  }
  unsetSnapExportedVariables() {
    if (!$n) {
      return;
    }
    for (const key in process.env) {
      if (key.endsWith("_VSCODE_SNAP_ORIG")) {
        const originalKey = key.slice(0, -17);
        if (this.d[originalKey]) {
          continue;
        }
        if (process.env[originalKey]) {
          this.d[originalKey] = process.env[originalKey];
        }
        if (process.env[key]) {
          process.env[originalKey] = process.env[key];
        } else {
          delete process.env[originalKey];
        }
      }
    }
  }
  restoreSnapExportedVariables() {
    if (!$n) {
      return;
    }
    for (const key in this.d) {
      process.env[key] = this.d[key];
      delete this.d[key];
    }
  }
};
__decorate([
  $ri
], $Djc.prototype, "backupHome", null);
__decorate([
  $ri
], $Djc.prototype, "mainIPCHandle", null);
__decorate([
  $ri
], $Djc.prototype, "mainLockfile", null);
__decorate([
  $ri
], $Djc.prototype, "disableUpdates", null);
__decorate([
  $ri
], $Djc.prototype, "crossOriginIsolated", null);
__decorate([
  $ri
], $Djc.prototype, "codeCachePath", null);
__decorate([
  $ri
], $Djc.prototype, "useCodeCache", null);

// out-build/vs/platform/contextkey/common/scanner.js
var TokenType;
(function(TokenType2) {
  TokenType2[TokenType2["LParen"] = 0] = "LParen";
  TokenType2[TokenType2["RParen"] = 1] = "RParen";
  TokenType2[TokenType2["Neg"] = 2] = "Neg";
  TokenType2[TokenType2["Eq"] = 3] = "Eq";
  TokenType2[TokenType2["NotEq"] = 4] = "NotEq";
  TokenType2[TokenType2["Lt"] = 5] = "Lt";
  TokenType2[TokenType2["LtEq"] = 6] = "LtEq";
  TokenType2[TokenType2["Gt"] = 7] = "Gt";
  TokenType2[TokenType2["GtEq"] = 8] = "GtEq";
  TokenType2[TokenType2["RegexOp"] = 9] = "RegexOp";
  TokenType2[TokenType2["RegexStr"] = 10] = "RegexStr";
  TokenType2[TokenType2["True"] = 11] = "True";
  TokenType2[TokenType2["False"] = 12] = "False";
  TokenType2[TokenType2["In"] = 13] = "In";
  TokenType2[TokenType2["Not"] = 14] = "Not";
  TokenType2[TokenType2["And"] = 15] = "And";
  TokenType2[TokenType2["Or"] = 16] = "Or";
  TokenType2[TokenType2["Str"] = 17] = "Str";
  TokenType2[TokenType2["QuotedStr"] = 18] = "QuotedStr";
  TokenType2[TokenType2["Error"] = 19] = "Error";
  TokenType2[TokenType2["EOF"] = 20] = "EOF";
})(TokenType || (TokenType = {}));
function hintDidYouMean(...meant) {
  switch (meant.length) {
    case 1:
      return localize(1703, null, meant[0]);
    case 2:
      return localize(1704, null, meant[0], meant[1]);
    case 3:
      return localize(1705, null, meant[0], meant[1], meant[2]);
    default:
      return void 0;
  }
}
var hintDidYouForgetToOpenOrCloseQuote = localize(1706, null);
var hintDidYouForgetToEscapeSlash = localize(1707, null);
var $Uj = class _$Uj {
  constructor() {
    this.c = "";
    this.d = 0;
    this.e = 0;
    this.f = [];
    this.g = [];
    this.m = /[a-zA-Z0-9_<>\-\./\\:\*\?\+\[\]\^,#@;"%\$\p{L}-]+/uy;
  }
  static getLexeme(token) {
    switch (token.type) {
      case 0:
        return "(";
      case 1:
        return ")";
      case 2:
        return "!";
      case 3:
        return token.isTripleEq ? "===" : "==";
      case 4:
        return token.isTripleEq ? "!==" : "!=";
      case 5:
        return "<";
      case 6:
        return "<=";
      case 7:
        return ">=";
      case 8:
        return ">=";
      case 9:
        return "=~";
      case 10:
        return token.lexeme;
      case 11:
        return "true";
      case 12:
        return "false";
      case 13:
        return "in";
      case 14:
        return "not";
      case 15:
        return "&&";
      case 16:
        return "||";
      case 17:
        return token.lexeme;
      case 18:
        return token.lexeme;
      case 19:
        return token.lexeme;
      case 20:
        return "EOF";
      default:
        throw $ib(`unhandled token type: ${JSON.stringify(token)}; have you forgotten to add a case?`);
    }
  }
  static {
    this.a = new Set(["i", "g", "s", "m", "y", "u"].map((ch) => ch.charCodeAt(0)));
  }
  static {
    this.b = /* @__PURE__ */ new Map([
      [
        "not",
        14
        /* TokenType.Not */
      ],
      [
        "in",
        13
        /* TokenType.In */
      ],
      [
        "false",
        12
        /* TokenType.False */
      ],
      [
        "true",
        11
        /* TokenType.True */
      ]
    ]);
  }
  get errors() {
    return this.g;
  }
  reset(value) {
    this.c = value;
    this.d = 0;
    this.e = 0;
    this.f = [];
    this.g = [];
    return this;
  }
  scan() {
    while (!this.r()) {
      this.d = this.e;
      const ch = this.i();
      switch (ch) {
        case 40:
          this.k(
            0
            /* TokenType.LParen */
          );
          break;
        case 41:
          this.k(
            1
            /* TokenType.RParen */
          );
          break;
        case 33:
          if (this.h(
            61
            /* CharCode.Equals */
          )) {
            const isTripleEq = this.h(
              61
              /* CharCode.Equals */
            );
            this.f.push({ type: 4, offset: this.d, isTripleEq });
          } else {
            this.k(
              2
              /* TokenType.Neg */
            );
          }
          break;
        case 39:
          this.o();
          break;
        case 47:
          this.q();
          break;
        case 61:
          if (this.h(
            61
            /* CharCode.Equals */
          )) {
            const isTripleEq = this.h(
              61
              /* CharCode.Equals */
            );
            this.f.push({ type: 3, offset: this.d, isTripleEq });
          } else if (this.h(
            126
            /* CharCode.Tilde */
          )) {
            this.k(
              9
              /* TokenType.RegexOp */
            );
          } else {
            this.l(hintDidYouMean("==", "=~"));
          }
          break;
        case 60:
          this.k(
            this.h(
              61
              /* CharCode.Equals */
            ) ? 6 : 5
            /* TokenType.Lt */
          );
          break;
        case 62:
          this.k(
            this.h(
              61
              /* CharCode.Equals */
            ) ? 8 : 7
            /* TokenType.Gt */
          );
          break;
        case 38:
          if (this.h(
            38
            /* CharCode.Ampersand */
          )) {
            this.k(
              15
              /* TokenType.And */
            );
          } else {
            this.l(hintDidYouMean("&&"));
          }
          break;
        case 124:
          if (this.h(
            124
            /* CharCode.Pipe */
          )) {
            this.k(
              16
              /* TokenType.Or */
            );
          } else {
            this.l(hintDidYouMean("||"));
          }
          break;
        case 32:
        case 13:
        case 9:
        case 10:
        case 160:
          break;
        default:
          this.n();
      }
    }
    this.d = this.e;
    this.k(
      20
      /* TokenType.EOF */
    );
    return Array.from(this.f);
  }
  h(expected) {
    if (this.r()) {
      return false;
    }
    if (this.c.charCodeAt(this.e) !== expected) {
      return false;
    }
    this.e++;
    return true;
  }
  i() {
    return this.c.charCodeAt(this.e++);
  }
  j() {
    return this.r() ? 0 : this.c.charCodeAt(this.e);
  }
  k(type4) {
    this.f.push({ type: type4, offset: this.d });
  }
  l(additional) {
    const offset = this.d;
    const lexeme = this.c.substring(this.d, this.e);
    const errToken = { type: 19, offset: this.d, lexeme };
    this.g.push({ offset, lexeme, additionalInfo: additional });
    this.f.push(errToken);
  }
  n() {
    this.m.lastIndex = this.d;
    const match = this.m.exec(this.c);
    if (match) {
      this.e = this.d + match[0].length;
      const lexeme = this.c.substring(this.d, this.e);
      const keyword = _$Uj.b.get(lexeme);
      if (keyword) {
        this.k(keyword);
      } else {
        this.f.push({ type: 17, lexeme, offset: this.d });
      }
    }
  }
  // captures the lexeme without the leading and trailing '
  o() {
    while (this.j() !== 39 && !this.r()) {
      this.i();
    }
    if (this.r()) {
      this.l(hintDidYouForgetToOpenOrCloseQuote);
      return;
    }
    this.i();
    this.f.push({ type: 18, lexeme: this.c.substring(this.d + 1, this.e - 1), offset: this.d + 1 });
  }
  /*
   * Lexing a regex expression: /.../[igsmyu]*
   * Based on https://github.com/microsoft/TypeScript/blob/9247ef115e617805983740ba795d7a8164babf89/src/compiler/scanner.ts#L2129-L2181
   *
   * Note that we want slashes within a regex to be escaped, e.g., /file:\\/\\/\\// should match `file:///`
   */
  q() {
    let p = this.e;
    let inEscape = false;
    let inCharacterClass = false;
    while (true) {
      if (p >= this.c.length) {
        this.e = p;
        this.l(hintDidYouForgetToEscapeSlash);
        return;
      }
      const ch = this.c.charCodeAt(p);
      if (inEscape) {
        inEscape = false;
      } else if (ch === 47 && !inCharacterClass) {
        p++;
        break;
      } else if (ch === 91) {
        inCharacterClass = true;
      } else if (ch === 92) {
        inEscape = true;
      } else if (ch === 93) {
        inCharacterClass = false;
      }
      p++;
    }
    while (p < this.c.length && _$Uj.a.has(this.c.charCodeAt(p))) {
      p++;
    }
    this.e = p;
    const lexeme = this.c.substring(this.d, this.e);
    this.f.push({ type: 10, lexeme, offset: this.d });
  }
  r() {
    return this.e >= this.c.length;
  }
};

// out-build/vs/platform/contextkey/common/contextkey.js
var CONSTANT_VALUES = /* @__PURE__ */ new Map();
CONSTANT_VALUES.set("false", false);
CONSTANT_VALUES.set("true", true);
CONSTANT_VALUES.set("isMac", $m);
CONSTANT_VALUES.set("isLinux", $n);
CONSTANT_VALUES.set("isWindows", $l);
CONSTANT_VALUES.set("isWeb", $r);
CONSTANT_VALUES.set("isMacNative", $m && !$r);
CONSTANT_VALUES.set("isEdge", $K);
CONSTANT_VALUES.set("isFirefox", $I);
CONSTANT_VALUES.set("isChrome", $H);
CONSTANT_VALUES.set("isSafari", $J);
var hasOwnProperty2 = Object.prototype.hasOwnProperty;
var ContextKeyExprType;
(function(ContextKeyExprType2) {
  ContextKeyExprType2[ContextKeyExprType2["False"] = 0] = "False";
  ContextKeyExprType2[ContextKeyExprType2["True"] = 1] = "True";
  ContextKeyExprType2[ContextKeyExprType2["Defined"] = 2] = "Defined";
  ContextKeyExprType2[ContextKeyExprType2["Not"] = 3] = "Not";
  ContextKeyExprType2[ContextKeyExprType2["Equals"] = 4] = "Equals";
  ContextKeyExprType2[ContextKeyExprType2["NotEquals"] = 5] = "NotEquals";
  ContextKeyExprType2[ContextKeyExprType2["And"] = 6] = "And";
  ContextKeyExprType2[ContextKeyExprType2["Regex"] = 7] = "Regex";
  ContextKeyExprType2[ContextKeyExprType2["NotRegex"] = 8] = "NotRegex";
  ContextKeyExprType2[ContextKeyExprType2["Or"] = 9] = "Or";
  ContextKeyExprType2[ContextKeyExprType2["In"] = 10] = "In";
  ContextKeyExprType2[ContextKeyExprType2["NotIn"] = 11] = "NotIn";
  ContextKeyExprType2[ContextKeyExprType2["Greater"] = 12] = "Greater";
  ContextKeyExprType2[ContextKeyExprType2["GreaterEquals"] = 13] = "GreaterEquals";
  ContextKeyExprType2[ContextKeyExprType2["Smaller"] = 14] = "Smaller";
  ContextKeyExprType2[ContextKeyExprType2["SmallerEquals"] = 15] = "SmallerEquals";
})(ContextKeyExprType || (ContextKeyExprType = {}));
var defaultConfig = {
  regexParsingWithErrorRecovery: true
};
var errorEmptyString = localize(1683, null);
var hintEmptyString = localize(1684, null);
var errorNoInAfterNot = localize(1685, null);
var errorClosingParenthesis = localize(1686, null);
var errorUnexpectedToken = localize(1687, null);
var hintUnexpectedToken = localize(1688, null);
var errorUnexpectedEOF = localize(1689, null);
var hintUnexpectedEOF = localize(1690, null);
var $Wj = class _$Wj {
  static {
    this.c = new Error();
  }
  get lexingErrors() {
    return this.d.errors;
  }
  get parsingErrors() {
    return this.h;
  }
  constructor(k = defaultConfig) {
    this.k = k;
    this.d = new $Uj();
    this.f = [];
    this.g = 0;
    this.h = [];
    this.v = /g|y/g;
  }
  /**
   * Parse a context key expression.
   *
   * @param input the expression to parse
   * @returns the parsed expression or `undefined` if there's an error - call `lexingErrors` and `parsingErrors` to see the errors
   */
  parse(input) {
    if (input === "") {
      this.h.push({ message: errorEmptyString, offset: 0, lexeme: "", additionalInfo: hintEmptyString });
      return void 0;
    }
    this.f = this.d.reset(input).scan();
    this.g = 0;
    this.h = [];
    try {
      const expr = this.l();
      if (!this.E()) {
        const peek = this.D();
        const additionalInfo = peek.type === 17 ? hintUnexpectedToken : void 0;
        this.h.push({ message: errorUnexpectedToken, offset: peek.offset, lexeme: $Uj.getLexeme(peek), additionalInfo });
        throw _$Wj.c;
      }
      return expr;
    } catch (e) {
      if (!(e === _$Wj.c)) {
        throw e;
      }
      return void 0;
    }
  }
  l() {
    return this.m();
  }
  m() {
    const expr = [this.o()];
    while (this.y(
      16
      /* TokenType.Or */
    )) {
      const right = this.o();
      expr.push(right);
    }
    return expr.length === 1 ? expr[0] : $Xj.or(...expr);
  }
  o() {
    const expr = [this.s()];
    while (this.y(
      15
      /* TokenType.And */
    )) {
      const right = this.s();
      expr.push(right);
    }
    return expr.length === 1 ? expr[0] : $Xj.and(...expr);
  }
  s() {
    if (this.y(
      2
      /* TokenType.Neg */
    )) {
      const peek = this.D();
      switch (peek.type) {
        case 11:
          this.z();
          return $1j.INSTANCE;
        case 12:
          this.z();
          return $2j.INSTANCE;
        case 0: {
          this.z();
          const expr = this.l();
          this.A(1, errorClosingParenthesis);
          return expr?.negate();
        }
        case 17:
          this.z();
          return $8j.create(peek.lexeme);
        default:
          throw this.B(`KEY | true | false | '(' expression ')'`, peek);
      }
    }
    return this.t();
  }
  t() {
    const peek = this.D();
    switch (peek.type) {
      case 11:
        this.z();
        return $Xj.true();
      case 12:
        this.z();
        return $Xj.false();
      case 0: {
        this.z();
        const expr = this.l();
        this.A(1, errorClosingParenthesis);
        return expr;
      }
      case 17: {
        const key = peek.lexeme;
        this.z();
        if (this.y(
          9
          /* TokenType.RegexOp */
        )) {
          const expr = this.D();
          if (!this.k.regexParsingWithErrorRecovery) {
            this.z();
            if (expr.type !== 10) {
              throw this.B(`REGEX`, expr);
            }
            const regexLexeme = expr.lexeme;
            const closingSlashIndex = regexLexeme.lastIndexOf("/");
            const flags = closingSlashIndex === regexLexeme.length - 1 ? void 0 : this.w(regexLexeme.substring(closingSlashIndex + 1));
            let regexp;
            try {
              regexp = new RegExp(regexLexeme.substring(1, closingSlashIndex), flags);
            } catch (e) {
              throw this.B(`REGEX`, expr);
            }
            return $ak.create(key, regexp);
          }
          switch (expr.type) {
            case 10:
            case 19: {
              const lexemeReconstruction = [expr.lexeme];
              this.z();
              let followingToken = this.D();
              let parenBalance = 0;
              for (let i = 0; i < expr.lexeme.length; i++) {
                if (expr.lexeme.charCodeAt(i) === 40) {
                  parenBalance++;
                } else if (expr.lexeme.charCodeAt(i) === 41) {
                  parenBalance--;
                }
              }
              while (!this.E() && followingToken.type !== 15 && followingToken.type !== 16) {
                switch (followingToken.type) {
                  case 0:
                    parenBalance++;
                    break;
                  case 1:
                    parenBalance--;
                    break;
                  case 10:
                  case 18:
                    for (let i = 0; i < followingToken.lexeme.length; i++) {
                      if (followingToken.lexeme.charCodeAt(i) === 40) {
                        parenBalance++;
                      } else if (expr.lexeme.charCodeAt(i) === 41) {
                        parenBalance--;
                      }
                    }
                }
                if (parenBalance < 0) {
                  break;
                }
                lexemeReconstruction.push($Uj.getLexeme(followingToken));
                this.z();
                followingToken = this.D();
              }
              const regexLexeme = lexemeReconstruction.join("");
              const closingSlashIndex = regexLexeme.lastIndexOf("/");
              const flags = closingSlashIndex === regexLexeme.length - 1 ? void 0 : this.w(regexLexeme.substring(closingSlashIndex + 1));
              let regexp;
              try {
                regexp = new RegExp(regexLexeme.substring(1, closingSlashIndex), flags);
              } catch (e) {
                throw this.B(`REGEX`, expr);
              }
              return $Xj.regex(key, regexp);
            }
            case 18: {
              const serializedValue = expr.lexeme;
              this.z();
              let regex = null;
              if (!$vf(serializedValue)) {
                const start = serializedValue.indexOf("/");
                const end = serializedValue.lastIndexOf("/");
                if (start !== end && start >= 0) {
                  const value = serializedValue.slice(start + 1, end);
                  const caseIgnoreFlag = serializedValue[end + 1] === "i" ? "i" : "";
                  try {
                    regex = new RegExp(value, caseIgnoreFlag);
                  } catch (_e) {
                    throw this.B(`REGEX`, expr);
                  }
                }
              }
              if (regex === null) {
                throw this.B("REGEX", expr);
              }
              return $ak.create(key, regex);
            }
            default:
              throw this.B("REGEX", this.D());
          }
        }
        if (this.y(
          14
          /* TokenType.Not */
        )) {
          this.A(13, errorNoInAfterNot);
          const right = this.u();
          return $Xj.notIn(key, right);
        }
        const maybeOp = this.D().type;
        switch (maybeOp) {
          case 3: {
            this.z();
            const right = this.u();
            if (this.x().type === 18) {
              return $Xj.equals(key, right);
            }
            switch (right) {
              case "true":
                return $Xj.has(key);
              case "false":
                return $Xj.not(key);
              default:
                return $Xj.equals(key, right);
            }
          }
          case 4: {
            this.z();
            const right = this.u();
            if (this.x().type === 18) {
              return $Xj.notEquals(key, right);
            }
            switch (right) {
              case "true":
                return $Xj.not(key);
              case "false":
                return $Xj.has(key);
              default:
                return $Xj.notEquals(key, right);
            }
          }
          case 5:
            this.z();
            return $$j.create(key, this.u());
          case 6:
            this.z();
            return $_j.create(key, this.u());
          case 7:
            this.z();
            return $9j.create(key, this.u());
          case 8:
            this.z();
            return $0j.create(key, this.u());
          case 13:
            this.z();
            return $Xj.in(key, this.u());
          default:
            return $Xj.has(key);
        }
      }
      case 20:
        this.h.push({ message: errorUnexpectedEOF, offset: peek.offset, lexeme: "", additionalInfo: hintUnexpectedEOF });
        throw _$Wj.c;
      default:
        throw this.B(`true | false | KEY 
	| KEY '=~' REGEX 
	| KEY ('==' | '!=' | '<' | '<=' | '>' | '>=' | 'in' | 'not' 'in') value`, this.D());
    }
  }
  u() {
    const token = this.D();
    switch (token.type) {
      case 17:
      case 18:
        this.z();
        return token.lexeme;
      case 11:
        this.z();
        return "true";
      case 12:
        this.z();
        return "false";
      case 13:
        this.z();
        return "in";
      default:
        return "";
    }
  }
  w(flags) {
    return flags.replaceAll(this.v, "");
  }
  // careful: this can throw if current token is the initial one (ie index = 0)
  x() {
    return this.f[this.g - 1];
  }
  y(token) {
    if (this.C(token)) {
      this.z();
      return true;
    }
    return false;
  }
  z() {
    if (!this.E()) {
      this.g++;
    }
    return this.x();
  }
  A(type4, message) {
    if (this.C(type4)) {
      return this.z();
    }
    throw this.B(message, this.D());
  }
  B(expected, got, additionalInfo) {
    const message = localize(1691, null, expected, $Uj.getLexeme(got));
    const offset = got.offset;
    const lexeme = $Uj.getLexeme(got);
    this.h.push({ message, offset, lexeme, additionalInfo });
    return _$Wj.c;
  }
  C(type4) {
    return this.D().type === type4;
  }
  D() {
    return this.f[this.g];
  }
  E() {
    return this.D().type === 20;
  }
};
var $Xj = class {
  static false() {
    return $1j.INSTANCE;
  }
  static true() {
    return $2j.INSTANCE;
  }
  static has(key) {
    return $3j.create(key);
  }
  static equals(key, value) {
    return $4j.create(key, value);
  }
  static notEquals(key, value) {
    return $7j.create(key, value);
  }
  static regex(key, value) {
    return $ak.create(key, value);
  }
  static in(key, value) {
    return $5j.create(key, value);
  }
  static notIn(key, value) {
    return $6j.create(key, value);
  }
  static not(key) {
    return $8j.create(key);
  }
  static and(...expr) {
    return $ck.create(expr, null, true);
  }
  static or(...expr) {
    return $dk.create(expr, null, true);
  }
  static greater(key, value) {
    return $9j.create(key, value);
  }
  static greaterEquals(key, value) {
    return $0j.create(key, value);
  }
  static smaller(key, value) {
    return $$j.create(key, value);
  }
  static smallerEquals(key, value) {
    return $_j.create(key, value);
  }
  static {
    this.c = new $Wj({ regexParsingWithErrorRecovery: false });
  }
  static deserialize(serialized) {
    if (serialized === void 0 || serialized === null) {
      return void 0;
    }
    const expr = this.c.parse(serialized);
    return expr;
  }
};
function cmp(a, b) {
  return a.cmp(b);
}
var $1j = class _$1j {
  static {
    this.INSTANCE = new _$1j();
  }
  constructor() {
    this.type = 0;
  }
  cmp(other) {
    return this.type - other.type;
  }
  equals(other) {
    return other.type === this.type;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    return false;
  }
  serialize() {
    return "false";
  }
  keys() {
    return [];
  }
  map(mapFnc) {
    return this;
  }
  negate() {
    return $2j.INSTANCE;
  }
};
var $2j = class _$2j {
  static {
    this.INSTANCE = new _$2j();
  }
  constructor() {
    this.type = 1;
  }
  cmp(other) {
    return this.type - other.type;
  }
  equals(other) {
    return other.type === this.type;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    return true;
  }
  serialize() {
    return "true";
  }
  keys() {
    return [];
  }
  map(mapFnc) {
    return this;
  }
  negate() {
    return $1j.INSTANCE;
  }
};
var $3j = class _$3j {
  static create(key, negated = null) {
    const constantValue = CONSTANT_VALUES.get(key);
    if (typeof constantValue === "boolean") {
      return constantValue ? $2j.INSTANCE : $1j.INSTANCE;
    }
    return new _$3j(key, negated);
  }
  constructor(key, c) {
    this.key = key;
    this.c = c;
    this.type = 2;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp1(this.key, other.key);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.key === other.key;
    }
    return false;
  }
  substituteConstants() {
    const constantValue = CONSTANT_VALUES.get(this.key);
    if (typeof constantValue === "boolean") {
      return constantValue ? $2j.INSTANCE : $1j.INSTANCE;
    }
    return this;
  }
  evaluate(context) {
    return !!context.getValue(this.key);
  }
  serialize() {
    return this.key;
  }
  keys() {
    return [this.key];
  }
  map(mapFnc) {
    return mapFnc.mapDefined(this.key);
  }
  negate() {
    if (!this.c) {
      this.c = $8j.create(this.key, this);
    }
    return this.c;
  }
};
var $4j = class _$4j {
  static create(key, value, negated = null) {
    if (typeof value === "boolean") {
      return value ? $3j.create(key, negated) : $8j.create(key, negated);
    }
    const constantValue = CONSTANT_VALUES.get(key);
    if (typeof constantValue === "boolean") {
      const trueValue = constantValue ? "true" : "false";
      return value === trueValue ? $2j.INSTANCE : $1j.INSTANCE;
    }
    return new _$4j(key, value, negated);
  }
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.type = 4;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.c, this.d, other.c, other.d);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.c === other.c && this.d === other.d;
    }
    return false;
  }
  substituteConstants() {
    const constantValue = CONSTANT_VALUES.get(this.c);
    if (typeof constantValue === "boolean") {
      const trueValue = constantValue ? "true" : "false";
      return this.d === trueValue ? $2j.INSTANCE : $1j.INSTANCE;
    }
    return this;
  }
  evaluate(context) {
    return context.getValue(this.c) == this.d;
  }
  serialize() {
    return `${this.c} == '${this.d}'`;
  }
  keys() {
    return [this.c];
  }
  map(mapFnc) {
    return mapFnc.mapEquals(this.c, this.d);
  }
  negate() {
    if (!this.f) {
      this.f = $7j.create(this.c, this.d, this);
    }
    return this.f;
  }
};
var $5j = class _$5j {
  static create(key, valueKey) {
    return new _$5j(key, valueKey);
  }
  constructor(d, f) {
    this.d = d;
    this.f = f;
    this.type = 10;
    this.c = null;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.d, this.f, other.d, other.f);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.d === other.d && this.f === other.f;
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    const source = context.getValue(this.f);
    const item = context.getValue(this.d);
    if (Array.isArray(source)) {
      return source.includes(item);
    }
    if (typeof item === "string" && typeof source === "object" && source !== null) {
      return hasOwnProperty2.call(source, item);
    }
    return false;
  }
  serialize() {
    return `${this.d} in '${this.f}'`;
  }
  keys() {
    return [this.d, this.f];
  }
  map(mapFnc) {
    return mapFnc.mapIn(this.d, this.f);
  }
  negate() {
    if (!this.c) {
      this.c = $6j.create(this.d, this.f);
    }
    return this.c;
  }
};
var $6j = class _$6j {
  static create(key, valueKey) {
    return new _$6j(key, valueKey);
  }
  constructor(d, f) {
    this.d = d;
    this.f = f;
    this.type = 11;
    this.c = $5j.create(d, f);
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return this.c.cmp(other.c);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.c.equals(other.c);
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    return !this.c.evaluate(context);
  }
  serialize() {
    return `${this.d} not in '${this.f}'`;
  }
  keys() {
    return this.c.keys();
  }
  map(mapFnc) {
    return mapFnc.mapNotIn(this.d, this.f);
  }
  negate() {
    return this.c;
  }
};
var $7j = class _$7j {
  static create(key, value, negated = null) {
    if (typeof value === "boolean") {
      if (value) {
        return $8j.create(key, negated);
      }
      return $3j.create(key, negated);
    }
    const constantValue = CONSTANT_VALUES.get(key);
    if (typeof constantValue === "boolean") {
      const falseValue = constantValue ? "true" : "false";
      return value === falseValue ? $1j.INSTANCE : $2j.INSTANCE;
    }
    return new _$7j(key, value, negated);
  }
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.type = 5;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.c, this.d, other.c, other.d);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.c === other.c && this.d === other.d;
    }
    return false;
  }
  substituteConstants() {
    const constantValue = CONSTANT_VALUES.get(this.c);
    if (typeof constantValue === "boolean") {
      const falseValue = constantValue ? "true" : "false";
      return this.d === falseValue ? $1j.INSTANCE : $2j.INSTANCE;
    }
    return this;
  }
  evaluate(context) {
    return context.getValue(this.c) != this.d;
  }
  serialize() {
    return `${this.c} != '${this.d}'`;
  }
  keys() {
    return [this.c];
  }
  map(mapFnc) {
    return mapFnc.mapNotEquals(this.c, this.d);
  }
  negate() {
    if (!this.f) {
      this.f = $4j.create(this.c, this.d, this);
    }
    return this.f;
  }
};
var $8j = class _$8j {
  static create(key, negated = null) {
    const constantValue = CONSTANT_VALUES.get(key);
    if (typeof constantValue === "boolean") {
      return constantValue ? $1j.INSTANCE : $2j.INSTANCE;
    }
    return new _$8j(key, negated);
  }
  constructor(c, d) {
    this.c = c;
    this.d = d;
    this.type = 3;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp1(this.c, other.c);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.c === other.c;
    }
    return false;
  }
  substituteConstants() {
    const constantValue = CONSTANT_VALUES.get(this.c);
    if (typeof constantValue === "boolean") {
      return constantValue ? $1j.INSTANCE : $2j.INSTANCE;
    }
    return this;
  }
  evaluate(context) {
    return !context.getValue(this.c);
  }
  serialize() {
    return `!${this.c}`;
  }
  keys() {
    return [this.c];
  }
  map(mapFnc) {
    return mapFnc.mapNot(this.c);
  }
  negate() {
    if (!this.d) {
      this.d = $3j.create(this.c, this);
    }
    return this.d;
  }
};
function withFloatOrStr(value, callback) {
  if (typeof value === "string") {
    const n = parseFloat(value);
    if (!isNaN(n)) {
      value = n;
    }
  }
  if (typeof value === "string" || typeof value === "number") {
    return callback(value);
  }
  return $1j.INSTANCE;
}
var $9j = class _$9j {
  static create(key, _value, negated = null) {
    return withFloatOrStr(_value, (value) => new _$9j(key, value, negated));
  }
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.type = 12;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.c, this.d, other.c, other.d);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.c === other.c && this.d === other.d;
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    if (typeof this.d === "string") {
      return false;
    }
    return parseFloat(context.getValue(this.c)) > this.d;
  }
  serialize() {
    return `${this.c} > ${this.d}`;
  }
  keys() {
    return [this.c];
  }
  map(mapFnc) {
    return mapFnc.mapGreater(this.c, this.d);
  }
  negate() {
    if (!this.f) {
      this.f = $_j.create(this.c, this.d, this);
    }
    return this.f;
  }
};
var $0j = class _$0j {
  static create(key, _value, negated = null) {
    return withFloatOrStr(_value, (value) => new _$0j(key, value, negated));
  }
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.type = 13;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.c, this.d, other.c, other.d);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.c === other.c && this.d === other.d;
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    if (typeof this.d === "string") {
      return false;
    }
    return parseFloat(context.getValue(this.c)) >= this.d;
  }
  serialize() {
    return `${this.c} >= ${this.d}`;
  }
  keys() {
    return [this.c];
  }
  map(mapFnc) {
    return mapFnc.mapGreaterEquals(this.c, this.d);
  }
  negate() {
    if (!this.f) {
      this.f = $$j.create(this.c, this.d, this);
    }
    return this.f;
  }
};
var $$j = class _$$j {
  static create(key, _value, negated = null) {
    return withFloatOrStr(_value, (value) => new _$$j(key, value, negated));
  }
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.type = 14;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.c, this.d, other.c, other.d);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.c === other.c && this.d === other.d;
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    if (typeof this.d === "string") {
      return false;
    }
    return parseFloat(context.getValue(this.c)) < this.d;
  }
  serialize() {
    return `${this.c} < ${this.d}`;
  }
  keys() {
    return [this.c];
  }
  map(mapFnc) {
    return mapFnc.mapSmaller(this.c, this.d);
  }
  negate() {
    if (!this.f) {
      this.f = $0j.create(this.c, this.d, this);
    }
    return this.f;
  }
};
var $_j = class _$_j {
  static create(key, _value, negated = null) {
    return withFloatOrStr(_value, (value) => new _$_j(key, value, negated));
  }
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.type = 15;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.c, this.d, other.c, other.d);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.c === other.c && this.d === other.d;
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    if (typeof this.d === "string") {
      return false;
    }
    return parseFloat(context.getValue(this.c)) <= this.d;
  }
  serialize() {
    return `${this.c} <= ${this.d}`;
  }
  keys() {
    return [this.c];
  }
  map(mapFnc) {
    return mapFnc.mapSmallerEquals(this.c, this.d);
  }
  negate() {
    if (!this.f) {
      this.f = $9j.create(this.c, this.d, this);
    }
    return this.f;
  }
};
var $ak = class _$ak {
  static create(key, regexp) {
    return new _$ak(key, regexp);
  }
  constructor(d, f) {
    this.d = d;
    this.f = f;
    this.type = 7;
    this.c = null;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    if (this.d < other.d) {
      return -1;
    }
    if (this.d > other.d) {
      return 1;
    }
    const thisSource = this.f ? this.f.source : "";
    const otherSource = other.f ? other.f.source : "";
    if (thisSource < otherSource) {
      return -1;
    }
    if (thisSource > otherSource) {
      return 1;
    }
    return 0;
  }
  equals(other) {
    if (other.type === this.type) {
      const thisSource = this.f ? this.f.source : "";
      const otherSource = other.f ? other.f.source : "";
      return this.d === other.d && thisSource === otherSource;
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    const value = context.getValue(this.d);
    return this.f ? this.f.test(value) : false;
  }
  serialize() {
    const value = this.f ? `/${this.f.source}/${this.f.flags}` : "/invalid/";
    return `${this.d} =~ ${value}`;
  }
  keys() {
    return [this.d];
  }
  map(mapFnc) {
    return mapFnc.mapRegex(this.d, this.f);
  }
  negate() {
    if (!this.c) {
      this.c = $bk.create(this);
    }
    return this.c;
  }
};
var $bk = class _$bk {
  static create(actual) {
    return new _$bk(actual);
  }
  constructor(c) {
    this.c = c;
    this.type = 8;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return this.c.cmp(other.c);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.c.equals(other.c);
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    return !this.c.evaluate(context);
  }
  serialize() {
    return `!(${this.c.serialize()})`;
  }
  keys() {
    return this.c.keys();
  }
  map(mapFnc) {
    return new _$bk(this.c.map(mapFnc));
  }
  negate() {
    return this.c;
  }
};
function eliminateConstantsInArray(arr) {
  let newArr = null;
  for (let i = 0, len = arr.length; i < len; i++) {
    const newExpr = arr[i].substituteConstants();
    if (arr[i] !== newExpr) {
      if (newArr === null) {
        newArr = [];
        for (let j = 0; j < i; j++) {
          newArr[j] = arr[j];
        }
      }
    }
    if (newArr !== null) {
      newArr[i] = newExpr;
    }
  }
  if (newArr === null) {
    return arr;
  }
  return newArr;
}
var $ck = class _$ck {
  static create(_expr, negated, extraRedundantCheck) {
    return _$ck.d(_expr, negated, extraRedundantCheck);
  }
  constructor(expr, c) {
    this.expr = expr;
    this.c = c;
    this.type = 6;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    if (this.expr.length < other.expr.length) {
      return -1;
    }
    if (this.expr.length > other.expr.length) {
      return 1;
    }
    for (let i = 0, len = this.expr.length; i < len; i++) {
      const r = cmp(this.expr[i], other.expr[i]);
      if (r !== 0) {
        return r;
      }
    }
    return 0;
  }
  equals(other) {
    if (other.type === this.type) {
      if (this.expr.length !== other.expr.length) {
        return false;
      }
      for (let i = 0, len = this.expr.length; i < len; i++) {
        if (!this.expr[i].equals(other.expr[i])) {
          return false;
        }
      }
      return true;
    }
    return false;
  }
  substituteConstants() {
    const exprArr = eliminateConstantsInArray(this.expr);
    if (exprArr === this.expr) {
      return this;
    }
    return _$ck.create(exprArr, this.c, false);
  }
  evaluate(context) {
    for (let i = 0, len = this.expr.length; i < len; i++) {
      if (!this.expr[i].evaluate(context)) {
        return false;
      }
    }
    return true;
  }
  static d(arr, negated, extraRedundantCheck) {
    const expr = [];
    let hasTrue = false;
    for (const e of arr) {
      if (!e) {
        continue;
      }
      if (e.type === 1) {
        hasTrue = true;
        continue;
      }
      if (e.type === 0) {
        return $1j.INSTANCE;
      }
      if (e.type === 6) {
        expr.push(...e.expr);
        continue;
      }
      expr.push(e);
    }
    if (expr.length === 0 && hasTrue) {
      return $2j.INSTANCE;
    }
    if (expr.length === 0) {
      return void 0;
    }
    if (expr.length === 1) {
      return expr[0];
    }
    expr.sort(cmp);
    for (let i = 1; i < expr.length; i++) {
      if (expr[i - 1].equals(expr[i])) {
        expr.splice(i, 1);
        i--;
      }
    }
    if (expr.length === 1) {
      return expr[0];
    }
    while (expr.length > 1) {
      const lastElement = expr[expr.length - 1];
      if (lastElement.type !== 9) {
        break;
      }
      expr.pop();
      const secondToLastElement = expr.pop();
      const isFinished = expr.length === 0;
      const resultElement = $dk.create(lastElement.expr.map((el) => _$ck.create([el, secondToLastElement], null, extraRedundantCheck)), null, isFinished);
      if (resultElement) {
        expr.push(resultElement);
        expr.sort(cmp);
      }
    }
    if (expr.length === 1) {
      return expr[0];
    }
    if (extraRedundantCheck) {
      for (let i = 0; i < expr.length; i++) {
        for (let j = i + 1; j < expr.length; j++) {
          if (expr[i].negate().equals(expr[j])) {
            return $1j.INSTANCE;
          }
        }
      }
      if (expr.length === 1) {
        return expr[0];
      }
    }
    return new _$ck(expr, negated);
  }
  serialize() {
    return this.expr.map((e) => e.serialize()).join(" && ");
  }
  keys() {
    const result = [];
    for (const expr of this.expr) {
      result.push(...expr.keys());
    }
    return result;
  }
  map(mapFnc) {
    return new _$ck(this.expr.map((expr) => expr.map(mapFnc)), null);
  }
  negate() {
    if (!this.c) {
      const result = [];
      for (const expr of this.expr) {
        result.push(expr.negate());
      }
      this.c = $dk.create(result, this, true);
    }
    return this.c;
  }
};
var $dk = class _$dk {
  static create(_expr, negated, extraRedundantCheck) {
    return _$dk.d(_expr, negated, extraRedundantCheck);
  }
  constructor(expr, c) {
    this.expr = expr;
    this.c = c;
    this.type = 9;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    if (this.expr.length < other.expr.length) {
      return -1;
    }
    if (this.expr.length > other.expr.length) {
      return 1;
    }
    for (let i = 0, len = this.expr.length; i < len; i++) {
      const r = cmp(this.expr[i], other.expr[i]);
      if (r !== 0) {
        return r;
      }
    }
    return 0;
  }
  equals(other) {
    if (other.type === this.type) {
      if (this.expr.length !== other.expr.length) {
        return false;
      }
      for (let i = 0, len = this.expr.length; i < len; i++) {
        if (!this.expr[i].equals(other.expr[i])) {
          return false;
        }
      }
      return true;
    }
    return false;
  }
  substituteConstants() {
    const exprArr = eliminateConstantsInArray(this.expr);
    if (exprArr === this.expr) {
      return this;
    }
    return _$dk.create(exprArr, this.c, false);
  }
  evaluate(context) {
    for (let i = 0, len = this.expr.length; i < len; i++) {
      if (this.expr[i].evaluate(context)) {
        return true;
      }
    }
    return false;
  }
  static d(arr, negated, extraRedundantCheck) {
    let expr = [];
    let hasFalse = false;
    if (arr) {
      for (let i = 0, len = arr.length; i < len; i++) {
        const e = arr[i];
        if (!e) {
          continue;
        }
        if (e.type === 0) {
          hasFalse = true;
          continue;
        }
        if (e.type === 1) {
          return $2j.INSTANCE;
        }
        if (e.type === 9) {
          expr = expr.concat(e.expr);
          continue;
        }
        expr.push(e);
      }
      if (expr.length === 0 && hasFalse) {
        return $1j.INSTANCE;
      }
      expr.sort(cmp);
    }
    if (expr.length === 0) {
      return void 0;
    }
    if (expr.length === 1) {
      return expr[0];
    }
    for (let i = 1; i < expr.length; i++) {
      if (expr[i - 1].equals(expr[i])) {
        expr.splice(i, 1);
        i--;
      }
    }
    if (expr.length === 1) {
      return expr[0];
    }
    if (extraRedundantCheck) {
      for (let i = 0; i < expr.length; i++) {
        for (let j = i + 1; j < expr.length; j++) {
          if (expr[i].negate().equals(expr[j])) {
            return $2j.INSTANCE;
          }
        }
      }
      if (expr.length === 1) {
        return expr[0];
      }
    }
    return new _$dk(expr, negated);
  }
  serialize() {
    return this.expr.map((e) => e.serialize()).join(" || ");
  }
  keys() {
    const result = [];
    for (const expr of this.expr) {
      result.push(...expr.keys());
    }
    return result;
  }
  map(mapFnc) {
    return new _$dk(this.expr.map((expr) => expr.map(mapFnc)), null);
  }
  negate() {
    if (!this.c) {
      const result = [];
      for (const expr of this.expr) {
        result.push(expr.negate());
      }
      while (result.length > 1) {
        const LEFT = result.shift();
        const RIGHT = result.shift();
        const all = [];
        for (const left of getTerminals(LEFT)) {
          for (const right of getTerminals(RIGHT)) {
            all.push($ck.create([left, right], null, false));
          }
        }
        result.unshift(_$dk.create(all, null, false));
      }
      this.c = _$dk.create(result, this, true);
    }
    return this.c;
  }
};
var $ek = class _$ek extends $3j {
  static {
    this.d = [];
  }
  static all() {
    return _$ek.d.values();
  }
  constructor(key, defaultValue, metaOrHide) {
    super(key, null);
    this.f = defaultValue;
    if (typeof metaOrHide === "object") {
      _$ek.d.push({ ...metaOrHide, key });
    } else if (metaOrHide !== true) {
      _$ek.d.push({ key, description: metaOrHide, type: defaultValue !== null && defaultValue !== void 0 ? typeof defaultValue : void 0 });
    }
  }
  bindTo(target) {
    return target.createKey(this.key, this.f);
  }
  getValue(target) {
    return target.getContextKeyValue(this.key);
  }
  toNegated() {
    return this.negate();
  }
  isEqualTo(value) {
    return $4j.create(this.key, value);
  }
  notEqualsTo(value) {
    return $7j.create(this.key, value);
  }
};
var $fk = $Zi("contextKeyService");
function cmp1(key1, key2) {
  if (key1 < key2) {
    return -1;
  }
  if (key1 > key2) {
    return 1;
  }
  return 0;
}
function cmp2(key1, value1, key2, value2) {
  if (key1 < key2) {
    return -1;
  }
  if (key1 > key2) {
    return 1;
  }
  if (value1 < value2) {
    return -1;
  }
  if (value1 > value2) {
    return 1;
  }
  return 0;
}
function getTerminals(node) {
  if (node.type === 9) {
    return node.expr;
  }
  return [node];
}

// out-build/vs/platform/log/common/log.js
var $uk = $Zi("logService");
var $vk = $Zi("loggerService");
function now() {
  return (/* @__PURE__ */ new Date()).toISOString();
}
function $wk(thing) {
  return $Cg(thing);
}
var LogLevel;
(function(LogLevel2) {
  LogLevel2[LogLevel2["Off"] = 0] = "Off";
  LogLevel2[LogLevel2["Trace"] = 1] = "Trace";
  LogLevel2[LogLevel2["Debug"] = 2] = "Debug";
  LogLevel2[LogLevel2["Info"] = 3] = "Info";
  LogLevel2[LogLevel2["Warning"] = 4] = "Warning";
  LogLevel2[LogLevel2["Error"] = 5] = "Error";
})(LogLevel || (LogLevel = {}));
var $xk = LogLevel.Info;
function log(logger, level, message) {
  switch (level) {
    case LogLevel.Trace:
      logger.trace(message);
      break;
    case LogLevel.Debug:
      logger.debug(message);
      break;
    case LogLevel.Info:
      logger.info(message);
      break;
    case LogLevel.Warning:
      logger.warn(message);
      break;
    case LogLevel.Error:
      logger.error(message);
      break;
    case LogLevel.Off:
      break;
    default:
      throw new Error(`Invalid log level ${level}`);
  }
}
function format(args, verbose = false) {
  let result = "";
  for (let i = 0; i < args.length; i++) {
    let a = args[i];
    if (a instanceof Error) {
      a = $Kj(a, verbose);
    }
    if (typeof a === "object") {
      try {
        a = JSON.stringify(a);
      } catch (e) {
      }
    }
    result += (i > 0 ? " " : "") + a;
  }
  return result;
}
var $zk = class extends $0c {
  constructor() {
    super(...arguments);
    this.b = $xk;
    this.c = this.B(new $De());
    this.onDidChangeLogLevel = this.c.event;
  }
  setLevel(level) {
    if (this.b !== level) {
      this.b = level;
      this.c.fire(this.b);
    }
  }
  getLevel() {
    return this.b;
  }
  f(level) {
    return this.b !== LogLevel.Off && this.b <= level;
  }
};
var $Ak = class extends $zk {
  constructor(h) {
    super();
    this.h = h;
  }
  f(level) {
    return this.h || super.f(level);
  }
  trace(message, ...args) {
    if (this.f(LogLevel.Trace)) {
      this.g(LogLevel.Trace, format([message, ...args], true));
    }
  }
  debug(message, ...args) {
    if (this.f(LogLevel.Debug)) {
      this.g(LogLevel.Debug, format([message, ...args]));
    }
  }
  info(message, ...args) {
    if (this.f(LogLevel.Info)) {
      this.g(LogLevel.Info, format([message, ...args]));
    }
  }
  warn(message, ...args) {
    if (this.f(LogLevel.Warning)) {
      this.g(LogLevel.Warning, format([message, ...args]));
    }
  }
  error(message, ...args) {
    if (this.f(LogLevel.Error)) {
      if (message instanceof Error) {
        const array = Array.prototype.slice.call(arguments);
        array[0] = message.stack;
        this.g(LogLevel.Error, format(array));
      } else {
        this.g(LogLevel.Error, format([message, ...args]));
      }
    }
  }
  flush() {
  }
};
var $Bk = class extends $zk {
  constructor(logLevel = $xk) {
    super();
    this.setLevel(logLevel);
    this.g = !$l;
  }
  trace(message, ...args) {
    if (this.f(LogLevel.Trace)) {
      if (this.g) {
        console.log(`\x1B[90m[main ${now()}]\x1B[0m`, message, ...args);
      } else {
        console.log(`[main ${now()}]`, message, ...args);
      }
    }
  }
  debug(message, ...args) {
    if (this.f(LogLevel.Debug)) {
      if (this.g) {
        console.log(`\x1B[90m[main ${now()}]\x1B[0m`, message, ...args);
      } else {
        console.log(`[main ${now()}]`, message, ...args);
      }
    }
  }
  info(message, ...args) {
    if (this.f(LogLevel.Info)) {
      if (this.g) {
        console.log(`\x1B[90m[main ${now()}]\x1B[0m`, message, ...args);
      } else {
        console.log(`[main ${now()}]`, message, ...args);
      }
    }
  }
  warn(message, ...args) {
    if (this.f(LogLevel.Warning)) {
      if (this.g) {
        console.warn(`\x1B[93m[main ${now()}]\x1B[0m`, message, ...args);
      } else {
        console.warn(`[main ${now()}]`, message, ...args);
      }
    }
  }
  error(message, ...args) {
    if (this.f(LogLevel.Error)) {
      if (this.g) {
        console.error(`\x1B[91m[main ${now()}]\x1B[0m`, message, ...args);
      } else {
        console.error(`[main ${now()}]`, message, ...args);
      }
    }
  }
  flush() {
  }
};
var $Ek = class extends $zk {
  constructor(g) {
    super();
    this.g = g;
    if (g.length) {
      this.setLevel(g[0].getLevel());
    }
  }
  setLevel(level) {
    for (const logger of this.g) {
      logger.setLevel(level);
    }
    super.setLevel(level);
  }
  trace(message, ...args) {
    for (const logger of this.g) {
      logger.trace(message, ...args);
    }
  }
  debug(message, ...args) {
    for (const logger of this.g) {
      logger.debug(message, ...args);
    }
  }
  info(message, ...args) {
    for (const logger of this.g) {
      logger.info(message, ...args);
    }
  }
  warn(message, ...args) {
    for (const logger of this.g) {
      logger.warn(message, ...args);
    }
  }
  error(message, ...args) {
    for (const logger of this.g) {
      logger.error(message, ...args);
    }
  }
  flush() {
    for (const logger of this.g) {
      logger.flush();
    }
  }
  dispose() {
    for (const logger of this.g) {
      logger.dispose();
    }
    super.dispose();
  }
};
var $Fk = class extends $0c {
  constructor(h, j, loggerResources) {
    super();
    this.h = h;
    this.j = j;
    this.b = new $Mc();
    this.c = this.B(new $De());
    this.onDidChangeLoggers = this.c.event;
    this.f = this.B(new $De());
    this.onDidChangeLogLevel = this.f.event;
    this.g = this.B(new $De());
    this.onDidChangeVisibility = this.g.event;
    if (loggerResources) {
      for (const loggerResource of loggerResources) {
        this.b.set(loggerResource.resource, { logger: void 0, info: loggerResource });
      }
    }
  }
  m(resourceOrId) {
    if ($yg(resourceOrId)) {
      return [...this.b.values()].find((logger) => logger.info.id === resourceOrId);
    }
    return this.b.get(resourceOrId);
  }
  getLogger(resourceOrId) {
    return this.m(resourceOrId)?.logger;
  }
  createLogger(idOrResource, options) {
    const resource = this.n(idOrResource);
    const id2 = $yg(idOrResource) ? idOrResource : options?.id ?? $Nj(resource.toString()).toString(16);
    let logger = this.b.get(resource)?.logger;
    const logLevel = options?.logLevel === "always" ? LogLevel.Trace : options?.logLevel;
    if (!logger) {
      logger = this.s(resource, logLevel ?? this.getLogLevel(resource) ?? this.h, { ...options, id: id2 });
    }
    const loggerEntry = {
      logger,
      info: { resource, id: id2, logLevel, name: options?.name, hidden: options?.hidden, extensionId: options?.extensionId, when: options?.when }
    };
    this.registerLogger(loggerEntry.info);
    this.b.set(resource, loggerEntry);
    return logger;
  }
  n(idOrResource) {
    return $yg(idOrResource) ? $Ah(this.j, `${idOrResource}.log`) : idOrResource;
  }
  setLogLevel(arg1, arg2) {
    if (URI.isUri(arg1)) {
      const resource = arg1;
      const logLevel = arg2;
      const logger = this.b.get(resource);
      if (logger && logLevel !== logger.info.logLevel) {
        logger.info.logLevel = logLevel === this.h ? void 0 : logLevel;
        logger.logger?.setLevel(logLevel);
        this.b.set(logger.info.resource, logger);
        this.f.fire([resource, logLevel]);
      }
    } else {
      this.h = arg1;
      for (const [resource, logger] of this.b.entries()) {
        if (this.b.get(resource)?.info.logLevel === void 0) {
          logger.logger?.setLevel(this.h);
        }
      }
      this.f.fire(this.h);
    }
  }
  setVisibility(resourceOrId, visibility) {
    const logger = this.m(resourceOrId);
    if (logger && visibility !== !logger.info.hidden) {
      logger.info.hidden = !visibility;
      this.b.set(logger.info.resource, logger);
      this.g.fire([logger.info.resource, visibility]);
    }
  }
  getLogLevel(resource) {
    let logLevel;
    if (resource) {
      logLevel = this.b.get(resource)?.info.logLevel;
    }
    return logLevel ?? this.h;
  }
  registerLogger(resource) {
    const existing = this.b.get(resource.resource);
    if (existing) {
      if (existing.info.hidden !== resource.hidden) {
        this.setVisibility(resource.resource, !resource.hidden);
      }
    } else {
      this.b.set(resource.resource, { info: resource, logger: void 0 });
      this.c.fire({ added: [resource], removed: [] });
    }
  }
  deregisterLogger(resource) {
    const existing = this.b.get(resource);
    if (existing) {
      if (existing.logger) {
        existing.logger.dispose();
      }
      this.b.delete(resource);
      this.c.fire({ added: [], removed: [existing.info] });
    }
  }
  *getRegisteredLoggers() {
    for (const entry of this.b.values()) {
      yield entry.info;
    }
  }
  getRegisteredLogger(resource) {
    return this.b.get(resource)?.info;
  }
  dispose() {
    this.b.forEach((logger) => logger.logger?.dispose());
    this.b.clear();
    super.dispose();
  }
};
var $Gk = class {
  constructor() {
    this.onDidChangeLogLevel = new $De().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() {
  }
  flush() {
  }
};
var $Hk = class extends $Gk {
};
function $Ik(environmentService) {
  if (environmentService.verbose) {
    return LogLevel.Trace;
  }
  if (typeof environmentService.logLevel === "string") {
    const logLevel = $Lk(environmentService.logLevel.toLowerCase());
    if (logLevel !== void 0) {
      return logLevel;
    }
  }
  return $xk;
}
function $Jk(logLevel) {
  switch (logLevel) {
    case LogLevel.Trace:
      return "trace";
    case LogLevel.Debug:
      return "debug";
    case LogLevel.Info:
      return "info";
    case LogLevel.Warning:
      return "warn";
    case LogLevel.Error:
      return "error";
    case LogLevel.Off:
      return "off";
  }
}
function $Lk(logLevel) {
  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.Error;
    case "off":
      return LogLevel.Off;
  }
  return void 0;
}
var $Mk = new $ek("logLevel", $Jk(LogLevel.Info));

// out-build/vs/base/common/ternarySearchTree.js
var $2i = class {
  constructor() {
    this.b = "";
    this.c = 0;
  }
  reset(key) {
    this.b = key;
    this.c = 0;
    return this;
  }
  next() {
    this.c += 1;
    return this;
  }
  hasNext() {
    return this.c < this.b.length - 1;
  }
  cmp(a) {
    const aCode = a.charCodeAt(0);
    const thisCode = this.b.charCodeAt(this.c);
    return aCode - thisCode;
  }
  value() {
    return this.b[this.c];
  }
};
var $3i = class {
  constructor(e = true) {
    this.e = e;
  }
  reset(key) {
    this.b = key;
    this.c = 0;
    this.d = 0;
    return this.next();
  }
  hasNext() {
    return this.d < this.b.length;
  }
  next() {
    this.c = this.d;
    let justSeps = true;
    for (; this.d < this.b.length; this.d++) {
      const ch = this.b.charCodeAt(this.d);
      if (ch === 46) {
        if (justSeps) {
          this.c++;
        } else {
          break;
        }
      } else {
        justSeps = false;
      }
    }
    return this;
  }
  cmp(a) {
    return this.e ? $Tf(a, this.b, 0, a.length, this.c, this.d) : $Vf(a, this.b, 0, a.length, this.c, this.d);
  }
  value() {
    return this.b.substring(this.c, this.d);
  }
};
var $4i = class {
  constructor(f = true, g = true) {
    this.f = f;
    this.g = g;
  }
  reset(key) {
    this.d = 0;
    this.e = 0;
    this.b = key;
    this.c = key.length;
    for (let pos = key.length - 1; pos >= 0; pos--, this.c--) {
      const ch = this.b.charCodeAt(pos);
      if (!(ch === 47 || this.f && ch === 92)) {
        break;
      }
    }
    return this.next();
  }
  hasNext() {
    return this.e < this.c;
  }
  next() {
    this.d = this.e;
    let justSeps = true;
    for (; this.e < this.c; this.e++) {
      const ch = this.b.charCodeAt(this.e);
      if (ch === 47 || this.f && ch === 92) {
        if (justSeps) {
          this.d++;
        } else {
          break;
        }
      } else {
        justSeps = false;
      }
    }
    return this;
  }
  cmp(a) {
    return this.g ? $Tf(a, this.b, 0, a.length, this.d, this.e) : $Vf(a, this.b, 0, a.length, this.d, this.e);
  }
  value() {
    return this.b.substring(this.d, this.e);
  }
};
var UriIteratorState;
(function(UriIteratorState2) {
  UriIteratorState2[UriIteratorState2["Scheme"] = 1] = "Scheme";
  UriIteratorState2[UriIteratorState2["Authority"] = 2] = "Authority";
  UriIteratorState2[UriIteratorState2["Path"] = 3] = "Path";
  UriIteratorState2[UriIteratorState2["Query"] = 4] = "Query";
  UriIteratorState2[UriIteratorState2["Fragment"] = 5] = "Fragment";
})(UriIteratorState || (UriIteratorState = {}));
var $5i = class {
  constructor(f, g) {
    this.f = f;
    this.g = g;
    this.d = [];
    this.e = 0;
  }
  reset(key) {
    this.c = key;
    this.d = [];
    if (this.c.scheme) {
      this.d.push(
        1
        /* UriIteratorState.Scheme */
      );
    }
    if (this.c.authority) {
      this.d.push(
        2
        /* UriIteratorState.Authority */
      );
    }
    if (this.c.path) {
      this.b = new $4i(false, !this.f(key));
      this.b.reset(key.path);
      if (this.b.value()) {
        this.d.push(
          3
          /* UriIteratorState.Path */
        );
      }
    }
    if (!this.g(key)) {
      if (this.c.query) {
        this.d.push(
          4
          /* UriIteratorState.Query */
        );
      }
      if (this.c.fragment) {
        this.d.push(
          5
          /* UriIteratorState.Fragment */
        );
      }
    }
    this.e = 0;
    return this;
  }
  next() {
    if (this.d[this.e] === 3 && this.b.hasNext()) {
      this.b.next();
    } else {
      this.e += 1;
    }
    return this;
  }
  hasNext() {
    return this.d[this.e] === 3 && this.b.hasNext() || this.e < this.d.length - 1;
  }
  cmp(a) {
    if (this.d[this.e] === 1) {
      return $Uf(a, this.c.scheme);
    } else if (this.d[this.e] === 2) {
      return $Uf(a, this.c.authority);
    } else if (this.d[this.e] === 3) {
      return this.b.cmp(a);
    } else if (this.d[this.e] === 4) {
      return $Sf(a, this.c.query);
    } else if (this.d[this.e] === 5) {
      return $Sf(a, this.c.fragment);
    }
    throw new Error();
  }
  value() {
    if (this.d[this.e] === 1) {
      return this.c.scheme;
    } else if (this.d[this.e] === 2) {
      return this.c.authority;
    } else if (this.d[this.e] === 3) {
      return this.b.value();
    } else if (this.d[this.e] === 4) {
      return this.c.query;
    } else if (this.d[this.e] === 5) {
      return this.c.fragment;
    }
    throw new Error();
  }
};
var TernarySearchTreeNode = class {
  constructor() {
    this.height = 1;
  }
  isEmpty() {
    return !this.left && !this.mid && !this.right && !this.value;
  }
  rotateLeft() {
    const tmp = this.right;
    this.right = tmp.left;
    tmp.left = this;
    this.updateHeight();
    tmp.updateHeight();
    return tmp;
  }
  rotateRight() {
    const tmp = this.left;
    this.left = tmp.right;
    tmp.right = this;
    this.updateHeight();
    tmp.updateHeight();
    return tmp;
  }
  updateHeight() {
    this.height = 1 + Math.max(this.heightLeft, this.heightRight);
  }
  balanceFactor() {
    return this.heightRight - this.heightLeft;
  }
  get heightLeft() {
    return this.left?.height ?? 0;
  }
  get heightRight() {
    return this.right?.height ?? 0;
  }
};
var Dir;
(function(Dir2) {
  Dir2[Dir2["Left"] = -1] = "Left";
  Dir2[Dir2["Mid"] = 0] = "Mid";
  Dir2[Dir2["Right"] = 1] = "Right";
})(Dir || (Dir = {}));
var $6i = class _$6i {
  static forUris(ignorePathCasing = () => false, ignoreQueryAndFragment = () => false) {
    return new _$6i(new $5i(ignorePathCasing, ignoreQueryAndFragment));
  }
  static forPaths(ignorePathCasing = false) {
    return new _$6i(new $4i(void 0, !ignorePathCasing));
  }
  static forStrings() {
    return new _$6i(new $2i());
  }
  static forConfigKeys() {
    return new _$6i(new $3i());
  }
  constructor(segments) {
    this.b = segments;
  }
  clear() {
    this.c = void 0;
  }
  fill(values, keys) {
    if (keys) {
      const arr = keys.slice(0);
      $8b(arr);
      for (const k of arr) {
        this.set(k, values);
      }
    } else {
      const arr = values.slice(0);
      $8b(arr);
      for (const entry of arr) {
        this.set(entry[0], entry[1]);
      }
    }
  }
  set(key, element) {
    const iter = this.b.reset(key);
    let node;
    if (!this.c) {
      this.c = new TernarySearchTreeNode();
      this.c.segment = iter.value();
    }
    const stack = [];
    node = this.c;
    while (true) {
      const val = iter.cmp(node.segment);
      if (val > 0) {
        if (!node.left) {
          node.left = new TernarySearchTreeNode();
          node.left.segment = iter.value();
        }
        stack.push([-1, node]);
        node = node.left;
      } else if (val < 0) {
        if (!node.right) {
          node.right = new TernarySearchTreeNode();
          node.right.segment = iter.value();
        }
        stack.push([1, node]);
        node = node.right;
      } else if (iter.hasNext()) {
        iter.next();
        if (!node.mid) {
          node.mid = new TernarySearchTreeNode();
          node.mid.segment = iter.value();
        }
        stack.push([0, node]);
        node = node.mid;
      } else {
        break;
      }
    }
    const oldElement = node.value;
    node.value = element;
    node.key = key;
    for (let i = stack.length - 1; i >= 0; i--) {
      const node2 = stack[i][1];
      node2.updateHeight();
      const bf = node2.balanceFactor();
      if (bf < -1 || bf > 1) {
        const d1 = stack[i][0];
        const d2 = stack[i + 1][0];
        if (d1 === 1 && d2 === 1) {
          stack[i][1] = node2.rotateLeft();
        } else if (d1 === -1 && d2 === -1) {
          stack[i][1] = node2.rotateRight();
        } else if (d1 === 1 && d2 === -1) {
          node2.right = stack[i + 1][1] = stack[i + 1][1].rotateRight();
          stack[i][1] = node2.rotateLeft();
        } else if (d1 === -1 && d2 === 1) {
          node2.left = stack[i + 1][1] = stack[i + 1][1].rotateLeft();
          stack[i][1] = node2.rotateRight();
        } else {
          throw new Error();
        }
        if (i > 0) {
          switch (stack[i - 1][0]) {
            case -1:
              stack[i - 1][1].left = stack[i][1];
              break;
            case 1:
              stack[i - 1][1].right = stack[i][1];
              break;
            case 0:
              stack[i - 1][1].mid = stack[i][1];
              break;
          }
        } else {
          this.c = stack[0][1];
        }
      }
    }
    return oldElement;
  }
  get(key) {
    return this.d(key)?.value;
  }
  d(key) {
    const iter = this.b.reset(key);
    let node = this.c;
    while (node) {
      const val = iter.cmp(node.segment);
      if (val > 0) {
        node = node.left;
      } else if (val < 0) {
        node = node.right;
      } else if (iter.hasNext()) {
        iter.next();
        node = node.mid;
      } else {
        break;
      }
    }
    return node;
  }
  has(key) {
    const node = this.d(key);
    return !(node?.value === void 0 && node?.mid === void 0);
  }
  delete(key) {
    return this.e(key, false);
  }
  deleteSuperstr(key) {
    return this.e(key, true);
  }
  e(key, superStr) {
    const iter = this.b.reset(key);
    const stack = [];
    let node = this.c;
    while (node) {
      const val = iter.cmp(node.segment);
      if (val > 0) {
        stack.push([-1, node]);
        node = node.left;
      } else if (val < 0) {
        stack.push([1, node]);
        node = node.right;
      } else if (iter.hasNext()) {
        iter.next();
        stack.push([0, node]);
        node = node.mid;
      } else {
        break;
      }
    }
    if (!node) {
      return;
    }
    if (superStr) {
      node.left = void 0;
      node.mid = void 0;
      node.right = void 0;
      node.height = 1;
    } else {
      node.key = void 0;
      node.value = void 0;
    }
    if (!node.mid && !node.value) {
      if (node.left && node.right) {
        const min = this.f(node.right);
        if (min.key) {
          const { key: key2, value, segment } = min;
          this.e(min.key, false);
          node.key = key2;
          node.value = value;
          node.segment = segment;
        }
      } else {
        const newChild = node.left ?? node.right;
        if (stack.length > 0) {
          const [dir, parent] = stack[stack.length - 1];
          switch (dir) {
            case -1:
              parent.left = newChild;
              break;
            case 0:
              parent.mid = newChild;
              break;
            case 1:
              parent.right = newChild;
              break;
          }
        } else {
          this.c = newChild;
        }
      }
    }
    for (let i = stack.length - 1; i >= 0; i--) {
      const node2 = stack[i][1];
      node2.updateHeight();
      const bf = node2.balanceFactor();
      if (bf > 1) {
        if (node2.right.balanceFactor() >= 0) {
          stack[i][1] = node2.rotateLeft();
        } else {
          node2.right = node2.right.rotateRight();
          stack[i][1] = node2.rotateLeft();
        }
      } else if (bf < -1) {
        if (node2.left.balanceFactor() <= 0) {
          stack[i][1] = node2.rotateRight();
        } else {
          node2.left = node2.left.rotateLeft();
          stack[i][1] = node2.rotateRight();
        }
      }
      if (i > 0) {
        switch (stack[i - 1][0]) {
          case -1:
            stack[i - 1][1].left = stack[i][1];
            break;
          case 1:
            stack[i - 1][1].right = stack[i][1];
            break;
          case 0:
            stack[i - 1][1].mid = stack[i][1];
            break;
        }
      } else {
        this.c = stack[0][1];
      }
    }
  }
  f(node) {
    while (node.left) {
      node = node.left;
    }
    return node;
  }
  findSubstr(key) {
    const iter = this.b.reset(key);
    let node = this.c;
    let candidate = void 0;
    while (node) {
      const val = iter.cmp(node.segment);
      if (val > 0) {
        node = node.left;
      } else if (val < 0) {
        node = node.right;
      } else if (iter.hasNext()) {
        iter.next();
        candidate = node.value || candidate;
        node = node.mid;
      } else {
        break;
      }
    }
    return node && node.value || candidate;
  }
  findSuperstr(key) {
    return this.g(key, false);
  }
  g(key, allowValue) {
    const iter = this.b.reset(key);
    let node = this.c;
    while (node) {
      const val = iter.cmp(node.segment);
      if (val > 0) {
        node = node.left;
      } else if (val < 0) {
        node = node.right;
      } else if (iter.hasNext()) {
        iter.next();
        node = node.mid;
      } else {
        if (!node.mid) {
          if (allowValue) {
            return node.value;
          } else {
            return void 0;
          }
        } else {
          return this.h(node.mid);
        }
      }
    }
    return void 0;
  }
  hasElementOrSubtree(key) {
    return this.g(key, true) !== void 0;
  }
  forEach(callback) {
    for (const [key, value] of this) {
      callback(value, key);
    }
  }
  *[Symbol.iterator]() {
    yield* this.h(this.c);
  }
  h(node) {
    const result = [];
    this.j(node, result);
    return result[Symbol.iterator]();
  }
  j(node, bucket) {
    if (!node) {
      return;
    }
    if (node.left) {
      this.j(node.left, bucket);
    }
    if (node.value) {
      bucket.push([node.key, node.value]);
    }
    if (node.mid) {
      this.j(node.mid, bucket);
    }
    if (node.right) {
      this.j(node.right, bucket);
    }
  }
  // for debug/testing
  _isBalanced() {
    const nodeIsBalanced = (node) => {
      if (!node) {
        return true;
      }
      const bf = node.balanceFactor();
      if (bf < -1 || bf > 1) {
        return false;
      }
      return nodeIsBalanced(node.left) && nodeIsBalanced(node.right);
    };
    return nodeIsBalanced(this.c);
  }
};

// out-build/vs/platform/files/common/files.js
var $ul = $Zi("fileService");
function $vl(options) {
  return options.create === true;
}
var FileType;
(function(FileType2) {
  FileType2[FileType2["Unknown"] = 0] = "Unknown";
  FileType2[FileType2["File"] = 1] = "File";
  FileType2[FileType2["Directory"] = 2] = "Directory";
  FileType2[FileType2["SymbolicLink"] = 64] = "SymbolicLink";
})(FileType || (FileType = {}));
var FilePermission;
(function(FilePermission2) {
  FilePermission2[FilePermission2["Readonly"] = 1] = "Readonly";
  FilePermission2[FilePermission2["Locked"] = 2] = "Locked";
})(FilePermission || (FilePermission = {}));
var FileChangeFilter;
(function(FileChangeFilter2) {
  FileChangeFilter2[FileChangeFilter2["UPDATED"] = 2] = "UPDATED";
  FileChangeFilter2[FileChangeFilter2["ADDED"] = 4] = "ADDED";
  FileChangeFilter2[FileChangeFilter2["DELETED"] = 8] = "DELETED";
})(FileChangeFilter || (FileChangeFilter = {}));
var FileSystemProviderCapabilities;
(function(FileSystemProviderCapabilities2) {
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["None"] = 0] = "None";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["FileReadWrite"] = 2] = "FileReadWrite";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["FileOpenReadWriteClose"] = 4] = "FileOpenReadWriteClose";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["FileReadStream"] = 16] = "FileReadStream";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["FileFolderCopy"] = 8] = "FileFolderCopy";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["PathCaseSensitive"] = 1024] = "PathCaseSensitive";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["Readonly"] = 2048] = "Readonly";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["Trash"] = 4096] = "Trash";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["FileWriteUnlock"] = 8192] = "FileWriteUnlock";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["FileAtomicRead"] = 16384] = "FileAtomicRead";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["FileAtomicWrite"] = 32768] = "FileAtomicWrite";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["FileAtomicDelete"] = 65536] = "FileAtomicDelete";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["FileClone"] = 131072] = "FileClone";
})(FileSystemProviderCapabilities || (FileSystemProviderCapabilities = {}));
function $xl(provider) {
  return !!(provider.capabilities & 2);
}
function $yl(provider) {
  return !!(provider.capabilities & 8);
}
function $zl(provider) {
  return !!(provider.capabilities & 131072);
}
function $Al(provider) {
  return !!(provider.capabilities & 4);
}
function $Bl(provider) {
  return !!(provider.capabilities & 16);
}
function $Cl(provider) {
  if (!$xl(provider)) {
    return false;
  }
  return !!(provider.capabilities & 16384);
}
function $Dl(provider) {
  if (!$xl(provider)) {
    return false;
  }
  return !!(provider.capabilities & 32768);
}
function $El(provider) {
  return !!(provider.capabilities & 65536);
}
var FileSystemProviderErrorCode;
(function(FileSystemProviderErrorCode2) {
  FileSystemProviderErrorCode2["FileExists"] = "EntryExists";
  FileSystemProviderErrorCode2["FileNotFound"] = "EntryNotFound";
  FileSystemProviderErrorCode2["FileNotADirectory"] = "EntryNotADirectory";
  FileSystemProviderErrorCode2["FileIsADirectory"] = "EntryIsADirectory";
  FileSystemProviderErrorCode2["FileExceedsStorageQuota"] = "EntryExceedsStorageQuota";
  FileSystemProviderErrorCode2["FileTooLarge"] = "EntryTooLarge";
  FileSystemProviderErrorCode2["FileWriteLocked"] = "EntryWriteLocked";
  FileSystemProviderErrorCode2["NoPermissions"] = "NoPermissions";
  FileSystemProviderErrorCode2["Unavailable"] = "Unavailable";
  FileSystemProviderErrorCode2["Unknown"] = "Unknown";
})(FileSystemProviderErrorCode || (FileSystemProviderErrorCode = {}));
var $Gl = class _$Gl extends Error {
  static create(error, code2) {
    const providerError = new _$Gl(error.toString(), code2);
    $Jl(providerError, code2);
    return providerError;
  }
  constructor(message, code2) {
    super(message);
    this.code = code2;
  }
};
function $Hl(error, code2) {
  return $Gl.create(error, code2);
}
function $Il(error) {
  if (!error) {
    return $Hl(localize(1879, null), FileSystemProviderErrorCode.Unknown);
  }
  return error;
}
function $Jl(error, code2) {
  error.name = code2 ? `${code2} (FileSystemError)` : `FileSystemError`;
  return error;
}
function $Kl(error) {
  if (!error) {
    return FileSystemProviderErrorCode.Unknown;
  }
  if (error instanceof $Gl) {
    return error.code;
  }
  const match = /^(.+) \(FileSystemError\)$/.exec(error.name);
  if (!match) {
    return FileSystemProviderErrorCode.Unknown;
  }
  switch (match[1]) {
    case FileSystemProviderErrorCode.FileExists:
      return FileSystemProviderErrorCode.FileExists;
    case FileSystemProviderErrorCode.FileIsADirectory:
      return FileSystemProviderErrorCode.FileIsADirectory;
    case FileSystemProviderErrorCode.FileNotADirectory:
      return FileSystemProviderErrorCode.FileNotADirectory;
    case FileSystemProviderErrorCode.FileNotFound:
      return FileSystemProviderErrorCode.FileNotFound;
    case FileSystemProviderErrorCode.FileTooLarge:
      return FileSystemProviderErrorCode.FileTooLarge;
    case FileSystemProviderErrorCode.FileWriteLocked:
      return FileSystemProviderErrorCode.FileWriteLocked;
    case FileSystemProviderErrorCode.NoPermissions:
      return FileSystemProviderErrorCode.NoPermissions;
    case FileSystemProviderErrorCode.Unavailable:
      return FileSystemProviderErrorCode.Unavailable;
  }
  return FileSystemProviderErrorCode.Unknown;
}
function $Ll(error) {
  if (error instanceof $Pl) {
    return error.fileOperationResult;
  }
  switch ($Kl(error)) {
    case FileSystemProviderErrorCode.FileNotFound:
      return 1;
    case FileSystemProviderErrorCode.FileIsADirectory:
      return 0;
    case FileSystemProviderErrorCode.FileNotADirectory:
      return 9;
    case FileSystemProviderErrorCode.FileWriteLocked:
      return 5;
    case FileSystemProviderErrorCode.NoPermissions:
      return 6;
    case FileSystemProviderErrorCode.FileExists:
      return 4;
    case FileSystemProviderErrorCode.FileTooLarge:
      return 7;
    default:
      return 10;
  }
}
var FileOperation;
(function(FileOperation2) {
  FileOperation2[FileOperation2["CREATE"] = 0] = "CREATE";
  FileOperation2[FileOperation2["DELETE"] = 1] = "DELETE";
  FileOperation2[FileOperation2["MOVE"] = 2] = "MOVE";
  FileOperation2[FileOperation2["COPY"] = 3] = "COPY";
  FileOperation2[FileOperation2["WRITE"] = 4] = "WRITE";
})(FileOperation || (FileOperation = {}));
var $Ml = class {
  constructor(resource, operation, target) {
    this.resource = resource;
    this.operation = operation;
    this.target = target;
  }
  isOperation(operation) {
    return this.operation === operation;
  }
};
var FileChangeType;
(function(FileChangeType2) {
  FileChangeType2[FileChangeType2["UPDATED"] = 0] = "UPDATED";
  FileChangeType2[FileChangeType2["ADDED"] = 1] = "ADDED";
  FileChangeType2[FileChangeType2["DELETED"] = 2] = "DELETED";
})(FileChangeType || (FileChangeType = {}));
var $Nl = class _$Nl {
  static {
    this.a = null;
  }
  constructor(changes, c) {
    this.c = c;
    this.b = void 0;
    this.d = new $7(() => {
      const added = $6i.forUris(() => this.c);
      added.fill(this.rawAdded.map((resource) => [resource, true]));
      return added;
    });
    this.f = new $7(() => {
      const updated = $6i.forUris(() => this.c);
      updated.fill(this.rawUpdated.map((resource) => [resource, true]));
      return updated;
    });
    this.g = new $7(() => {
      const deleted = $6i.forUris(() => this.c);
      deleted.fill(this.rawDeleted.map((resource) => [resource, true]));
      return deleted;
    });
    this.rawAdded = [];
    this.rawUpdated = [];
    this.rawDeleted = [];
    for (const change of changes) {
      switch (change.type) {
        case 1:
          this.rawAdded.push(change.resource);
          break;
        case 0:
          this.rawUpdated.push(change.resource);
          break;
        case 2:
          this.rawDeleted.push(change.resource);
          break;
      }
      if (this.b !== _$Nl.a) {
        if (typeof change.cId === "number") {
          if (this.b === void 0) {
            this.b = change.cId;
          } else if (this.b !== change.cId) {
            this.b = _$Nl.a;
          }
        } else {
          if (this.b !== void 0) {
            this.b = _$Nl.a;
          }
        }
      }
    }
  }
  /**
   * Find out if the file change events match the provided resource.
   *
   * Note: when passing `FileChangeType.DELETED`, we consider a match
   * also when the parent of the resource got deleted.
   */
  contains(resource, ...types) {
    return this.h(resource, { includeChildren: false }, ...types);
  }
  /**
   * Find out if the file change events either match the provided
   * resource, or contain a child of this resource.
   */
  affects(resource, ...types) {
    return this.h(resource, { includeChildren: true }, ...types);
  }
  h(resource, options, ...types) {
    if (!resource) {
      return false;
    }
    const hasTypesFilter = types.length > 0;
    if (!hasTypesFilter || types.includes(
      1
      /* FileChangeType.ADDED */
    )) {
      if (this.d.value.get(resource)) {
        return true;
      }
      if (options.includeChildren && this.d.value.findSuperstr(resource)) {
        return true;
      }
    }
    if (!hasTypesFilter || types.includes(
      0
      /* FileChangeType.UPDATED */
    )) {
      if (this.f.value.get(resource)) {
        return true;
      }
      if (options.includeChildren && this.f.value.findSuperstr(resource)) {
        return true;
      }
    }
    if (!hasTypesFilter || types.includes(
      2
      /* FileChangeType.DELETED */
    )) {
      if (this.g.value.findSubstr(resource)) {
        return true;
      }
      if (options.includeChildren && this.g.value.findSuperstr(resource)) {
        return true;
      }
    }
    return false;
  }
  /**
   * Returns if this event contains added files.
   */
  gotAdded() {
    return this.rawAdded.length > 0;
  }
  /**
   * Returns if this event contains deleted files.
   */
  gotDeleted() {
    return this.rawDeleted.length > 0;
  }
  /**
   * Returns if this event contains updated files.
   */
  gotUpdated() {
    return this.rawUpdated.length > 0;
  }
  /**
   * Returns if this event contains changes that correlate to the
   * provided `correlationId`.
   *
   * File change event correlation is an advanced watch feature that
   * allows to  identify from which watch request the events originate
   * from. This correlation allows to route events specifically
   * only to the requestor and not emit them to all listeners.
   */
  correlates(correlationId) {
    return this.b === correlationId;
  }
  /**
   * Figure out if the event contains changes that correlate to one
   * correlation identifier.
   *
   * File change event correlation is an advanced watch feature that
   * allows to  identify from which watch request the events originate
   * from. This correlation allows to route events specifically
   * only to the requestor and not emit them to all listeners.
   */
  hasCorrelation() {
    return typeof this.b === "number";
  }
};
function $Ol(path3, candidate, ignoreCase) {
  if (!path3 || !candidate || path3 === candidate) {
    return false;
  }
  if (candidate.length > path3.length) {
    return false;
  }
  if (candidate.charAt(candidate.length - 1) !== sep) {
    candidate += sep;
  }
  if (ignoreCase) {
    return $1f(path3, candidate);
  }
  return path3.indexOf(candidate) === 0;
}
var $Pl = class extends Error {
  constructor(message, fileOperationResult, options) {
    super(message);
    this.fileOperationResult = fileOperationResult;
    this.options = options;
  }
};
var $Ql = class extends $Pl {
  constructor(message, fileOperationResult, size, options) {
    super(message, fileOperationResult, options);
    this.fileOperationResult = fileOperationResult;
    this.size = size;
  }
};
var $Rl = class extends $Pl {
  constructor(message, stat, options) {
    super(message, 2, options);
    this.stat = stat;
  }
};
var FileOperationResult;
(function(FileOperationResult2) {
  FileOperationResult2[FileOperationResult2["FILE_IS_DIRECTORY"] = 0] = "FILE_IS_DIRECTORY";
  FileOperationResult2[FileOperationResult2["FILE_NOT_FOUND"] = 1] = "FILE_NOT_FOUND";
  FileOperationResult2[FileOperationResult2["FILE_NOT_MODIFIED_SINCE"] = 2] = "FILE_NOT_MODIFIED_SINCE";
  FileOperationResult2[FileOperationResult2["FILE_MODIFIED_SINCE"] = 3] = "FILE_MODIFIED_SINCE";
  FileOperationResult2[FileOperationResult2["FILE_MOVE_CONFLICT"] = 4] = "FILE_MOVE_CONFLICT";
  FileOperationResult2[FileOperationResult2["FILE_WRITE_LOCKED"] = 5] = "FILE_WRITE_LOCKED";
  FileOperationResult2[FileOperationResult2["FILE_PERMISSION_DENIED"] = 6] = "FILE_PERMISSION_DENIED";
  FileOperationResult2[FileOperationResult2["FILE_TOO_LARGE"] = 7] = "FILE_TOO_LARGE";
  FileOperationResult2[FileOperationResult2["FILE_INVALID_PATH"] = 8] = "FILE_INVALID_PATH";
  FileOperationResult2[FileOperationResult2["FILE_NOT_DIRECTORY"] = 9] = "FILE_NOT_DIRECTORY";
  FileOperationResult2[FileOperationResult2["FILE_OTHER_ERROR"] = 10] = "FILE_OTHER_ERROR";
})(FileOperationResult || (FileOperationResult = {}));
var $Tl = {
  OFF: "off",
  ON_EXIT: "onExit",
  ON_EXIT_AND_WINDOW_CLOSE: "onExitAndWindowClose"
};
var FileKind;
(function(FileKind2) {
  FileKind2[FileKind2["FILE"] = 0] = "FILE";
  FileKind2[FileKind2["FOLDER"] = 1] = "FOLDER";
  FileKind2[FileKind2["ROOT_FOLDER"] = 2] = "ROOT_FOLDER";
})(FileKind || (FileKind = {}));
var $Zl = "";
function $1l(stat) {
  if (typeof stat.size !== "number" || typeof stat.mtime !== "number") {
    return void 0;
  }
  return stat.mtime.toString(29) + stat.size.toString(31);
}
var $3l = class _$3l {
  static {
    this.KB = 1024;
  }
  static {
    this.MB = _$3l.KB * _$3l.KB;
  }
  static {
    this.GB = _$3l.MB * _$3l.KB;
  }
  static {
    this.TB = _$3l.GB * _$3l.KB;
  }
  static formatSize(size) {
    if (!$Cg(size)) {
      size = 0;
    }
    if (size < _$3l.KB) {
      return localize(1880, null, size.toFixed(0));
    }
    if (size < _$3l.MB) {
      return localize(1881, null, (size / _$3l.KB).toFixed(2));
    }
    if (size < _$3l.GB) {
      return localize(1882, null, (size / _$3l.MB).toFixed(2));
    }
    if (size < _$3l.TB) {
      return localize(1883, null, (size / _$3l.GB).toFixed(2));
    }
    return localize(1884, null, (size / _$3l.TB).toFixed(2));
  }
};

// out-build/vs/platform/lifecycle/electron-main/lifecycleMainService.js
import electron2 from "electron";

// out-build/vs/platform/state/node/state.js
var $AS = $Zi("stateReadService");
var $BS = $Zi("stateService");

// out-build/vs/platform/lifecycle/electron-main/lifecycleMainService.js
var $0jc_1;
var $9jc = $Zi("lifecycleMainService");
var ShutdownReason;
(function(ShutdownReason2) {
  ShutdownReason2[ShutdownReason2["QUIT"] = 1] = "QUIT";
  ShutdownReason2[ShutdownReason2["KILL"] = 2] = "KILL";
})(ShutdownReason || (ShutdownReason = {}));
var LifecycleMainPhase;
(function(LifecycleMainPhase2) {
  LifecycleMainPhase2[LifecycleMainPhase2["Starting"] = 1] = "Starting";
  LifecycleMainPhase2[LifecycleMainPhase2["Ready"] = 2] = "Ready";
  LifecycleMainPhase2[LifecycleMainPhase2["AfterWindowOpen"] = 3] = "AfterWindowOpen";
  LifecycleMainPhase2[LifecycleMainPhase2["Eventually"] = 4] = "Eventually";
})(LifecycleMainPhase || (LifecycleMainPhase = {}));
var $0jc = class $0jc2 extends $0c {
  static {
    $0jc_1 = this;
  }
  static {
    this.b = "lifecycle.quitAndRestart";
  }
  get quitRequested() {
    return this.j;
  }
  get wasRestarted() {
    return this.m;
  }
  get phase() {
    return this.n;
  }
  constructor(F, G, H) {
    super();
    this.F = F;
    this.G = G;
    this.H = H;
    this.c = this.B(new $De());
    this.onBeforeShutdown = this.c.event;
    this.f = this.B(new $De());
    this.onWillShutdown = this.f.event;
    this.g = this.B(new $De());
    this.onWillLoadWindow = this.g.event;
    this.h = this.B(new $De());
    this.onBeforeCloseWindow = this.h.event;
    this.j = false;
    this.m = false;
    this.n = 1;
    this.r = /* @__PURE__ */ new Set();
    this.s = 0;
    this.t = 0;
    this.u = void 0;
    this.w = void 0;
    this.y = void 0;
    this.z = /* @__PURE__ */ new Map();
    this.C = /* @__PURE__ */ new Map();
    this.D = void 0;
    this.I();
    this.when(
      2
      /* LifecycleMainPhase.Ready */
    ).then(() => this.J());
  }
  I() {
    this.m = !!this.G.getItem($0jc_1.b);
    if (this.m) {
      this.G.removeItem($0jc_1.b);
    }
  }
  J() {
    const beforeQuitListener = () => {
      if (this.j) {
        return;
      }
      this.S("Lifecycle#app.on(before-quit)");
      this.j = true;
      this.S("Lifecycle#onBeforeShutdown.fire()");
      this.c.fire();
      if ($m && this.t === 0) {
        this.L(
          1
          /* ShutdownReason.QUIT */
        );
      }
    };
    electron2.app.addListener("before-quit", beforeQuitListener);
    const windowAllClosedListener = () => {
      this.S("Lifecycle#app.on(window-all-closed)");
      if (this.j || !$m) {
        electron2.app.quit();
      }
    };
    electron2.app.addListener("window-all-closed", windowAllClosedListener);
    electron2.app.once("will-quit", (e) => {
      this.S("Lifecycle#app.on(will-quit) - begin");
      e.preventDefault();
      const shutdownPromise = this.L(
        1
        /* ShutdownReason.QUIT */
      );
      shutdownPromise.finally(() => {
        this.S("Lifecycle#app.on(will-quit) - after fireOnWillShutdown");
        this.O(
          false
          /* no veto */
        );
        electron2.app.removeListener("before-quit", beforeQuitListener);
        electron2.app.removeListener("window-all-closed", windowAllClosedListener);
        this.S("Lifecycle#app.on(will-quit) - calling app.quit()");
        electron2.app.quit();
      });
    });
  }
  L(reason) {
    if (this.y) {
      return this.y;
    }
    const logService = this.F;
    this.S("Lifecycle#onWillShutdown.fire()");
    const joiners = [];
    this.f.fire({
      reason,
      join(id2, promise) {
        logService.trace(`Lifecycle#onWillShutdown - begin '${id2}'`);
        joiners.push(promise.finally(() => {
          logService.trace(`Lifecycle#onWillShutdown - end '${id2}'`);
        }));
      }
    });
    this.y = (async () => {
      try {
        await Promises.settled(joiners);
      } catch (error) {
        this.F.error(error);
      }
      try {
        await this.G.close();
      } catch (error) {
        this.F.error(error);
      }
    })();
    return this.y;
  }
  set phase(value) {
    if (value < this.phase) {
      throw new Error("Lifecycle cannot go backwards");
    }
    if (this.n === value) {
      return;
    }
    this.S(`lifecycle (main): phase changed (value: ${value})`);
    this.n = value;
    const barrier = this.C.get(this.n);
    if (barrier) {
      barrier.open();
      this.C.delete(this.n);
    }
  }
  async when(phase) {
    if (phase <= this.n) {
      return;
    }
    let barrier = this.C.get(phase);
    if (!barrier) {
      barrier = new $Yh();
      this.C.set(phase, barrier);
    }
    await barrier.wait();
  }
  registerWindow(window2) {
    const windowListeners = new $9c();
    this.t++;
    windowListeners.add(window2.onWillLoad((e) => this.g.fire({ window: window2, workspace: e.workspace, reason: e.reason })));
    const win = $Jg(window2.win);
    windowListeners.add(Event.fromNodeEventEmitter(win, "close")((e) => {
      const windowId = window2.id;
      if (this.r.has(windowId)) {
        this.r.delete(windowId);
        return;
      }
      this.S(`Lifecycle#window.on('close') - window ID ${window2.id}`);
      e.preventDefault();
      this.unload(
        window2,
        1
        /* UnloadReason.CLOSE */
      ).then((veto) => {
        if (veto) {
          this.r.delete(windowId);
          return;
        }
        this.r.add(windowId);
        this.S(`Lifecycle#onBeforeCloseWindow.fire() - window ID ${windowId}`);
        this.h.fire(window2);
        window2.close();
      });
    }));
    windowListeners.add(Event.fromNodeEventEmitter(win, "closed")(() => {
      this.S(`Lifecycle#window.on('closed') - window ID ${window2.id}`);
      this.t--;
      windowListeners.dispose();
      if (this.t === 0 && (!$m || this.j)) {
        this.L(
          1
          /* ShutdownReason.QUIT */
        );
      }
    }));
  }
  registerAuxWindow(auxWindow) {
    const win = $Jg(auxWindow.win);
    const windowListeners = new $9c();
    windowListeners.add(Event.fromNodeEventEmitter(win, "close")((e) => {
      this.S(`Lifecycle#auxWindow.on('close') - window ID ${auxWindow.id}`);
      if (this.j) {
        this.S(`Lifecycle#auxWindow.on('close') - preventDefault() because quit requested`);
        e.preventDefault();
      }
    }));
    windowListeners.add(Event.fromNodeEventEmitter(win, "closed")(() => {
      this.S(`Lifecycle#auxWindow.on('closed') - window ID ${auxWindow.id}`);
      windowListeners.dispose();
    }));
  }
  async reload(window2, cli) {
    const veto = await this.unload(
      window2,
      3
      /* UnloadReason.RELOAD */
    );
    if (!veto) {
      window2.reload(cli);
    }
  }
  unload(window2, reason) {
    const pendingUnloadPromise = this.z.get(window2.id);
    if (pendingUnloadPromise) {
      return pendingUnloadPromise;
    }
    const unloadPromise = this.M(window2, reason).finally(() => {
      this.z.delete(window2.id);
    });
    this.z.set(window2.id, unloadPromise);
    return unloadPromise;
  }
  async M(window2, reason) {
    if (!window2.isReady) {
      return false;
    }
    this.S(`Lifecycle#unload() - window ID ${window2.id}`);
    const windowUnloadReason = this.j ? 2 : reason;
    const veto = await this.P(window2, windowUnloadReason);
    if (veto) {
      this.S(`Lifecycle#unload() - veto in renderer (window ID ${window2.id})`);
      return this.N(veto);
    }
    await this.Q(window2, windowUnloadReason);
    return false;
  }
  N(veto) {
    if (!veto) {
      return false;
    }
    this.O(
      true
      /* veto */
    );
    this.j = false;
    return true;
  }
  O(veto) {
    if (this.w) {
      this.w(veto);
      this.w = void 0;
      this.u = void 0;
    }
  }
  P(window2, reason) {
    return new Promise((resolve2) => {
      const oneTimeEventToken = this.s++;
      const okChannel = `vscode:ok${oneTimeEventToken}`;
      const cancelChannel = `vscode:cancel${oneTimeEventToken}`;
      $ZY.once(okChannel, () => {
        resolve2(false);
      });
      $ZY.once(cancelChannel, () => {
        resolve2(true);
      });
      window2.send("vscode:onBeforeUnload", { okChannel, cancelChannel, reason });
    });
  }
  Q(window2, reason) {
    return new Promise((resolve2) => {
      const oneTimeEventToken = this.s++;
      const replyChannel = `vscode:reply${oneTimeEventToken}`;
      $ZY.once(replyChannel, () => resolve2());
      window2.send("vscode:onWillUnload", { replyChannel, reason });
    });
  }
  quit(willRestart) {
    return this.R(willRestart).then((veto) => {
      if (!veto && willRestart) {
        try {
          if ($l) {
            const currentWorkingDir = cwd();
            if (currentWorkingDir !== process.cwd()) {
              process.chdir(currentWorkingDir);
            }
          }
        } catch (err) {
          this.F.error(err);
        }
      }
      return veto;
    });
  }
  R(willRestart) {
    this.S(`Lifecycle#quit() - begin (willRestart: ${willRestart})`);
    if (this.u) {
      this.S("Lifecycle#quit() - returning pending quit promise");
      return this.u;
    }
    if (willRestart) {
      this.G.setItem($0jc_1.b, true);
    }
    this.u = new Promise((resolve2) => {
      this.w = resolve2;
      this.S("Lifecycle#quit() - calling app.quit()");
      electron2.app.quit();
    });
    return this.u;
  }
  S(msg) {
    if (this.H.args["enable-smoke-test-driver"]) {
      this.F.info(msg);
    } else {
      this.F.trace(msg);
    }
  }
  setRelaunchHandler(handler) {
    this.D = handler;
  }
  async relaunch(options) {
    this.S("Lifecycle#relaunch()");
    const args = process.argv.slice(1);
    if (options?.addArgs) {
      args.push(...options.addArgs);
    }
    if (options?.removeArgs) {
      for (const a of options.removeArgs) {
        const idx = args.indexOf(a);
        if (idx >= 0) {
          args.splice(idx, 1);
        }
      }
    }
    const quitListener = () => {
      if (!this.D?.handleRelaunch(options)) {
        this.S("Lifecycle#relaunch() - calling app.relaunch()");
        electron2.app.relaunch({ args });
      }
    };
    electron2.app.once("quit", quitListener);
    const veto = await this.quit(
      true
      /* will restart */
    );
    if (veto) {
      electron2.app.removeListener("quit", quitListener);
    }
  }
  async kill(code2) {
    this.S("Lifecycle#kill()");
    await this.L(
      2
      /* ShutdownReason.KILL */
    );
    await Promise.race([
      // Still do not block more than 1s
      $1h(1e3),
      // Destroy any opened window: we do not unload windows here because
      // there is a chance that the unload is veto'd or long running due
      // to a participant within the window. this is not wanted when we
      // are asked to kill the application.
      (async () => {
        for (const window2 of electron2.BrowserWindow.getAllWindows()) {
          if (window2 && !window2.isDestroyed()) {
            let whenWindowClosed;
            if (window2.webContents && !window2.webContents.isDestroyed()) {
              whenWindowClosed = new Promise((resolve2) => window2.once("closed", resolve2));
            } else {
              whenWindowClosed = Promise.resolve();
            }
            window2.destroy();
            await whenWindowClosed;
          }
        }
      })()
    ]);
    electron2.app.exit(code2);
  }
};
$0jc = $0jc_1 = __decorate([
  __param(0, $uk),
  __param(1, $BS),
  __param(2, $Cjc)
], $0jc);

// out-build/vs/base/parts/storage/common/storage.js
var StorageHint;
(function(StorageHint2) {
  StorageHint2[StorageHint2["STORAGE_DOES_NOT_EXIST"] = 0] = "STORAGE_DOES_NOT_EXIST";
  StorageHint2[StorageHint2["STORAGE_IN_MEMORY"] = 1] = "STORAGE_IN_MEMORY";
})(StorageHint || (StorageHint = {}));
var StorageState;
(function(StorageState2) {
  StorageState2[StorageState2["None"] = 0] = "None";
  StorageState2[StorageState2["Initialized"] = 1] = "Initialized";
  StorageState2[StorageState2["Closed"] = 2] = "Closed";
})(StorageState || (StorageState = {}));
var $zq = class _$zq extends $0c {
  static {
    this.a = 100;
  }
  constructor(r, s = /* @__PURE__ */ Object.create(null)) {
    super();
    this.r = r;
    this.s = s;
    this.b = this.B(new $Ge());
    this.onDidChangeStorage = this.b.event;
    this.c = StorageState.None;
    this.f = /* @__PURE__ */ new Map();
    this.g = this.B(new $Xh(_$zq.a));
    this.h = /* @__PURE__ */ new Set();
    this.j = /* @__PURE__ */ new Map();
    this.m = void 0;
    this.n = [];
    this.t();
  }
  t() {
    this.B(this.r.onDidChangeItemsExternal((e) => this.u(e)));
  }
  u(e) {
    this.b.pause();
    try {
      e.changed?.forEach((value, key) => this.w(key, value));
      e.deleted?.forEach((key) => this.w(key, void 0));
    } finally {
      this.b.resume();
    }
  }
  w(key, value) {
    if (this.c === StorageState.Closed) {
      return;
    }
    let changed = false;
    if ($Hg(value)) {
      changed = this.f.delete(key);
    } else {
      const currentValue = this.f.get(key);
      if (currentValue !== value) {
        this.f.set(key, value);
        changed = true;
      }
    }
    if (changed) {
      this.b.fire({ key, external: true });
    }
  }
  get items() {
    return this.f;
  }
  get size() {
    return this.f.size;
  }
  async init() {
    if (this.c !== StorageState.None) {
      return;
    }
    this.c = StorageState.Initialized;
    if (this.s.hint === StorageHint.STORAGE_DOES_NOT_EXIST) {
      return;
    }
    this.f = await this.r.getItems();
  }
  get(key, fallbackValue) {
    const value = this.f.get(key);
    if ($Hg(value)) {
      return fallbackValue;
    }
    return value;
  }
  getBoolean(key, fallbackValue) {
    const value = this.get(key);
    if ($Hg(value)) {
      return fallbackValue;
    }
    return value === "true";
  }
  getNumber(key, fallbackValue) {
    const value = this.get(key);
    if ($Hg(value)) {
      return fallbackValue;
    }
    return parseInt(value, 10);
  }
  getObject(key, fallbackValue) {
    const value = this.get(key);
    if ($Hg(value)) {
      return fallbackValue;
    }
    return $vi(value);
  }
  async set(key, value, external = false) {
    if (this.c === StorageState.Closed) {
      return;
    }
    if ($Hg(value)) {
      return this.delete(key, external);
    }
    const valueStr = $Ag(value) || Array.isArray(value) ? $ui(value) : String(value);
    const currentValue = this.f.get(key);
    if (currentValue === valueStr) {
      return;
    }
    this.f.set(key, valueStr);
    this.j.set(key, valueStr);
    this.h.delete(key);
    this.b.fire({ key, external });
    return this.D();
  }
  async delete(key, external = false) {
    if (this.c === StorageState.Closed) {
      return;
    }
    const wasDeleted = this.f.delete(key);
    if (!wasDeleted) {
      return;
    }
    if (!this.h.has(key)) {
      this.h.add(key);
    }
    this.j.delete(key);
    this.b.fire({ key, external });
    return this.D();
  }
  async optimize() {
    if (this.c === StorageState.Closed) {
      return;
    }
    await this.flush(0);
    return this.r.optimize();
  }
  async close() {
    if (!this.m) {
      this.m = this.y();
    }
    return this.m;
  }
  async y() {
    this.c = StorageState.Closed;
    try {
      await this.D(
        0
        /* as soon as possible */
      );
    } catch (error) {
    }
    await this.r.close(() => this.f);
  }
  get z() {
    return this.j.size > 0 || this.h.size > 0;
  }
  async C() {
    if (!this.z) {
      return;
    }
    const updateRequest = { insert: this.j, delete: this.h };
    this.h = /* @__PURE__ */ new Set();
    this.j = /* @__PURE__ */ new Map();
    return this.r.updateItems(updateRequest).finally(() => {
      if (!this.z) {
        while (this.n.length) {
          this.n.pop()?.();
        }
      }
    });
  }
  async flush(delay) {
    if (this.c === StorageState.Closed || // Return early if we are already closed
    this.m) {
      return;
    }
    return this.D(delay);
  }
  async D(delay) {
    if (this.s.hint === StorageHint.STORAGE_IN_MEMORY) {
      return this.C();
    }
    return this.g.trigger(() => this.C(), delay);
  }
  async whenFlushed() {
    if (!this.z) {
      return;
    }
    return new Promise((resolve2) => this.n.push(resolve2));
  }
  isInMemory() {
    return this.s.hint === StorageHint.STORAGE_IN_MEMORY;
  }
};
var $Aq = class {
  constructor() {
    this.onDidChangeItemsExternal = Event.None;
    this.a = /* @__PURE__ */ new Map();
  }
  async getItems() {
    return this.a;
  }
  async updateItems(request) {
    request.insert?.forEach((value, key) => this.a.set(key, value));
    request.delete?.forEach((key) => this.a.delete(key));
  }
  async optimize() {
  }
  async close() {
  }
};

// out-build/vs/platform/workspace/common/workspace.js
var $9i = $Zi("contextService");
function $0i(obj) {
  const singleFolderIdentifier = obj;
  return typeof singleFolderIdentifier?.id === "string" && URI.isUri(singleFolderIdentifier.uri);
}
var $_i = { id: "ext-dev" };
var $aj = { id: "empty-window" };
function $bj(arg0, isExtensionDevelopment) {
  if (typeof arg0 === "string" || typeof arg0 === "undefined") {
    if (typeof arg0 === "string") {
      return {
        id: $zc(arg0)
      };
    }
    if (isExtensionDevelopment) {
      return $_i;
    }
    return $aj;
  }
  const workspace = arg0;
  if (workspace.configuration) {
    return {
      id: workspace.id,
      configPath: workspace.configuration
    };
  }
  if (workspace.folders.length === 1) {
    return {
      id: workspace.id,
      uri: workspace.folders[0].uri
    };
  }
  return {
    id: workspace.id
  };
}
function $cj(obj) {
  const workspaceIdentifier = obj;
  return typeof workspaceIdentifier?.id === "string" && URI.isUri(workspaceIdentifier.configPath);
}
function $dj(identifier) {
  const singleFolderIdentifierCandidate = identifier;
  if (singleFolderIdentifierCandidate?.uri) {
    return { id: singleFolderIdentifierCandidate.id, uri: URI.revive(singleFolderIdentifierCandidate.uri) };
  }
  const workspaceIdentifierCandidate = identifier;
  if (workspaceIdentifierCandidate?.configPath) {
    return { id: workspaceIdentifierCandidate.id, configPath: URI.revive(workspaceIdentifierCandidate.configPath) };
  }
  if (identifier?.id) {
    return { id: identifier.id };
  }
  return void 0;
}
var WorkbenchState;
(function(WorkbenchState2) {
  WorkbenchState2[WorkbenchState2["EMPTY"] = 1] = "EMPTY";
  WorkbenchState2[WorkbenchState2["FOLDER"] = 2] = "FOLDER";
  WorkbenchState2[WorkbenchState2["WORKSPACE"] = 3] = "WORKSPACE";
})(WorkbenchState || (WorkbenchState = {}));
var $hj = class {
  constructor(data, raw) {
    this.raw = raw;
    this.uri = data.uri;
    this.index = data.index;
    this.name = data.name;
  }
  toResource(relativePath) {
    return $Ah(this.uri, relativePath);
  }
  toJSON() {
    return { uri: this.uri, name: this.name, index: this.index };
  }
};
var $jj = "code-workspace";
var $kj = `.${$jj}`;
var $lj = [{ name: localize(2503, null), extensions: [$jj] }];
var $mj = "workspace.json";
function $nj(path3, environmentService) {
  return $rh.isEqualOrParent(path3, environmentService.untitledWorkspacesHome);
}
function $sj(path3) {
  const ext = typeof path3 === "string" ? $Ac(path3) : $yh(path3);
  return ext === $kj;
}

// out-build/vs/platform/uriIdentity/common/uriIdentity.js
var $5l = $Zi("IUriIdentityService");

// out-build/vs/platform/userDataProfile/common/userDataProfile.js
var ProfileResourceType;
(function(ProfileResourceType2) {
  ProfileResourceType2["Settings"] = "settings";
  ProfileResourceType2["Keybindings"] = "keybindings";
  ProfileResourceType2["Snippets"] = "snippets";
  ProfileResourceType2["Tasks"] = "tasks";
  ProfileResourceType2["Extensions"] = "extensions";
  ProfileResourceType2["GlobalState"] = "globalState";
})(ProfileResourceType || (ProfileResourceType = {}));
function $6l(thing) {
  const candidate = thing;
  return !!(candidate && typeof candidate === "object" && typeof candidate.id === "string" && typeof candidate.isDefault === "boolean" && typeof candidate.name === "string" && URI.isUri(candidate.location) && URI.isUri(candidate.globalStorageHome) && URI.isUri(candidate.settingsResource) && URI.isUri(candidate.keybindingsResource) && URI.isUri(candidate.tasksResource) && URI.isUri(candidate.snippetsHome) && URI.isUri(candidate.extensionsResource));
}
var $7l = $Zi("IUserDataProfilesService");
function $9l(id2, name, location, profilesCacheHome, options, defaultProfile) {
  return {
    id: id2,
    name,
    location,
    isDefault: false,
    shortName: options?.shortName,
    icon: options?.icon,
    globalStorageHome: defaultProfile && options?.useDefaultFlags?.globalState ? defaultProfile.globalStorageHome : $Ah(location, "globalStorage"),
    settingsResource: defaultProfile && options?.useDefaultFlags?.settings ? defaultProfile.settingsResource : $Ah(location, "settings.json"),
    keybindingsResource: defaultProfile && options?.useDefaultFlags?.keybindings ? defaultProfile.keybindingsResource : $Ah(location, "keybindings.json"),
    tasksResource: defaultProfile && options?.useDefaultFlags?.tasks ? defaultProfile.tasksResource : $Ah(location, "tasks.json"),
    snippetsHome: defaultProfile && options?.useDefaultFlags?.snippets ? defaultProfile.snippetsHome : $Ah(location, "snippets"),
    extensionsResource: defaultProfile && options?.useDefaultFlags?.extensions ? defaultProfile.extensionsResource : $Ah(location, "extensions.json"),
    cacheHome: $Ah(profilesCacheHome, id2),
    useDefaultFlags: options?.useDefaultFlags,
    isTransient: options?.transient,
    workspaces: options?.workspaces
  };
}
var $0l = class $0l2 extends $0c {
  static {
    this.b = "userDataProfiles";
  }
  static {
    this.c = "profileAssociations";
  }
  get defaultProfile() {
    return this.profiles[0];
  }
  get profiles() {
    return [...this.D.profiles, ...this.s.profiles];
  }
  constructor(t, u, y, z) {
    super();
    this.t = t;
    this.u = u;
    this.y = y;
    this.z = z;
    this.f = true;
    this.h = this.B(new $De());
    this.onDidChangeProfiles = this.h.event;
    this.j = this.B(new $De());
    this.onWillCreateProfile = this.j.event;
    this.m = this.B(new $De());
    this.onWillRemoveProfile = this.m.event;
    this.n = this.B(new $De());
    this.onDidResetWorkspaces = this.n.event;
    this.r = /* @__PURE__ */ new Map();
    this.s = {
      profiles: [],
      emptyWindows: /* @__PURE__ */ new Map()
    };
    this.profilesHome = $Ah(this.t.userRoamingDataHome, "profiles");
    this.g = $Ah(this.t.cacheHome, "CachedProfilesData");
  }
  init() {
    this.C = void 0;
  }
  setEnablement(enabled) {
    if (this.f !== enabled) {
      this.C = void 0;
      this.f = enabled;
    }
  }
  isEnabled() {
    return this.f;
  }
  get D() {
    if (!this.C) {
      const defaultProfile = this.F();
      const profiles = [defaultProfile];
      if (this.f) {
        try {
          for (const storedProfile of this.P()) {
            if (!storedProfile.name || !$yg(storedProfile.name) || !storedProfile.location) {
              this.z.warn("Skipping the invalid stored profile", storedProfile.location || storedProfile.name);
              continue;
            }
            profiles.push($9l($xh(storedProfile.location), storedProfile.name, storedProfile.location, this.g, { shortName: storedProfile.shortName, icon: storedProfile.icon, useDefaultFlags: storedProfile.useDefaultFlags }, defaultProfile));
          }
        } catch (error) {
          this.z.error(error);
        }
      }
      const emptyWindows = /* @__PURE__ */ new Map();
      if (profiles.length) {
        try {
          const profileAssociaitions = this.R();
          if (profileAssociaitions.workspaces) {
            for (const [workspacePath, profileId] of Object.entries(profileAssociaitions.workspaces)) {
              const workspace = URI.parse(workspacePath);
              const profile = profiles.find((p) => p.id === profileId);
              if (profile) {
                const workspaces = profile.workspaces ? profile.workspaces.slice(0) : [];
                workspaces.push(workspace);
                profile.workspaces = workspaces;
              }
            }
          }
          if (profileAssociaitions.emptyWindows) {
            for (const [windowId, profileId] of Object.entries(profileAssociaitions.emptyWindows)) {
              const profile = profiles.find((p) => p.id === profileId);
              if (profile) {
                emptyWindows.set(windowId, profile);
              }
            }
          }
        } catch (error) {
          this.z.error(error);
        }
      }
      this.C = { profiles, emptyWindows };
    }
    return this.C;
  }
  F() {
    const defaultProfile = $9l("__default__profile__", localize(2456, null), this.t.userRoamingDataHome, this.g);
    return { ...defaultProfile, extensionsResource: this.U() ?? defaultProfile.extensionsResource, isDefault: true };
  }
  async createTransientProfile(workspaceIdentifier) {
    const namePrefix = `Temp`;
    const nameRegEx = new RegExp(`${$Af(namePrefix)}\\s(\\d+)`);
    let nameIndex = 0;
    for (const profile of this.profiles) {
      const matches = nameRegEx.exec(profile.name);
      const index = matches ? parseInt(matches[1]) : 0;
      nameIndex = index > nameIndex ? index : nameIndex;
    }
    const name = `${namePrefix} ${nameIndex + 1}`;
    return this.createProfile($Nj($jh()).toString(16), name, { transient: true }, workspaceIdentifier);
  }
  async createNamedProfile(name, options, workspaceIdentifier) {
    return this.createProfile($Nj($jh()).toString(16), name, options, workspaceIdentifier);
  }
  async createProfile(id2, name, options, workspaceIdentifier) {
    if (!this.f) {
      throw new Error(`Profiles are disabled in the current environment.`);
    }
    const profile = await this.G(id2, name, options, workspaceIdentifier);
    return profile;
  }
  async G(id2, name, options, workspaceIdentifier) {
    if (!$yg(name) || !name) {
      throw new Error("Name of the profile is mandatory and must be of type `string`");
    }
    let profileCreationPromise = this.r.get(name);
    if (!profileCreationPromise) {
      profileCreationPromise = (async () => {
        try {
          const existing = this.profiles.find((p) => p.id === id2 || !p.isTransient && !options?.transient && p.name === name);
          if (existing) {
            throw new Error(`Profile with ${name} name already exists`);
          }
          const workspace = workspaceIdentifier ? this.H(workspaceIdentifier) : void 0;
          if (URI.isUri(workspace)) {
            options = { ...options, workspaces: [workspace] };
          }
          const profile = $9l(id2, name, $Ah(this.profilesHome, id2), this.g, options, this.defaultProfile);
          await this.u.createFolder(profile.location);
          const joiners = [];
          this.j.fire({
            profile,
            join(promise) {
              joiners.push(promise);
            }
          });
          await Promises.settled(joiners);
          if (workspace && !URI.isUri(workspace)) {
            this.M(workspace, profile, !!profile.isTransient);
          }
          this.J([profile], [], []);
          return profile;
        } finally {
          this.r.delete(name);
        }
      })();
      this.r.set(name, profileCreationPromise);
    }
    return profileCreationPromise;
  }
  async updateProfile(profile, options) {
    if (!this.f) {
      throw new Error(`Profiles are disabled in the current environment.`);
    }
    const profilesToUpdate = [];
    for (const existing of this.profiles) {
      let profileToUpdate;
      if (profile.id === existing.id) {
        if (!existing.isDefault) {
          profileToUpdate = $9l(existing.id, options.name ?? existing.name, existing.location, this.g, {
            shortName: options.shortName ?? existing.shortName,
            icon: options.icon === null ? void 0 : options.icon ?? existing.icon,
            transient: options.transient ?? existing.isTransient,
            useDefaultFlags: options.useDefaultFlags ?? existing.useDefaultFlags,
            workspaces: options.workspaces ?? existing.workspaces
          }, this.defaultProfile);
        } else if (options.workspaces) {
          profileToUpdate = existing;
          profileToUpdate.workspaces = options.workspaces;
        }
      } else if (options.workspaces) {
        const workspaces = existing.workspaces?.filter((w1) => !options.workspaces?.some((w2) => this.y.extUri.isEqual(w1, w2)));
        if (existing.workspaces?.length !== workspaces?.length) {
          profileToUpdate = existing;
          profileToUpdate.workspaces = workspaces;
        }
      }
      if (profileToUpdate) {
        profilesToUpdate.push(profileToUpdate);
      }
    }
    if (!profilesToUpdate.length) {
      if (profile.isDefault) {
        throw new Error("Cannot update default profile");
      }
      throw new Error(`Profile '${profile.name}' does not exist`);
    }
    this.J([], [], profilesToUpdate);
    const updatedProfile = this.profiles.find((p) => p.id === profile.id);
    if (!updatedProfile) {
      throw new Error(`Profile '${profile.name}' was not updated`);
    }
    return updatedProfile;
  }
  async removeProfile(profileToRemove) {
    if (!this.f) {
      throw new Error(`Profiles are disabled in the current environment.`);
    }
    if (profileToRemove.isDefault) {
      throw new Error("Cannot remove default profile");
    }
    const profile = this.profiles.find((p) => p.id === profileToRemove.id);
    if (!profile) {
      throw new Error(`Profile '${profileToRemove.name}' does not exist`);
    }
    const joiners = [];
    this.m.fire({
      profile,
      join(promise) {
        joiners.push(promise);
      }
    });
    try {
      await Promise.allSettled(joiners);
    } catch (error) {
      this.z.error(error);
    }
    this.J([], [profile], []);
    try {
      await this.u.del(profile.cacheHome, { recursive: true });
    } catch (error) {
      if ($Ll(error) !== 1) {
        this.z.error(error);
      }
    }
  }
  async setProfileForWorkspace(workspaceIdentifier, profileToSet) {
    if (!this.f) {
      throw new Error(`Profiles are disabled in the current environment.`);
    }
    const profile = this.profiles.find((p) => p.id === profileToSet.id);
    if (!profile) {
      throw new Error(`Profile '${profileToSet.name}' does not exist`);
    }
    const workspace = this.H(workspaceIdentifier);
    if (URI.isUri(workspace)) {
      const workspaces = profile.workspaces ? [...profile.workspaces] : [];
      if (!workspaces.some((w) => this.y.extUri.isEqual(w, workspace))) {
        workspaces.push(workspace);
        await this.updateProfile(profile, { workspaces });
      }
    } else {
      this.M(workspace, profile, false);
      this.N(this.profiles);
    }
  }
  unsetWorkspace(workspaceIdentifier, transient = false) {
    if (!this.f) {
      throw new Error(`Profiles are disabled in the current environment.`);
    }
    const workspace = this.H(workspaceIdentifier);
    if (URI.isUri(workspace)) {
      const currentlyAssociatedProfile = this.getProfileForWorkspace(workspaceIdentifier);
      if (currentlyAssociatedProfile) {
        this.updateProfile(currentlyAssociatedProfile, { workspaces: currentlyAssociatedProfile.workspaces?.filter((w) => !this.y.extUri.isEqual(w, workspace)) });
      }
    } else {
      this.M(workspace, void 0, transient);
      this.N(this.profiles);
    }
  }
  async resetWorkspaces() {
    this.s.emptyWindows.clear();
    this.D.emptyWindows.clear();
    for (const profile of this.profiles) {
      profile.workspaces = void 0;
    }
    this.J([], [], this.profiles);
    this.n.fire();
  }
  async cleanUp() {
    if (!this.f) {
      return;
    }
    if (await this.u.exists(this.profilesHome)) {
      const stat = await this.u.resolve(this.profilesHome);
      await Promise.all((stat.children || []).filter((child) => child.isDirectory && this.profiles.every((p) => !this.y.extUri.isEqual(p.location, child.resource))).map((child) => this.u.del(child.resource, { recursive: true })));
    }
  }
  async cleanUpTransientProfiles() {
    if (!this.f) {
      return;
    }
    const unAssociatedTransientProfiles = this.s.profiles.filter((p) => !this.I(p));
    await Promise.allSettled(unAssociatedTransientProfiles.map((p) => this.removeProfile(p)));
  }
  getProfileForWorkspace(workspaceIdentifier) {
    const workspace = this.H(workspaceIdentifier);
    return URI.isUri(workspace) ? this.profiles.find((p) => p.workspaces?.some((w) => this.y.extUri.isEqual(w, workspace))) : this.D.emptyWindows.get(workspace) ?? this.s.emptyWindows.get(workspace);
  }
  H(workspaceIdentifier) {
    if ($0i(workspaceIdentifier)) {
      return workspaceIdentifier.uri;
    }
    if ($cj(workspaceIdentifier)) {
      return workspaceIdentifier.configPath;
    }
    return workspaceIdentifier.id;
  }
  I(profile) {
    if (profile.workspaces?.length) {
      return true;
    }
    if ([...this.D.emptyWindows.values()].some((windowProfile) => this.y.extUri.isEqual(windowProfile.location, profile.location))) {
      return true;
    }
    if ([...this.s.emptyWindows.values()].some((windowProfile) => this.y.extUri.isEqual(windowProfile.location, profile.location))) {
      return true;
    }
    return false;
  }
  J(added, removed, updated) {
    const allProfiles = [...this.profiles, ...added];
    const transientProfiles = this.s.profiles;
    this.s.profiles = [];
    const profiles = [];
    for (let profile of allProfiles) {
      if (removed.some((p) => profile.id === p.id)) {
        for (const windowId of [...this.D.emptyWindows.keys()]) {
          if (profile.id === this.D.emptyWindows.get(windowId)?.id) {
            this.D.emptyWindows.delete(windowId);
          }
        }
        continue;
      }
      if (!profile.isDefault) {
        profile = updated.find((p) => profile.id === p.id) ?? profile;
        const transientProfile = transientProfiles.find((p) => profile.id === p.id);
        if (profile.isTransient) {
          this.s.profiles.push(profile);
        } else {
          if (transientProfile) {
            for (const [windowId, p] of this.s.emptyWindows.entries()) {
              if (profile.id === p.id) {
                this.s.emptyWindows.delete(windowId);
                this.D.emptyWindows.set(windowId, profile);
                break;
              }
            }
          }
        }
      }
      if (profile.workspaces?.length === 0) {
        profile.workspaces = void 0;
      }
      profiles.push(profile);
    }
    this.N(profiles);
    this.L(added, removed, updated);
  }
  L(added, removed, updated) {
    this.h.fire({ added, removed, updated, all: this.profiles });
  }
  M(windowId, newProfile, transient) {
    transient = newProfile?.isTransient ? true : transient;
    if (transient) {
      if (newProfile) {
        this.s.emptyWindows.set(windowId, newProfile);
      } else {
        this.s.emptyWindows.delete(windowId);
      }
    } else {
      this.s.emptyWindows.delete(windowId);
      if (newProfile) {
        this.D.emptyWindows.set(windowId, newProfile);
      } else {
        this.D.emptyWindows.delete(windowId);
      }
    }
  }
  N(profiles) {
    const storedProfiles = [];
    const workspaces = {};
    const emptyWindows = {};
    for (const profile of profiles) {
      if (profile.isTransient) {
        continue;
      }
      if (!profile.isDefault) {
        storedProfiles.push({ location: profile.location, name: profile.name, shortName: profile.shortName, icon: profile.icon, useDefaultFlags: profile.useDefaultFlags });
      }
      if (profile.workspaces) {
        for (const workspace of profile.workspaces) {
          workspaces[workspace.toString()] = profile.id;
        }
      }
    }
    for (const [windowId, profile] of this.D.emptyWindows.entries()) {
      emptyWindows[windowId.toString()] = profile.id;
    }
    this.S({ workspaces, emptyWindows });
    this.Q(storedProfiles);
    this.C = void 0;
  }
  // TODO: @sandy081 Remove migration after couple of releases
  O(storedProfileAssociations) {
    const workspaces = {};
    const defaultProfile = this.F();
    if (storedProfileAssociations.workspaces) {
      for (const [workspace, location] of Object.entries(storedProfileAssociations.workspaces)) {
        const uri = URI.parse(location);
        workspaces[workspace] = this.y.extUri.isEqual(uri, defaultProfile.location) ? defaultProfile.id : this.y.extUri.basename(uri);
      }
    }
    const emptyWindows = {};
    if (storedProfileAssociations.emptyWindows) {
      for (const [workspace, location] of Object.entries(storedProfileAssociations.emptyWindows)) {
        const uri = URI.parse(location);
        emptyWindows[workspace] = this.y.extUri.isEqual(uri, defaultProfile.location) ? defaultProfile.id : this.y.extUri.basename(uri);
      }
    }
    return { workspaces, emptyWindows };
  }
  P() {
    return [];
  }
  Q(storedProfiles) {
    throw new Error("not implemented");
  }
  R() {
    return {};
  }
  S(storedProfileAssociations) {
    throw new Error("not implemented");
  }
  U() {
    return void 0;
  }
};
$0l = __decorate([
  __param(0, $7i),
  __param(1, $ul),
  __param(2, $5l),
  __param(3, $uk)
], $0l);

// out-build/vs/platform/storage/common/storage.js
var $Bq = "__$__isNewStorageMarker";
var $Cq = "__$__targetStorageMarker";
var $Dq = $Zi("storageService");
var WillSaveStateReason;
(function(WillSaveStateReason2) {
  WillSaveStateReason2[WillSaveStateReason2["NONE"] = 0] = "NONE";
  WillSaveStateReason2[WillSaveStateReason2["SHUTDOWN"] = 1] = "SHUTDOWN";
})(WillSaveStateReason || (WillSaveStateReason = {}));
var StorageScope;
(function(StorageScope2) {
  StorageScope2[StorageScope2["APPLICATION"] = -1] = "APPLICATION";
  StorageScope2[StorageScope2["PROFILE"] = 0] = "PROFILE";
  StorageScope2[StorageScope2["WORKSPACE"] = 1] = "WORKSPACE";
})(StorageScope || (StorageScope = {}));
var StorageTarget;
(function(StorageTarget2) {
  StorageTarget2[StorageTarget2["USER"] = 0] = "USER";
  StorageTarget2[StorageTarget2["MACHINE"] = 1] = "MACHINE";
})(StorageTarget || (StorageTarget = {}));
function $Eq(storage) {
  const keysRaw = storage.get($Cq);
  if (keysRaw) {
    try {
      return JSON.parse(keysRaw);
    } catch (error) {
    }
  }
  return /* @__PURE__ */ Object.create(null);
}
var $Fq = class _$Fq extends $0c {
  static {
    this.a = 60 * 1e3;
  }
  // every minute
  constructor(m = { flushInterval: _$Fq.a }) {
    super();
    this.m = m;
    this.b = this.B(new $Ge());
    this.c = this.B(new $Ge());
    this.onDidChangeTarget = this.c.event;
    this.f = this.B(new $De());
    this.onWillSaveState = this.f.event;
    this.h = this.B(new $_h(() => this.n(), this.m.flushInterval));
    this.j = this.B(new $$c());
    this.C = void 0;
    this.F = void 0;
    this.H = void 0;
  }
  onDidChangeValue(scope, key, disposable) {
    return Event.filter(this.b.event, (e) => e.scope === scope && (key === void 0 || e.key === key), disposable);
  }
  n() {
    this.j.value = $di(() => {
      if (this.r()) {
        this.flush();
      }
      this.h.schedule();
    });
  }
  r() {
    return true;
  }
  t() {
    $5c([this.j, this.h]);
  }
  initialize() {
    if (!this.g) {
      this.g = (async () => {
        mark("code/willInitStorage");
        try {
          await this.O();
        } finally {
          mark("code/didInitStorage");
        }
        this.h.schedule();
      })();
    }
    return this.g;
  }
  u(scope, event) {
    const { key, external } = event;
    if (key === $Cq) {
      switch (scope) {
        case -1:
          this.H = void 0;
          break;
        case 0:
          this.F = void 0;
          break;
        case 1:
          this.C = void 0;
          break;
      }
      this.c.fire({ scope });
    } else {
      this.b.fire({ scope, key, target: this.J(scope)[key], external });
    }
  }
  w(reason) {
    this.f.fire({ reason });
  }
  get(key, scope, fallbackValue) {
    return this.P(scope)?.get(key, fallbackValue);
  }
  getBoolean(key, scope, fallbackValue) {
    return this.P(scope)?.getBoolean(key, fallbackValue);
  }
  getNumber(key, scope, fallbackValue) {
    return this.P(scope)?.getNumber(key, fallbackValue);
  }
  getObject(key, scope, fallbackValue) {
    return this.P(scope)?.getObject(key, fallbackValue);
  }
  storeAll(entries, external) {
    this.y(() => {
      for (const entry of entries) {
        this.store(entry.key, entry.value, entry.scope, entry.target, external);
      }
    });
  }
  store(key, value, scope, target, external = false) {
    if ($Hg(value)) {
      this.remove(key, scope, external);
      return;
    }
    this.y(() => {
      this.z(key, scope, target);
      this.P(scope)?.set(key, value, external);
    });
  }
  remove(key, scope, external = false) {
    this.y(() => {
      this.z(key, scope, void 0);
      this.P(scope)?.delete(key, external);
    });
  }
  y(fn) {
    this.b.pause();
    this.c.pause();
    try {
      fn();
    } finally {
      this.b.resume();
      this.c.resume();
    }
  }
  keys(scope, target) {
    const keys = [];
    const keyTargets = this.J(scope);
    for (const key of Object.keys(keyTargets)) {
      const keyTarget = keyTargets[key];
      if (keyTarget === target) {
        keys.push(key);
      }
    }
    return keys;
  }
  z(key, scope, target, external = false) {
    const keyTargets = this.J(scope);
    if (typeof target === "number") {
      if (keyTargets[key] !== target) {
        keyTargets[key] = target;
        this.P(scope)?.set($Cq, JSON.stringify(keyTargets), external);
      }
    } else {
      if (typeof keyTargets[key] === "number") {
        delete keyTargets[key];
        this.P(scope)?.set($Cq, JSON.stringify(keyTargets), external);
      }
    }
  }
  get D() {
    if (!this.C) {
      this.C = this.L(
        1
        /* StorageScope.WORKSPACE */
      );
    }
    return this.C;
  }
  get G() {
    if (!this.F) {
      this.F = this.L(
        0
        /* StorageScope.PROFILE */
      );
    }
    return this.F;
  }
  get I() {
    if (!this.H) {
      this.H = this.L(
        -1
        /* StorageScope.APPLICATION */
      );
    }
    return this.H;
  }
  J(scope) {
    switch (scope) {
      case -1:
        return this.I;
      case 0:
        return this.G;
      default:
        return this.D;
    }
  }
  L(scope) {
    const storage = this.P(scope);
    return storage ? $Eq(storage) : /* @__PURE__ */ Object.create(null);
  }
  isNew(scope) {
    return this.getBoolean($Bq, scope) === true;
  }
  async flush(reason = WillSaveStateReason.NONE) {
    this.f.fire({ reason });
    const applicationStorage = this.P(
      -1
      /* StorageScope.APPLICATION */
    );
    const profileStorage = this.P(
      0
      /* StorageScope.PROFILE */
    );
    const workspaceStorage = this.P(
      1
      /* StorageScope.WORKSPACE */
    );
    switch (reason) {
      case WillSaveStateReason.NONE:
        await Promises.settled([
          applicationStorage?.whenFlushed() ?? Promise.resolve(),
          profileStorage?.whenFlushed() ?? Promise.resolve(),
          workspaceStorage?.whenFlushed() ?? Promise.resolve()
        ]);
        break;
      case WillSaveStateReason.SHUTDOWN:
        await Promises.settled([
          applicationStorage?.flush(0) ?? Promise.resolve(),
          profileStorage?.flush(0) ?? Promise.resolve(),
          workspaceStorage?.flush(0) ?? Promise.resolve()
        ]);
        break;
    }
  }
  async log() {
    const applicationItems = this.P(
      -1
      /* StorageScope.APPLICATION */
    )?.items ?? /* @__PURE__ */ new Map();
    const profileItems = this.P(
      0
      /* StorageScope.PROFILE */
    )?.items ?? /* @__PURE__ */ new Map();
    const workspaceItems = this.P(
      1
      /* StorageScope.WORKSPACE */
    )?.items ?? /* @__PURE__ */ new Map();
    return $Iq(applicationItems, profileItems, workspaceItems, this.Q(
      -1
      /* StorageScope.APPLICATION */
    ) ?? "", this.Q(
      0
      /* StorageScope.PROFILE */
    ) ?? "", this.Q(
      1
      /* StorageScope.WORKSPACE */
    ) ?? "");
  }
  async optimize(scope) {
    await this.flush();
    return this.P(scope)?.optimize();
  }
  async switch(to, preserveData) {
    this.w(WillSaveStateReason.NONE);
    if ($6l(to)) {
      return this.R(to, preserveData);
    }
    return this.S(to, preserveData);
  }
  M(from, to) {
    if (from.id === to.id) {
      return false;
    }
    if ($Gq(to) && $Gq(from)) {
      return false;
    }
    return true;
  }
  N(oldStorage, newStorage, scope) {
    this.y(() => {
      const handledkeys = /* @__PURE__ */ new Set();
      for (const [key, oldValue] of oldStorage) {
        handledkeys.add(key);
        const newValue = newStorage.get(key);
        if (newValue !== oldValue) {
          this.u(scope, { key, external: true });
        }
      }
      for (const [key] of newStorage.items) {
        if (!handledkeys.has(key)) {
          this.u(scope, { key, external: true });
        }
      }
    });
  }
};
function $Gq(profile) {
  return profile.isDefault || !!profile.useDefaultFlags?.globalState;
}
async function $Iq(application, profile, workspace, applicationPath, profilePath, workspacePath) {
  const safeParse = (value) => {
    try {
      return JSON.parse(value);
    } catch (error) {
      return value;
    }
  };
  const applicationItems = /* @__PURE__ */ new Map();
  const applicationItemsParsed = /* @__PURE__ */ new Map();
  application.forEach((value, key) => {
    applicationItems.set(key, value);
    applicationItemsParsed.set(key, safeParse(value));
  });
  const profileItems = /* @__PURE__ */ new Map();
  const profileItemsParsed = /* @__PURE__ */ new Map();
  profile.forEach((value, key) => {
    profileItems.set(key, value);
    profileItemsParsed.set(key, safeParse(value));
  });
  const workspaceItems = /* @__PURE__ */ new Map();
  const workspaceItemsParsed = /* @__PURE__ */ new Map();
  workspace.forEach((value, key) => {
    workspaceItems.set(key, value);
    workspaceItemsParsed.set(key, safeParse(value));
  });
  if (applicationPath !== profilePath) {
    console.group(`Storage: Application (path: ${applicationPath})`);
  } else {
    console.group(`Storage: Application & Profile (path: ${applicationPath}, default profile)`);
  }
  const applicationValues = [];
  applicationItems.forEach((value, key) => {
    applicationValues.push({ key, value });
  });
  console.table(applicationValues);
  console.groupEnd();
  console.log(applicationItemsParsed);
  if (applicationPath !== profilePath) {
    console.group(`Storage: Profile (path: ${profilePath}, profile specific)`);
    const profileValues = [];
    profileItems.forEach((value, key) => {
      profileValues.push({ key, value });
    });
    console.table(profileValues);
    console.groupEnd();
    console.log(profileItemsParsed);
  }
  console.group(`Storage: Workspace (path: ${workspacePath})`);
  const workspaceValues = [];
  workspaceItems.forEach((value, key) => {
    workspaceValues.push({ key, value });
  });
  console.table(workspaceValues);
  console.groupEnd();
  console.log(workspaceItemsParsed);
}

// out-build/vs/platform/storage/electron-main/storageMain.js
import * as fs3 from "fs";

// out-build/vs/base/parts/storage/node/storage.js
import * as fs2 from "fs";
var $sZ = class _$sZ {
  static {
    this.IN_MEMORY_PATH = ":memory:";
  }
  get onDidChangeItemsExternal() {
    return Event.None;
  }
  static {
    this.a = 2e3;
  }
  static {
    this.b = 256;
  }
  // maximum number of parameters within a statement
  constructor(g, h = /* @__PURE__ */ Object.create(null)) {
    this.g = g;
    this.h = h;
    this.c = $zc(this.g);
    this.d = new SQLiteStorageDatabaseLogger(this.h.logging);
    this.f = this.n(this.g);
  }
  async getItems() {
    const connection = await this.f;
    const items = /* @__PURE__ */ new Map();
    const rows = await this.s(connection, "SELECT * FROM ItemTable");
    rows.forEach((row) => items.set(row.key, row.value));
    if (this.d.isTracing) {
      this.d.trace(`[storage ${this.c}] getItems(): ${items.size} rows`);
    }
    return items;
  }
  async updateItems(request) {
    const connection = await this.f;
    return this.j(connection, request);
  }
  j(connection, request) {
    if (this.d.isTracing) {
      this.d.trace(`[storage ${this.c}] updateItems(): insert(${request.insert ? $Kc(request.insert) : "0"}), delete(${request.delete ? $Lc(request.delete) : "0"})`);
    }
    return this.t(connection, () => {
      const toInsert = request.insert;
      const toDelete = request.delete;
      if (toInsert && toInsert.size > 0) {
        const keysValuesChunks = [];
        keysValuesChunks.push([]);
        let currentChunkIndex = 0;
        toInsert.forEach((value, key) => {
          let keyValueChunk = keysValuesChunks[currentChunkIndex];
          if (keyValueChunk.length > _$sZ.b) {
            currentChunkIndex++;
            keyValueChunk = [];
            keysValuesChunks.push(keyValueChunk);
          }
          keyValueChunk.push(key, value);
        });
        keysValuesChunks.forEach((keysValuesChunk) => {
          this.u(connection, `INSERT INTO ItemTable VALUES ${new Array(keysValuesChunk.length / 2).fill("(?,?)").join(",")}`, (stmt) => stmt.run(keysValuesChunk), () => {
            const keys = [];
            let length = 0;
            toInsert.forEach((value, key) => {
              keys.push(key);
              length += value.length;
            });
            return `Keys: ${keys.join(", ")} Length: ${length}`;
          });
        });
      }
      if (toDelete && toDelete.size) {
        const keysChunks = [];
        keysChunks.push([]);
        let currentChunkIndex = 0;
        toDelete.forEach((key) => {
          let keyChunk = keysChunks[currentChunkIndex];
          if (keyChunk.length > _$sZ.b) {
            currentChunkIndex++;
            keyChunk = [];
            keysChunks.push(keyChunk);
          }
          keyChunk.push(key);
        });
        keysChunks.forEach((keysChunk) => {
          this.u(connection, `DELETE FROM ItemTable WHERE key IN (${new Array(keysChunk.length).fill("?").join(",")})`, (stmt) => stmt.run(keysChunk), () => {
            const keys = [];
            toDelete.forEach((key) => {
              keys.push(key);
            });
            return `Keys: ${keys.join(", ")}`;
          });
        });
      }
    });
  }
  async optimize() {
    this.d.trace(`[storage ${this.c}] vacuum()`);
    const connection = await this.f;
    return this.q(connection, "VACUUM");
  }
  async close(recovery) {
    this.d.trace(`[storage ${this.c}] close()`);
    const connection = await this.f;
    return this.k(connection, recovery);
  }
  k(connection, recovery) {
    return new Promise((resolve2, reject) => {
      connection.db.close((closeError) => {
        if (closeError) {
          this.o(connection, `[storage ${this.c}] close(): ${closeError}`);
        }
        if (this.g === _$sZ.IN_MEMORY_PATH) {
          return resolve2();
        }
        if (!connection.isErroneous && !connection.isInMemory) {
          return this.l().then(resolve2, (error) => {
            this.d.error(`[storage ${this.c}] backup(): ${error}`);
            return resolve2();
          });
        }
        if (typeof recovery === "function") {
          return fs2.promises.unlink(this.g).then(() => {
            return this.p(this.g).then((recoveryConnection) => {
              const closeRecoveryConnection = () => {
                return this.k(
                  recoveryConnection,
                  void 0
                  /* do not attempt to recover again */
                );
              };
              return this.j(recoveryConnection, { insert: recovery() }).then(() => closeRecoveryConnection(), (error) => {
                closeRecoveryConnection();
                return Promise.reject(error);
              });
            });
          }).then(resolve2, reject);
        }
        return reject(closeError || new Error("Database has errors or is in-memory without recovery option"));
      });
    });
  }
  l() {
    const backupPath = this.m(this.g);
    return Promises2.copy(this.g, backupPath, { preserveSymlinks: false });
  }
  m(path3) {
    return `${path3}.backup`;
  }
  async checkIntegrity(full) {
    this.d.trace(`[storage ${this.c}] checkIntegrity(full: ${full})`);
    const connection = await this.f;
    const row = await this.r(connection, full ? "PRAGMA integrity_check" : "PRAGMA quick_check");
    const integrity = full ? row["integrity_check"] : row["quick_check"];
    if (connection.isErroneous) {
      return `${integrity} (last error: ${connection.lastError})`;
    }
    if (connection.isInMemory) {
      return `${integrity} (in-memory!)`;
    }
    return integrity;
  }
  async n(path3, retryOnBusy = true) {
    this.d.trace(`[storage ${this.c}] open(${path3}, retryOnBusy: ${retryOnBusy})`);
    try {
      return await this.p(path3);
    } catch (error) {
      this.d.error(`[storage ${this.c}] open(): Unable to open DB due to ${error}`);
      if (error.code === "SQLITE_BUSY" && retryOnBusy) {
        await $1h(_$sZ.a);
        return this.n(
          path3,
          false
          /* not another retry */
        );
      }
      try {
        await fs2.promises.unlink(path3);
        try {
          await Promises2.rename(
            this.m(path3),
            path3,
            false
            /* no retry */
          );
        } catch (error2) {
        }
        return await this.p(path3);
      } catch (error2) {
        this.d.error(`[storage ${this.c}] open(): Unable to use backup due to ${error2}`);
        return this.p(_$sZ.IN_MEMORY_PATH);
      }
    }
  }
  o(connection, msg) {
    connection.isErroneous = true;
    connection.lastError = msg;
    this.d.error(msg);
  }
  p(path3) {
    return new Promise((resolve2, reject) => {
      import("@vscode/sqlite3").then((sqlite3) => {
        const ctor = this.d.isTracing ? sqlite3.default.verbose().Database : sqlite3.default.Database;
        const connection = {
          db: new ctor(path3, (error) => {
            if (error) {
              return connection.db && error.code !== "SQLITE_CANTOPEN" ? connection.db.close(() => reject(error)) : reject(error);
            }
            return this.q(connection, [
              "PRAGMA user_version = 1;",
              "CREATE TABLE IF NOT EXISTS ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB)"
            ].join("")).then(() => {
              return resolve2(connection);
            }, (error2) => {
              return connection.db.close(() => reject(error2));
            });
          }),
          isInMemory: path3 === _$sZ.IN_MEMORY_PATH
        };
        connection.db.on("error", (error) => this.o(connection, `[storage ${this.c}] Error (event): ${error}`));
        if (this.d.isTracing) {
          connection.db.on("trace", (sql) => this.d.trace(`[storage ${this.c}] Trace (event): ${sql}`));
        }
      }, reject);
    });
  }
  q(connection, sql) {
    return new Promise((resolve2, reject) => {
      connection.db.exec(sql, (error) => {
        if (error) {
          this.o(connection, `[storage ${this.c}] exec(): ${error}`);
          return reject(error);
        }
        return resolve2();
      });
    });
  }
  r(connection, sql) {
    return new Promise((resolve2, reject) => {
      connection.db.get(sql, (error, row) => {
        if (error) {
          this.o(connection, `[storage ${this.c}] get(): ${error}`);
          return reject(error);
        }
        return resolve2(row);
      });
    });
  }
  s(connection, sql) {
    return new Promise((resolve2, reject) => {
      connection.db.all(sql, (error, rows) => {
        if (error) {
          this.o(connection, `[storage ${this.c}] all(): ${error}`);
          return reject(error);
        }
        return resolve2(rows);
      });
    });
  }
  t(connection, transactions) {
    return new Promise((resolve2, reject) => {
      connection.db.serialize(() => {
        connection.db.run("BEGIN TRANSACTION");
        transactions();
        connection.db.run("END TRANSACTION", (error) => {
          if (error) {
            this.o(connection, `[storage ${this.c}] transaction(): ${error}`);
            return reject(error);
          }
          return resolve2();
        });
      });
    });
  }
  u(connection, sql, runCallback, errorDetails) {
    const stmt = connection.db.prepare(sql);
    const statementErrorListener = (error) => {
      this.o(connection, `[storage ${this.c}] prepare(): ${error} (${sql}). Details: ${errorDetails()}`);
    };
    stmt.on("error", statementErrorListener);
    runCallback(stmt);
    stmt.finalize((error) => {
      if (error) {
        statementErrorListener(error);
      }
      stmt.removeListener("error", statementErrorListener);
    });
  }
};
var SQLiteStorageDatabaseLogger = class _SQLiteStorageDatabaseLogger {
  static {
    this.a = "VSCODE_TRACE_STORAGE";
  }
  constructor(options) {
    if (options && typeof options.logTrace === "function" && process.env[_SQLiteStorageDatabaseLogger.a]) {
      this.b = options.logTrace;
    }
    if (options && typeof options.logError === "function") {
      this.c = options.logError;
    }
  }
  get isTracing() {
    return !!this.b;
  }
  trace(msg) {
    this.b?.(msg);
  }
  error(error) {
    this.c?.(error);
  }
};

// out-build/vs/platform/telemetry/common/telemetry.js
var $tm = $Zi("telemetryService");
var $um = $Zi("customEndpointTelemetryService");
var $vm = "telemetry.currentSessionDate";
var $wm = "telemetry.firstSessionDate";
var $xm = "telemetry.lastSessionDate";
var $ym = "telemetry.machineId";
var $zm = "telemetry.sqmId";
var $Am = "telemetry.devDeviceId";
var $Bm = "telemetry";
var $Cm = "telemetry.telemetryLevel";
var $Dm = "telemetry.enableCrashReporter";
var $Em = "telemetry.enableTelemetry";
var TelemetryLevel;
(function(TelemetryLevel2) {
  TelemetryLevel2[TelemetryLevel2["NONE"] = 0] = "NONE";
  TelemetryLevel2[TelemetryLevel2["CRASH"] = 1] = "CRASH";
  TelemetryLevel2[TelemetryLevel2["ERROR"] = 2] = "ERROR";
  TelemetryLevel2[TelemetryLevel2["USAGE"] = 3] = "USAGE";
})(TelemetryLevel || (TelemetryLevel = {}));
var TelemetryConfiguration;
(function(TelemetryConfiguration2) {
  TelemetryConfiguration2["OFF"] = "off";
  TelemetryConfiguration2["CRASH"] = "crash";
  TelemetryConfiguration2["ERROR"] = "error";
  TelemetryConfiguration2["ON"] = "all";
})(TelemetryConfiguration || (TelemetryConfiguration = {}));

// out-build/vs/platform/storage/electron-main/storageMain.js
var BaseStorageMain = class _BaseStorageMain extends $0c {
  static {
    this.a = 2e3;
  }
  get storage() {
    return this.f;
  }
  constructor(m, n) {
    super();
    this.m = m;
    this.n = n;
    this.b = this.B(new $De());
    this.onDidChangeStorage = this.b.event;
    this.c = this.B(new $De());
    this.onDidCloseStorage = this.c.event;
    this.f = this.B(new $zq(new $Aq(), { hint: StorageHint.STORAGE_IN_MEMORY }));
    this.g = void 0;
    this.h = new $ki();
    this.whenInit = this.h.p;
    this.j = StorageState.None;
  }
  isInMemory() {
    return this.f.isInMemory();
  }
  init() {
    if (!this.g) {
      this.g = (async () => {
        if (this.j !== StorageState.None) {
          return;
        }
        try {
          const storage = this.B(await this.t());
          this.f.dispose();
          this.f = storage;
          this.B(storage.onDidChangeStorage((e) => this.b.fire(e)));
          await this.s(storage);
          const isNewStorage = storage.getBoolean($Bq);
          if (isNewStorage === void 0) {
            storage.set($Bq, true);
          } else if (isNewStorage) {
            storage.set($Bq, false);
          }
        } catch (error) {
          this.m.error(`[storage main] initialize(): Unable to init storage due to ${error}`);
        } finally {
          this.j = StorageState.Initialized;
          this.h.complete();
        }
      })();
    }
    return this.g;
  }
  r() {
    return {
      logTrace: this.m.getLevel() === LogLevel.Trace ? (msg) => this.m.trace(msg) : void 0,
      logError: (error) => this.m.error(error)
    };
  }
  s(storage) {
    return storage.init();
  }
  get items() {
    return this.f.items;
  }
  get(key, fallbackValue) {
    return this.f.get(key, fallbackValue);
  }
  set(key, value) {
    return this.f.set(key, value);
  }
  delete(key) {
    return this.f.delete(key);
  }
  optimize() {
    return this.f.optimize();
  }
  async close() {
    const watch3 = new $xe(false);
    await this.w();
    watch3.stop();
    if (watch3.elapsed() > _BaseStorageMain.a) {
      await this.u(watch3);
    }
    this.c.fire();
  }
  async u(watch3) {
    if (!this.path) {
      return;
    }
    try {
      const largestEntries = top(Array.from(this.f.items.entries()).map(([key, value]) => ({ key, length: value.length })), (entryA, entryB) => entryB.length - entryA.length, 5).map((entry) => `${entry.key}:${entry.length}`).join(", ");
      const dbSize = (await this.n.stat(URI.file(this.path))).size;
      this.m.warn(`[storage main] detected slow close() operation: Time: ${watch3.elapsed()}ms, DB size: ${dbSize}b, Large Keys: ${largestEntries}`);
    } catch (error) {
      this.m.error("[storage main] figuring out stats for slow DB on close() resulted in an error", error);
    }
  }
  async w() {
    if (this.g) {
      await this.g;
    }
    this.j = StorageState.Closed;
    await this.f.close();
  }
};
var BaseProfileAwareStorageMain = class _BaseProfileAwareStorageMain extends BaseStorageMain {
  static {
    this.y = "state.vscdb";
  }
  get path() {
    if (!this.C.useInMemoryStorage) {
      return $vc(this.z.globalStorageHome.with({ scheme: Schemas.file }).fsPath, _BaseProfileAwareStorageMain.y);
    }
    return void 0;
  }
  constructor(z, C, logService, fileService) {
    super(logService, fileService);
    this.z = z;
    this.C = C;
  }
  async t() {
    return new $zq(new $sZ(this.path ?? $sZ.IN_MEMORY_PATH, {
      logging: this.r()
    }), !this.path ? { hint: StorageHint.STORAGE_IN_MEMORY } : void 0);
  }
};
var $$jc = class extends BaseProfileAwareStorageMain {
  constructor(profile, options, logService, fileService) {
    super(profile, options, logService, fileService);
  }
};
var $_jc = class extends BaseProfileAwareStorageMain {
  constructor(options, userDataProfileService, logService, fileService) {
    super(userDataProfileService.defaultProfile, options, logService, fileService);
  }
  async s(storage) {
    await super.s(storage);
    this.G(storage);
  }
  G(storage) {
    const firstSessionDate = storage.get($wm, void 0);
    if (firstSessionDate === void 0) {
      storage.set($wm, (/* @__PURE__ */ new Date()).toUTCString());
    }
    const lastSessionDate = storage.get($vm, void 0);
    const currentSessionDate = (/* @__PURE__ */ new Date()).toUTCString();
    storage.set($xm, typeof lastSessionDate === "undefined" ? null : lastSessionDate);
    storage.set($vm, currentSessionDate);
  }
};
var $akc = class _$akc extends BaseStorageMain {
  static {
    this.y = "state.vscdb";
  }
  static {
    this.z = "workspace.json";
  }
  get path() {
    if (!this.D.useInMemoryStorage) {
      return $vc(this.F.workspaceStorageHome.with({ scheme: Schemas.file }).fsPath, this.C.id, _$akc.y);
    }
    return void 0;
  }
  constructor(C, D, logService, F, fileService) {
    super(logService, fileService);
    this.C = C;
    this.D = D;
    this.F = F;
  }
  async t() {
    const { storageFilePath, wasCreated } = await this.H();
    return new $zq(new $sZ(storageFilePath, {
      logging: this.r()
    }), { hint: this.D.useInMemoryStorage ? StorageHint.STORAGE_IN_MEMORY : wasCreated ? StorageHint.STORAGE_DOES_NOT_EXIST : void 0 });
  }
  async H() {
    if (this.D.useInMemoryStorage) {
      return { storageFilePath: $sZ.IN_MEMORY_PATH, wasCreated: true };
    }
    const workspaceStorageFolderPath = $vc(this.F.workspaceStorageHome.with({ scheme: Schemas.file }).fsPath, this.C.id);
    const workspaceStorageDatabasePath = $vc(workspaceStorageFolderPath, _$akc.y);
    const storageExists = await Promises2.exists(workspaceStorageFolderPath);
    if (storageExists) {
      return { storageFilePath: workspaceStorageDatabasePath, wasCreated: false };
    }
    await fs3.promises.mkdir(workspaceStorageFolderPath, { recursive: true });
    this.I(workspaceStorageFolderPath);
    return { storageFilePath: workspaceStorageDatabasePath, wasCreated: true };
  }
  async I(workspaceStorageFolderPath) {
    let meta = void 0;
    if ($0i(this.C)) {
      meta = { folder: this.C.uri.toString() };
    } else if ($cj(this.C)) {
      meta = { workspace: this.C.configPath.toString() };
    }
    if (meta) {
      try {
        const workspaceStorageMetaPath = $vc(workspaceStorageFolderPath, _$akc.z);
        const storageExists = await Promises2.exists(workspaceStorageMetaPath);
        if (!storageExists) {
          await Promises2.writeFile(workspaceStorageMetaPath, JSON.stringify(meta, void 0, 2));
        }
      } catch (error) {
        this.m.error(`[storage main] ensureWorkspaceStorageFolderMeta(): Unable to create workspace storage metadata due to ${error}`);
      }
    }
  }
};
var $bkc = class extends BaseStorageMain {
  get path() {
    return void 0;
  }
  async t() {
    return new $zq(new $Aq(), { hint: StorageHint.STORAGE_IN_MEMORY });
  }
};

// out-build/vs/platform/state/node/stateService.js
var SaveStrategy;
(function(SaveStrategy2) {
  SaveStrategy2[SaveStrategy2["IMMEDIATE"] = 0] = "IMMEDIATE";
  SaveStrategy2[SaveStrategy2["DELAYED"] = 1] = "DELAYED";
})(SaveStrategy || (SaveStrategy = {}));
var $CS = class extends $0c {
  constructor(h, j, m, n) {
    super();
    this.h = h;
    this.j = j;
    this.m = m;
    this.n = n;
    this.a = /* @__PURE__ */ Object.create(null);
    this.b = "";
    this.c = this.B(new $Xh(
      this.j === 0 ? 0 : 100
      /* buffer saves over a short time */
    ));
    this.f = void 0;
    this.g = void 0;
  }
  init() {
    if (!this.f) {
      this.f = this.r();
    }
    return this.f;
  }
  async r() {
    try {
      this.b = (await this.n.readFile(this.h)).value.toString();
      this.a = JSON.parse(this.b);
    } catch (error) {
      if (error.fileOperationResult !== 1) {
        this.m.error(error);
      }
    }
  }
  getItem(key, defaultValue) {
    const res = this.a[key];
    if ($Hg(res)) {
      return defaultValue;
    }
    return res;
  }
  setItem(key, data) {
    this.setItems([{ key, data }]);
  }
  setItems(items) {
    let save = false;
    for (const { key, data } of items) {
      if (this.a[key] === data) {
        continue;
      }
      if ($Hg(data)) {
        if (!$Fg(this.a[key])) {
          this.a[key] = void 0;
          save = true;
        }
      } else {
        this.a[key] = data;
        save = true;
      }
    }
    if (save) {
      this.s();
    }
  }
  removeItem(key) {
    if (!$Fg(this.a[key])) {
      this.a[key] = void 0;
      this.s();
    }
  }
  async s() {
    if (this.g) {
      return;
    }
    return this.c.trigger(() => this.t());
  }
  async t() {
    if (!this.f) {
      return;
    }
    await this.f;
    const serializedDatabase = JSON.stringify(this.a, null, 4);
    if (serializedDatabase === this.b) {
      return;
    }
    try {
      await this.n.writeFile(this.h, $7e.fromString(serializedDatabase), { atomic: { postfix: ".vsctmp" } });
      this.b = serializedDatabase;
    } catch (error) {
      this.m.error(error);
    }
  }
  async close() {
    if (!this.g) {
      this.g = this.c.trigger(
        () => this.t(),
        0
        /* as soon as possible */
      );
    }
    return this.g;
  }
};
var $DS = class $DS2 extends $0c {
  constructor(saveStrategy, environmentService, logService, fileService) {
    super();
    this.a = this.B(new $CS(environmentService.stateResource, saveStrategy, logService, fileService));
  }
  async init() {
    await this.a.init();
  }
  getItem(key, defaultValue) {
    return this.a.getItem(key, defaultValue);
  }
};
$DS = __decorate([
  __param(1, $7i),
  __param(2, $uk),
  __param(3, $ul)
], $DS);
var $ES = class extends $DS {
  setItem(key, data) {
    this.a.setItem(key, data);
  }
  setItems(items) {
    this.a.setItems(items);
  }
  removeItem(key) {
    this.a.removeItem(key);
  }
  close() {
    return this.a.close();
  }
};

// out-build/vs/platform/userDataProfile/node/userDataProfile.js
var $FS_1;
var $GS_1;
var $FS = class $FS2 extends $0l {
  static {
    $FS_1 = this;
  }
  static {
    this.a = "profileAssociationsMigration";
  }
  constructor(W, uriIdentityService, X, fileService, logService) {
    super(X, fileService, uriIdentityService, logService);
    this.W = W;
    this.X = X;
  }
  P() {
    const storedProfilesState = this.W.getItem($FS_1.b, []);
    return storedProfilesState.map((p) => ({ ...p, location: $yg(p.location) ? this.y.extUri.joinPath(this.profilesHome, p.location) : URI.revive(p.location) }));
  }
  R() {
    const associations = this.W.getItem($FS_1.c, {});
    const migrated = this.W.getItem($FS_1.a, false);
    return migrated ? associations : this.O(associations);
  }
  U() {
    return this.y.extUri.joinPath(URI.file(this.X.extensionsPath).with({ scheme: this.profilesHome.scheme }), "extensions.json");
  }
};
$FS = $FS_1 = __decorate([
  __param(0, $AS),
  __param(1, $5l),
  __param(2, $8i),
  __param(3, $ul),
  __param(4, $uk)
], $FS);
var $GS = $GS_1 = class $GS2 extends $FS {
  constructor(ab, uriIdentityService, environmentService, fileService, logService) {
    super(ab, uriIdentityService, environmentService, fileService, logService);
    this.ab = ab;
  }
  Q(storedProfiles) {
    if (storedProfiles.length) {
      this.ab.setItem($GS_1.b, storedProfiles.map((profile) => ({ ...profile, location: this.y.extUri.basename(profile.location) })));
    } else {
      this.ab.removeItem($GS_1.b);
    }
  }
  P() {
    const storedProfiles = super.P();
    if (!this.ab.getItem("userDataProfilesMigration", false)) {
      this.Q(storedProfiles);
      this.ab.setItem("userDataProfilesMigration", true);
    }
    return storedProfiles;
  }
  S(storedProfileAssociations) {
    if (storedProfileAssociations.emptyWindows || storedProfileAssociations.workspaces) {
      this.ab.setItem($GS_1.c, storedProfileAssociations);
    } else {
      this.ab.removeItem($GS_1.c);
    }
  }
  R() {
    const oldKey = "workspaceAndProfileInfo";
    const storedWorkspaceInfos = this.ab.getItem(oldKey, void 0);
    if (storedWorkspaceInfos) {
      this.ab.removeItem(oldKey);
      const workspaces = storedWorkspaceInfos.reduce((result, { workspace, profile }) => {
        result[URI.revive(workspace).toString()] = URI.revive(profile).toString();
        return result;
      }, {});
      this.ab.setItem($GS_1.c, { workspaces });
    }
    const associations = super.R();
    if (!this.ab.getItem($GS_1.a, false)) {
      this.S(associations);
      this.ab.setItem($GS_1.a, true);
    }
    return associations;
  }
};
$GS = $GS_1 = __decorate([
  __param(0, $BS),
  __param(1, $5l),
  __param(2, $8i),
  __param(3, $ul),
  __param(4, $uk)
], $GS);
var $HS = class $HS2 extends $GS {
  constructor(uriIdentityService, environmentService, fileService, logService) {
    super(new $ES(0, environmentService, logService, fileService), uriIdentityService, environmentService, fileService, logService);
  }
  async init() {
    await this.ab.init();
    return super.init();
  }
};
$HS = __decorate([
  __param(0, $5l),
  __param(1, $8i),
  __param(2, $ul),
  __param(3, $uk)
], $HS);

// out-build/vs/platform/userDataProfile/electron-main/userDataProfile.js
var $Sjc = $1i($7l);
var $Tjc = class $Tjc2 extends $GS {
  constructor(stateService, uriIdentityService, environmentService, fileService, logService) {
    super(stateService, uriIdentityService, environmentService, fileService, logService);
  }
  getAssociatedEmptyWindows() {
    const emptyWindows = [];
    for (const id2 of this.D.emptyWindows.keys()) {
      emptyWindows.push({ id: id2 });
    }
    return emptyWindows;
  }
};
$Tjc = __decorate([
  __param(0, $BS),
  __param(1, $5l),
  __param(2, $8i),
  __param(3, $ul),
  __param(4, $uk)
], $Tjc);

// out-build/vs/platform/storage/electron-main/storageMainService.js
var $ckc = $Zi("storageMainService");
var $dkc = class $dkc2 extends $0c {
  constructor(c, f, g, h, j, m) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h;
    this.j = j;
    this.m = m;
    this.a = void 0;
    this.b = this.B(new $De());
    this.onDidChangeProfileStorage = this.b.event;
    this.applicationStorage = this.B(this.s());
    this.t = /* @__PURE__ */ new Map();
    this.w = /* @__PURE__ */ new Map();
    this.r();
  }
  n() {
    return {
      useInMemoryStorage: !!this.f.extensionTestsLocationURI
      // no storage during extension tests!
    };
  }
  r() {
    (async () => {
      await this.h.when(
        3
        /* LifecycleMainPhase.AfterWindowOpen */
      );
      this.applicationStorage.init();
    })();
    this.B(this.h.onWillLoadWindow((e) => {
      if (e.window.profile) {
        this.profileStorage(e.window.profile).init();
      }
      if (e.workspace) {
        this.workspaceStorage(e.workspace).init();
      }
    }));
    this.B(this.h.onWillShutdown((e) => {
      this.c.trace("storageMainService#onWillShutdown()");
      this.a = e.reason;
      e.join("applicationStorage", this.applicationStorage.close());
      for (const [, profileStorage] of this.t) {
        e.join("profileStorage", profileStorage.close());
      }
      for (const [, workspaceStorage] of this.w) {
        e.join("workspaceStorage", workspaceStorage.close());
      }
    }));
    this.B(this.g.onWillCreateProfile((e) => {
      e.join((async () => {
        if (!await this.j.exists(e.profile.globalStorageHome)) {
          await this.j.createFolder(e.profile.globalStorageHome);
        }
      })());
    }));
    this.B(this.g.onWillRemoveProfile((e) => {
      const storage = this.t.get(e.profile.id);
      if (storage) {
        e.join(storage.close());
      }
    }));
  }
  s() {
    this.c.trace(`StorageMainService: creating application storage`);
    const applicationStorage = new $_jc(this.n(), this.g, this.c, this.j);
    this.B(Event.once(applicationStorage.onDidCloseStorage)(() => {
      this.c.trace(`StorageMainService: closed application storage`);
    }));
    return applicationStorage;
  }
  profileStorage(profile) {
    if ($Gq(profile)) {
      return this.applicationStorage;
    }
    let profileStorage = this.t.get(profile.id);
    if (!profileStorage) {
      this.c.trace(`StorageMainService: creating profile storage (${profile.name})`);
      profileStorage = this.B(this.u(profile));
      this.t.set(profile.id, profileStorage);
      const listener = this.B(profileStorage.onDidChangeStorage((e) => this.b.fire({
        ...e,
        storage: profileStorage,
        profile
      })));
      this.B(Event.once(profileStorage.onDidCloseStorage)(() => {
        this.c.trace(`StorageMainService: closed profile storage (${profile.name})`);
        this.t.delete(profile.id);
        listener.dispose();
      }));
    }
    return profileStorage;
  }
  u(profile) {
    if (this.a === 2) {
      return new $bkc(this.c, this.j);
    }
    return new $$jc(profile, this.n(), this.c, this.j);
  }
  workspaceStorage(workspace) {
    let workspaceStorage = this.w.get(workspace.id);
    if (!workspaceStorage) {
      this.c.trace(`StorageMainService: creating workspace storage (${workspace.id})`);
      workspaceStorage = this.B(this.y(workspace));
      this.w.set(workspace.id, workspaceStorage);
      this.B(Event.once(workspaceStorage.onDidCloseStorage)(() => {
        this.c.trace(`StorageMainService: closed workspace storage (${workspace.id})`);
        this.w.delete(workspace.id);
      }));
    }
    return workspaceStorage;
  }
  y(workspace) {
    if (this.a === 2) {
      return new $bkc(this.c, this.j);
    }
    return new $akc(workspace, this.n(), this.c, this.f, this.j);
  }
  //#endregion
  isUsed(path3) {
    const pathUri = URI.file(path3);
    for (const storage of [this.applicationStorage, ...this.t.values(), ...this.w.values()]) {
      if (!storage.path) {
        continue;
      }
      if (this.m.extUri.isEqualOrParent(URI.file(storage.path), pathUri)) {
        return true;
      }
    }
    return false;
  }
};
$dkc = __decorate([
  __param(0, $uk),
  __param(1, $7i),
  __param(2, $Sjc),
  __param(3, $9jc),
  __param(4, $ul),
  __param(5, $5l)
], $dkc);
var $ekc = $Zi("applicationStorageMainService");
var $fkc = class $fkc2 extends $Fq {
  constructor(s, U) {
    super();
    this.s = s;
    this.U = U;
    this.whenReady = this.U.applicationStorage.whenInit;
  }
  O() {
    return this.U.applicationStorage.whenInit;
  }
  P(scope) {
    if (scope === -1) {
      return this.U.applicationStorage.storage;
    }
    return void 0;
  }
  Q(scope) {
    if (scope === -1) {
      return this.s.defaultProfile.globalStorageHome.with({ scheme: Schemas.file }).fsPath;
    }
    return void 0;
  }
  r() {
    return false;
  }
  switch() {
    throw new Error("Migrating storage is unsupported from main process");
  }
  R() {
    throw new Error("Switching storage profile is unsupported from main process");
  }
  S() {
    throw new Error("Switching storage workspace is unsupported from main process");
  }
  hasScope() {
    throw new Error("Main process is never profile or workspace scoped");
  }
};
$fkc = __decorate([
  __param(0, $7l),
  __param(1, $ckc)
], $fkc);

// out-build/vs/platform/windows/electron-main/windows.js
import electron5 from "electron";

// out-build/vs/base/common/color.js
function roundFloat(number, decimalPoints) {
  const decimal = Math.pow(10, decimalPoints);
  return Math.round(number * decimal) / decimal;
}
var $Lu = class {
  constructor(r, g, b, a = 1) {
    this._rgbaBrand = void 0;
    this.r = Math.min(255, Math.max(0, r)) | 0;
    this.g = Math.min(255, Math.max(0, g)) | 0;
    this.b = Math.min(255, Math.max(0, b)) | 0;
    this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
  }
  static equals(a, b) {
    return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a;
  }
};
var $Mu = class _$Mu {
  constructor(h, s, l, a) {
    this._hslaBrand = void 0;
    this.h = Math.max(Math.min(360, h), 0) | 0;
    this.s = roundFloat(Math.max(Math.min(1, s), 0), 3);
    this.l = roundFloat(Math.max(Math.min(1, l), 0), 3);
    this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
  }
  static equals(a, b) {
    return a.h === b.h && a.s === b.s && a.l === b.l && a.a === b.a;
  }
  /**
   * Converts an RGB color value to HSL. Conversion formula
   * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
   * Assumes r, g, and b are contained in the set [0, 255] and
   * returns h in the set [0, 360], s, and l in the set [0, 1].
   */
  static fromRGBA(rgba) {
    const r = rgba.r / 255;
    const g = rgba.g / 255;
    const b = rgba.b / 255;
    const a = rgba.a;
    const max = Math.max(r, g, b);
    const min = Math.min(r, g, b);
    let h = 0;
    let s = 0;
    const l = (min + max) / 2;
    const chroma = max - min;
    if (chroma > 0) {
      s = Math.min(l <= 0.5 ? chroma / (2 * l) : chroma / (2 - 2 * l), 1);
      switch (max) {
        case r:
          h = (g - b) / chroma + (g < b ? 6 : 0);
          break;
        case g:
          h = (b - r) / chroma + 2;
          break;
        case b:
          h = (r - g) / chroma + 4;
          break;
      }
      h *= 60;
      h = Math.round(h);
    }
    return new _$Mu(h, s, l, a);
  }
  static i(p, q, t) {
    if (t < 0) {
      t += 1;
    }
    if (t > 1) {
      t -= 1;
    }
    if (t < 1 / 6) {
      return p + (q - p) * 6 * t;
    }
    if (t < 1 / 2) {
      return q;
    }
    if (t < 2 / 3) {
      return p + (q - p) * (2 / 3 - t) * 6;
    }
    return p;
  }
  /**
   * Converts an HSL color value to RGB. Conversion formula
   * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
   * Assumes h in the set [0, 360] s, and l are contained in the set [0, 1] and
   * returns r, g, and b in the set [0, 255].
   */
  static toRGBA(hsla) {
    const h = hsla.h / 360;
    const { s, l, a } = hsla;
    let r, g, b;
    if (s === 0) {
      r = g = b = l;
    } else {
      const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
      const p = 2 * l - q;
      r = _$Mu.i(p, q, h + 1 / 3);
      g = _$Mu.i(p, q, h);
      b = _$Mu.i(p, q, h - 1 / 3);
    }
    return new $Lu(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a);
  }
};
var $Nu = class _$Nu {
  constructor(h, s, v, a) {
    this._hsvaBrand = void 0;
    this.h = Math.max(Math.min(360, h), 0) | 0;
    this.s = roundFloat(Math.max(Math.min(1, s), 0), 3);
    this.v = roundFloat(Math.max(Math.min(1, v), 0), 3);
    this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
  }
  static equals(a, b) {
    return a.h === b.h && a.s === b.s && a.v === b.v && a.a === b.a;
  }
  // from http://www.rapidtables.com/convert/color/rgb-to-hsv.htm
  static fromRGBA(rgba) {
    const r = rgba.r / 255;
    const g = rgba.g / 255;
    const b = rgba.b / 255;
    const cmax = Math.max(r, g, b);
    const cmin = Math.min(r, g, b);
    const delta = cmax - cmin;
    const s = cmax === 0 ? 0 : delta / cmax;
    let m;
    if (delta === 0) {
      m = 0;
    } else if (cmax === r) {
      m = ((g - b) / delta % 6 + 6) % 6;
    } else if (cmax === g) {
      m = (b - r) / delta + 2;
    } else {
      m = (r - g) / delta + 4;
    }
    return new _$Nu(Math.round(m * 60), s, cmax, rgba.a);
  }
  // from http://www.rapidtables.com/convert/color/hsv-to-rgb.htm
  static toRGBA(hsva) {
    const { h, s, v, a } = hsva;
    const c = v * s;
    const x = c * (1 - Math.abs(h / 60 % 2 - 1));
    const m = v - c;
    let [r, g, b] = [0, 0, 0];
    if (h < 60) {
      r = c;
      g = x;
    } else if (h < 120) {
      r = x;
      g = c;
    } else if (h < 180) {
      g = c;
      b = x;
    } else if (h < 240) {
      g = x;
      b = c;
    } else if (h < 300) {
      r = x;
      b = c;
    } else if (h <= 360) {
      r = c;
      b = x;
    }
    r = Math.round((r + m) * 255);
    g = Math.round((g + m) * 255);
    b = Math.round((b + m) * 255);
    return new $Lu(r, g, b, a);
  }
};
var $Ou = class _$Ou {
  static fromHex(hex) {
    return _$Ou.Format.CSS.parseHex(hex) || _$Ou.red;
  }
  static equals(a, b) {
    if (!a && !b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    return a.equals(b);
  }
  get hsla() {
    if (this.i) {
      return this.i;
    } else {
      return $Mu.fromRGBA(this.rgba);
    }
  }
  get hsva() {
    if (this.j) {
      return this.j;
    }
    return $Nu.fromRGBA(this.rgba);
  }
  constructor(arg) {
    if (!arg) {
      throw new Error("Color needs a value");
    } else if (arg instanceof $Lu) {
      this.rgba = arg;
    } else if (arg instanceof $Mu) {
      this.i = arg;
      this.rgba = $Mu.toRGBA(arg);
    } else if (arg instanceof $Nu) {
      this.j = arg;
      this.rgba = $Nu.toRGBA(arg);
    } else {
      throw new Error("Invalid color ctor argument");
    }
  }
  equals(other) {
    return !!other && $Lu.equals(this.rgba, other.rgba) && $Mu.equals(this.hsla, other.hsla) && $Nu.equals(this.hsva, other.hsva);
  }
  /**
   * http://www.w3.org/TR/WCAG20/#relativeluminancedef
   * Returns the number in the set [0, 1]. O => Darkest Black. 1 => Lightest white.
   */
  getRelativeLuminance() {
    const R = _$Ou.k(this.rgba.r);
    const G = _$Ou.k(this.rgba.g);
    const B = _$Ou.k(this.rgba.b);
    const luminance = 0.2126 * R + 0.7152 * G + 0.0722 * B;
    return roundFloat(luminance, 4);
  }
  /**
   * Reduces the "foreground" color on this "background" color unti it is
   * below the relative luminace ratio.
   * @returns the new foreground color
   * @see https://github.com/xtermjs/xterm.js/blob/44f9fa39ae03e2ca6d28354d88a399608686770e/src/common/Color.ts#L315
   */
  reduceRelativeLuminace(foreground, ratio) {
    let { r: fgR, g: fgG, b: fgB } = foreground.rgba;
    let cr = this.getContrastRatio(foreground);
    while (cr < ratio && (fgR > 0 || fgG > 0 || fgB > 0)) {
      fgR -= Math.max(0, Math.ceil(fgR * 0.1));
      fgG -= Math.max(0, Math.ceil(fgG * 0.1));
      fgB -= Math.max(0, Math.ceil(fgB * 0.1));
      cr = this.getContrastRatio(new _$Ou(new $Lu(fgR, fgG, fgB)));
    }
    return new _$Ou(new $Lu(fgR, fgG, fgB));
  }
  /**
   * Increases the "foreground" color on this "background" color unti it is
   * below the relative luminace ratio.
   * @returns the new foreground color
   * @see https://github.com/xtermjs/xterm.js/blob/44f9fa39ae03e2ca6d28354d88a399608686770e/src/common/Color.ts#L335
   */
  increaseRelativeLuminace(foreground, ratio) {
    let { r: fgR, g: fgG, b: fgB } = foreground.rgba;
    let cr = this.getContrastRatio(foreground);
    while (cr < ratio && (fgR < 255 || fgG < 255 || fgB < 255)) {
      fgR = Math.min(255, fgR + Math.ceil((255 - fgR) * 0.1));
      fgG = Math.min(255, fgG + Math.ceil((255 - fgG) * 0.1));
      fgB = Math.min(255, fgB + Math.ceil((255 - fgB) * 0.1));
      cr = this.getContrastRatio(new _$Ou(new $Lu(fgR, fgG, fgB)));
    }
    return new _$Ou(new $Lu(fgR, fgG, fgB));
  }
  static k(color2) {
    const c = color2 / 255;
    return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
  }
  /**
   * http://www.w3.org/TR/WCAG20/#contrast-ratiodef
   * Returns the contrast ration number in the set [1, 21].
   */
  getContrastRatio(another) {
    const lum1 = this.getRelativeLuminance();
    const lum2 = another.getRelativeLuminance();
    return lum1 > lum2 ? (lum1 + 0.05) / (lum2 + 0.05) : (lum2 + 0.05) / (lum1 + 0.05);
  }
  /**
   *	http://24ways.org/2010/calculating-color-contrast
   *  Return 'true' if darker color otherwise 'false'
   */
  isDarker() {
    const yiq = (this.rgba.r * 299 + this.rgba.g * 587 + this.rgba.b * 114) / 1e3;
    return yiq < 128;
  }
  /**
   *	http://24ways.org/2010/calculating-color-contrast
   *  Return 'true' if lighter color otherwise 'false'
   */
  isLighter() {
    const yiq = (this.rgba.r * 299 + this.rgba.g * 587 + this.rgba.b * 114) / 1e3;
    return yiq >= 128;
  }
  isLighterThan(another) {
    const lum1 = this.getRelativeLuminance();
    const lum2 = another.getRelativeLuminance();
    return lum1 > lum2;
  }
  isDarkerThan(another) {
    const lum1 = this.getRelativeLuminance();
    const lum2 = another.getRelativeLuminance();
    return lum1 < lum2;
  }
  /**
   * Based on xterm.js: https://github.com/xtermjs/xterm.js/blob/44f9fa39ae03e2ca6d28354d88a399608686770e/src/common/Color.ts#L288
   *
   * Given a foreground color and a background color, either increase or reduce the luminance of the
   * foreground color until the specified contrast ratio is met. If pure white or black is hit
   * without the contrast ratio being met, go the other direction using the background color as the
   * foreground color and take either the first or second result depending on which has the higher
   * contrast ratio.
   *
   * @param foreground The foreground color.
   * @param ratio The contrast ratio to achieve.
   * @returns The adjusted foreground color.
   */
  ensureConstrast(foreground, ratio) {
    const bgL = this.getRelativeLuminance();
    const fgL = foreground.getRelativeLuminance();
    const cr = this.getContrastRatio(foreground);
    if (cr < ratio) {
      if (fgL < bgL) {
        const resultA2 = this.reduceRelativeLuminace(foreground, ratio);
        const resultARatio2 = this.getContrastRatio(resultA2);
        if (resultARatio2 < ratio) {
          const resultB = this.increaseRelativeLuminace(foreground, ratio);
          const resultBRatio = this.getContrastRatio(resultB);
          return resultARatio2 > resultBRatio ? resultA2 : resultB;
        }
        return resultA2;
      }
      const resultA = this.increaseRelativeLuminace(foreground, ratio);
      const resultARatio = this.getContrastRatio(resultA);
      if (resultARatio < ratio) {
        const resultB = this.reduceRelativeLuminace(foreground, ratio);
        const resultBRatio = this.getContrastRatio(resultB);
        return resultARatio > resultBRatio ? resultA : resultB;
      }
      return resultA;
    }
    return foreground;
  }
  lighten(factor) {
    return new _$Ou(new $Mu(this.hsla.h, this.hsla.s, this.hsla.l + this.hsla.l * factor, this.hsla.a));
  }
  darken(factor) {
    return new _$Ou(new $Mu(this.hsla.h, this.hsla.s, this.hsla.l - this.hsla.l * factor, this.hsla.a));
  }
  transparent(factor) {
    const { r, g, b, a } = this.rgba;
    return new _$Ou(new $Lu(r, g, b, a * factor));
  }
  isTransparent() {
    return this.rgba.a === 0;
  }
  isOpaque() {
    return this.rgba.a === 1;
  }
  opposite() {
    return new _$Ou(new $Lu(255 - this.rgba.r, 255 - this.rgba.g, 255 - this.rgba.b, this.rgba.a));
  }
  blend(c) {
    const rgba = c.rgba;
    const thisA = this.rgba.a;
    const colorA = rgba.a;
    const a = thisA + colorA * (1 - thisA);
    if (a < 1e-6) {
      return _$Ou.transparent;
    }
    const r = this.rgba.r * thisA / a + rgba.r * colorA * (1 - thisA) / a;
    const g = this.rgba.g * thisA / a + rgba.g * colorA * (1 - thisA) / a;
    const b = this.rgba.b * thisA / a + rgba.b * colorA * (1 - thisA) / a;
    return new _$Ou(new $Lu(r, g, b, a));
  }
  makeOpaque(opaqueBackground) {
    if (this.isOpaque() || opaqueBackground.rgba.a !== 1) {
      return this;
    }
    const { r, g, b, a } = this.rgba;
    return new _$Ou(new $Lu(opaqueBackground.rgba.r - a * (opaqueBackground.rgba.r - r), opaqueBackground.rgba.g - a * (opaqueBackground.rgba.g - g), opaqueBackground.rgba.b - a * (opaqueBackground.rgba.b - b), 1));
  }
  flatten(...backgrounds) {
    const background = backgrounds.reduceRight((accumulator, color2) => {
      return _$Ou.o(color2, accumulator);
    });
    return _$Ou.o(this, background);
  }
  static o(foreground, background) {
    const backgroundAlpha = 1 - foreground.rgba.a;
    return new _$Ou(new $Lu(backgroundAlpha * background.rgba.r + foreground.rgba.a * foreground.rgba.r, backgroundAlpha * background.rgba.g + foreground.rgba.a * foreground.rgba.g, backgroundAlpha * background.rgba.b + foreground.rgba.a * foreground.rgba.b));
  }
  toString() {
    if (!this.u) {
      this.u = _$Ou.Format.CSS.format(this);
    }
    return this.u;
  }
  static getLighterColor(of, relative2, factor) {
    if (of.isLighterThan(relative2)) {
      return of;
    }
    factor = factor ? factor : 0.5;
    const lum1 = of.getRelativeLuminance();
    const lum2 = relative2.getRelativeLuminance();
    factor = factor * (lum2 - lum1) / lum2;
    return of.lighten(factor);
  }
  static getDarkerColor(of, relative2, factor) {
    if (of.isDarkerThan(relative2)) {
      return of;
    }
    factor = factor ? factor : 0.5;
    const lum1 = of.getRelativeLuminance();
    const lum2 = relative2.getRelativeLuminance();
    factor = factor * (lum1 - lum2) / lum1;
    return of.darken(factor);
  }
  static {
    this.white = new _$Ou(new $Lu(255, 255, 255, 1));
  }
  static {
    this.black = new _$Ou(new $Lu(0, 0, 0, 1));
  }
  static {
    this.red = new _$Ou(new $Lu(255, 0, 0, 1));
  }
  static {
    this.blue = new _$Ou(new $Lu(0, 0, 255, 1));
  }
  static {
    this.green = new _$Ou(new $Lu(0, 255, 0, 1));
  }
  static {
    this.cyan = new _$Ou(new $Lu(0, 255, 255, 1));
  }
  static {
    this.lightgrey = new _$Ou(new $Lu(211, 211, 211, 1));
  }
  static {
    this.transparent = new _$Ou(new $Lu(0, 0, 0, 0));
  }
};
(function($Ou2) {
  let Format;
  (function(Format2) {
    let CSS;
    (function(CSS2) {
      function formatRGB(color2) {
        if (color2.rgba.a === 1) {
          return `rgb(${color2.rgba.r}, ${color2.rgba.g}, ${color2.rgba.b})`;
        }
        return $Ou2.Format.CSS.formatRGBA(color2);
      }
      CSS2.formatRGB = formatRGB;
      function formatRGBA(color2) {
        return `rgba(${color2.rgba.r}, ${color2.rgba.g}, ${color2.rgba.b}, ${+color2.rgba.a.toFixed(2)})`;
      }
      CSS2.formatRGBA = formatRGBA;
      function formatHSL(color2) {
        if (color2.hsla.a === 1) {
          return `hsl(${color2.hsla.h}, ${(color2.hsla.s * 100).toFixed(2)}%, ${(color2.hsla.l * 100).toFixed(2)}%)`;
        }
        return $Ou2.Format.CSS.formatHSLA(color2);
      }
      CSS2.formatHSL = formatHSL;
      function formatHSLA(color2) {
        return `hsla(${color2.hsla.h}, ${(color2.hsla.s * 100).toFixed(2)}%, ${(color2.hsla.l * 100).toFixed(2)}%, ${color2.hsla.a.toFixed(2)})`;
      }
      CSS2.formatHSLA = formatHSLA;
      function _toTwoDigitHex(n) {
        const r = n.toString(16);
        return r.length !== 2 ? "0" + r : r;
      }
      function formatHex(color2) {
        return `#${_toTwoDigitHex(color2.rgba.r)}${_toTwoDigitHex(color2.rgba.g)}${_toTwoDigitHex(color2.rgba.b)}`;
      }
      CSS2.formatHex = formatHex;
      function formatHexA(color2, compact = false) {
        if (compact && color2.rgba.a === 1) {
          return $Ou2.Format.CSS.formatHex(color2);
        }
        return `#${_toTwoDigitHex(color2.rgba.r)}${_toTwoDigitHex(color2.rgba.g)}${_toTwoDigitHex(color2.rgba.b)}${_toTwoDigitHex(Math.round(color2.rgba.a * 255))}`;
      }
      CSS2.formatHexA = formatHexA;
      function format2(color2) {
        if (color2.isOpaque()) {
          return $Ou2.Format.CSS.formatHex(color2);
        }
        return $Ou2.Format.CSS.formatRGBA(color2);
      }
      CSS2.format = format2;
      function parseHex(hex) {
        const length = hex.length;
        if (length === 0) {
          return null;
        }
        if (hex.charCodeAt(0) !== 35) {
          return null;
        }
        if (length === 7) {
          const r = 16 * _parseHexDigit(hex.charCodeAt(1)) + _parseHexDigit(hex.charCodeAt(2));
          const g = 16 * _parseHexDigit(hex.charCodeAt(3)) + _parseHexDigit(hex.charCodeAt(4));
          const b = 16 * _parseHexDigit(hex.charCodeAt(5)) + _parseHexDigit(hex.charCodeAt(6));
          return new $Ou2(new $Lu(r, g, b, 1));
        }
        if (length === 9) {
          const r = 16 * _parseHexDigit(hex.charCodeAt(1)) + _parseHexDigit(hex.charCodeAt(2));
          const g = 16 * _parseHexDigit(hex.charCodeAt(3)) + _parseHexDigit(hex.charCodeAt(4));
          const b = 16 * _parseHexDigit(hex.charCodeAt(5)) + _parseHexDigit(hex.charCodeAt(6));
          const a = 16 * _parseHexDigit(hex.charCodeAt(7)) + _parseHexDigit(hex.charCodeAt(8));
          return new $Ou2(new $Lu(r, g, b, a / 255));
        }
        if (length === 4) {
          const r = _parseHexDigit(hex.charCodeAt(1));
          const g = _parseHexDigit(hex.charCodeAt(2));
          const b = _parseHexDigit(hex.charCodeAt(3));
          return new $Ou2(new $Lu(16 * r + r, 16 * g + g, 16 * b + b));
        }
        if (length === 5) {
          const r = _parseHexDigit(hex.charCodeAt(1));
          const g = _parseHexDigit(hex.charCodeAt(2));
          const b = _parseHexDigit(hex.charCodeAt(3));
          const a = _parseHexDigit(hex.charCodeAt(4));
          return new $Ou2(new $Lu(16 * r + r, 16 * g + g, 16 * b + b, (16 * a + a) / 255));
        }
        return null;
      }
      CSS2.parseHex = parseHex;
      function _parseHexDigit(charCode) {
        switch (charCode) {
          case 48:
            return 0;
          case 49:
            return 1;
          case 50:
            return 2;
          case 51:
            return 3;
          case 52:
            return 4;
          case 53:
            return 5;
          case 54:
            return 6;
          case 55:
            return 7;
          case 56:
            return 8;
          case 57:
            return 9;
          case 97:
            return 10;
          case 65:
            return 10;
          case 98:
            return 11;
          case 66:
            return 11;
          case 99:
            return 12;
          case 67:
            return 12;
          case 100:
            return 13;
          case 68:
            return 13;
          case 101:
            return 14;
          case 69:
            return 14;
          case 102:
            return 15;
          case 70:
            return 15;
        }
        return 0;
      }
    })(CSS = Format2.CSS || (Format2.CSS = {}));
  })(Format = $Ou2.Format || ($Ou2.Format = {}));
})($Ou || ($Ou = {}));

// out-build/vs/platform/product/common/productService.js
var $Nk = $Zi("productService");

// out-build/vs/platform/theme/electron-main/themeMainService.js
import electron3 from "electron";
var DEFAULT_BG_LIGHT = "#FFFFFF";
var DEFAULT_BG_DARK = "#1F1F1F";
var DEFAULT_BG_HC_BLACK = "#000000";
var DEFAULT_BG_HC_LIGHT = "#FFFFFF";
var THEME_STORAGE_KEY = "theme";
var THEME_BG_STORAGE_KEY = "themeBackground";
var THEME_WINDOW_SPLASH = "windowSplash";
var ThemeSettings;
(function(ThemeSettings2) {
  ThemeSettings2.DETECT_COLOR_SCHEME = "window.autoDetectColorScheme";
  ThemeSettings2.SYSTEM_COLOR_THEME = "window.systemColorTheme";
})(ThemeSettings || (ThemeSettings = {}));
var $Njc = $Zi("themeMainService");
var $Ojc = class $Ojc2 extends $0c {
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.a = this.B(new $De());
    this.onDidChangeColorScheme = this.a.event;
    if (!$n) {
      this.B(this.c.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration(ThemeSettings.SYSTEM_COLOR_THEME) || e.affectsConfiguration(ThemeSettings.DETECT_COLOR_SCHEME)) {
          this.f();
        }
      }));
    }
    this.f();
    this.B(Event.fromNodeEventEmitter(electron3.nativeTheme, "updated")(() => this.a.fire(this.getColorScheme())));
  }
  f() {
    if ($n || this.c.getValue(ThemeSettings.DETECT_COLOR_SCHEME)) {
      electron3.nativeTheme.themeSource = "system";
    } else {
      switch (this.c.getValue(ThemeSettings.SYSTEM_COLOR_THEME)) {
        case "dark":
          electron3.nativeTheme.themeSource = "dark";
          break;
        case "light":
          electron3.nativeTheme.themeSource = "light";
          break;
        case "auto":
          switch (this.g()) {
            case "vs":
              electron3.nativeTheme.themeSource = "light";
              break;
            case "vs-dark":
              electron3.nativeTheme.themeSource = "dark";
              break;
            default:
              electron3.nativeTheme.themeSource = "system";
          }
          break;
        default:
          electron3.nativeTheme.themeSource = "system";
          break;
      }
    }
  }
  getColorScheme() {
    if ($l) {
      if (electron3.nativeTheme.shouldUseHighContrastColors) {
        return { dark: electron3.nativeTheme.shouldUseInvertedColorScheme, highContrast: true };
      }
    } else if ($m) {
      if (electron3.nativeTheme.shouldUseInvertedColorScheme || electron3.nativeTheme.shouldUseHighContrastColors) {
        return { dark: electron3.nativeTheme.shouldUseDarkColors, highContrast: true };
      }
    } else if ($n) {
      if (electron3.nativeTheme.shouldUseHighContrastColors) {
        return { dark: true, highContrast: true };
      }
    }
    return {
      dark: electron3.nativeTheme.shouldUseDarkColors,
      highContrast: false
    };
  }
  getBackgroundColor() {
    const colorScheme = this.getColorScheme();
    if (colorScheme.highContrast && this.c.getValue("window.autoDetectHighContrast")) {
      return colorScheme.dark ? DEFAULT_BG_HC_BLACK : DEFAULT_BG_HC_LIGHT;
    }
    let background = this.b.getItem(THEME_BG_STORAGE_KEY, null);
    if (!background) {
      switch (this.g()) {
        case "vs":
          background = DEFAULT_BG_LIGHT;
          break;
        case "hc-black":
          background = DEFAULT_BG_HC_BLACK;
          break;
        case "hc-light":
          background = DEFAULT_BG_HC_LIGHT;
          break;
        default:
          background = DEFAULT_BG_DARK;
      }
    }
    return background;
  }
  g() {
    const baseTheme = this.b.getItem(THEME_STORAGE_KEY, "vs-dark").split(" ")[0];
    switch (baseTheme) {
      case "vs":
        return "vs";
      case "hc-black":
        return "hc-black";
      case "hc-light":
        return "hc-light";
      default:
        return "vs-dark";
    }
  }
  saveWindowSplash(windowId, splash) {
    this.b.setItems([
      { key: THEME_STORAGE_KEY, data: splash.baseTheme },
      { key: THEME_BG_STORAGE_KEY, data: splash.colorInfo.background },
      { key: THEME_WINDOW_SPLASH, data: splash }
    ]);
    if (typeof windowId === "number") {
      this.h(windowId, splash);
    }
    this.f();
  }
  h(windowId, splash) {
    for (const window2 of electron3.BrowserWindow.getAllWindows()) {
      if (window2.id === windowId) {
        window2.setBackgroundColor(splash.colorInfo.background);
        break;
      }
    }
  }
  getWindowSplash() {
    return this.b.getItem(THEME_WINDOW_SPLASH);
  }
};
$Ojc = __decorate([
  __param(0, $BS),
  __param(1, $tj)
], $Ojc);

// out-build/vs/platform/window/common/window.js
var $JE = {
  WIDTH: 400,
  WIDTH_WITH_VERTICAL_PANEL: 600,
  HEIGHT: 270
};
function $LE(uriToOpen) {
  return !!uriToOpen.workspaceUri;
}
function $ME(uriToOpen) {
  return !!uriToOpen.folderUri;
}
function $NE(uriToOpen) {
  return !!uriToOpen.fileUri;
}
function $OE(configurationService) {
  const nativeTitleBarEnabled = $QE(configurationService);
  const menuBarVisibility = configurationService.getValue("window.menuBarVisibility");
  if (menuBarVisibility === "default" || nativeTitleBarEnabled && menuBarVisibility === "compact" || $m && $p) {
    return "classic";
  } else {
    return menuBarVisibility;
  }
}
var TitleBarSetting;
(function(TitleBarSetting2) {
  TitleBarSetting2["TITLE_BAR_STYLE"] = "window.titleBarStyle";
  TitleBarSetting2["CUSTOM_TITLE_BAR_VISIBILITY"] = "window.customTitleBarVisibility";
})(TitleBarSetting || (TitleBarSetting = {}));
var TitlebarStyle;
(function(TitlebarStyle2) {
  TitlebarStyle2["NATIVE"] = "native";
  TitlebarStyle2["CUSTOM"] = "custom";
})(TitlebarStyle || (TitlebarStyle = {}));
var CustomTitleBarVisibility;
(function(CustomTitleBarVisibility2) {
  CustomTitleBarVisibility2["AUTO"] = "auto";
  CustomTitleBarVisibility2["WINDOWED"] = "windowed";
  CustomTitleBarVisibility2["NEVER"] = "never";
})(CustomTitleBarVisibility || (CustomTitleBarVisibility = {}));
function $QE(configurationService, titleBarStyle) {
  if (!titleBarStyle) {
    titleBarStyle = $RE(configurationService);
  }
  return titleBarStyle === "native";
}
function $RE(configurationService) {
  if ($r) {
    return "custom";
  }
  const configuration = configurationService.getValue("window");
  if (configuration) {
    const useNativeTabs = $m && configuration.nativeTabs === true;
    if (useNativeTabs) {
      return "native";
    }
    const useSimpleFullScreen = $m && configuration.nativeFullScreen === false;
    if (useSimpleFullScreen) {
      return "native";
    }
    const style = configuration.titleBarStyle;
    if (style === "native" || style === "custom") {
      return style;
    }
  }
  return $n ? "native" : "custom";
}
var $SE = 35;
function $TE(configurationService) {
  if ($m || $r) {
    return false;
  }
  if ($QE(configurationService)) {
    return false;
  }
  if ($n) {
    const setting = configurationService.getValue("window.experimentalControlOverlay");
    if (typeof setting === "boolean") {
      return setting;
    }
  }
  return true;
}
function $UE(configurationService) {
  const windowConfig = configurationService.getValue("window");
  if (!windowConfig || typeof windowConfig.nativeFullScreen !== "boolean") {
    return true;
  }
  if (windowConfig.nativeTabs) {
    return true;
  }
  return windowConfig.nativeFullScreen !== false;
}
function $VE(zoomLevel = 0) {
  return Math.pow(1.2, zoomLevel);
}

// out-build/vs/platform/window/electron-main/window.js
import electron4 from "electron";
var LoadReason;
(function(LoadReason2) {
  LoadReason2[LoadReason2["INITIAL"] = 1] = "INITIAL";
  LoadReason2[LoadReason2["LOAD"] = 2] = "LOAD";
  LoadReason2[LoadReason2["RELOAD"] = 3] = "RELOAD";
})(LoadReason || (LoadReason = {}));
var UnloadReason;
(function(UnloadReason2) {
  UnloadReason2[UnloadReason2["CLOSE"] = 1] = "CLOSE";
  UnloadReason2[UnloadReason2["QUIT"] = 2] = "QUIT";
  UnloadReason2[UnloadReason2["RELOAD"] = 3] = "RELOAD";
  UnloadReason2[UnloadReason2["LOAD"] = 4] = "LOAD";
})(UnloadReason || (UnloadReason = {}));
var $Ejc = function(mode = 1) {
  return {
    width: 1024,
    height: 768,
    mode
  };
};
var $Fjc = function() {
  const width = 800;
  const height = 600;
  const workArea = electron4.screen.getPrimaryDisplay().workArea;
  const x = Math.max(workArea.x + workArea.width / 2 - width / 2, 0);
  const y = Math.max(workArea.y + workArea.height / 2 - height / 2, 0);
  return {
    x,
    y,
    width,
    height,
    mode: 1
    /* WindowMode.Normal */
  };
};
var WindowMode;
(function(WindowMode2) {
  WindowMode2[WindowMode2["Maximized"] = 0] = "Maximized";
  WindowMode2[WindowMode2["Normal"] = 1] = "Normal";
  WindowMode2[WindowMode2["Minimized"] = 2] = "Minimized";
  WindowMode2[WindowMode2["Fullscreen"] = 3] = "Fullscreen";
})(WindowMode || (WindowMode = {}));
var WindowError;
(function(WindowError2) {
  WindowError2[WindowError2["UNRESPONSIVE"] = 1] = "UNRESPONSIVE";
  WindowError2[WindowError2["PROCESS_GONE"] = 2] = "PROCESS_GONE";
  WindowError2[WindowError2["LOAD"] = 3] = "LOAD";
})(WindowError || (WindowError = {}));

// out-build/vs/platform/windows/electron-main/windows.js
var $Pjc = $Zi("windowsMainService");
var OpenContext;
(function(OpenContext2) {
  OpenContext2[OpenContext2["CLI"] = 0] = "CLI";
  OpenContext2[OpenContext2["DOCK"] = 1] = "DOCK";
  OpenContext2[OpenContext2["MENU"] = 2] = "MENU";
  OpenContext2[OpenContext2["DIALOG"] = 3] = "DIALOG";
  OpenContext2[OpenContext2["DESKTOP"] = 4] = "DESKTOP";
  OpenContext2[OpenContext2["API"] = 5] = "API";
  OpenContext2[OpenContext2["LINK"] = 6] = "LINK";
})(OpenContext || (OpenContext = {}));
function $Qjc(accessor, windowState, overrides, webPreferences) {
  const themeMainService = accessor.get($Njc);
  const productService = accessor.get($Nk);
  const configurationService = accessor.get($tj);
  const environmentMainService = accessor.get($Cjc);
  const windowSettings = configurationService.getValue("window");
  const options = {
    backgroundColor: themeMainService.getBackgroundColor(),
    minWidth: $JE.WIDTH,
    minHeight: $JE.HEIGHT,
    title: productService.nameLong,
    show: windowState.mode !== 0 && windowState.mode !== 3,
    // reduce flicker by showing later
    x: windowState.x,
    y: windowState.y,
    width: windowState.width,
    height: windowState.height,
    webPreferences: {
      ...webPreferences,
      enableWebSQL: false,
      spellcheck: false,
      zoomFactor: $VE(windowState.zoomLevel ?? windowSettings?.zoomLevel),
      autoplayPolicy: "user-gesture-required",
      // Enable experimental css highlight api https://chromestatus.com/feature/5436441440026624
      // Refs https://github.com/microsoft/vscode/issues/140098
      enableBlinkFeatures: "HighlightAPI",
      sandbox: true
    },
    experimentalDarkMode: true
  };
  if ($n) {
    options.icon = $vc(environmentMainService.appRoot, "resources/linux/code.png");
  } else if ($l && !environmentMainService.isBuilt) {
    options.icon = $vc(environmentMainService.appRoot, "resources/win32/code_150x150.png");
  }
  if ($m) {
    options.acceptFirstMouse = true;
    if (windowSettings?.clickThroughInactive === false) {
      options.acceptFirstMouse = false;
    }
  }
  if (overrides?.disableFullscreen) {
    options.fullscreen = false;
  } else if ($m && !$UE(configurationService)) {
    options.fullscreenable = false;
  }
  const useNativeTabs = $m && windowSettings?.nativeTabs === true;
  if (useNativeTabs) {
    options.tabbingIdentifier = productService.nameShort;
  }
  const hideNativeTitleBar = !$QE(configurationService, overrides?.forceNativeTitlebar ? "native" : void 0);
  if (hideNativeTitleBar) {
    options.titleBarStyle = "hidden";
    if (!$m) {
      options.frame = false;
    }
    if ($TE(configurationService)) {
      const titleBarColor = themeMainService.getWindowSplash()?.colorInfo.titleBarBackground ?? themeMainService.getBackgroundColor();
      const symbolColor = $Ou.fromHex(titleBarColor).isDarker() ? "#FFFFFF" : "#000000";
      options.titleBarOverlay = {
        height: 29,
        // the smallest size of the title bar on windows accounting for the border on windows 11
        color: titleBarColor,
        symbolColor
      };
    }
  }
  return options;
}
function $Rjc(windows) {
  let lastFocusedWindow = void 0;
  let maxLastFocusTime = Number.MIN_VALUE;
  for (const window2 of windows) {
    if (window2.lastFocusTime > maxLastFocusTime) {
      maxLastFocusTime = window2.lastFocusTime;
      lastFocusedWindow = window2;
    }
  }
  return lastFocusedWindow;
}
var WindowStateValidator;
(function(WindowStateValidator2) {
  function validateWindowState(logService, state, displays = electron5.screen.getAllDisplays()) {
    logService.trace(`window#validateWindowState: validating window state on ${displays.length} display(s)`, state);
    if (typeof state.x !== "number" || typeof state.y !== "number" || typeof state.width !== "number" || typeof state.height !== "number") {
      logService.trace("window#validateWindowState: unexpected type of state values");
      return void 0;
    }
    if (state.width <= 0 || state.height <= 0) {
      logService.trace("window#validateWindowState: unexpected negative values");
      return void 0;
    }
    if (displays.length === 1) {
      const displayWorkingArea2 = getWorkingArea(displays[0]);
      logService.trace("window#validateWindowState: single monitor working area", displayWorkingArea2);
      if (displayWorkingArea2) {
        let ensureStateInDisplayWorkingArea2 = function() {
          if (!state || typeof state.x !== "number" || typeof state.y !== "number" || !displayWorkingArea2) {
            return;
          }
          if (state.x < displayWorkingArea2.x) {
            state.x = displayWorkingArea2.x;
          }
          if (state.y < displayWorkingArea2.y) {
            state.y = displayWorkingArea2.y;
          }
        };
        var ensureStateInDisplayWorkingArea = ensureStateInDisplayWorkingArea2;
        ensureStateInDisplayWorkingArea2();
        if (state.width > displayWorkingArea2.width) {
          state.width = displayWorkingArea2.width;
        }
        if (state.height > displayWorkingArea2.height) {
          state.height = displayWorkingArea2.height;
        }
        if (state.x > displayWorkingArea2.x + displayWorkingArea2.width - 128) {
          state.x = displayWorkingArea2.x + displayWorkingArea2.width - state.width;
        }
        if (state.y > displayWorkingArea2.y + displayWorkingArea2.height - 128) {
          state.y = displayWorkingArea2.y + displayWorkingArea2.height - state.height;
        }
        ensureStateInDisplayWorkingArea2();
      }
      return state;
    }
    if (state.display && state.mode === 3) {
      const display2 = displays.find((d) => d.id === state.display);
      if (display2 && typeof display2.bounds?.x === "number" && typeof display2.bounds?.y === "number") {
        logService.trace("window#validateWindowState: restoring fullscreen to previous display");
        const defaults = $Ejc(
          3
          /* WindowMode.Fullscreen */
        );
        defaults.x = display2.bounds.x;
        defaults.y = display2.bounds.y;
        return defaults;
      }
    }
    let display;
    let displayWorkingArea;
    try {
      display = electron5.screen.getDisplayMatching({ x: state.x, y: state.y, width: state.width, height: state.height });
      displayWorkingArea = getWorkingArea(display);
      logService.trace("window#validateWindowState: multi-monitor working area", displayWorkingArea);
    } catch (error) {
      logService.error("window#validateWindowState: error finding display for window state", error);
    }
    if (display && // we have a display matching the desired bounds
    displayWorkingArea && // we have valid working area bounds
    state.x + state.width > displayWorkingArea.x && // prevent window from falling out of the screen to the left
    state.y + state.height > displayWorkingArea.y && // prevent window from falling out of the screen to the top
    state.x < displayWorkingArea.x + displayWorkingArea.width && // prevent window from falling out of the screen to the right
    state.y < displayWorkingArea.y + displayWorkingArea.height) {
      return state;
    }
    logService.trace("window#validateWindowState: state is outside of the multi-monitor working area");
    return void 0;
  }
  WindowStateValidator2.validateWindowState = validateWindowState;
  function getWorkingArea(display) {
    if (display.workArea.width > 0 && display.workArea.height > 0) {
      return display.workArea;
    }
    if (display.bounds.width > 0 && display.bounds.height > 0) {
      return display.bounds;
    }
    return void 0;
  }
})(WindowStateValidator || (WindowStateValidator = {}));

// out-build/vs/platform/native/electron-main/auth.js
var $gkc = $Zi("proxyAuthService");
var $hkc = class $hkc2 extends $0c {
  constructor(h, m, n, r, s, t) {
    super();
    this.h = h;
    this.m = m;
    this.n = n;
    this.r = r;
    this.s = s;
    this.t = t;
    this.a = "proxy-credentials://";
    this.b = /* @__PURE__ */ new Map();
    this.c = void 0;
    this.f = /* @__PURE__ */ new Set();
    this.g = /* @__PURE__ */ new Map();
    this.u();
  }
  u() {
    const onLogin = Event.fromNodeEventEmitter(app, "login", (event, _webContents, req, authInfo, callback) => ({ event, authInfo: { ...authInfo, attempt: req.firstAuthAttempt ? 1 : 2 }, callback }));
    this.B(onLogin(this.w, this));
  }
  async lookupAuthorization(authInfo) {
    return this.w({ authInfo });
  }
  async w({ event, authInfo, callback }) {
    if (!authInfo.isProxy) {
      return;
    }
    event?.preventDefault();
    const authInfoHash = String($Nj({ scheme: authInfo.scheme, host: authInfo.host, port: authInfo.port }));
    let credentials = void 0;
    let pendingProxyResolve = this.b.get(authInfoHash);
    if (!pendingProxyResolve) {
      this.h.trace("auth#onLogin (proxy) - no pending proxy handling found, starting new");
      pendingProxyResolve = this.y(authInfo, authInfoHash);
      this.b.set(authInfoHash, pendingProxyResolve);
      try {
        credentials = await pendingProxyResolve;
      } finally {
        this.b.delete(authInfoHash);
      }
    } else {
      this.h.trace("auth#onLogin (proxy) - pending proxy handling found");
      credentials = await pendingProxyResolve;
    }
    callback?.(credentials?.username, credentials?.password);
    return credentials;
  }
  async y(authInfo, authInfoHash) {
    this.h.trace("auth#resolveProxyCredentials (proxy) - enter");
    try {
      const credentials = await this.z(authInfo, authInfoHash);
      if (credentials) {
        this.h.trace("auth#resolveProxyCredentials (proxy) - got credentials");
        return credentials;
      } else {
        this.h.trace("auth#resolveProxyCredentials (proxy) - did not get credentials");
      }
    } finally {
      this.h.trace("auth#resolveProxyCredentials (proxy) - exit");
    }
    return void 0;
  }
  async z(authInfo, authInfoHash) {
    this.h.trace("auth#doResolveProxyCredentials - enter", authInfo);
    if (this.t.extensionTestsLocationURI) {
      const credentials = this.s.getValue("integration-test.http.proxyAuth");
      if (credentials) {
        const j = credentials.indexOf(":");
        if (j !== -1) {
          return {
            username: credentials.substring(0, j),
            password: credentials.substring(j + 1)
          };
        } else {
          return {
            username: credentials,
            password: ""
          };
        }
      }
      return void 0;
    }
    const newHttpProxy = (this.s.getValue("http.proxy") || "").trim() || (process.env["https_proxy"] || process.env["HTTPS_PROXY"] || process.env["http_proxy"] || process.env["HTTP_PROXY"] || "").trim() || void 0;
    if (newHttpProxy?.indexOf("@") !== -1) {
      const uri = URI.parse(newHttpProxy);
      const i = uri.authority.indexOf("@");
      if (i !== -1) {
        if (authInfo.attempt > 1) {
          this.h.trace("auth#doResolveProxyCredentials (proxy) - exit - ignoring previously used config/envvar credentials");
          return void 0;
        }
        this.h.trace("auth#doResolveProxyCredentials (proxy) - exit - found config/envvar credentials to use");
        const credentials = uri.authority.substring(0, i);
        const j = credentials.indexOf(":");
        if (j !== -1) {
          return {
            username: credentials.substring(0, j),
            password: credentials.substring(j + 1)
          };
        } else {
          return {
            username: credentials,
            password: ""
          };
        }
      }
    }
    const sessionCredentials = authInfo.attempt === 1 && this.g.get(authInfoHash);
    if (sessionCredentials) {
      this.h.trace("auth#doResolveProxyCredentials (proxy) - exit - found session credentials to use");
      const { username, password } = sessionCredentials;
      return { username, password };
    }
    let storedUsername;
    let storedPassword;
    try {
      const encryptedValue = this.r.get(
        this.a + authInfoHash,
        -1
        /* StorageScope.APPLICATION */
      );
      if (encryptedValue) {
        const credentials = JSON.parse(await this.n.decrypt(encryptedValue));
        storedUsername = credentials.username;
        storedPassword = credentials.password;
      }
    } catch (error) {
      this.h.error(error);
    }
    if (authInfo.attempt === 1 && typeof storedUsername === "string" && typeof storedPassword === "string") {
      this.h.trace("auth#doResolveProxyCredentials (proxy) - exit - found stored credentials to use");
      this.g.set(authInfoHash, { username: storedUsername, password: storedPassword });
      return { username: storedUsername, password: storedPassword };
    }
    const previousDialog = this.c;
    const currentDialog = this.c = (async () => {
      await previousDialog;
      const credentials = await this.C(authInfo, authInfoHash, storedUsername, storedPassword);
      if (this.c === currentDialog) {
        this.c = void 0;
      }
      return credentials;
    })();
    return currentDialog;
  }
  async C(authInfo, authInfoHash, storedUsername, storedPassword) {
    if (this.f.has(authInfoHash)) {
      this.h.trace("auth#doResolveProxyCredentials (proxy) - exit - login dialog was cancelled before, not showing again");
      return void 0;
    }
    const window2 = this.m.getFocusedWindow() || this.m.getLastActiveWindow();
    if (!window2) {
      this.h.trace("auth#doResolveProxyCredentials (proxy) - exit - no opened window found to show dialog in");
      return void 0;
    }
    this.h.trace(`auth#doResolveProxyCredentials (proxy) - asking window ${window2.id} to handle proxy login`);
    const sessionCredentials = this.g.get(authInfoHash);
    const payload = {
      authInfo,
      username: sessionCredentials?.username ?? storedUsername,
      // prefer to show already used username (if any) over stored
      password: sessionCredentials?.password ?? storedPassword,
      // prefer to show already used password (if any) over stored
      replyChannel: `vscode:proxyAuthResponse:${$jh()}`
    };
    window2.sendWhenReady("vscode:openProxyAuthenticationDialog", CancellationToken.None, payload);
    const loginDialogCredentials = await new Promise((resolve2) => {
      const proxyAuthResponseHandler = async (event, channel, reply) => {
        if (channel === payload.replyChannel) {
          this.h.trace(`auth#doResolveProxyCredentials - exit - received credentials from window ${window2.id}`);
          window2.win?.webContents.off("ipc-message", proxyAuthResponseHandler);
          if (reply) {
            const credentials = { username: reply.username, password: reply.password };
            try {
              if (reply.remember) {
                const encryptedSerializedCredentials = await this.n.encrypt(JSON.stringify(credentials));
                this.r.store(
                  this.a + authInfoHash,
                  encryptedSerializedCredentials,
                  -1,
                  1
                  /* StorageTarget.MACHINE */
                );
              } else {
                this.r.remove(
                  this.a + authInfoHash,
                  -1
                  /* StorageScope.APPLICATION */
                );
              }
            } catch (error) {
              this.h.error(error);
            }
            resolve2({ username: credentials.username, password: credentials.password });
          } else {
            this.f.add(authInfoHash);
            resolve2(void 0);
          }
        }
      };
      window2.win?.webContents.on("ipc-message", proxyAuthResponseHandler);
    });
    this.g.set(authInfoHash, loginDialogCredentials);
    return loginDialogCredentials;
  }
};
$hkc = __decorate([
  __param(0, $uk),
  __param(1, $Pjc),
  __param(2, $IZ),
  __param(3, $ekc),
  __param(4, $tj),
  __param(5, $Cjc)
], $hkc);

// out-build/vs/platform/backup/electron-main/backup.js
var $Jjc = $Zi("backupMainService");

// out-build/vs/platform/backup/electron-main/backupMainService.js
import { createHash as createHash3 } from "crypto";

// out-build/vs/platform/backup/node/backup.js
function $Gjc(obj) {
  const candidate = obj;
  return typeof candidate?.backupFolder === "string";
}
function $Hjc(serializedBackupWorkspaces) {
  let workspaceBackupInfos = [];
  try {
    if (Array.isArray(serializedBackupWorkspaces.workspaces)) {
      workspaceBackupInfos = serializedBackupWorkspaces.workspaces.map((workspace) => ({
        workspace: {
          id: workspace.id,
          configPath: URI.parse(workspace.configURIPath)
        },
        remoteAuthority: workspace.remoteAuthority
      }));
    }
  } catch (e) {
  }
  return workspaceBackupInfos;
}
function $Ijc(serializedBackupWorkspaces) {
  let folderBackupInfos = [];
  try {
    if (Array.isArray(serializedBackupWorkspaces.folders)) {
      folderBackupInfos = serializedBackupWorkspaces.folders.map((folder) => ({
        folderUri: URI.parse(folder.folderUri),
        remoteAuthority: folder.remoteAuthority
      }));
    }
  } catch (e) {
  }
  return folderBackupInfos;
}

// out-build/vs/platform/backup/common/backup.js
function $6jb(curr) {
  return curr && curr.hasOwnProperty("folderUri");
}

// out-build/vs/platform/workspaces/node/workspaces.js
import { createHash as createHash2 } from "crypto";
var $Xjc = 128 / 4;
function $Yjc(configPath) {
  function getWorkspaceId() {
    let configPathStr = configPath.scheme === Schemas.file ? $oh(configPath) : configPath.toString();
    if (!$n) {
      configPathStr = configPathStr.toLowerCase();
    }
    return createHash2("md5").update(configPathStr).digest("hex");
  }
  return {
    id: getWorkspaceId(),
    configPath
  };
}
function $Zjc(folderUri, folderStat) {
  function getFolderId() {
    if (folderUri.scheme !== Schemas.file) {
      return createHash2("md5").update(folderUri.toString()).digest("hex");
    }
    if (!folderStat) {
      return void 0;
    }
    let ctime;
    if ($n) {
      ctime = folderStat.ino;
    } else if ($m) {
      ctime = folderStat.birthtime.getTime();
    } else if ($l) {
      if (typeof folderStat.birthtimeMs === "number") {
        ctime = Math.floor(folderStat.birthtimeMs);
      } else {
        ctime = folderStat.birthtime.getTime();
      }
    }
    return createHash2("md5").update(folderUri.fsPath).update(ctime ? String(ctime) : "").digest("hex");
  }
  const folderId = getFolderId();
  if (typeof folderId === "string") {
    return {
      id: folderId,
      uri: folderUri
    };
  }
  return void 0;
}
function $1jc() {
  return {
    id: (Date.now() + Math.round(Math.random() * 1e3)).toString()
  };
}

// out-build/vs/platform/backup/electron-main/backupMainService.js
var $ikc_1;
var $ikc = class $ikc2 {
  static {
    $ikc_1 = this;
  }
  static {
    this.a = "backupWorkspaces";
  }
  constructor(j, k, l, m) {
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.c = this.j.backupHome;
    this.d = [];
    this.e = [];
    this.g = [];
    this.h = $rh;
    this.i = { isEqual: (pathA, pathB) => $Xg(pathA, pathB, !$n) };
  }
  async initialize() {
    const serializedBackupWorkspaces = this.m.getItem($ikc_1.a) ?? { workspaces: [], folders: [], emptyWindows: [] };
    this.g = await this.w(serializedBackupWorkspaces.emptyWindows);
    this.d = await this.u($Hjc(serializedBackupWorkspaces));
    this.e = await this.v($Ijc(serializedBackupWorkspaces));
    this.C();
  }
  n() {
    if (this.q()) {
      return [];
    }
    return this.d.slice(0);
  }
  o() {
    if (this.q()) {
      return [];
    }
    return this.e.slice(0);
  }
  isHotExitEnabled() {
    return this.s() !== $Tl.OFF;
  }
  q() {
    return this.s() === $Tl.ON_EXIT_AND_WINDOW_CLOSE;
  }
  s() {
    const config = this.k.getValue();
    return config?.files?.hotExit || $Tl.ON_EXIT;
  }
  getEmptyWindowBackups() {
    return this.g.slice(0);
  }
  registerWorkspaceBackup(workspaceInfo, migrateFrom) {
    if (!this.d.some((workspace) => workspaceInfo.workspace.id === workspace.workspace.id)) {
      this.d.push(workspaceInfo);
      this.C();
    }
    const backupPath = $vc(this.c, workspaceInfo.workspace.id);
    if (migrateFrom) {
      return this.t(backupPath, migrateFrom).then(() => backupPath);
    }
    return backupPath;
  }
  async t(backupPath, moveFromPath) {
    if (await Promises2.exists(backupPath)) {
      await this.z(backupPath);
    }
    if (await Promises2.exists(moveFromPath)) {
      try {
        await Promises2.rename(
          moveFromPath,
          backupPath,
          false
          /* no retry */
        );
      } catch (error) {
        this.l.error(`Backup: Could not move backup folder to new location: ${error.toString()}`);
      }
    }
  }
  registerFolderBackup(folderInfo) {
    if (!this.e.some((folder) => this.h.isEqual(folderInfo.folderUri, folder.folderUri))) {
      this.e.push(folderInfo);
      this.C();
    }
    return $vc(this.c, this.D(folderInfo));
  }
  registerEmptyWindowBackup(emptyWindowInfo) {
    if (!this.g.some((emptyWindow) => !!emptyWindow.backupFolder && this.i.isEqual(emptyWindow.backupFolder, emptyWindowInfo.backupFolder))) {
      this.g.push(emptyWindowInfo);
      this.C();
    }
    return $vc(this.c, emptyWindowInfo.backupFolder);
  }
  async u(rootWorkspaces) {
    if (!Array.isArray(rootWorkspaces)) {
      return [];
    }
    const seenIds = /* @__PURE__ */ new Set();
    const result = [];
    for (const workspaceInfo of rootWorkspaces) {
      const workspace = workspaceInfo.workspace;
      if (!$cj(workspace)) {
        return [];
      }
      if (!seenIds.has(workspace.id)) {
        seenIds.add(workspace.id);
        const backupPath = $vc(this.c, workspace.id);
        const hasBackups = await this.B(backupPath);
        if (hasBackups) {
          if (workspace.configPath.scheme !== Schemas.file || await Promises2.exists(workspace.configPath.fsPath)) {
            result.push(workspaceInfo);
          } else {
            await this.z(backupPath);
          }
        } else {
          await this.x(backupPath);
        }
      }
    }
    return result;
  }
  async v(folderWorkspaces) {
    if (!Array.isArray(folderWorkspaces)) {
      return [];
    }
    const result = [];
    const seenIds = /* @__PURE__ */ new Set();
    for (const folderInfo of folderWorkspaces) {
      const folderURI = folderInfo.folderUri;
      const key = this.h.getComparisonKey(folderURI);
      if (!seenIds.has(key)) {
        seenIds.add(key);
        const backupPath = $vc(this.c, this.D(folderInfo));
        const hasBackups = await this.B(backupPath);
        if (hasBackups) {
          if (folderURI.scheme !== Schemas.file || await Promises2.exists(folderURI.fsPath)) {
            result.push(folderInfo);
          } else {
            await this.z(backupPath);
          }
        } else {
          await this.x(backupPath);
        }
      }
    }
    return result;
  }
  async w(emptyWorkspaces) {
    if (!Array.isArray(emptyWorkspaces)) {
      return [];
    }
    const result = [];
    const seenIds = /* @__PURE__ */ new Set();
    for (const backupInfo of emptyWorkspaces) {
      const backupFolder = backupInfo.backupFolder;
      if (typeof backupFolder !== "string") {
        return [];
      }
      if (!seenIds.has(backupFolder)) {
        seenIds.add(backupFolder);
        const backupPath = $vc(this.c, backupFolder);
        if (await this.B(backupPath)) {
          result.push(backupInfo);
        } else {
          await this.x(backupPath);
        }
      }
    }
    return result;
  }
  async x(backupPath) {
    try {
      await Promises2.rm(backupPath, RimRafMode.MOVE);
    } catch (error) {
      this.l.error(`Backup: Could not delete stale backup: ${error.toString()}`);
    }
  }
  y() {
    let emptyWorkspaceIdentifier = $1jc();
    while (this.g.some((emptyWindow) => !!emptyWindow.backupFolder && this.i.isEqual(emptyWindow.backupFolder, emptyWorkspaceIdentifier.id))) {
      emptyWorkspaceIdentifier = $1jc();
    }
    return { backupFolder: emptyWorkspaceIdentifier.id };
  }
  async z(backupPath) {
    const newEmptyWindowBackupInfo = this.y();
    const newEmptyWindowBackupPath = $vc(this.c, newEmptyWindowBackupInfo.backupFolder);
    try {
      await Promises2.rename(
        backupPath,
        newEmptyWindowBackupPath,
        false
        /* no retry */
      );
    } catch (error) {
      this.l.error(`Backup: Could not rename backup folder: ${error.toString()}`);
      return false;
    }
    this.g.push(newEmptyWindowBackupInfo);
    return true;
  }
  async getDirtyWorkspaces() {
    const dirtyWorkspaces = [];
    for (const workspace of this.d) {
      if (await this.A(workspace)) {
        dirtyWorkspaces.push(workspace);
      }
    }
    for (const folder of this.e) {
      if (await this.A(folder)) {
        dirtyWorkspaces.push(folder);
      }
    }
    return dirtyWorkspaces;
  }
  A(backupLocation) {
    let backupPath;
    if ($Gjc(backupLocation)) {
      backupPath = $vc(this.c, backupLocation.backupFolder);
    } else if ($6jb(backupLocation)) {
      backupPath = $vc(this.c, this.D(backupLocation));
    } else {
      backupPath = $vc(this.c, backupLocation.workspace.id);
    }
    return this.B(backupPath);
  }
  async B(backupPath) {
    try {
      const backupSchemas = await Promises2.readdir(backupPath);
      for (const backupSchema of backupSchemas) {
        try {
          const backupSchemaChildren = await Promises2.readdir($vc(backupPath, backupSchema));
          if (backupSchemaChildren.length > 0) {
            return true;
          }
        } catch (error) {
        }
      }
    } catch (error) {
    }
    return false;
  }
  C() {
    const serializedBackupWorkspaces = {
      workspaces: this.d.map(({ workspace, remoteAuthority }) => {
        const serializedWorkspaceBackupInfo = {
          id: workspace.id,
          configURIPath: workspace.configPath.toString()
        };
        if (remoteAuthority) {
          serializedWorkspaceBackupInfo.remoteAuthority = remoteAuthority;
        }
        return serializedWorkspaceBackupInfo;
      }),
      folders: this.e.map(({ folderUri, remoteAuthority }) => {
        const serializedFolderBackupInfo = {
          folderUri: folderUri.toString()
        };
        if (remoteAuthority) {
          serializedFolderBackupInfo.remoteAuthority = remoteAuthority;
        }
        return serializedFolderBackupInfo;
      }),
      emptyWindows: this.g.map(({ backupFolder, remoteAuthority }) => {
        const serializedEmptyWindowBackupInfo = {
          backupFolder
        };
        if (remoteAuthority) {
          serializedEmptyWindowBackupInfo.remoteAuthority = remoteAuthority;
        }
        return serializedEmptyWindowBackupInfo;
      })
    };
    this.m.setItem($ikc_1.a, serializedBackupWorkspaces);
  }
  D(folder) {
    const folderUri = folder.folderUri;
    let key;
    if (folderUri.scheme === Schemas.file) {
      key = $n ? folderUri.fsPath : folderUri.fsPath.toLowerCase();
    } else {
      key = folderUri.toString().toLowerCase();
    }
    return createHash3("md5").update(key).digest("hex");
  }
};
$ikc = $ikc_1 = __decorate([
  __param(0, $Cjc),
  __param(1, $tj),
  __param(2, $uk),
  __param(3, $BS)
], $ikc);

// out-build/vs/platform/debug/electron-main/extensionHostDebugIpc.js
import { createServer as createServer2 } from "net";

// out-build/vs/platform/debug/common/extensionHostDebugIpc.js
var $ip = class {
  constructor() {
    this.a = new $De();
    this.b = new $De();
    this.c = new $De();
    this.d = new $De();
  }
  static {
    this.ChannelName = "extensionhostdebugservice";
  }
  call(ctx, command, arg) {
    switch (command) {
      case "close":
        return Promise.resolve(this.a.fire({ sessionId: arg[0] }));
      case "reload":
        return Promise.resolve(this.b.fire({ sessionId: arg[0] }));
      case "terminate":
        return Promise.resolve(this.c.fire({ sessionId: arg[0] }));
      case "attach":
        return Promise.resolve(this.d.fire({ sessionId: arg[0], port: arg[1], subId: arg[2] }));
    }
    throw new Error("Method not implemented.");
  }
  listen(ctx, event, arg) {
    switch (event) {
      case "close":
        return this.a.event;
      case "reload":
        return this.b.event;
      case "terminate":
        return this.c.event;
      case "attach":
        return this.d.event;
    }
    throw new Error("Method not implemented.");
  }
};

// out-build/vs/platform/environment/node/argv.js
import minimist from "minimist";
var helpCategories = {
  o: localize(1723, null),
  e: localize(1724, null),
  t: localize(1725, null)
};
var $Vm = ["tunnel", "serve-web"];
var $Wm = {
  "tunnel": {
    type: "subcommand",
    description: "Make the current machine accessible from vscode.dev or other machines through a secure tunnel",
    options: {
      "cli-data-dir": { type: "string", args: "dir", description: localize(1726, null) },
      "disable-telemetry": { type: "boolean" },
      "telemetry-level": { type: "string" },
      user: {
        type: "subcommand",
        options: {
          login: {
            type: "subcommand",
            options: {
              provider: { type: "string" },
              "access-token": { type: "string" }
            }
          }
        }
      }
    }
  },
  "serve-web": {
    type: "subcommand",
    description: "Run a server that displays the editor UI in browsers.",
    options: {
      "cli-data-dir": { type: "string", args: "dir", description: localize(1727, null) },
      "disable-telemetry": { type: "boolean" },
      "telemetry-level": { type: "string" }
    }
  },
  "diff": { type: "boolean", cat: "o", alias: "d", args: ["file", "file"], description: localize(1728, null) },
  "merge": { type: "boolean", cat: "o", alias: "m", args: ["path1", "path2", "base", "result"], description: localize(1729, null) },
  "add": { type: "boolean", cat: "o", alias: "a", args: "folder", description: localize(1730, null) },
  "goto": { type: "boolean", cat: "o", alias: "g", args: "file:line[:character]", description: localize(1731, null) },
  "new-window": { type: "boolean", cat: "o", alias: "n", description: localize(1732, null) },
  "reuse-window": { type: "boolean", cat: "o", alias: "r", description: localize(1733, null) },
  "wait": { type: "boolean", cat: "o", alias: "w", description: localize(1734, null) },
  "waitMarkerFilePath": { type: "string" },
  "locale": { type: "string", cat: "o", args: "locale", description: localize(1735, null) },
  "user-data-dir": { type: "string", cat: "o", args: "dir", description: localize(1736, null) },
  "profile": { type: "string", "cat": "o", args: "profileName", description: localize(1737, null) },
  "help": { type: "boolean", cat: "o", alias: "h", description: localize(1738, null) },
  "extensions-dir": { type: "string", deprecates: ["extensionHomePath"], cat: "e", args: "dir", description: localize(1739, null) },
  "extensions-download-dir": { type: "string" },
  "builtin-extensions-dir": { type: "string" },
  "list-extensions": { type: "boolean", cat: "e", description: localize(1740, null) },
  "show-versions": { type: "boolean", cat: "e", description: localize(1741, null) },
  "category": { type: "string", allowEmptyValue: true, cat: "e", description: localize(1742, null), args: "category" },
  "install-extension": { type: "string[]", cat: "e", args: "ext-id | path", description: localize(1743, null) },
  "pre-release": { type: "boolean", cat: "e", description: localize(1744, null) },
  "uninstall-extension": { type: "string[]", cat: "e", args: "ext-id", description: localize(1745, null) },
  "update-extensions": { type: "boolean", cat: "e", description: localize(1746, null) },
  "enable-proposed-api": { type: "string[]", allowEmptyValue: true, cat: "e", args: "ext-id", description: localize(1747, null) },
  "version": { type: "boolean", cat: "t", alias: "v", description: localize(1748, null) },
  "verbose": { type: "boolean", cat: "t", global: true, description: localize(1749, null) },
  "log": { type: "string[]", cat: "t", args: "level", global: true, description: localize(1750, null) },
  "status": { type: "boolean", alias: "s", cat: "t", description: localize(1751, null) },
  "prof-startup": { type: "boolean", cat: "t", description: localize(1752, null) },
  "prof-append-timers": { type: "string" },
  "prof-duration-markers": { type: "string[]" },
  "prof-duration-markers-file": { type: "string" },
  "no-cached-data": { type: "boolean" },
  "prof-startup-prefix": { type: "string" },
  "prof-v8-extensions": { type: "boolean" },
  "disable-extensions": { type: "boolean", deprecates: ["disableExtensions"], cat: "t", description: localize(1753, null) },
  "disable-extension": { type: "string[]", cat: "t", args: "ext-id", description: localize(1754, null) },
  "sync": { type: "string", cat: "t", description: localize(1755, null), args: ["on | off"] },
  "inspect-extensions": { type: "string", allowEmptyValue: true, deprecates: ["debugPluginHost"], args: "port", cat: "t", description: localize(1756, null) },
  "inspect-brk-extensions": { type: "string", allowEmptyValue: true, deprecates: ["debugBrkPluginHost"], args: "port", cat: "t", description: localize(1757, null) },
  "disable-lcd-text": { type: "boolean", cat: "t", description: localize(1758, null) },
  "disable-gpu": { type: "boolean", cat: "t", description: localize(1759, null) },
  "disable-chromium-sandbox": { type: "boolean", cat: "t", description: localize(1760, null) },
  "sandbox": { type: "boolean" },
  "telemetry": { type: "boolean", cat: "t", description: localize(1761, null) },
  "remote": { type: "string", allowEmptyValue: true },
  "folder-uri": { type: "string[]", cat: "o", args: "uri" },
  "file-uri": { type: "string[]", cat: "o", args: "uri" },
  "locate-extension": { type: "string[]" },
  "extensionDevelopmentPath": { type: "string[]" },
  "extensionDevelopmentKind": { type: "string[]" },
  "extensionTestsPath": { type: "string" },
  "extensionEnvironment": { type: "string" },
  "debugId": { type: "string" },
  "debugRenderer": { type: "boolean" },
  "inspect-ptyhost": { type: "string", allowEmptyValue: true },
  "inspect-brk-ptyhost": { type: "string", allowEmptyValue: true },
  "inspect-search": { type: "string", deprecates: ["debugSearch"], allowEmptyValue: true },
  "inspect-brk-search": { type: "string", deprecates: ["debugBrkSearch"], allowEmptyValue: true },
  "inspect-sharedprocess": { type: "string", allowEmptyValue: true },
  "inspect-brk-sharedprocess": { type: "string", allowEmptyValue: true },
  "export-default-configuration": { type: "string" },
  "install-source": { type: "string" },
  "enable-smoke-test-driver": { type: "boolean" },
  "logExtensionHostCommunication": { type: "boolean" },
  "skip-release-notes": { type: "boolean" },
  "skip-welcome": { type: "boolean" },
  "disable-telemetry": { type: "boolean" },
  "disable-updates": { type: "boolean" },
  "use-inmemory-secretstorage": { type: "boolean", deprecates: ["disable-keytar"] },
  "password-store": { type: "string" },
  "disable-workspace-trust": { type: "boolean" },
  "disable-crash-reporter": { type: "boolean" },
  "crash-reporter-directory": { type: "string" },
  "crash-reporter-id": { type: "string" },
  "skip-add-to-recently-opened": { type: "boolean" },
  "open-url": { type: "boolean" },
  "file-write": { type: "boolean" },
  "file-chmod": { type: "boolean" },
  "install-builtin-extension": { type: "string[]" },
  "force": { type: "boolean" },
  "do-not-sync": { type: "boolean" },
  "trace": { type: "boolean" },
  "trace-category-filter": { type: "string" },
  "trace-options": { type: "string" },
  "preserve-env": { type: "boolean" },
  "force-user-env": { type: "boolean" },
  "force-disable-user-env": { type: "boolean" },
  "open-devtools": { type: "boolean" },
  "disable-gpu-sandbox": { type: "boolean" },
  "logsPath": { type: "string" },
  "__enable-file-policy": { type: "boolean" },
  "editSessionId": { type: "string" },
  "continueOn": { type: "string" },
  "locate-shell-integration-path": { type: "string", args: ["bash", "pwsh", "zsh", "fish"] },
  "enable-coi": { type: "boolean" },
  // chromium flags
  "no-proxy-server": { type: "boolean" },
  // Minimist incorrectly parses keys that start with `--no`
  // https://github.com/substack/minimist/blob/aeb3e27dae0412de5c0494e9563a5f10c82cc7a9/index.js#L118-L121
  // If --no-sandbox is passed via cli wrapper it will be treated as --sandbox which is incorrect, we use
  // the alias here to make sure --no-sandbox is always respected.
  // For https://github.com/microsoft/vscode/issues/128279
  "no-sandbox": { type: "boolean", alias: "sandbox" },
  "proxy-server": { type: "string" },
  "proxy-bypass-list": { type: "string" },
  "proxy-pac-url": { type: "string" },
  "js-flags": { type: "string" },
  // chrome js flags
  "inspect": { type: "string", allowEmptyValue: true },
  "inspect-brk": { type: "string", allowEmptyValue: true },
  "nolazy": { type: "boolean" },
  // node inspect
  "force-device-scale-factor": { type: "string" },
  "force-renderer-accessibility": { type: "boolean" },
  "ignore-certificate-errors": { type: "boolean" },
  "allow-insecure-localhost": { type: "boolean" },
  "log-net-log": { type: "string" },
  "vmodule": { type: "string" },
  "_urls": { type: "string[]" },
  "disable-dev-shm-usage": { type: "boolean" },
  "profile-temp": { type: "boolean" },
  "ozone-platform": { type: "string" },
  "enable-tracing": { type: "string" },
  "trace-startup-format": { type: "string" },
  "trace-startup-file": { type: "string" },
  "trace-startup-duration": { type: "string" },
  _: { type: "string[]" }
  // main arguments
};
var ignoringReporter = {
  onUnknownOption: () => {
  },
  onMultipleValues: () => {
  },
  onEmptyValue: () => {
  },
  onDeprecatedOption: () => {
  }
};
function $Xm(args, options, errorReporter = ignoringReporter) {
  const firstArg = args.find((a) => a.length > 0 && a[0] !== "-");
  const alias = {};
  const stringOptions = ["_"];
  const booleanOptions = [];
  const globalOptions = {};
  let command = void 0;
  for (const optionId in options) {
    const o = options[optionId];
    if (o.type === "subcommand") {
      if (optionId === firstArg) {
        command = o;
      }
    } else {
      if (o.alias) {
        alias[optionId] = o.alias;
      }
      if (o.type === "string" || o.type === "string[]") {
        stringOptions.push(optionId);
        if (o.deprecates) {
          stringOptions.push(...o.deprecates);
        }
      } else if (o.type === "boolean") {
        booleanOptions.push(optionId);
        if (o.deprecates) {
          booleanOptions.push(...o.deprecates);
        }
      }
      if (o.global) {
        globalOptions[optionId] = o;
      }
    }
  }
  if (command && firstArg) {
    const options2 = globalOptions;
    for (const optionId in command.options) {
      options2[optionId] = command.options[optionId];
    }
    const newArgs = args.filter((a) => a !== firstArg);
    const reporter = errorReporter.getSubcommandReporter ? errorReporter.getSubcommandReporter(firstArg) : void 0;
    const subcommandOptions = $Xm(newArgs, options2, reporter);
    return {
      [firstArg]: subcommandOptions,
      _: []
    };
  }
  const parsedArgs = minimist(args, { string: stringOptions, boolean: booleanOptions, alias });
  const cleanedArgs = {};
  const remainingArgs = parsedArgs;
  cleanedArgs._ = parsedArgs._.map((arg) => String(arg)).filter((arg) => arg.length > 0);
  delete remainingArgs._;
  for (const optionId in options) {
    const o = options[optionId];
    if (o.type === "subcommand") {
      continue;
    }
    if (o.alias) {
      delete remainingArgs[o.alias];
    }
    let val = remainingArgs[optionId];
    if (o.deprecates) {
      for (const deprecatedId of o.deprecates) {
        if (remainingArgs.hasOwnProperty(deprecatedId)) {
          if (!val) {
            val = remainingArgs[deprecatedId];
            if (val) {
              errorReporter.onDeprecatedOption(deprecatedId, o.deprecationMessage || localize(1762, null, optionId));
            }
          }
          delete remainingArgs[deprecatedId];
        }
      }
    }
    if (typeof val !== "undefined") {
      if (o.type === "string[]") {
        if (!Array.isArray(val)) {
          val = [val];
        }
        if (!o.allowEmptyValue) {
          const sanitized = val.filter((v) => v.length > 0);
          if (sanitized.length !== val.length) {
            errorReporter.onEmptyValue(optionId);
            val = sanitized.length > 0 ? sanitized : void 0;
          }
        }
      } else if (o.type === "string") {
        if (Array.isArray(val)) {
          val = val.pop();
          errorReporter.onMultipleValues(optionId, val);
        } else if (!val && !o.allowEmptyValue) {
          errorReporter.onEmptyValue(optionId);
          val = void 0;
        }
      }
      cleanedArgs[optionId] = val;
      if (o.deprecationMessage) {
        errorReporter.onDeprecatedOption(optionId, o.deprecationMessage);
      }
    }
    delete remainingArgs[optionId];
  }
  for (const key in remainingArgs) {
    errorReporter.onUnknownOption(key);
  }
  return cleanedArgs;
}

// out-build/vs/platform/debug/electron-main/extensionHostDebugIpc.js
var $jkc = class extends $ip {
  constructor(f) {
    super();
    this.f = f;
  }
  call(ctx, command, arg) {
    if (command === "openExtensionDevelopmentHostWindow") {
      return this.g(arg[0], arg[1]);
    } else {
      return super.call(ctx, command, arg);
    }
  }
  async g(args, debugRenderer) {
    const pargs = $Xm(args, $Wm);
    pargs.debugRenderer = debugRenderer;
    const extDevPaths = pargs.extensionDevelopmentPath;
    if (!extDevPaths) {
      return { success: false };
    }
    const [codeWindow] = await this.f.openExtensionDevelopmentHostWindow(extDevPaths, {
      context: 5,
      cli: pargs,
      forceProfile: pargs.profile,
      forceTempProfile: pargs["profile-temp"]
    });
    if (!debugRenderer) {
      return { success: true };
    }
    const win = codeWindow.win;
    if (!win) {
      return { success: true };
    }
    const debug = win.webContents.debugger;
    let listeners = debug.isAttached() ? Infinity : 0;
    const server = createServer2((listener) => {
      if (listeners++ === 0) {
        debug.attach();
      }
      let closed = false;
      const writeMessage = (message) => {
        if (!closed) {
          listener.write(JSON.stringify(message) + "\0");
        }
      };
      const onMessage = (_event, method, params, sessionId) => writeMessage({ method, params, sessionId });
      win.on("close", () => {
        debug.removeListener("message", onMessage);
        listener.end();
        closed = true;
      });
      debug.addListener("message", onMessage);
      let buf = Buffer.alloc(0);
      listener.on("data", (data) => {
        buf = Buffer.concat([buf, data]);
        for (let delimiter = buf.indexOf(0); delimiter !== -1; delimiter = buf.indexOf(0)) {
          let data2;
          try {
            const contents = buf.slice(0, delimiter).toString("utf8");
            buf = buf.slice(delimiter + 1);
            data2 = JSON.parse(contents);
          } catch (e) {
            console.error("error reading cdp line", e);
          }
          debug.sendCommand(data2.method, data2.params, data2.sessionId).then((result) => writeMessage({ id: data2.id, sessionId: data2.sessionId, result })).catch((error) => writeMessage({ id: data2.id, sessionId: data2.sessionId, error: { code: 0, message: error.message } }));
        }
      });
      listener.on("error", (err) => {
        console.error("error on cdp pipe:", err);
      });
      listener.on("close", () => {
        closed = true;
        if (--listeners === 0) {
          debug.detach();
        }
      });
    });
    await new Promise((r) => server.listen(0, r));
    win.on("close", () => server.close());
    return { rendererDebugPort: server.address().port, success: true };
  }
};

// out-build/vs/platform/diagnostics/common/diagnostics.js
var ID = "diagnosticsService";
var $bn = $Zi(ID);
function $cn(x) {
  return !!x.hostName && !!x.errorMessage;
}

// out-build/vs/platform/diagnostics/electron-main/diagnosticsMainService.js
import { app as app3, BrowserWindow } from "electron";

// out-build/vs/platform/workspaces/electron-main/workspacesManagementMainService.js
import * as fs4 from "fs";
import electron7 from "electron";

// out-build/vs/base/common/json.js
var ScanError;
(function(ScanError2) {
  ScanError2[ScanError2["None"] = 0] = "None";
  ScanError2[ScanError2["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
  ScanError2[ScanError2["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
  ScanError2[ScanError2["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
  ScanError2[ScanError2["InvalidUnicode"] = 4] = "InvalidUnicode";
  ScanError2[ScanError2["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
  ScanError2[ScanError2["InvalidCharacter"] = 6] = "InvalidCharacter";
})(ScanError || (ScanError = {}));
var SyntaxKind;
(function(SyntaxKind2) {
  SyntaxKind2[SyntaxKind2["OpenBraceToken"] = 1] = "OpenBraceToken";
  SyntaxKind2[SyntaxKind2["CloseBraceToken"] = 2] = "CloseBraceToken";
  SyntaxKind2[SyntaxKind2["OpenBracketToken"] = 3] = "OpenBracketToken";
  SyntaxKind2[SyntaxKind2["CloseBracketToken"] = 4] = "CloseBracketToken";
  SyntaxKind2[SyntaxKind2["CommaToken"] = 5] = "CommaToken";
  SyntaxKind2[SyntaxKind2["ColonToken"] = 6] = "ColonToken";
  SyntaxKind2[SyntaxKind2["NullKeyword"] = 7] = "NullKeyword";
  SyntaxKind2[SyntaxKind2["TrueKeyword"] = 8] = "TrueKeyword";
  SyntaxKind2[SyntaxKind2["FalseKeyword"] = 9] = "FalseKeyword";
  SyntaxKind2[SyntaxKind2["StringLiteral"] = 10] = "StringLiteral";
  SyntaxKind2[SyntaxKind2["NumericLiteral"] = 11] = "NumericLiteral";
  SyntaxKind2[SyntaxKind2["LineCommentTrivia"] = 12] = "LineCommentTrivia";
  SyntaxKind2[SyntaxKind2["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
  SyntaxKind2[SyntaxKind2["LineBreakTrivia"] = 14] = "LineBreakTrivia";
  SyntaxKind2[SyntaxKind2["Trivia"] = 15] = "Trivia";
  SyntaxKind2[SyntaxKind2["Unknown"] = 16] = "Unknown";
  SyntaxKind2[SyntaxKind2["EOF"] = 17] = "EOF";
})(SyntaxKind || (SyntaxKind = {}));
var ParseErrorCode;
(function(ParseErrorCode2) {
  ParseErrorCode2[ParseErrorCode2["InvalidSymbol"] = 1] = "InvalidSymbol";
  ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
  ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"] = 3] = "PropertyNameExpected";
  ParseErrorCode2[ParseErrorCode2["ValueExpected"] = 4] = "ValueExpected";
  ParseErrorCode2[ParseErrorCode2["ColonExpected"] = 5] = "ColonExpected";
  ParseErrorCode2[ParseErrorCode2["CommaExpected"] = 6] = "CommaExpected";
  ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"] = 7] = "CloseBraceExpected";
  ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"] = 8] = "CloseBracketExpected";
  ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"] = 9] = "EndOfFileExpected";
  ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"] = 10] = "InvalidCommentToken";
  ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
  ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
  ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
  ParseErrorCode2[ParseErrorCode2["InvalidUnicode"] = 14] = "InvalidUnicode";
  ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
  ParseErrorCode2[ParseErrorCode2["InvalidCharacter"] = 16] = "InvalidCharacter";
})(ParseErrorCode || (ParseErrorCode = {}));
var ParseOptions;
(function(ParseOptions2) {
  ParseOptions2.DEFAULT = {
    allowTrailingComma: true
  };
})(ParseOptions || (ParseOptions = {}));
function $fo(text, ignoreTrivia = false) {
  let pos = 0;
  const len = text.length;
  let value = "";
  let tokenOffset = 0;
  let token = 16;
  let scanError = 0;
  function scanHexDigits(count) {
    let digits = 0;
    let hexValue = 0;
    while (digits < count) {
      const ch = text.charCodeAt(pos);
      if (ch >= 48 && ch <= 57) {
        hexValue = hexValue * 16 + ch - 48;
      } else if (ch >= 65 && ch <= 70) {
        hexValue = hexValue * 16 + ch - 65 + 10;
      } else if (ch >= 97 && ch <= 102) {
        hexValue = hexValue * 16 + ch - 97 + 10;
      } else {
        break;
      }
      pos++;
      digits++;
    }
    if (digits < count) {
      hexValue = -1;
    }
    return hexValue;
  }
  function setPosition(newPosition) {
    pos = newPosition;
    value = "";
    tokenOffset = 0;
    token = 16;
    scanError = 0;
  }
  function scanNumber() {
    const start = pos;
    if (text.charCodeAt(pos) === 48) {
      pos++;
    } else {
      pos++;
      while (pos < text.length && isDigit(text.charCodeAt(pos))) {
        pos++;
      }
    }
    if (pos < text.length && text.charCodeAt(pos) === 46) {
      pos++;
      if (pos < text.length && isDigit(text.charCodeAt(pos))) {
        pos++;
        while (pos < text.length && isDigit(text.charCodeAt(pos))) {
          pos++;
        }
      } else {
        scanError = 3;
        return text.substring(start, pos);
      }
    }
    let end = pos;
    if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
      pos++;
      if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) {
        pos++;
      }
      if (pos < text.length && isDigit(text.charCodeAt(pos))) {
        pos++;
        while (pos < text.length && isDigit(text.charCodeAt(pos))) {
          pos++;
        }
        end = pos;
      } else {
        scanError = 3;
      }
    }
    return text.substring(start, end);
  }
  function scanString() {
    let result = "", start = pos;
    while (true) {
      if (pos >= len) {
        result += text.substring(start, pos);
        scanError = 2;
        break;
      }
      const ch = text.charCodeAt(pos);
      if (ch === 34) {
        result += text.substring(start, pos);
        pos++;
        break;
      }
      if (ch === 92) {
        result += text.substring(start, pos);
        pos++;
        if (pos >= len) {
          scanError = 2;
          break;
        }
        const ch2 = text.charCodeAt(pos++);
        switch (ch2) {
          case 34:
            result += '"';
            break;
          case 92:
            result += "\\";
            break;
          case 47:
            result += "/";
            break;
          case 98:
            result += "\b";
            break;
          case 102:
            result += "\f";
            break;
          case 110:
            result += "\n";
            break;
          case 114:
            result += "\r";
            break;
          case 116:
            result += "	";
            break;
          case 117: {
            const ch3 = scanHexDigits(4);
            if (ch3 >= 0) {
              result += String.fromCharCode(ch3);
            } else {
              scanError = 4;
            }
            break;
          }
          default:
            scanError = 5;
        }
        start = pos;
        continue;
      }
      if (ch >= 0 && ch <= 31) {
        if (isLineBreak(ch)) {
          result += text.substring(start, pos);
          scanError = 2;
          break;
        } else {
          scanError = 6;
        }
      }
      pos++;
    }
    return result;
  }
  function scanNext() {
    value = "";
    scanError = 0;
    tokenOffset = pos;
    if (pos >= len) {
      tokenOffset = len;
      return token = 17;
    }
    let code2 = text.charCodeAt(pos);
    if (isWhitespace(code2)) {
      do {
        pos++;
        value += String.fromCharCode(code2);
        code2 = text.charCodeAt(pos);
      } while (isWhitespace(code2));
      return token = 15;
    }
    if (isLineBreak(code2)) {
      pos++;
      value += String.fromCharCode(code2);
      if (code2 === 13 && text.charCodeAt(pos) === 10) {
        pos++;
        value += "\n";
      }
      return token = 14;
    }
    switch (code2) {
      case 123:
        pos++;
        return token = 1;
      case 125:
        pos++;
        return token = 2;
      case 91:
        pos++;
        return token = 3;
      case 93:
        pos++;
        return token = 4;
      case 58:
        pos++;
        return token = 6;
      case 44:
        pos++;
        return token = 5;
      case 34:
        pos++;
        value = scanString();
        return token = 10;
      case 47: {
        const start = pos - 1;
        if (text.charCodeAt(pos + 1) === 47) {
          pos += 2;
          while (pos < len) {
            if (isLineBreak(text.charCodeAt(pos))) {
              break;
            }
            pos++;
          }
          value = text.substring(start, pos);
          return token = 12;
        }
        if (text.charCodeAt(pos + 1) === 42) {
          pos += 2;
          const safeLength = len - 1;
          let commentClosed = false;
          while (pos < safeLength) {
            const ch = text.charCodeAt(pos);
            if (ch === 42 && text.charCodeAt(pos + 1) === 47) {
              pos += 2;
              commentClosed = true;
              break;
            }
            pos++;
          }
          if (!commentClosed) {
            pos++;
            scanError = 1;
          }
          value = text.substring(start, pos);
          return token = 13;
        }
        value += String.fromCharCode(code2);
        pos++;
        return token = 16;
      }
      case 45:
        value += String.fromCharCode(code2);
        pos++;
        if (pos === len || !isDigit(text.charCodeAt(pos))) {
          return token = 16;
        }
      case 48:
      case 49:
      case 50:
      case 51:
      case 52:
      case 53:
      case 54:
      case 55:
      case 56:
      case 57:
        value += scanNumber();
        return token = 11;
      default:
        while (pos < len && isUnknownContentCharacter(code2)) {
          pos++;
          code2 = text.charCodeAt(pos);
        }
        if (tokenOffset !== pos) {
          value = text.substring(tokenOffset, pos);
          switch (value) {
            case "true":
              return token = 8;
            case "false":
              return token = 9;
            case "null":
              return token = 7;
          }
          return token = 16;
        }
        value += String.fromCharCode(code2);
        pos++;
        return token = 16;
    }
  }
  function isUnknownContentCharacter(code2) {
    if (isWhitespace(code2) || isLineBreak(code2)) {
      return false;
    }
    switch (code2) {
      case 125:
      case 93:
      case 123:
      case 91:
      case 34:
      case 58:
      case 44:
      case 47:
        return false;
    }
    return true;
  }
  function scanNextNonTrivia() {
    let result;
    do {
      result = scanNext();
    } while (result >= 12 && result <= 15);
    return result;
  }
  return {
    setPosition,
    getPosition: () => pos,
    scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
    getToken: () => token,
    getTokenValue: () => value,
    getTokenOffset: () => tokenOffset,
    getTokenLength: () => pos - tokenOffset,
    getTokenError: () => scanError
  };
}
function isWhitespace(ch) {
  return ch === 32 || ch === 9 || ch === 11 || ch === 12 || ch === 160 || ch === 5760 || ch >= 8192 && ch <= 8203 || ch === 8239 || ch === 8287 || ch === 12288 || ch === 65279;
}
function isLineBreak(ch) {
  return ch === 10 || ch === 13 || ch === 8232 || ch === 8233;
}
function isDigit(ch) {
  return ch >= 48 && ch <= 57;
}
var CharacterCodes;
(function(CharacterCodes2) {
  CharacterCodes2[CharacterCodes2["nullCharacter"] = 0] = "nullCharacter";
  CharacterCodes2[CharacterCodes2["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
  CharacterCodes2[CharacterCodes2["lineFeed"] = 10] = "lineFeed";
  CharacterCodes2[CharacterCodes2["carriageReturn"] = 13] = "carriageReturn";
  CharacterCodes2[CharacterCodes2["lineSeparator"] = 8232] = "lineSeparator";
  CharacterCodes2[CharacterCodes2["paragraphSeparator"] = 8233] = "paragraphSeparator";
  CharacterCodes2[CharacterCodes2["nextLine"] = 133] = "nextLine";
  CharacterCodes2[CharacterCodes2["space"] = 32] = "space";
  CharacterCodes2[CharacterCodes2["nonBreakingSpace"] = 160] = "nonBreakingSpace";
  CharacterCodes2[CharacterCodes2["enQuad"] = 8192] = "enQuad";
  CharacterCodes2[CharacterCodes2["emQuad"] = 8193] = "emQuad";
  CharacterCodes2[CharacterCodes2["enSpace"] = 8194] = "enSpace";
  CharacterCodes2[CharacterCodes2["emSpace"] = 8195] = "emSpace";
  CharacterCodes2[CharacterCodes2["threePerEmSpace"] = 8196] = "threePerEmSpace";
  CharacterCodes2[CharacterCodes2["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
  CharacterCodes2[CharacterCodes2["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
  CharacterCodes2[CharacterCodes2["figureSpace"] = 8199] = "figureSpace";
  CharacterCodes2[CharacterCodes2["punctuationSpace"] = 8200] = "punctuationSpace";
  CharacterCodes2[CharacterCodes2["thinSpace"] = 8201] = "thinSpace";
  CharacterCodes2[CharacterCodes2["hairSpace"] = 8202] = "hairSpace";
  CharacterCodes2[CharacterCodes2["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
  CharacterCodes2[CharacterCodes2["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
  CharacterCodes2[CharacterCodes2["ideographicSpace"] = 12288] = "ideographicSpace";
  CharacterCodes2[CharacterCodes2["mathematicalSpace"] = 8287] = "mathematicalSpace";
  CharacterCodes2[CharacterCodes2["ogham"] = 5760] = "ogham";
  CharacterCodes2[CharacterCodes2["_"] = 95] = "_";
  CharacterCodes2[CharacterCodes2["$"] = 36] = "$";
  CharacterCodes2[CharacterCodes2["_0"] = 48] = "_0";
  CharacterCodes2[CharacterCodes2["_1"] = 49] = "_1";
  CharacterCodes2[CharacterCodes2["_2"] = 50] = "_2";
  CharacterCodes2[CharacterCodes2["_3"] = 51] = "_3";
  CharacterCodes2[CharacterCodes2["_4"] = 52] = "_4";
  CharacterCodes2[CharacterCodes2["_5"] = 53] = "_5";
  CharacterCodes2[CharacterCodes2["_6"] = 54] = "_6";
  CharacterCodes2[CharacterCodes2["_7"] = 55] = "_7";
  CharacterCodes2[CharacterCodes2["_8"] = 56] = "_8";
  CharacterCodes2[CharacterCodes2["_9"] = 57] = "_9";
  CharacterCodes2[CharacterCodes2["a"] = 97] = "a";
  CharacterCodes2[CharacterCodes2["b"] = 98] = "b";
  CharacterCodes2[CharacterCodes2["c"] = 99] = "c";
  CharacterCodes2[CharacterCodes2["d"] = 100] = "d";
  CharacterCodes2[CharacterCodes2["e"] = 101] = "e";
  CharacterCodes2[CharacterCodes2["f"] = 102] = "f";
  CharacterCodes2[CharacterCodes2["g"] = 103] = "g";
  CharacterCodes2[CharacterCodes2["h"] = 104] = "h";
  CharacterCodes2[CharacterCodes2["i"] = 105] = "i";
  CharacterCodes2[CharacterCodes2["j"] = 106] = "j";
  CharacterCodes2[CharacterCodes2["k"] = 107] = "k";
  CharacterCodes2[CharacterCodes2["l"] = 108] = "l";
  CharacterCodes2[CharacterCodes2["m"] = 109] = "m";
  CharacterCodes2[CharacterCodes2["n"] = 110] = "n";
  CharacterCodes2[CharacterCodes2["o"] = 111] = "o";
  CharacterCodes2[CharacterCodes2["p"] = 112] = "p";
  CharacterCodes2[CharacterCodes2["q"] = 113] = "q";
  CharacterCodes2[CharacterCodes2["r"] = 114] = "r";
  CharacterCodes2[CharacterCodes2["s"] = 115] = "s";
  CharacterCodes2[CharacterCodes2["t"] = 116] = "t";
  CharacterCodes2[CharacterCodes2["u"] = 117] = "u";
  CharacterCodes2[CharacterCodes2["v"] = 118] = "v";
  CharacterCodes2[CharacterCodes2["w"] = 119] = "w";
  CharacterCodes2[CharacterCodes2["x"] = 120] = "x";
  CharacterCodes2[CharacterCodes2["y"] = 121] = "y";
  CharacterCodes2[CharacterCodes2["z"] = 122] = "z";
  CharacterCodes2[CharacterCodes2["A"] = 65] = "A";
  CharacterCodes2[CharacterCodes2["B"] = 66] = "B";
  CharacterCodes2[CharacterCodes2["C"] = 67] = "C";
  CharacterCodes2[CharacterCodes2["D"] = 68] = "D";
  CharacterCodes2[CharacterCodes2["E"] = 69] = "E";
  CharacterCodes2[CharacterCodes2["F"] = 70] = "F";
  CharacterCodes2[CharacterCodes2["G"] = 71] = "G";
  CharacterCodes2[CharacterCodes2["H"] = 72] = "H";
  CharacterCodes2[CharacterCodes2["I"] = 73] = "I";
  CharacterCodes2[CharacterCodes2["J"] = 74] = "J";
  CharacterCodes2[CharacterCodes2["K"] = 75] = "K";
  CharacterCodes2[CharacterCodes2["L"] = 76] = "L";
  CharacterCodes2[CharacterCodes2["M"] = 77] = "M";
  CharacterCodes2[CharacterCodes2["N"] = 78] = "N";
  CharacterCodes2[CharacterCodes2["O"] = 79] = "O";
  CharacterCodes2[CharacterCodes2["P"] = 80] = "P";
  CharacterCodes2[CharacterCodes2["Q"] = 81] = "Q";
  CharacterCodes2[CharacterCodes2["R"] = 82] = "R";
  CharacterCodes2[CharacterCodes2["S"] = 83] = "S";
  CharacterCodes2[CharacterCodes2["T"] = 84] = "T";
  CharacterCodes2[CharacterCodes2["U"] = 85] = "U";
  CharacterCodes2[CharacterCodes2["V"] = 86] = "V";
  CharacterCodes2[CharacterCodes2["W"] = 87] = "W";
  CharacterCodes2[CharacterCodes2["X"] = 88] = "X";
  CharacterCodes2[CharacterCodes2["Y"] = 89] = "Y";
  CharacterCodes2[CharacterCodes2["Z"] = 90] = "Z";
  CharacterCodes2[CharacterCodes2["ampersand"] = 38] = "ampersand";
  CharacterCodes2[CharacterCodes2["asterisk"] = 42] = "asterisk";
  CharacterCodes2[CharacterCodes2["at"] = 64] = "at";
  CharacterCodes2[CharacterCodes2["backslash"] = 92] = "backslash";
  CharacterCodes2[CharacterCodes2["bar"] = 124] = "bar";
  CharacterCodes2[CharacterCodes2["caret"] = 94] = "caret";
  CharacterCodes2[CharacterCodes2["closeBrace"] = 125] = "closeBrace";
  CharacterCodes2[CharacterCodes2["closeBracket"] = 93] = "closeBracket";
  CharacterCodes2[CharacterCodes2["closeParen"] = 41] = "closeParen";
  CharacterCodes2[CharacterCodes2["colon"] = 58] = "colon";
  CharacterCodes2[CharacterCodes2["comma"] = 44] = "comma";
  CharacterCodes2[CharacterCodes2["dot"] = 46] = "dot";
  CharacterCodes2[CharacterCodes2["doubleQuote"] = 34] = "doubleQuote";
  CharacterCodes2[CharacterCodes2["equals"] = 61] = "equals";
  CharacterCodes2[CharacterCodes2["exclamation"] = 33] = "exclamation";
  CharacterCodes2[CharacterCodes2["greaterThan"] = 62] = "greaterThan";
  CharacterCodes2[CharacterCodes2["lessThan"] = 60] = "lessThan";
  CharacterCodes2[CharacterCodes2["minus"] = 45] = "minus";
  CharacterCodes2[CharacterCodes2["openBrace"] = 123] = "openBrace";
  CharacterCodes2[CharacterCodes2["openBracket"] = 91] = "openBracket";
  CharacterCodes2[CharacterCodes2["openParen"] = 40] = "openParen";
  CharacterCodes2[CharacterCodes2["percent"] = 37] = "percent";
  CharacterCodes2[CharacterCodes2["plus"] = 43] = "plus";
  CharacterCodes2[CharacterCodes2["question"] = 63] = "question";
  CharacterCodes2[CharacterCodes2["semicolon"] = 59] = "semicolon";
  CharacterCodes2[CharacterCodes2["singleQuote"] = 39] = "singleQuote";
  CharacterCodes2[CharacterCodes2["slash"] = 47] = "slash";
  CharacterCodes2[CharacterCodes2["tilde"] = 126] = "tilde";
  CharacterCodes2[CharacterCodes2["backspace"] = 8] = "backspace";
  CharacterCodes2[CharacterCodes2["formFeed"] = 12] = "formFeed";
  CharacterCodes2[CharacterCodes2["byteOrderMark"] = 65279] = "byteOrderMark";
  CharacterCodes2[CharacterCodes2["tab"] = 9] = "tab";
  CharacterCodes2[CharacterCodes2["verticalTab"] = 11] = "verticalTab";
})(CharacterCodes || (CharacterCodes = {}));
function $ho(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 !== null) {
      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 });
    }
  };
  $oo(text, visitor, options);
  return currentParent[0];
}
function $io(text, errors = [], options = ParseOptions.DEFAULT) {
  let currentParent = { type: "array", offset: -1, length: -1, children: [], parent: void 0 };
  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: $po(value), offset, length, parent: currentParent, value });
      ensurePropertyComplete(offset + length);
    },
    onSeparator: (sep2, offset, length) => {
      if (currentParent.type === "property") {
        if (sep2 === ":") {
          currentParent.colonOffset = offset;
        } else if (sep2 === ",") {
          ensurePropertyComplete(offset);
        }
      }
    },
    onError: (error, offset, length) => {
      errors.push({ error, offset, length });
    }
  };
  $oo(text, visitor, options);
  const result = currentParent.children[0];
  if (result) {
    delete result.parent;
  }
  return result;
}
function $jo(root, path3) {
  if (!root) {
    return void 0;
  }
  let node = root;
  for (const segment of path3) {
    if (typeof segment === "string") {
      if (node.type !== "object" || !Array.isArray(node.children)) {
        return void 0;
      }
      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 void 0;
      }
    } else {
      const index = segment;
      if (node.type !== "array" || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {
        return void 0;
      }
      node = node.children[index];
    }
  }
  return node;
}
function $oo(text, visitor, options = ParseOptions.DEFAULT) {
  const _scanner = $fo(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:
          handleError(
            14
            /* ParseErrorCode.InvalidUnicode */
          );
          break;
        case 5:
          handleError(
            15
            /* ParseErrorCode.InvalidEscapeCharacter */
          );
          break;
        case 3:
          handleError(
            13
            /* ParseErrorCode.UnexpectedEndOfNumber */
          );
          break;
        case 1:
          if (!disallowComments) {
            handleError(
              11
              /* ParseErrorCode.UnexpectedEndOfComment */
            );
          }
          break;
        case 2:
          handleError(
            12
            /* ParseErrorCode.UnexpectedEndOfString */
          );
          break;
        case 6:
          handleError(
            16
            /* ParseErrorCode.InvalidCharacter */
          );
          break;
      }
      switch (token) {
        case 12:
        case 13:
          if (disallowComments) {
            handleError(
              10
              /* ParseErrorCode.InvalidCommentToken */
            );
          } else {
            onComment();
          }
          break;
        case 16:
          handleError(
            1
            /* ParseErrorCode.InvalidSymbol */
          );
          break;
        case 15:
        case 14:
          break;
        default:
          return token;
      }
    }
  }
  function handleError(error, skipUntilAfter = [], skipUntil = []) {
    onError(error);
    if (skipUntilAfter.length + skipUntil.length > 0) {
      let token = _scanner.getToken();
      while (token !== 17) {
        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: {
        let value = 0;
        try {
          value = JSON.parse(_scanner.getTokenValue());
          if (typeof value !== "number") {
            handleError(
              2
              /* ParseErrorCode.InvalidNumberFormat */
            );
            value = 0;
          }
        } catch (e) {
          handleError(
            2
            /* ParseErrorCode.InvalidNumberFormat */
          );
        }
        onLiteralValue(value);
        break;
      }
      case 7:
        onLiteralValue(null);
        break;
      case 8:
        onLiteralValue(true);
        break;
      case 9:
        onLiteralValue(false);
        break;
      default:
        return false;
    }
    scanNext();
    return true;
  }
  function parseProperty() {
    if (_scanner.getToken() !== 10) {
      handleError(3, [], [
        2,
        5
        /* SyntaxKind.CommaToken */
      ]);
      return false;
    }
    parseString(false);
    if (_scanner.getToken() === 6) {
      onSeparator(":");
      scanNext();
      if (!parseValue()) {
        handleError(4, [], [
          2,
          5
          /* SyntaxKind.CommaToken */
        ]);
      }
    } else {
      handleError(5, [], [
        2,
        5
        /* SyntaxKind.CommaToken */
      ]);
    }
    return true;
  }
  function parseObject() {
    onObjectBegin();
    scanNext();
    let needsComma = false;
    while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) {
      if (_scanner.getToken() === 5) {
        if (!needsComma) {
          handleError(4, [], []);
        }
        onSeparator(",");
        scanNext();
        if (_scanner.getToken() === 2 && allowTrailingComma) {
          break;
        }
      } else if (needsComma) {
        handleError(6, [], []);
      }
      if (!parseProperty()) {
        handleError(4, [], [
          2,
          5
          /* SyntaxKind.CommaToken */
        ]);
      }
      needsComma = true;
    }
    onObjectEnd();
    if (_scanner.getToken() !== 2) {
      handleError(7, [
        2
        /* SyntaxKind.CloseBraceToken */
      ], []);
    } else {
      scanNext();
    }
    return true;
  }
  function parseArray() {
    onArrayBegin();
    scanNext();
    let needsComma = false;
    while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) {
      if (_scanner.getToken() === 5) {
        if (!needsComma) {
          handleError(4, [], []);
        }
        onSeparator(",");
        scanNext();
        if (_scanner.getToken() === 4 && allowTrailingComma) {
          break;
        }
      } else if (needsComma) {
        handleError(6, [], []);
      }
      if (!parseValue()) {
        handleError(4, [], [
          4,
          5
          /* SyntaxKind.CommaToken */
        ]);
      }
      needsComma = true;
    }
    onArrayEnd();
    if (_scanner.getToken() !== 4) {
      handleError(8, [
        4
        /* SyntaxKind.CloseBracketToken */
      ], []);
    } else {
      scanNext();
    }
    return true;
  }
  function parseValue() {
    switch (_scanner.getToken()) {
      case 3:
        return parseArray();
      case 1:
        return parseObject();
      case 10:
        return parseString(true);
      default:
        return parseLiteral();
    }
  }
  scanNext();
  if (_scanner.getToken() === 17) {
    if (options.allowEmptyContent) {
      return true;
    }
    handleError(4, [], []);
    return false;
  }
  if (!parseValue()) {
    handleError(4, [], []);
    return false;
  }
  if (_scanner.getToken() !== 17) {
    handleError(9, [], []);
  }
  return true;
}
function $po(value) {
  switch (typeof value) {
    case "boolean":
      return "boolean";
    case "number":
      return "number";
    case "string":
      return "string";
    case "object": {
      if (!value) {
        return "null";
      } else if (Array.isArray(value)) {
        return "array";
      }
      return "object";
    }
    default:
      return "null";
  }
}

// out-build/vs/platform/dialogs/electron-main/dialogMainService.js
import electron6 from "electron";

// out-build/vs/base/common/severity.js
var Severity;
(function(Severity2) {
  Severity2[Severity2["Ignore"] = 0] = "Ignore";
  Severity2[Severity2["Info"] = 1] = "Info";
  Severity2[Severity2["Warning"] = 2] = "Warning";
  Severity2[Severity2["Error"] = 3] = "Error";
})(Severity || (Severity = {}));
(function(Severity2) {
  const _error = "error";
  const _warning = "warning";
  const _warn = "warn";
  const _info = "info";
  const _ignore = "ignore";
  function fromValue(value) {
    if (!value) {
      return Severity2.Ignore;
    }
    if ($Zf(_error, value)) {
      return Severity2.Error;
    }
    if ($Zf(_warning, value) || $Zf(_warn, value)) {
      return Severity2.Warning;
    }
    if ($Zf(_info, value)) {
      return Severity2.Info;
    }
    return Severity2.Ignore;
  }
  Severity2.fromValue = fromValue;
  function toString(severity) {
    switch (severity) {
      case Severity2.Error:
        return _error;
      case Severity2.Warning:
        return _warning;
      case Severity2.Info:
        return _info;
      default:
        return _ignore;
    }
  }
  Severity2.toString = toString;
})(Severity || (Severity = {}));
var severity_default = Severity;

// out-build/vs/base/common/objects.js
function $zo(obj) {
  if (!obj || typeof obj !== "object") {
    return obj;
  }
  if (obj instanceof RegExp) {
    return obj;
  }
  const result = Array.isArray(obj) ? [] : {};
  Object.entries(obj).forEach(([key, value]) => {
    result[key] = value && typeof value === "object" ? $zo(value) : value;
  });
  return result;
}
function $Ao(obj) {
  if (!obj || typeof obj !== "object") {
    return obj;
  }
  const stack = [obj];
  while (stack.length > 0) {
    const obj2 = stack.shift();
    Object.freeze(obj2);
    for (const key in obj2) {
      if (_hasOwnProperty.call(obj2, key)) {
        const prop = obj2[key];
        if (typeof prop === "object" && !Object.isFrozen(prop) && !$Bg(prop)) {
          stack.push(prop);
        }
      }
    }
  }
  return obj;
}
var _hasOwnProperty = Object.prototype.hasOwnProperty;
function $Bo(obj, changer) {
  return _cloneAndChange(obj, changer, /* @__PURE__ */ new Set());
}
function _cloneAndChange(obj, changer, seen) {
  if ($Hg(obj)) {
    return obj;
  }
  const changed = changer(obj);
  if (typeof changed !== "undefined") {
    return changed;
  }
  if (Array.isArray(obj)) {
    const r1 = [];
    for (const e of obj) {
      r1.push(_cloneAndChange(e, changer, seen));
    }
    return r1;
  }
  if ($Ag(obj)) {
    if (seen.has(obj)) {
      throw new Error("Cannot clone recursive data-structure");
    }
    seen.add(obj);
    const r2 = {};
    for (const i2 in obj) {
      if (_hasOwnProperty.call(obj, i2)) {
        r2[i2] = _cloneAndChange(obj[i2], changer, seen);
      }
    }
    seen.delete(obj);
    return r2;
  }
  return obj;
}
function $Co(destination, source, overwrite = true) {
  if (!$Ag(destination)) {
    return source;
  }
  if ($Ag(source)) {
    Object.keys(source).forEach((key) => {
      if (key in destination) {
        if (overwrite) {
          if ($Ag(destination[key]) && $Ag(source[key])) {
            $Co(destination[key], source[key], overwrite);
          } else {
            destination[key] = source[key];
          }
        }
      } else {
        destination[key] = source[key];
      }
    });
  }
  return destination;
}
function $Do(one, other) {
  if (one === other) {
    return true;
  }
  if (one === null || one === void 0 || other === null || other === void 0) {
    return false;
  }
  if (typeof one !== typeof other) {
    return false;
  }
  if (typeof one !== "object") {
    return false;
  }
  if (Array.isArray(one) !== Array.isArray(other)) {
    return false;
  }
  let i;
  let key;
  if (Array.isArray(one)) {
    if (one.length !== other.length) {
      return false;
    }
    for (i = 0; i < one.length; i++) {
      if (!$Do(one[i], other[i])) {
        return false;
      }
    }
  } else {
    const oneKeys = [];
    for (key in one) {
      oneKeys.push(key);
    }
    oneKeys.sort();
    const otherKeys = [];
    for (key in other) {
      otherKeys.push(key);
    }
    otherKeys.sort();
    if (!$Do(oneKeys, otherKeys)) {
      return false;
    }
    for (i = 0; i < oneKeys.length; i++) {
      if (!$Do(one[oneKeys[i]], other[oneKeys[i]])) {
        return false;
      }
    }
  }
  return true;
}
function $Go(target, key) {
  const lowercaseKey = key.toLowerCase();
  const equivalentKey = Object.keys(target).find((k) => k.toLowerCase() === lowercaseKey);
  return equivalentKey ? target[equivalentKey] : target[key];
}

// out-build/vs/platform/dialogs/common/dialogs.js
var $Bx = $Zi("dialogService");
var DialogKind;
(function(DialogKind2) {
  DialogKind2[DialogKind2["Confirmation"] = 1] = "Confirmation";
  DialogKind2[DialogKind2["Prompt"] = 2] = "Prompt";
  DialogKind2[DialogKind2["Input"] = 3] = "Input";
})(DialogKind || (DialogKind = {}));
var $Dx = $Zi("fileDialogService");
var ConfirmResult;
(function(ConfirmResult2) {
  ConfirmResult2[ConfirmResult2["SAVE"] = 0] = "SAVE";
  ConfirmResult2[ConfirmResult2["DONT_SAVE"] = 1] = "DONT_SAVE";
  ConfirmResult2[ConfirmResult2["CANCEL"] = 2] = "CANCEL";
})(ConfirmResult || (ConfirmResult = {}));
function $Fx(options, productService) {
  const massagedOptions = $zo(options);
  let buttons = (massagedOptions.buttons ?? []).map((button) => $yx(button));
  let buttonIndeces = (options.buttons || []).map((button, index) => index);
  let defaultId = 0;
  let cancelId = massagedOptions.cancelId ?? buttons.length - 1;
  if (buttons.length > 1) {
    const cancelButton = typeof cancelId === "number" ? buttons[cancelId] : void 0;
    if ($n || $m) {
      if (typeof cancelButton === "string" && buttons.length > 1 && cancelId !== 1) {
        buttons.splice(cancelId, 1);
        buttons.splice(1, 0, cancelButton);
        const cancelButtonIndex = buttonIndeces[cancelId];
        buttonIndeces.splice(cancelId, 1);
        buttonIndeces.splice(1, 0, cancelButtonIndex);
        cancelId = 1;
      }
      if ($n && buttons.length > 1) {
        buttons = buttons.reverse();
        buttonIndeces = buttonIndeces.reverse();
        defaultId = buttons.length - 1;
        if (typeof cancelButton === "string") {
          cancelId = defaultId - 1;
        }
      }
    } else if ($l) {
      if (typeof cancelButton === "string" && buttons.length > 1 && cancelId !== buttons.length - 1) {
        buttons.splice(cancelId, 1);
        buttons.push(cancelButton);
        const buttonIndex = buttonIndeces[cancelId];
        buttonIndeces.splice(cancelId, 1);
        buttonIndeces.push(buttonIndex);
        cancelId = buttons.length - 1;
      }
    }
  }
  massagedOptions.buttons = buttons;
  massagedOptions.defaultId = defaultId;
  massagedOptions.cancelId = cancelId;
  massagedOptions.noLink = true;
  massagedOptions.title = massagedOptions.title || productService.nameLong;
  return {
    options: massagedOptions,
    buttonIndeces
  };
}

// out-build/vs/platform/dialogs/electron-main/dialogMainService.js
var $Kjc = $Zi("dialogMainService");
var $Ljc = class $Ljc2 {
  constructor(d, e) {
    this.d = d;
    this.e = e;
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Map();
    this.c = new $7h();
  }
  pickFileFolder(options, window2) {
    return this.f({ ...options, pickFolders: true, pickFiles: true, title: localize(1717, null) }, window2);
  }
  pickFolder(options, window2) {
    return this.f({ ...options, pickFolders: true, title: localize(1718, null) }, window2);
  }
  pickFile(options, window2) {
    return this.f({ ...options, pickFiles: true, title: localize(1719, null) }, window2);
  }
  pickWorkspace(options, window2) {
    const title = localize(1720, null);
    const buttonLabel = $yx(localize(1721, null));
    const filters = $lj;
    return this.f({ ...options, pickFiles: true, title, filters, buttonLabel }, window2);
  }
  async f(options, window2) {
    const dialogOptions = {
      title: options.title,
      buttonLabel: options.buttonLabel,
      filters: options.filters,
      defaultPath: options.defaultPath
    };
    if (typeof options.pickFiles === "boolean" || typeof options.pickFolders === "boolean") {
      dialogOptions.properties = void 0;
      if (options.pickFiles && options.pickFolders) {
        dialogOptions.properties = ["multiSelections", "openDirectory", "openFile", "createDirectory"];
      }
    }
    if (!dialogOptions.properties) {
      dialogOptions.properties = ["multiSelections", options.pickFolders ? "openDirectory" : "openFile", "createDirectory"];
    }
    if ($m) {
      dialogOptions.properties.push("treatPackageAsDirectory");
    }
    const result = await this.showOpenDialog(dialogOptions, (window2 || electron6.BrowserWindow.getFocusedWindow()) ?? void 0);
    if (result && result.filePaths && result.filePaths.length > 0) {
      return result.filePaths;
    }
    return void 0;
  }
  g(window2) {
    if (window2) {
      let windowDialogQueue = this.b.get(window2.id);
      if (!windowDialogQueue) {
        windowDialogQueue = new $7h();
        this.b.set(window2.id, windowDialogQueue);
      }
      return windowDialogQueue;
    } else {
      return this.c;
    }
  }
  showMessageBox(rawOptions, window2) {
    return this.g(window2).queue(async () => {
      const { options, buttonIndeces } = $Fx(rawOptions, this.e);
      let result = void 0;
      if (window2) {
        result = await electron6.dialog.showMessageBox(window2, options);
      } else {
        result = await electron6.dialog.showMessageBox(options);
      }
      return {
        response: buttonIndeces[result.response],
        checkboxChecked: result.checkboxChecked
      };
    });
  }
  async showSaveDialog(options, window2) {
    const fileDialogLock = this.j(options, window2);
    if (!fileDialogLock) {
      this.d.error("[DialogMainService]: file save dialog is already or will be showing for the window with the same configuration");
      return { canceled: true, filePath: "" };
    }
    try {
      return await this.g(window2).queue(async () => {
        let result;
        if (window2) {
          result = await electron6.dialog.showSaveDialog(window2, options);
        } else {
          result = await electron6.dialog.showSaveDialog(options);
        }
        result.filePath = this.h(result.filePath);
        return result;
      });
    } finally {
      $5c(fileDialogLock);
    }
  }
  h(path3) {
    if (path3 && $m) {
      path3 = $Hm(path3);
    }
    return path3;
  }
  i(paths) {
    return paths.map((path3) => this.h(path3));
  }
  async showOpenDialog(options, window2) {
    if (options.defaultPath) {
      const pathExists = await Promises2.exists(options.defaultPath);
      if (!pathExists) {
        options.defaultPath = void 0;
      }
    }
    const fileDialogLock = this.j(options, window2);
    if (!fileDialogLock) {
      this.d.error("[DialogMainService]: file open dialog is already or will be showing for the window with the same configuration");
      return { canceled: true, filePaths: [] };
    }
    try {
      return await this.g(window2).queue(async () => {
        let result;
        if (window2) {
          result = await electron6.dialog.showOpenDialog(window2, options);
        } else {
          result = await electron6.dialog.showOpenDialog(options);
        }
        result.filePaths = this.i(result.filePaths);
        return result;
      });
    } finally {
      $5c(fileDialogLock);
    }
  }
  j(options, window2) {
    if (!window2) {
      return $0c.None;
    }
    this.d.trace("[DialogMainService]: request to acquire file dialog lock", options);
    let windowFileDialogLocks = this.a.get(window2.id);
    if (!windowFileDialogLocks) {
      windowFileDialogLocks = /* @__PURE__ */ new Set();
      this.a.set(window2.id, windowFileDialogLocks);
    }
    const optionsHash = $Nj(options);
    if (windowFileDialogLocks.has(optionsHash)) {
      return void 0;
    }
    this.d.trace("[DialogMainService]: new file dialog lock created", options);
    windowFileDialogLocks.add(optionsHash);
    return $8c(() => {
      this.d.trace("[DialogMainService]: file dialog lock disposed", options);
      windowFileDialogLocks?.delete(optionsHash);
      if (windowFileDialogLocks?.size === 0) {
        this.a.delete(window2.id);
      }
    });
  }
};
$Ljc = __decorate([
  __param(0, $uk),
  __param(1, $Nk)
], $Ljc);

// out-build/vs/platform/windows/electron-main/windowsFinder.js
async function $Ujc(windows, fileUri, localWorkspaceResolver) {
  for (const window2 of windows) {
    const workspace = window2.openedWorkspace;
    if ($cj(workspace)) {
      const resolvedWorkspace = await localWorkspaceResolver(workspace);
      if (resolvedWorkspace) {
        if (resolvedWorkspace.folders.some((folder) => $rh.isEqualOrParent(fileUri, folder.uri))) {
          return window2;
        }
      } else {
        if ($rh.isEqualOrParent(fileUri, workspace.configPath)) {
          return window2;
        }
      }
    }
  }
  const singleFolderWindowsOnFilePath = windows.filter((window2) => $0i(window2.openedWorkspace) && $rh.isEqualOrParent(fileUri, window2.openedWorkspace.uri));
  if (singleFolderWindowsOnFilePath.length) {
    return singleFolderWindowsOnFilePath.sort((windowA, windowB) => -(windowA.openedWorkspace.uri.path.length - windowB.openedWorkspace.uri.path.length))[0];
  }
  return void 0;
}
function $Vjc(windows, folderOrWorkspaceConfigUri) {
  for (const window2 of windows) {
    if ($cj(window2.openedWorkspace) && $rh.isEqual(window2.openedWorkspace.configPath, folderOrWorkspaceConfigUri)) {
      return window2;
    }
    if ($0i(window2.openedWorkspace) && $rh.isEqual(window2.openedWorkspace.uri, folderOrWorkspaceConfigUri)) {
      return window2;
    }
  }
  return void 0;
}
function $Wjc(windows, extensionDevelopmentPaths) {
  const matches = (uriString) => {
    return extensionDevelopmentPaths.some((path3) => $rh.isEqual(URI.file(path3), URI.file(uriString)));
  };
  for (const window2 of windows) {
    if (window2.config?.extensionDevelopmentPath?.some((path3) => matches(path3))) {
      return window2;
    }
  }
  return void 0;
}

// out-build/vs/base/common/jsonFormatter.js
function $qo(documentText, range, options) {
  let initialIndentLevel;
  let formatText;
  let formatTextStart;
  let rangeStart;
  let rangeEnd;
  if (range) {
    rangeStart = range.offset;
    rangeEnd = rangeStart + range.length;
    formatTextStart = rangeStart;
    while (formatTextStart > 0 && !$to(documentText, formatTextStart - 1)) {
      formatTextStart--;
    }
    let endOffset = rangeEnd;
    while (endOffset < documentText.length && !$to(documentText, endOffset)) {
      endOffset++;
    }
    formatText = documentText.substring(formatTextStart, endOffset);
    initialIndentLevel = computeIndentLevel(formatText, options);
  } else {
    formatText = documentText;
    initialIndentLevel = 0;
    formatTextStart = 0;
    rangeStart = 0;
    rangeEnd = documentText.length;
  }
  const eol = $so(options, documentText);
  let lineBreak = false;
  let indentLevel = 0;
  let indentValue;
  if (options.insertSpaces) {
    indentValue = repeat(" ", options.tabSize || 4);
  } else {
    indentValue = "	";
  }
  const scanner = $fo(formatText, false);
  let hasError = false;
  function newLineAndIndent() {
    return eol + repeat(indentValue, initialIndentLevel + indentLevel);
  }
  function scanNext() {
    let token = scanner.scan();
    lineBreak = false;
    while (token === 15 || token === 14) {
      lineBreak = lineBreak || token === 14;
      token = scanner.scan();
    }
    hasError = token === 16 || scanner.getTokenError() !== 0;
    return token;
  }
  const editOperations = [];
  function addEdit(text, startOffset, endOffset) {
    if (!hasError && startOffset < rangeEnd && endOffset > rangeStart && documentText.substring(startOffset, endOffset) !== text) {
      editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
    }
  }
  let firstToken = scanNext();
  if (firstToken !== 17) {
    const firstTokenStart = scanner.getTokenOffset() + formatTextStart;
    const initialIndent = repeat(indentValue, initialIndentLevel);
    addEdit(initialIndent, formatTextStart, firstTokenStart);
  }
  while (firstToken !== 17) {
    let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
    let secondToken = scanNext();
    let replaceContent = "";
    while (!lineBreak && (secondToken === 12 || secondToken === 13)) {
      const commentTokenStart = scanner.getTokenOffset() + formatTextStart;
      addEdit(" ", firstTokenEnd, commentTokenStart);
      firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
      replaceContent = secondToken === 12 ? newLineAndIndent() : "";
      secondToken = scanNext();
    }
    if (secondToken === 2) {
      if (firstToken !== 1) {
        indentLevel--;
        replaceContent = newLineAndIndent();
      }
    } else if (secondToken === 4) {
      if (firstToken !== 3) {
        indentLevel--;
        replaceContent = newLineAndIndent();
      }
    } else {
      switch (firstToken) {
        case 3:
        case 1:
          indentLevel++;
          replaceContent = newLineAndIndent();
          break;
        case 5:
        case 12:
          replaceContent = newLineAndIndent();
          break;
        case 13:
          if (lineBreak) {
            replaceContent = newLineAndIndent();
          } else {
            replaceContent = " ";
          }
          break;
        case 6:
          replaceContent = " ";
          break;
        case 10:
          if (secondToken === 6) {
            replaceContent = "";
            break;
          }
        case 7:
        case 8:
        case 9:
        case 11:
        case 2:
        case 4:
          if (secondToken === 12 || secondToken === 13) {
            replaceContent = " ";
          } else if (secondToken !== 5 && secondToken !== 17) {
            hasError = true;
          }
          break;
        case 16:
          hasError = true;
          break;
      }
      if (lineBreak && (secondToken === 12 || secondToken === 13)) {
        replaceContent = newLineAndIndent();
      }
    }
    const secondTokenStart = scanner.getTokenOffset() + formatTextStart;
    addEdit(replaceContent, firstTokenEnd, secondTokenStart);
    firstToken = secondToken;
  }
  return editOperations;
}
function repeat(s, count) {
  let result = "";
  for (let i = 0; i < count; i++) {
    result += s;
  }
  return result;
}
function computeIndentLevel(content, options) {
  let i = 0;
  let nChars = 0;
  const tabSize = options.tabSize || 4;
  while (i < content.length) {
    const ch = content.charAt(i);
    if (ch === " ") {
      nChars++;
    } else if (ch === "	") {
      nChars += tabSize;
    } else {
      break;
    }
    i++;
  }
  return Math.floor(nChars / tabSize);
}
function $so(options, text) {
  for (let i = 0; i < text.length; i++) {
    const ch = text.charAt(i);
    if (ch === "\r") {
      if (i + 1 < text.length && text.charAt(i + 1) === "\n") {
        return "\r\n";
      }
      return "\r";
    } else if (ch === "\n") {
      return "\n";
    }
  }
  return options && options.eol || "\n";
}
function $to(text, offset) {
  return "\r\n".indexOf(text.charAt(offset)) !== -1;
}

// out-build/vs/base/common/jsonEdit.js
function $vo(text, originalPath, value, formattingOptions, getInsertionIndex) {
  const path3 = originalPath.slice();
  const errors = [];
  const root = $io(text, errors);
  let parent = void 0;
  let lastSegment = void 0;
  while (path3.length > 0) {
    lastSegment = path3.pop();
    parent = $jo(root, path3);
    if (parent === void 0 && value !== void 0) {
      if (typeof lastSegment === "string") {
        value = { [lastSegment]: value };
      } else {
        value = [value];
      }
    } else {
      break;
    }
  }
  if (!parent) {
    if (value === void 0) {
      return [];
    }
    return $wo(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, formattingOptions);
  } else if (parent.type === "object" && typeof lastSegment === "string" && Array.isArray(parent.children)) {
    const existing = $jo(parent, [lastSegment]);
    if (existing !== void 0) {
      if (value === void 0) {
        if (!existing.parent) {
          throw new Error("Malformed AST");
        }
        const propertyIndex = parent.children.indexOf(existing.parent);
        let removeBegin;
        let removeEnd = existing.parent.offset + existing.parent.length;
        if (propertyIndex > 0) {
          const previous = parent.children[propertyIndex - 1];
          removeBegin = previous.offset + previous.length;
        } else {
          removeBegin = parent.offset + 1;
          if (parent.children.length > 1) {
            const next = parent.children[1];
            removeEnd = next.offset;
          }
        }
        return $wo(text, { offset: removeBegin, length: removeEnd - removeBegin, content: "" }, formattingOptions);
      } else {
        return $wo(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, formattingOptions);
      }
    } else {
      if (value === void 0) {
        return [];
      }
      const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;
      const index = getInsertionIndex ? getInsertionIndex(parent.children.map((p) => p.children[0].value)) : parent.children.length;
      let edit;
      if (index > 0) {
        const previous = parent.children[index - 1];
        edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
      } else if (parent.children.length === 0) {
        edit = { offset: parent.offset + 1, length: 0, content: newProperty };
      } else {
        edit = { offset: parent.offset + 1, length: 0, content: newProperty + "," };
      }
      return $wo(text, edit, formattingOptions);
    }
  } else if (parent.type === "array" && typeof lastSegment === "number" && Array.isArray(parent.children)) {
    if (value !== void 0) {
      const newProperty = `${JSON.stringify(value)}`;
      let edit;
      if (parent.children.length === 0 || lastSegment === 0) {
        edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + "," };
      } else {
        const index = lastSegment === -1 || lastSegment > parent.children.length ? parent.children.length : lastSegment;
        const previous = parent.children[index - 1];
        edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
      }
      return $wo(text, edit, formattingOptions);
    } else {
      const removalIndex = lastSegment;
      const toRemove = parent.children[removalIndex];
      let edit;
      if (parent.children.length === 1) {
        edit = { offset: parent.offset + 1, length: parent.length - 2, content: "" };
      } else if (parent.children.length - 1 === removalIndex) {
        const previous = parent.children[removalIndex - 1];
        const offset = previous.offset + previous.length;
        const parentEndOffset = parent.offset + parent.length;
        edit = { offset, length: parentEndOffset - 2 - offset, content: "" };
      } else {
        edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: "" };
      }
      return $wo(text, edit, formattingOptions);
    }
  } else {
    throw new Error(`Can not add ${typeof lastSegment !== "number" ? "index" : "property"} to parent of type ${parent.type}`);
  }
}
function $wo(text, edit, formattingOptions) {
  let newText = $xo(text, edit);
  let begin = edit.offset;
  let end = edit.offset + edit.content.length;
  if (edit.length === 0 || edit.content.length === 0) {
    while (begin > 0 && !$to(newText, begin - 1)) {
      begin--;
    }
    while (end < newText.length && !$to(newText, end)) {
      end++;
    }
  }
  const edits = $qo(newText, { offset: begin, length: end - begin }, formattingOptions);
  for (let i = edits.length - 1; i >= 0; i--) {
    const curr = edits[i];
    newText = $xo(newText, curr);
    begin = Math.min(begin, curr.offset);
    end = Math.max(end, curr.offset + curr.length);
    end += curr.content.length - curr.length;
  }
  const editLength = text.length - (newText.length - end) - begin;
  return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
}
function $xo(text, edit) {
  return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
}
function $yo(text, edits) {
  const sortedEdits = edits.slice(0).sort((a, b) => {
    const diff2 = a.offset - b.offset;
    if (diff2 === 0) {
      return a.length - b.length;
    }
    return diff2;
  });
  let lastModifiedOffset = text.length;
  for (let i = sortedEdits.length - 1; i >= 0; i--) {
    const e = sortedEdits[i];
    if (e.offset + e.length <= lastModifiedOffset) {
      text = $xo(text, e);
    } else {
      throw new Error("Overlapping edit");
    }
    lastModifiedOffset = e.offset;
  }
  return text;
}

// out-build/vs/platform/remote/common/remoteHosts.js
function $Cn(uri) {
  return uri.scheme === Schemas.vscodeRemote ? uri.authority : void 0;
}

// out-build/vs/platform/workspaces/common/workspaces.js
var $8jb = $Zi("workspacesService");
function $9jb(curr) {
  return curr.hasOwnProperty("workspace");
}
function $0jb(curr) {
  return curr.hasOwnProperty("folderUri");
}
function $$jb(curr) {
  return curr.hasOwnProperty("fileUri");
}
function $_jb(obj) {
  return isRawFileWorkspaceFolder(obj) || isRawUriWorkspaceFolder(obj);
}
function isRawFileWorkspaceFolder(obj) {
  const candidate = obj;
  return typeof candidate?.path === "string" && (!candidate.name || typeof candidate.name === "string");
}
function isRawUriWorkspaceFolder(obj) {
  const candidate = obj;
  return typeof candidate?.uri === "string" && (!candidate.name || typeof candidate.name === "string");
}
function $akb(folderURI, forceAbsolute, folderName, targetConfigFolderURI, extUri) {
  if (folderURI.scheme !== targetConfigFolderURI.scheme) {
    return { name: folderName, uri: folderURI.toString(true) };
  }
  let folderPath = !forceAbsolute ? extUri.relativePath(targetConfigFolderURI, folderURI) : void 0;
  if (folderPath !== void 0) {
    if (folderPath.length === 0) {
      folderPath = ".";
    } else {
      if ($l) {
        folderPath = massagePathForWindows(folderPath);
      }
    }
  } else {
    if (folderURI.scheme === Schemas.file) {
      folderPath = folderURI.fsPath;
      if ($l) {
        folderPath = massagePathForWindows(folderPath);
      }
    } else if (!extUri.isEqualAuthority(folderURI.authority, targetConfigFolderURI.authority)) {
      return { name: folderName, uri: folderURI.toString(true) };
    } else {
      folderPath = folderURI.path;
    }
  }
  return { name: folderName, path: folderPath };
}
function massagePathForWindows(folderPath) {
  folderPath = $sx(folderPath);
  if (!$Vg(folderPath)) {
    folderPath = $Sg(folderPath);
  }
  return folderPath;
}
function $bkb(configuredFolders, workspaceConfigFile, extUri) {
  const result = [];
  const seen = /* @__PURE__ */ new Set();
  const relativeTo = extUri.dirname(workspaceConfigFile);
  for (const configuredFolder of configuredFolders) {
    let uri = void 0;
    if (isRawFileWorkspaceFolder(configuredFolder)) {
      if (configuredFolder.path) {
        uri = extUri.resolvePath(relativeTo, configuredFolder.path);
      }
    } else if (isRawUriWorkspaceFolder(configuredFolder)) {
      try {
        uri = URI.parse(configuredFolder.uri);
        if (uri.path[0] !== $sc.sep) {
          uri = uri.with({ path: $sc.sep + uri.path });
        }
      } catch (e) {
        console.warn(e);
      }
    }
    if (uri) {
      const comparisonKey = extUri.getComparisonKey(uri);
      if (!seen.has(comparisonKey)) {
        seen.add(comparisonKey);
        const name = configuredFolder.name || extUri.basenameOrAuthority(uri);
        result.push(new $hj({ uri, name, index: result.length }, configuredFolder));
      }
    }
  }
  return result;
}
function isSerializedRecentWorkspace(data) {
  return data.workspace && typeof data.workspace === "object" && typeof data.workspace.id === "string" && typeof data.workspace.configPath === "string";
}
function isSerializedRecentFolder(data) {
  return typeof data.folderUri === "string";
}
function isSerializedRecentFile(data) {
  return typeof data.fileUri === "string";
}
function $dkb(data, logService) {
  const result = { workspaces: [], files: [] };
  if (data) {
    const restoreGracefully = function(entries, onEntry) {
      for (let i = 0; i < entries.length; i++) {
        try {
          onEntry(entries[i], i);
        } catch (e) {
          logService.warn(`Error restoring recent entry ${JSON.stringify(entries[i])}: ${e.toString()}. Skip entry.`);
        }
      }
    };
    const storedRecents = data;
    if (Array.isArray(storedRecents.entries)) {
      restoreGracefully(storedRecents.entries, (entry) => {
        const label = entry.label;
        const remoteAuthority = entry.remoteAuthority;
        if (isSerializedRecentWorkspace(entry)) {
          result.workspaces.push({ label, remoteAuthority, workspace: { id: entry.workspace.id, configPath: URI.parse(entry.workspace.configPath) } });
        } else if (isSerializedRecentFolder(entry)) {
          result.workspaces.push({ label, remoteAuthority, folderUri: URI.parse(entry.folderUri) });
        } else if (isSerializedRecentFile(entry)) {
          result.files.push({ label, remoteAuthority, fileUri: URI.parse(entry.fileUri) });
        }
      });
    }
  }
  return result;
}
function $ekb(recents) {
  const serialized = { entries: [] };
  for (const recent of recents.workspaces) {
    if ($0jb(recent)) {
      serialized.entries.push({ folderUri: recent.folderUri.toString(), label: recent.label, remoteAuthority: recent.remoteAuthority });
    } else {
      serialized.entries.push({ workspace: { id: recent.workspace.id, configPath: recent.workspace.configPath.toString() }, label: recent.label, remoteAuthority: recent.remoteAuthority });
    }
  }
  for (const recent of recents.files) {
    serialized.entries.push({ fileUri: recent.fileUri.toString(), label: recent.label, remoteAuthority: recent.remoteAuthority });
  }
  return serialized;
}

// out-build/vs/platform/workspaces/electron-main/workspacesManagementMainService.js
var $2jc = $Zi("workspacesManagementMainService");
var $3jc = class $3jc2 extends $0c {
  constructor(g, h, j, m, n) {
    super();
    this.g = g;
    this.h = h;
    this.j = j;
    this.m = m;
    this.n = n;
    this.a = this.B(new $De());
    this.onDidDeleteUntitledWorkspace = this.a.event;
    this.b = this.B(new $De());
    this.onDidEnterWorkspace = this.b.event;
    this.c = this.g.untitledWorkspacesHome;
    this.f = [];
  }
  async initialize() {
    this.f = [];
    try {
      const untitledWorkspacePaths = (await Promises2.readdir(this.c.with({ scheme: Schemas.file }).fsPath)).map((folder) => $Ah(this.c, folder, $mj));
      for (const untitledWorkspacePath of untitledWorkspacePaths) {
        const workspace = $Yjc(untitledWorkspacePath);
        const resolvedWorkspace = await this.resolveLocalWorkspace(untitledWorkspacePath);
        if (!resolvedWorkspace) {
          await this.deleteUntitledWorkspace(workspace);
        } else {
          this.f.push({ workspace, remoteAuthority: resolvedWorkspace.remoteAuthority });
        }
      }
    } catch (error) {
      if (error.code !== "ENOENT") {
        this.h.warn(`Unable to read folders in ${this.c} (${error}).`);
      }
    }
  }
  resolveLocalWorkspace(uri) {
    return this.r(uri, (path3) => fs4.promises.readFile(path3, "utf8"));
  }
  r(uri, contentsFn) {
    if (!this.s(uri)) {
      return void 0;
    }
    if (uri.scheme !== Schemas.file) {
      return void 0;
    }
    try {
      const contents = contentsFn(uri.fsPath);
      if (contents instanceof Promise) {
        return contents.then(
          (value) => this.t(uri, value),
          (error) => void 0
          /* invalid workspace */
        );
      } else {
        return this.t(uri, contents);
      }
    } catch {
      return void 0;
    }
  }
  s(uri) {
    return $nj(uri, this.g) || $sj(uri);
  }
  t(path3, contents) {
    try {
      const workspace = this.u(path3, contents);
      const workspaceIdentifier = $Yjc(path3);
      return {
        id: workspaceIdentifier.id,
        configPath: workspaceIdentifier.configPath,
        folders: $bkb(workspace.folders, workspaceIdentifier.configPath, $rh),
        remoteAuthority: workspace.remoteAuthority,
        transient: workspace.transient
      };
    } catch (error) {
      this.h.warn(error.toString());
    }
    return void 0;
  }
  u(path3, contents) {
    const storedWorkspace = $ho(contents);
    if (storedWorkspace && Array.isArray(storedWorkspace.folders)) {
      storedWorkspace.folders = storedWorkspace.folders.filter((folder) => $_jb(folder));
    } else {
      throw new Error(`${path3.toString(true)} looks like an invalid workspace file.`);
    }
    return storedWorkspace;
  }
  async createUntitledWorkspace(folders, remoteAuthority) {
    const { workspace, storedWorkspace } = this.w(folders, remoteAuthority);
    const configPath = workspace.configPath.fsPath;
    await fs4.promises.mkdir($yc(configPath), { recursive: true });
    await Promises2.writeFile(configPath, JSON.stringify(storedWorkspace, null, "	"));
    this.f.push({ workspace, remoteAuthority });
    return workspace;
  }
  w(folders = [], remoteAuthority) {
    const randomId = (Date.now() + Math.round(Math.random() * 1e3)).toString();
    const untitledWorkspaceConfigFolder = $Ah(this.c, randomId);
    const untitledWorkspaceConfigPath = $Ah(untitledWorkspaceConfigFolder, $mj);
    const storedWorkspaceFolder = [];
    for (const folder of folders) {
      storedWorkspaceFolder.push($akb(folder.uri, true, folder.name, untitledWorkspaceConfigFolder, $rh));
    }
    return {
      workspace: $Yjc(untitledWorkspaceConfigPath),
      storedWorkspace: { folders: storedWorkspaceFolder, remoteAuthority }
    };
  }
  async getWorkspaceIdentifier(configPath) {
    return $Yjc(configPath);
  }
  isUntitledWorkspace(workspace) {
    return $nj(workspace.configPath, this.g);
  }
  async deleteUntitledWorkspace(workspace) {
    if (!this.isUntitledWorkspace(workspace)) {
      return;
    }
    await this.y(workspace);
    if (this.j.isEnabled()) {
      this.j.unsetWorkspace(workspace);
    }
    this.a.fire(workspace);
  }
  async y(workspace) {
    const configPath = $oh(workspace.configPath);
    try {
      await Promises2.rm($yc(configPath));
      const workspaceStoragePath = $vc(this.g.workspaceStorageHome.with({ scheme: Schemas.file }).fsPath, workspace.id);
      if (await Promises2.exists(workspaceStoragePath)) {
        await Promises2.writeFile($vc(workspaceStoragePath, "obsolete"), "");
      }
      this.f = this.f.filter((untitledWorkspace) => untitledWorkspace.workspace.id !== workspace.id);
    } catch (error) {
      this.h.warn(`Unable to delete untitled workspace ${configPath} (${error}).`);
    }
  }
  getUntitledWorkspaces() {
    return this.f;
  }
  async enterWorkspace(window2, windows, path3) {
    if (!window2 || !window2.win || !window2.isReady) {
      return void 0;
    }
    const isValid = await this.z(window2, windows, path3);
    if (!isValid) {
      return void 0;
    }
    const result = await this.C(window2, $Yjc(path3));
    if (!result) {
      return void 0;
    }
    this.b.fire({ window: window2, workspace: result.workspace });
    return result;
  }
  async z(window2, windows, workspacePath) {
    if (!workspacePath) {
      return true;
    }
    if ($cj(window2.openedWorkspace) && $rh.isEqual(window2.openedWorkspace.configPath, workspacePath)) {
      return false;
    }
    if ($Vjc(windows, workspacePath)) {
      await this.n.showMessageBox({
        type: "info",
        buttons: [localize(2514, null)],
        message: localize(2515, null, $xh(workspacePath)),
        detail: localize(2516, null)
      }, electron7.BrowserWindow.getFocusedWindow() ?? void 0);
      return false;
    }
    return true;
  }
  async C(window2, workspace) {
    if (!window2.config) {
      return void 0;
    }
    window2.focus();
    let backupPath;
    if (!window2.config.extensionDevelopmentPath) {
      if (window2.config.backupPath) {
        backupPath = await this.m.registerWorkspaceBackup({ workspace, remoteAuthority: window2.remoteAuthority }, window2.config.backupPath);
      } else {
        backupPath = this.m.registerWorkspaceBackup({ workspace, remoteAuthority: window2.remoteAuthority });
      }
    }
    if ($cj(window2.openedWorkspace) && this.isUntitledWorkspace(window2.openedWorkspace)) {
      await this.deleteUntitledWorkspace(window2.openedWorkspace);
    }
    window2.config.workspace = workspace;
    window2.config.backupPath = backupPath;
    return { workspace, backupPath };
  }
};
$3jc = __decorate([
  __param(0, $Cjc),
  __param(1, $uk),
  __param(2, $Sjc),
  __param(3, $Jjc),
  __param(4, $Kjc)
], $3jc);

// out-build/vs/platform/utilityProcess/electron-main/utilityProcess.js
import { MessageChannelMain, app as app2, utilityProcess } from "electron";
import { StringDecoder } from "string_decoder";

// out-build/vs/base/common/processes.js
var Source;
(function(Source2) {
  Source2[Source2["stdout"] = 0] = "stdout";
  Source2[Source2["stderr"] = 1] = "stderr";
})(Source || (Source = {}));
var TerminateResponseCode;
(function(TerminateResponseCode2) {
  TerminateResponseCode2[TerminateResponseCode2["Success"] = 0] = "Success";
  TerminateResponseCode2[TerminateResponseCode2["Unknown"] = 1] = "Unknown";
  TerminateResponseCode2[TerminateResponseCode2["AccessDenied"] = 2] = "AccessDenied";
  TerminateResponseCode2[TerminateResponseCode2["ProcessNotFound"] = 3] = "ProcessNotFound";
})(TerminateResponseCode || (TerminateResponseCode = {}));
function $Fm(env2, ...preserve) {
  const set = preserve.reduce((set2, key) => {
    set2[key] = true;
    return set2;
  }, {});
  const keysToRemove = [
    /^ELECTRON_.+$/,
    /^VSCODE_(?!(PORTABLE|SHELL_LOGIN|ENV_REPLACE|ENV_APPEND|ENV_PREPEND)).+$/,
    /^SNAP(|_.*)$/,
    /^GDK_PIXBUF_.+$/
  ];
  const envKeys = Object.keys(env2);
  envKeys.filter((key) => !set[key]).forEach((envKey) => {
    for (let i = 0; i < keysToRemove.length; i++) {
      if (envKey.search(keysToRemove[i]) !== -1) {
        delete env2[envKey];
        break;
      }
    }
  });
}
function $Gm(env2) {
  if (!env2) {
    return;
  }
  delete env2["DEBUG"];
  if ($n) {
    delete env2["LD_PRELOAD"];
  }
}

// out-build/vs/platform/utilityProcess/electron-main/utilityProcess.js
var $kkc_1;
function isWindowUtilityProcessConfiguration(config) {
  const candidate = config;
  return typeof candidate.responseWindowId === "number";
}
var $kkc = class $kkc2 extends $0c {
  static {
    $kkc_1 = this;
  }
  static {
    this.a = 0;
  }
  static {
    this.b = /* @__PURE__ */ new Map();
  }
  static getAll() {
    return Array.from($kkc_1.b.values());
  }
  constructor(w, y, z) {
    super();
    this.w = w;
    this.y = y;
    this.z = z;
    this.c = String(++$kkc_1.a);
    this.f = this.B(new $De());
    this.onStdout = this.f.event;
    this.g = this.B(new $De());
    this.onStderr = this.g.event;
    this.h = this.B(new $De());
    this.onMessage = this.h.event;
    this.j = this.B(new $De());
    this.onSpawn = this.j.event;
    this.m = this.B(new $De());
    this.onExit = this.m.event;
    this.n = this.B(new $De());
    this.onCrash = this.n.event;
    this.r = void 0;
    this.s = void 0;
    this.t = void 0;
    this.u = false;
  }
  C(msg, severity) {
    let logMsg;
    if (this.t?.correlationId) {
      logMsg = `[UtilityProcess id: ${this.t?.correlationId}, type: ${this.t?.type}, pid: ${this.s ?? "<none>"}]: ${msg}`;
    } else {
      logMsg = `[UtilityProcess type: ${this.t?.type}, pid: ${this.s ?? "<none>"}]: ${msg}`;
    }
    switch (severity) {
      case severity_default.Error:
        this.w.error(logMsg);
        break;
      case severity_default.Warning:
        this.w.warn(logMsg);
        break;
      case severity_default.Info:
        this.w.trace(logMsg);
        break;
    }
  }
  D() {
    if (this.r) {
      this.C("Cannot start utility process because it is already running...", severity_default.Error);
      return false;
    }
    return true;
  }
  start(configuration) {
    const started = this.F(configuration);
    if (started && configuration.payload) {
      const posted = this.postMessage(configuration.payload);
      if (posted) {
        this.C("payload sent via postMessage()", severity_default.Info);
      }
    }
    return started;
  }
  F(configuration) {
    if (!this.D()) {
      return false;
    }
    this.t = configuration;
    const serviceName = `${this.t.type}-${this.c}`;
    const modulePath = $hh.asFileUri("bootstrap-fork.js").fsPath;
    const args = this.t.args ?? [];
    const execArgv = this.t.execArgv ?? [];
    const allowLoadingUnsignedLibraries = this.t.allowLoadingUnsignedLibraries;
    const respondToAuthRequestsFromMainProcess = this.t.respondToAuthRequestsFromMainProcess;
    const stdio = "pipe";
    const env2 = this.G(configuration);
    this.C("creating new...", severity_default.Info);
    this.r = utilityProcess.fork(modulePath, args, $Qg({
      serviceName,
      env: env2,
      execArgv,
      allowLoadingUnsignedLibraries,
      respondToAuthRequestsFromMainProcess,
      stdio
    }));
    this.H(this.r, this.t, serviceName);
    return true;
  }
  G(configuration) {
    const env2 = configuration.env ? { ...configuration.env } : { ...$zo(process.env) };
    env2["VSCODE_AMD_ENTRYPOINT"] = configuration.entryPoint;
    if (typeof configuration.parentLifecycleBound === "number") {
      env2["VSCODE_PARENT_PID"] = String(configuration.parentLifecycleBound);
    }
    env2["VSCODE_CRASH_REPORTER_PROCESS_TYPE"] = configuration.type;
    if ($l) {
      if (isUNCAccessRestrictionsDisabled()) {
        env2["NODE_DISABLE_UNC_ACCESS_CHECKS"] = "1";
      } else {
        env2["NODE_UNC_HOST_ALLOWLIST"] = getUNCHostAllowlist().join("\\");
      }
    }
    $Gm(env2);
    for (const key of Object.keys(env2)) {
      env2[key] = String(env2[key]);
    }
    return env2;
  }
  H(process2, configuration, serviceName) {
    if (process2.stdout) {
      const stdoutDecoder = new StringDecoder("utf-8");
      this.B(Event.fromNodeEventEmitter(process2.stdout, "data")((chunk) => this.f.fire(typeof chunk === "string" ? chunk : stdoutDecoder.write(chunk))));
    }
    if (process2.stderr) {
      const stderrDecoder = new StringDecoder("utf-8");
      this.B(Event.fromNodeEventEmitter(process2.stderr, "data")((chunk) => this.g.fire(typeof chunk === "string" ? chunk : stderrDecoder.write(chunk))));
    }
    this.B(Event.fromNodeEventEmitter(process2, "message")((msg) => this.h.fire(msg)));
    this.B(Event.fromNodeEventEmitter(process2, "spawn")(() => {
      this.s = process2.pid;
      if (typeof process2.pid === "number") {
        $kkc_1.b.set(process2.pid, { pid: process2.pid, name: isWindowUtilityProcessConfiguration(configuration) ? `${configuration.type} [${configuration.responseWindowId}]` : configuration.type });
      }
      this.C("successfully created", severity_default.Info);
      this.j.fire(process2.pid);
    }));
    this.B(Event.fromNodeEventEmitter(process2, "exit")((code2) => {
      const normalizedCode = this.I(code2) ? 0 : code2;
      this.C(`received exit event with code ${normalizedCode}`, severity_default.Info);
      this.m.fire({ pid: this.s, code: normalizedCode, signal: "unknown" });
      this.J();
    }));
    this.B(Event.fromNodeEventEmitter(process2, "error", (type4, location, report) => ({ type: type4, location, report }))(({ type: type4, location, report }) => {
      this.C(`crashed due to ${type4} from V8 at ${location}`, severity_default.Info);
      let addons = [];
      try {
        const reportJSON = JSON.parse(report);
        addons = reportJSON.sharedObjects.filter((sharedObject) => sharedObject.endsWith(".node")).map((addon) => {
          const index = addon.indexOf("extensions") === -1 ? addon.indexOf("node_modules") : addon.indexOf("extensions");
          return addon.substring(index);
        });
      } catch (e) {
      }
      this.y.publicLog2("utilityprocessv8error", {
        processtype: configuration.type,
        error: type4,
        location,
        addons
      });
    }));
    this.B(Event.fromNodeEventEmitter(app2, "child-process-gone", (event, details) => ({ event, details }))(({ details }) => {
      if (details.type === "Utility" && details.name === serviceName && !this.I(details.exitCode)) {
        this.C(`crashed with code ${details.exitCode} and reason '${details.reason}'`, severity_default.Error);
        this.y.publicLog2("utilityprocesscrash", {
          type: configuration.type,
          reason: details.reason,
          code: details.exitCode
        });
        this.n.fire({ pid: this.s, code: details.exitCode, reason: details.reason });
        this.J();
      }
    }));
  }
  once(message, callback) {
    const disposable = this.B(this.h.event((msg) => {
      if (msg === message) {
        disposable.dispose();
        callback();
      }
    }));
  }
  postMessage(message, transfer) {
    if (!this.r) {
      return false;
    }
    this.r.postMessage(message, transfer);
    return true;
  }
  connect(payload) {
    const { port1: outPort, port2: utilityProcessPort } = new MessageChannelMain();
    this.postMessage(payload, [utilityProcessPort]);
    return outPort;
  }
  enableInspectPort() {
    if (!this.r || typeof this.s !== "number") {
      return false;
    }
    this.C("enabling inspect port", severity_default.Info);
    const processExt = process;
    if (typeof processExt._debugProcess === "function") {
      processExt._debugProcess(this.s);
      return true;
    }
    return false;
  }
  kill() {
    if (!this.r) {
      return;
    }
    this.C("attempting to kill the process...", severity_default.Info);
    const killed = this.r.kill();
    if (killed) {
      this.C("successfully killed the process", severity_default.Info);
      this.u = true;
      this.J();
    } else {
      this.C("unable to kill the process", severity_default.Warning);
    }
  }
  I(exitCode) {
    if (exitCode === 0) {
      return true;
    }
    return this.u && exitCode === 15;
  }
  J() {
    if (typeof this.s === "number") {
      $kkc_1.b.delete(this.s);
    }
    this.r = void 0;
  }
  async waitForExit(maxWaitTimeMs) {
    if (!this.r) {
      return;
    }
    this.C("waiting to exit...", severity_default.Info);
    await Promise.race([Event.toPromise(this.onExit), $1h(maxWaitTimeMs)]);
    if (this.r) {
      this.C(`did not exit within ${maxWaitTimeMs}ms, will kill it now...`, severity_default.Info);
      this.kill();
    }
  }
};
$kkc = $kkc_1 = __decorate([
  __param(0, $uk),
  __param(1, $tm),
  __param(2, $9jc)
], $kkc);
var $lkc = class $lkc2 extends $kkc {
  constructor(logService, L, telemetryService, lifecycleMainService) {
    super(logService, telemetryService, lifecycleMainService);
    this.L = L;
  }
  start(configuration) {
    const responseWindow = this.L.getWindowById(configuration.responseWindowId);
    if (!responseWindow?.win || responseWindow.win.isDestroyed() || responseWindow.win.webContents.isDestroyed()) {
      this.C("Refusing to start utility process because requesting window cannot be found or is destroyed...", severity_default.Error);
      return true;
    }
    const started = super.F(configuration);
    if (!started) {
      return false;
    }
    this.M(responseWindow.win, configuration);
    const windowPort = this.connect(configuration.payload);
    responseWindow.win.webContents.postMessage(configuration.responseChannel, configuration.responseNonce, [windowPort]);
    return true;
  }
  M(window2, configuration) {
    if (configuration.windowLifecycleBound) {
      this.B(Event.filter(this.z.onWillLoadWindow, (e) => e.window.win === window2)(() => this.kill()));
      this.B(Event.fromNodeEventEmitter(window2, "closed")(() => this.kill()));
    }
  }
};
$lkc = __decorate([
  __param(0, $uk),
  __param(1, $Pjc),
  __param(2, $tm),
  __param(3, $9jc)
], $lkc);

// out-build/vs/platform/diagnostics/electron-main/diagnosticsMainService.js
var ID2 = "diagnosticsMainService";
var $nkc = $Zi(ID2);
var $okc = class $okc2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  async getRemoteDiagnostics(options) {
    const windows = this.a.getWindows();
    const diagnostics = await Promise.all(windows.map(async (window2) => {
      const remoteAuthority = window2.remoteAuthority;
      if (!remoteAuthority) {
        return void 0;
      }
      const replyChannel = `vscode:getDiagnosticInfoResponse${window2.id}`;
      const args = {
        includeProcesses: options.includeProcesses,
        folders: options.includeWorkspaceMetadata ? await this.f(window2) : void 0
      };
      return new Promise((resolve2) => {
        window2.sendWhenReady("vscode:getDiagnosticInfo", CancellationToken.None, { replyChannel, args });
        $ZY.once(replyChannel, (_, data) => {
          if (!data) {
            resolve2({ hostName: remoteAuthority, errorMessage: `Unable to resolve connection to '${remoteAuthority}'.` });
          }
          resolve2(data);
        });
        setTimeout(() => {
          resolve2({ hostName: remoteAuthority, errorMessage: `Connection to '${remoteAuthority}' could not be established` });
        }, 5e3);
      });
    }));
    return diagnostics.filter((x) => !!x);
  }
  async getMainDiagnostics() {
    this.c.trace("Received request for main process info from other instance.");
    const windows = [];
    for (const window2 of BrowserWindow.getAllWindows()) {
      const codeWindow = this.a.getWindowById(window2.id);
      if (codeWindow) {
        windows.push(await this.d(codeWindow));
      } else {
        windows.push(this.e(window2));
      }
    }
    const pidToNames = [];
    for (const { pid, name } of $kkc.getAll()) {
      pidToNames.push({ pid, name });
    }
    return {
      mainPID: process.pid,
      mainArguments: process.argv.slice(1),
      windows,
      pidToNames,
      screenReader: !!app3.accessibilitySupportEnabled,
      gpuFeatureStatus: app3.getGPUFeatureStatus()
    };
  }
  async d(window2) {
    const folderURIs = await this.f(window2);
    const win = $Jg(window2.win);
    return this.e(win, folderURIs, window2.remoteAuthority);
  }
  e(window2, folderURIs = [], remoteAuthority) {
    return {
      id: window2.id,
      pid: window2.webContents.getOSProcessId(),
      title: window2.getTitle(),
      folderURIs,
      remoteAuthority
    };
  }
  async f(window2) {
    const folderURIs = [];
    const workspace = window2.openedWorkspace;
    if ($0i(workspace)) {
      folderURIs.push(workspace.uri);
    } else if ($cj(workspace)) {
      const resolvedWorkspace = await this.b.resolveLocalWorkspace(workspace.configPath);
      if (resolvedWorkspace) {
        const rootFolders = resolvedWorkspace.folders;
        rootFolders.forEach((root) => {
          folderURIs.push(root.uri);
        });
      }
    }
    return folderURIs;
  }
};
$okc = __decorate([
  __param(0, $Pjc),
  __param(1, $2jc),
  __param(2, $uk)
], $okc);

// out-build/vs/platform/encryption/electron-main/encryptionMainService.js
import { safeStorage as safeStorageElectron, app as app4 } from "electron";
var safeStorage = safeStorageElectron;
var $pkc = class $pkc2 {
  constructor(a) {
    this.a = a;
    if (app4.commandLine.getSwitchValue("password-store") === "basic") {
      this.a.trace("[EncryptionMainService] setting usePlainTextEncryption to true...");
      safeStorage.setUsePlainTextEncryption?.(true);
      this.a.trace("[EncryptionMainService] set usePlainTextEncryption to true");
    }
  }
  async encrypt(value) {
    this.a.trace("[EncryptionMainService] Encrypting value...");
    try {
      const result = JSON.stringify(safeStorage.encryptString(value));
      this.a.trace("[EncryptionMainService] Encrypted value.");
      return result;
    } catch (e) {
      this.a.error(e);
      throw e;
    }
  }
  async decrypt(value) {
    let parsedValue;
    try {
      parsedValue = JSON.parse(value);
      if (!parsedValue.data) {
        throw new Error(`[EncryptionMainService] Invalid encrypted value: ${value}`);
      }
      const bufferToDecrypt = Buffer.from(parsedValue.data);
      this.a.trace("[EncryptionMainService] Decrypting value...");
      const result = safeStorage.decryptString(bufferToDecrypt);
      this.a.trace("[EncryptionMainService] Decrypted value.");
      return result;
    } catch (e) {
      this.a.error(e);
      throw e;
    }
  }
  isEncryptionAvailable() {
    this.a.trace("[EncryptionMainService] Checking if encryption is available...");
    const result = safeStorage.isEncryptionAvailable();
    this.a.trace("[EncryptionMainService] Encryption is available: ", result);
    return Promise.resolve(result);
  }
  getKeyStorageProvider() {
    if ($l) {
      return Promise.resolve(
        "dpapi"
        /* KnownStorageProvider.dplib */
      );
    }
    if ($m) {
      return Promise.resolve(
        "keychain_access"
        /* KnownStorageProvider.keychainAccess */
      );
    }
    if (safeStorage.getSelectedStorageBackend) {
      try {
        this.a.trace("[EncryptionMainService] Getting selected storage backend...");
        const result = safeStorage.getSelectedStorageBackend();
        this.a.trace("[EncryptionMainService] Selected storage backend: ", result);
        return Promise.resolve(result);
      } catch (e) {
        this.a.error(e);
      }
    }
    return Promise.resolve(
      "unknown"
      /* KnownStorageProvider.unknown */
    );
  }
  async setUsePlainTextEncryption() {
    if ($l) {
      throw new Error("Setting plain text encryption is not supported on Windows.");
    }
    if ($m) {
      throw new Error("Setting plain text encryption is not supported on macOS.");
    }
    if (!safeStorage.setUsePlainTextEncryption) {
      throw new Error("Setting plain text encryption is not supported.");
    }
    this.a.trace("[EncryptionMainService] Setting usePlainTextEncryption to true...");
    safeStorage.setUsePlainTextEncryption(true);
    this.a.trace("[EncryptionMainService] Set usePlainTextEncryption to true");
  }
};
$pkc = __decorate([
  __param(0, $uk)
], $pkc);

// out-build/vs/platform/environment/node/argvHelper.js
import assert from "assert";
function parseAndValidate(cmdLineArgs, reportWarnings) {
  const onMultipleValues = (id2, val) => {
    console.warn(localize(1771, null, id2, val));
  };
  const onEmptyValue = (id2) => {
    console.warn(localize(1772, null, id2));
  };
  const onDeprecatedOption = (deprecatedOption, message) => {
    console.warn(localize(1773, null, deprecatedOption, message));
  };
  const getSubcommandReporter = (command) => ({
    onUnknownOption: (id2) => {
      if (!$Vm.includes(command)) {
        console.warn(localize(1774, null, id2, command));
      }
    },
    onMultipleValues,
    onEmptyValue,
    onDeprecatedOption,
    getSubcommandReporter: $Vm.includes(command) ? getSubcommandReporter : void 0
  });
  const errorReporter = {
    onUnknownOption: (id2) => {
      console.warn(localize(1775, null, id2));
    },
    onMultipleValues,
    onEmptyValue,
    onDeprecatedOption,
    getSubcommandReporter
  };
  const args = $Xm(cmdLineArgs, $Wm, reportWarnings ? errorReporter : void 0);
  if (args.goto) {
    args._.forEach((arg) => assert(/^(\w:)?[^:]+(:\d*){0,2}:?$/.test(arg), localize(1776, null)));
  }
  return args;
}
function stripAppPath(argv) {
  const index = argv.findIndex((a) => !/^-/.test(a));
  if (index > -1) {
    return [...argv.slice(0, index), ...argv.slice(index + 1)];
  }
  return void 0;
}
function $2m(processArgv) {
  let [, ...args] = processArgv;
  if (process.env["VSCODE_DEV"]) {
    args = stripAppPath(args) || [];
  }
  const reportWarnings = !$5m(process.env);
  return parseAndValidate(args, reportWarnings);
}
function $4m(argv, ...args) {
  const endOfArgsMarkerIndex = argv.indexOf("--");
  if (endOfArgsMarkerIndex === -1) {
    argv.push(...args);
  } else {
    argv.splice(endOfArgsMarkerIndex, 0, ...args);
  }
  return argv;
}
function $5m(env2) {
  return env2["VSCODE_CLI"] === "1";
}

// out-build/vs/platform/shell/node/shellEnv.js
import { spawn } from "child_process";

// out-build/vs/base/node/shell.js
import { userInfo } from "os";

// out-build/vs/base/node/powershell.js
import * as os2 from "os";
var IntRegex = /^\d+$/;
var PwshMsixRegex = /^Microsoft.PowerShell_.*/;
var PwshPreviewMsixRegex = /^Microsoft.PowerShellPreview_.*/;
var Arch;
(function(Arch2) {
  Arch2[Arch2["x64"] = 0] = "x64";
  Arch2[Arch2["x86"] = 1] = "x86";
  Arch2[Arch2["ARM"] = 2] = "ARM";
})(Arch || (Arch = {}));
var processArch;
switch (process.arch) {
  case "ia32":
    processArch = 1;
    break;
  case "arm":
  case "arm64":
    processArch = 2;
    break;
  default:
    processArch = 0;
    break;
}
var osArch;
if (process.env["PROCESSOR_ARCHITEW6432"]) {
  osArch = process.env["PROCESSOR_ARCHITEW6432"] === "ARM64" ? 2 : 0;
} else if (process.env["PROCESSOR_ARCHITECTURE"] === "ARM64") {
  osArch = 2;
} else if (process.env["PROCESSOR_ARCHITECTURE"] === "X86") {
  osArch = 1;
} else {
  osArch = 0;
}
var PossiblePowerShellExe = class {
  constructor(exePath, displayName, a) {
    this.exePath = exePath;
    this.displayName = displayName;
    this.a = a;
  }
  async exists() {
    if (this.a === void 0) {
      this.a = await SymlinkSupport.existsFile(this.exePath);
    }
    return this.a;
  }
};
function getProgramFilesPath({ useAlternateBitness = false } = {}) {
  if (!useAlternateBitness) {
    return process.env.ProgramFiles || null;
  }
  if (processArch === 0) {
    return process.env["ProgramFiles(x86)"] || null;
  }
  if (osArch === 0) {
    return process.env.ProgramW6432 || null;
  }
  return null;
}
async function findPSCoreWindowsInstallation({ useAlternateBitness = false, findPreview = false } = {}) {
  const programFilesPath = getProgramFilesPath({ useAlternateBitness });
  if (!programFilesPath) {
    return null;
  }
  const powerShellInstallBaseDir = $vc(programFilesPath, "PowerShell");
  if (!await SymlinkSupport.existsDirectory(powerShellInstallBaseDir)) {
    return null;
  }
  let highestSeenVersion = -1;
  let pwshExePath = null;
  for (const item of await Promises2.readdir(powerShellInstallBaseDir)) {
    let currentVersion = -1;
    if (findPreview) {
      const dashIndex = item.indexOf("-");
      if (dashIndex < 0) {
        continue;
      }
      const intPart = item.substring(0, dashIndex);
      if (!IntRegex.test(intPart) || item.substring(dashIndex + 1) !== "preview") {
        continue;
      }
      currentVersion = parseInt(intPart, 10);
    } else {
      if (!IntRegex.test(item)) {
        continue;
      }
      currentVersion = parseInt(item, 10);
    }
    if (currentVersion <= highestSeenVersion) {
      continue;
    }
    const exePath = $vc(powerShellInstallBaseDir, item, "pwsh.exe");
    if (!await SymlinkSupport.existsFile(exePath)) {
      continue;
    }
    pwshExePath = exePath;
    highestSeenVersion = currentVersion;
  }
  if (!pwshExePath) {
    return null;
  }
  const bitness = programFilesPath.includes("x86") ? " (x86)" : "";
  const preview = findPreview ? " Preview" : "";
  return new PossiblePowerShellExe(pwshExePath, `PowerShell${preview}${bitness}`, true);
}
async function findPSCoreMsix({ findPreview } = {}) {
  if (!process.env.LOCALAPPDATA) {
    return null;
  }
  const msixAppDir = $vc(process.env.LOCALAPPDATA, "Microsoft", "WindowsApps");
  if (!await SymlinkSupport.existsDirectory(msixAppDir)) {
    return null;
  }
  const { pwshMsixDirRegex, pwshMsixName } = findPreview ? { pwshMsixDirRegex: PwshPreviewMsixRegex, pwshMsixName: "PowerShell Preview (Store)" } : { pwshMsixDirRegex: PwshMsixRegex, pwshMsixName: "PowerShell (Store)" };
  for (const subdir of await Promises2.readdir(msixAppDir)) {
    if (pwshMsixDirRegex.test(subdir)) {
      const pwshMsixPath = $vc(msixAppDir, subdir, "pwsh.exe");
      return new PossiblePowerShellExe(pwshMsixPath, pwshMsixName);
    }
  }
  return null;
}
function findPSCoreDotnetGlobalTool() {
  const dotnetGlobalToolExePath = $vc(os2.homedir(), ".dotnet", "tools", "pwsh.exe");
  return new PossiblePowerShellExe(dotnetGlobalToolExePath, ".NET Core PowerShell Global Tool");
}
function findWinPS() {
  const winPSPath = $vc(process.env.windir, processArch === 1 && osArch !== 1 ? "SysNative" : "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
  return new PossiblePowerShellExe(winPSPath, "Windows PowerShell", true);
}
async function* enumerateDefaultPowerShellInstallations() {
  let pwshExe = await findPSCoreWindowsInstallation();
  if (pwshExe) {
    yield pwshExe;
  }
  pwshExe = await findPSCoreWindowsInstallation({ useAlternateBitness: true });
  if (pwshExe) {
    yield pwshExe;
  }
  pwshExe = await findPSCoreMsix();
  if (pwshExe) {
    yield pwshExe;
  }
  pwshExe = findPSCoreDotnetGlobalTool();
  if (pwshExe) {
    yield pwshExe;
  }
  pwshExe = await findPSCoreWindowsInstallation({ findPreview: true });
  if (pwshExe) {
    yield pwshExe;
  }
  pwshExe = await findPSCoreMsix({ findPreview: true });
  if (pwshExe) {
    yield pwshExe;
  }
  pwshExe = await findPSCoreWindowsInstallation({ useAlternateBitness: true, findPreview: true });
  if (pwshExe) {
    yield pwshExe;
  }
  pwshExe = findWinPS();
  if (pwshExe) {
    yield pwshExe;
  }
}
async function* $Qm() {
  for await (const defaultPwsh of enumerateDefaultPowerShellInstallations()) {
    if (await defaultPwsh.exists()) {
      yield defaultPwsh;
    }
  }
}
async function $Rm() {
  for await (const pwsh of $Qm()) {
    return pwsh;
  }
  return null;
}

// out-build/vs/base/node/processes.js
import { promises as promises5 } from "fs";
function $Sm(env2 = env) {
  return env2["comspec"] || "cmd.exe";
}
function $Tm(childProcess) {
  let msgQueue = [];
  let useQueue = false;
  const send = function(msg) {
    if (useQueue) {
      msgQueue.push(msg);
      return;
    }
    const result = childProcess.send(msg, (error) => {
      if (error) {
        console.error(error);
      }
      useQueue = false;
      if (msgQueue.length > 0) {
        const msgQueueCopy = msgQueue.slice(0);
        msgQueue = [];
        msgQueueCopy.forEach((entry) => send(entry));
      }
    });
    if (!result || $l) {
      useQueue = true;
    }
  };
  return { send };
}
var win32;
(function(win322) {
  async function findExecutable(command, cwd2, paths) {
    if ($uc(command)) {
      return command;
    }
    if (cwd2 === void 0) {
      cwd2 = cwd();
    }
    const dir = $yc(command);
    if (dir !== ".") {
      return $vc(cwd2, command);
    }
    if (paths === void 0 && $yg(env["PATH"])) {
      paths = env["PATH"].split($Fc);
    }
    if (paths === void 0 || paths.length === 0) {
      return $vc(cwd2, command);
    }
    async function fileExists(path3) {
      if (await Promises2.exists(path3)) {
        let statValue;
        try {
          statValue = await promises5.stat(path3);
        } catch (e) {
          if (e.message.startsWith("EACCES")) {
            statValue = await promises5.lstat(path3);
          }
        }
        return statValue ? !statValue.isDirectory() : false;
      }
      return false;
    }
    for (const pathEntry of paths) {
      let fullPath;
      if ($uc(pathEntry)) {
        fullPath = $vc(pathEntry, command);
      } else {
        fullPath = $vc(cwd2, pathEntry, command);
      }
      if (await fileExists(fullPath)) {
        return fullPath;
      }
      let withExtension = fullPath + ".com";
      if (await fileExists(withExtension)) {
        return withExtension;
      }
      withExtension = fullPath + ".exe";
      if (await fileExists(withExtension)) {
        return withExtension;
      }
    }
    return $vc(cwd2, command);
  }
  win322.findExecutable = findExecutable;
})(win32 || (win32 = {}));

// out-build/vs/base/node/shell.js
async function $Um(os6, env2) {
  if (os6 === 1) {
    if ($l) {
      return getSystemShellWindows();
    }
    return $Sm(env2);
  }
  return getSystemShellUnixLike(os6, env2);
}
var _TERMINAL_DEFAULT_SHELL_UNIX_LIKE = null;
function getSystemShellUnixLike(os6, env2) {
  if ($n && os6 === 2 || $m && os6 === 3) {
    return "/bin/bash";
  }
  if (!_TERMINAL_DEFAULT_SHELL_UNIX_LIKE) {
    let unixLikeTerminal;
    if ($l) {
      unixLikeTerminal = "/bin/bash";
    } else {
      unixLikeTerminal = env2["SHELL"];
      if (!unixLikeTerminal) {
        try {
          unixLikeTerminal = userInfo().shell;
        } catch (err) {
        }
      }
      if (!unixLikeTerminal) {
        unixLikeTerminal = "sh";
      }
      if (unixLikeTerminal === "/bin/false") {
        unixLikeTerminal = "/bin/bash";
      }
    }
    _TERMINAL_DEFAULT_SHELL_UNIX_LIKE = unixLikeTerminal;
  }
  return _TERMINAL_DEFAULT_SHELL_UNIX_LIKE;
}
var _TERMINAL_DEFAULT_SHELL_WINDOWS = null;
async function getSystemShellWindows() {
  if (!_TERMINAL_DEFAULT_SHELL_WINDOWS) {
    _TERMINAL_DEFAULT_SHELL_WINDOWS = (await $Rm()).exePath;
  }
  return _TERMINAL_DEFAULT_SHELL_WINDOWS;
}

// out-build/vs/base/common/numbers.js
function $6m(value, min, max) {
  return Math.min(Math.max(value, min), max);
}

// out-build/vs/platform/shell/node/shellEnv.js
var unixShellEnvPromise = void 0;
async function $_m(configurationService, logService, args, env2) {
  if (args["force-disable-user-env"]) {
    logService.trace("resolveShellEnv(): skipped (--force-disable-user-env)");
    return {};
  } else if ($l) {
    logService.trace("resolveShellEnv(): skipped (Windows)");
    return {};
  } else if ($5m(env2) && !args["force-user-env"]) {
    logService.trace("resolveShellEnv(): skipped (VSCODE_CLI is set)");
    return {};
  } else {
    if ($5m(env2)) {
      logService.trace("resolveShellEnv(): running (--force-user-env)");
    } else {
      logService.trace("resolveShellEnv(): running (macOS/Linux)");
    }
    if (!unixShellEnvPromise) {
      unixShellEnvPromise = Promises.withAsyncBody(async (resolve2, reject) => {
        const cts = new $Pe();
        let timeoutValue = 1e4;
        const configuredTimeoutValue = configurationService.getValue("application.shellEnvironmentResolutionTimeout");
        if (typeof configuredTimeoutValue === "number") {
          timeoutValue = $6m(configuredTimeoutValue, 1, 120) * 1e3;
        }
        const timeout = setTimeout(() => {
          cts.dispose(true);
          reject(new Error(localize(2078, null)));
        }, timeoutValue);
        try {
          resolve2(await doResolveUnixShellEnv(logService, cts.token));
        } catch (error) {
          if (!$eb(error) && !cts.token.isCancellationRequested) {
            reject(new Error(localize(2079, null, $Kj(error))));
          } else {
            resolve2({});
          }
        } finally {
          clearTimeout(timeout);
          cts.dispose();
        }
      });
    }
    return unixShellEnvPromise;
  }
}
async function doResolveUnixShellEnv(logService, token) {
  const runAsNode = process.env["ELECTRON_RUN_AS_NODE"];
  logService.trace("getUnixShellEnvironment#runAsNode", runAsNode);
  const noAttach = process.env["ELECTRON_NO_ATTACH_CONSOLE"];
  logService.trace("getUnixShellEnvironment#noAttach", noAttach);
  const mark2 = $jh().replace(/-/g, "").substr(0, 12);
  const regex = new RegExp(mark2 + "({.*})" + mark2);
  const env2 = {
    ...process.env,
    ELECTRON_RUN_AS_NODE: "1",
    ELECTRON_NO_ATTACH_CONSOLE: "1",
    VSCODE_RESOLVING_ENVIRONMENT: "1"
  };
  logService.trace("getUnixShellEnvironment#env", env2);
  const systemShellUnix = await $Um(OS, env2);
  logService.trace("getUnixShellEnvironment#shell", systemShellUnix);
  return new Promise((resolve2, reject) => {
    if (token.isCancellationRequested) {
      return reject(new $fb());
    }
    const name = $zc(systemShellUnix);
    let command, shellArgs;
    const extraArgs = "";
    if (/^pwsh(-preview)?$/.test(name)) {
      command = `& '${process.execPath}' ${extraArgs} -p '''${mark2}'' + JSON.stringify(process.env) + ''${mark2}'''`;
      shellArgs = ["-Login", "-Command"];
    } else if (name === "nu") {
      command = `^'${process.execPath}' ${extraArgs} -p '"${mark2}" + JSON.stringify(process.env) + "${mark2}"'`;
      shellArgs = ["-i", "-l", "-c"];
    } else if (name === "xonsh") {
      command = `import os, json; print("${mark2}", json.dumps(dict(os.environ)), "${mark2}")`;
      shellArgs = ["-i", "-l", "-c"];
    } else {
      command = `'${process.execPath}' ${extraArgs} -p '"${mark2}" + JSON.stringify(process.env) + "${mark2}"'`;
      if (name === "tcsh" || name === "csh") {
        shellArgs = ["-ic"];
      } else {
        shellArgs = ["-i", "-l", "-c"];
      }
    }
    logService.trace("getUnixShellEnvironment#spawn", JSON.stringify(shellArgs), command);
    const child = spawn(systemShellUnix, [...shellArgs, command], {
      detached: true,
      stdio: ["ignore", "pipe", "pipe"],
      env: env2
    });
    token.onCancellationRequested(() => {
      child.kill();
      return reject(new $fb());
    });
    child.on("error", (err) => {
      logService.error("getUnixShellEnvironment#errorChildProcess", $Kj(err));
      reject(err);
    });
    const buffers = [];
    child.stdout.on("data", (b) => buffers.push(b));
    const stderr = [];
    child.stderr.on("data", (b) => stderr.push(b));
    child.on("close", (code2, signal) => {
      const raw = Buffer.concat(buffers).toString("utf8");
      logService.trace("getUnixShellEnvironment#raw", raw);
      const stderrStr = Buffer.concat(stderr).toString("utf8");
      if (stderrStr.trim()) {
        logService.trace("getUnixShellEnvironment#stderr", stderrStr);
      }
      if (code2 || signal) {
        return reject(new Error(localize(2080, null, code2, signal)));
      }
      const match = regex.exec(raw);
      const rawStripped = match ? match[1] : "{}";
      try {
        const env3 = JSON.parse(rawStripped);
        if (runAsNode) {
          env3["ELECTRON_RUN_AS_NODE"] = runAsNode;
        } else {
          delete env3["ELECTRON_RUN_AS_NODE"];
        }
        if (noAttach) {
          env3["ELECTRON_NO_ATTACH_CONSOLE"] = noAttach;
        } else {
          delete env3["ELECTRON_NO_ATTACH_CONSOLE"];
        }
        delete env3["VSCODE_RESOLVING_ENVIRONMENT"];
        delete env3["XDG_RUNTIME_DIR"];
        logService.trace("getUnixShellEnvironment#result", env3);
        resolve2(env3);
      } catch (err) {
        logService.error("getUnixShellEnvironment#errorCaught", $Kj(err));
        reject(err);
      }
    });
  });
}

// out-build/vs/platform/extensions/common/extensionHostStarter.js
var $qkc = $Zi("extensionHostStarter");
var $rkc = "extensionHostStarter";

// out-build/vs/platform/extensions/electron-main/extensionHostStarter.js
var $skc_1;
var $skc = class $skc2 extends $0c {
  static {
    $skc_1 = this;
  }
  static {
    this.a = 0;
  }
  constructor(f, g, h, j) {
    super();
    this.f = f;
    this.g = g;
    this.h = h;
    this.j = j;
    this.b = /* @__PURE__ */ new Map();
    this.c = false;
    this.B(this.g.onWillShutdown((e) => {
      this.c = true;
      e.join("extHostStarter", this._waitForAllExit(6e3));
    }));
  }
  dispose() {
    super.dispose();
  }
  m(id2) {
    const extHostProcess = this.b.get(id2);
    if (!extHostProcess) {
      throw new Error(`Unknown extension host!`);
    }
    return extHostProcess;
  }
  onDynamicStdout(id2) {
    return this.m(id2).onStdout;
  }
  onDynamicStderr(id2) {
    return this.m(id2).onStderr;
  }
  onDynamicMessage(id2) {
    return this.m(id2).onMessage;
  }
  onDynamicExit(id2) {
    return this.m(id2).onExit;
  }
  async createExtensionHost() {
    if (this.c) {
      throw $gb();
    }
    const id2 = String(++$skc_1.a);
    const extHost = new $lkc(this.f, this.h, this.j, this.g);
    this.b.set(id2, extHost);
    const disposable = extHost.onExit(({ pid, code: code2, signal }) => {
      disposable.dispose();
      this.f.info(`Extension host with pid ${pid} exited with code: ${code2}, signal: ${signal}.`);
      setTimeout(() => {
        extHost.dispose();
        this.b.delete(id2);
      });
      setTimeout(() => {
        try {
          process.kill(pid, 0);
          this.f.error(`Extension host with pid ${pid} still exists, forcefully killing it...`);
          process.kill(pid);
        } catch (er) {
        }
      }, 1e3);
    });
    return { id: id2 };
  }
  async start(id2, opts) {
    if (this.c) {
      throw $gb();
    }
    const extHost = this.m(id2);
    extHost.start({
      ...opts,
      type: "extensionHost",
      entryPoint: "vs/workbench/api/node/extensionHostProcess",
      args: ["--skipWorkspaceStorageLock"],
      execArgv: opts.execArgv,
      allowLoadingUnsignedLibraries: true,
      respondToAuthRequestsFromMainProcess: true,
      correlationId: id2
    });
    const pid = await Event.toPromise(extHost.onSpawn);
    return { pid };
  }
  async enableInspectPort(id2) {
    if (this.c) {
      throw $gb();
    }
    const extHostProcess = this.b.get(id2);
    if (!extHostProcess) {
      return false;
    }
    return extHostProcess.enableInspectPort();
  }
  async kill(id2) {
    if (this.c) {
      throw $gb();
    }
    const extHostProcess = this.b.get(id2);
    if (!extHostProcess) {
      return;
    }
    extHostProcess.kill();
  }
  async _killAllNow() {
    for (const [, extHost] of this.b) {
      extHost.kill();
    }
  }
  async _waitForAllExit(maxWaitTimeMs) {
    const exitPromises = [];
    for (const [, extHost] of this.b) {
      exitPromises.push(extHost.waitForExit(maxWaitTimeMs));
    }
    return Promises.settled(exitPromises).then(() => {
    });
  }
};
$skc = $skc_1 = __decorate([
  __param(0, $uk),
  __param(1, $9jc),
  __param(2, $Pjc),
  __param(3, $tm)
], $skc);

// out-build/vs/platform/externalTerminal/electron-main/externalTerminal.js
var $tkc = $Zi("externalTerminal");

// out-build/vs/platform/externalTerminal/node/externalTerminalService.js
import * as cp from "child_process";

// out-build/vs/platform/externalTerminal/common/externalTerminal.js
var $3bc = $Zi("externalTerminal");
var $4bc = "Terminal.app";

// out-build/vs/platform/externalTerminal/node/externalTerminalService.js
var TERMINAL_TITLE = localize(1865, null);
var ExternalTerminalService = class {
  async getDefaultTerminalForPlatforms() {
    return {
      windows: $ukc.getDefaultTerminalWindows(),
      linux: await $wkc.getDefaultTerminalLinuxReady(),
      osx: "xterm"
    };
  }
};
var $ukc = class _$ukc extends ExternalTerminalService {
  static {
    this.b = "cmd.exe";
  }
  openTerminal(configuration, cwd2) {
    return this.spawnTerminal(cp, configuration, $Sm(), cwd2);
  }
  spawnTerminal(spawner, configuration, command, cwd2) {
    const exec4 = configuration.windowsExec || _$ukc.getDefaultTerminalWindows();
    if (cwd2 && cwd2[1] === ":") {
      cwd2 = cwd2[0].toUpperCase() + cwd2.substr(1);
    }
    const basename = $zc(exec4, ".exe").toLowerCase();
    if (basename === "cmder") {
      spawner.spawn(exec4, cwd2 ? [cwd2] : void 0);
      return Promise.resolve(void 0);
    }
    const cmdArgs = ["/c", "start", "/wait"];
    if (exec4.indexOf(" ") >= 0) {
      cmdArgs.push(exec4);
    }
    cmdArgs.push(exec4);
    if (basename === "wt") {
      cmdArgs.push("-d .");
    }
    return new Promise((c, e) => {
      const env2 = getSanitizedEnvironment(process);
      const child = spawner.spawn(command, cmdArgs, { cwd: cwd2, env: env2, detached: true });
      child.on("error", e);
      child.on("exit", () => c());
    });
  }
  async runInTerminal(title, dir, args, envVars, settings) {
    const exec4 = "windowsExec" in settings && settings.windowsExec ? settings.windowsExec : _$ukc.getDefaultTerminalWindows();
    const wt = await _$ukc.f();
    return new Promise((resolve2, reject) => {
      const title2 = `"${dir} - ${TERMINAL_TITLE}"`;
      const command = `"${args.join('" "')}" & pause`;
      const env2 = Object.assign({}, getSanitizedEnvironment(process), envVars);
      Object.keys(env2).filter((v) => env2[v] === null).forEach((key) => delete env2[key]);
      const options = {
        cwd: dir,
        env: env2,
        windowsVerbatimArguments: true
      };
      let spawnExec;
      let cmdArgs;
      if ($zc(exec4, ".exe") === "wt") {
        spawnExec = exec4;
        cmdArgs = ["-d", ".", _$ukc.b, "/c", command];
      } else if (wt) {
        spawnExec = wt;
        cmdArgs = ["-d", ".", exec4, "/c", command];
      } else {
        spawnExec = _$ukc.b;
        cmdArgs = ["/c", "start", title2, "/wait", exec4, "/c", `"${command}"`];
      }
      const cmd = cp.spawn(spawnExec, cmdArgs, options);
      cmd.on("error", (err) => {
        reject(improveError(err));
      });
      resolve2(void 0);
    });
  }
  static getDefaultTerminalWindows() {
    if (!_$ukc.d) {
      const isWoW64 = !!process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432");
      _$ukc.d = `${process.env.windir ? process.env.windir : "C:\\Windows"}\\${isWoW64 ? "Sysnative" : "System32"}\\cmd.exe`;
    }
    return _$ukc.d;
  }
  static async f() {
    try {
      const wtPath = await win32.findExecutable("wt");
      return await Promises2.exists(wtPath) ? wtPath : void 0;
    } catch {
      return void 0;
    }
  }
};
__decorate([
  $ri
], $ukc, "f", null);
var $vkc = class _$vkc extends ExternalTerminalService {
  static {
    this.b = "/usr/bin/osascript";
  }
  // osascript is the AppleScript interpreter on OS X
  openTerminal(configuration, cwd2) {
    return this.spawnTerminal(cp, configuration, cwd2);
  }
  runInTerminal(title, dir, args, envVars, settings) {
    const terminalApp = settings.osxExec || $4bc;
    return new Promise((resolve2, reject) => {
      if (terminalApp === $4bc || terminalApp === "iTerm.app") {
        const script = terminalApp === $4bc ? "TerminalHelper" : "iTermHelper";
        const scriptpath = $hh.asFileUri(`vs/workbench/contrib/externalTerminal/node/${script}.scpt`).fsPath;
        const osaArgs = [
          scriptpath,
          "-t",
          title || TERMINAL_TITLE,
          "-w",
          dir
        ];
        for (const a of args) {
          osaArgs.push("-a");
          osaArgs.push(a);
        }
        if (envVars) {
          const env2 = Object.assign({}, getSanitizedEnvironment(process), envVars);
          for (const key in env2) {
            const value = env2[key];
            if (value === null) {
              osaArgs.push("-u");
              osaArgs.push(key);
            } else {
              osaArgs.push("-e");
              osaArgs.push(`${key}=${value}`);
            }
          }
        }
        let stderr = "";
        const osa = cp.spawn(_$vkc.b, osaArgs);
        osa.on("error", (err) => {
          reject(improveError(err));
        });
        osa.stderr.on("data", (data) => {
          stderr += data.toString();
        });
        osa.on("exit", (code2) => {
          if (code2 === 0) {
            resolve2(void 0);
          } else {
            if (stderr) {
              const lines = stderr.split("\n", 1);
              reject(new Error(lines[0]));
            } else {
              reject(new Error(localize(1866, null, script, code2)));
            }
          }
        });
      } else {
        reject(new Error(localize(1867, null, terminalApp)));
      }
    });
  }
  spawnTerminal(spawner, configuration, cwd2) {
    const terminalApp = configuration.osxExec || $4bc;
    return new Promise((c, e) => {
      const args = ["-a", terminalApp];
      if (cwd2) {
        args.push(cwd2);
      }
      const env2 = getSanitizedEnvironment(process);
      const child = spawner.spawn("/usr/bin/open", args, { cwd: cwd2, env: env2 });
      child.on("error", e);
      child.on("exit", () => c());
    });
  }
};
var $wkc = class _$wkc extends ExternalTerminalService {
  static {
    this.b = localize(1868, null);
  }
  openTerminal(configuration, cwd2) {
    return this.spawnTerminal(cp, configuration, cwd2);
  }
  runInTerminal(title, dir, args, envVars, settings) {
    const execPromise = settings.linuxExec ? Promise.resolve(settings.linuxExec) : _$wkc.getDefaultTerminalLinuxReady();
    return new Promise((resolve2, reject) => {
      const termArgs = [];
      execPromise.then((exec4) => {
        if (exec4.indexOf("gnome-terminal") >= 0) {
          termArgs.push("-x");
        } else {
          termArgs.push("-e");
        }
        termArgs.push("bash");
        termArgs.push("-c");
        const bashCommand = `${quote(args)}; echo; read -p "${_$wkc.b}" -n1;`;
        termArgs.push(`''${bashCommand}''`);
        const env2 = Object.assign({}, getSanitizedEnvironment(process), envVars);
        Object.keys(env2).filter((v) => env2[v] === null).forEach((key) => delete env2[key]);
        const options = {
          cwd: dir,
          env: env2
        };
        let stderr = "";
        const cmd = cp.spawn(exec4, termArgs, options);
        cmd.on("error", (err) => {
          reject(improveError(err));
        });
        cmd.stderr.on("data", (data) => {
          stderr += data.toString();
        });
        cmd.on("exit", (code2) => {
          if (code2 === 0) {
            resolve2(void 0);
          } else {
            if (stderr) {
              const lines = stderr.split("\n", 1);
              reject(new Error(lines[0]));
            } else {
              reject(new Error(localize(1869, null, exec4, code2)));
            }
          }
        });
      });
    });
  }
  static async getDefaultTerminalLinuxReady() {
    if (!_$wkc.d) {
      if (!$n) {
        _$wkc.d = Promise.resolve("xterm");
      } else {
        const isDebian = await Promises2.exists("/etc/debian_version");
        _$wkc.d = new Promise((r) => {
          if (isDebian) {
            r("x-terminal-emulator");
          } else if (process.env.DESKTOP_SESSION === "gnome" || process.env.DESKTOP_SESSION === "gnome-classic") {
            r("gnome-terminal");
          } else if (process.env.DESKTOP_SESSION === "kde-plasma") {
            r("konsole");
          } else if (process.env.COLORTERM) {
            r(process.env.COLORTERM);
          } else if (process.env.TERM) {
            r(process.env.TERM);
          } else {
            r("xterm");
          }
        });
      }
    }
    return _$wkc.d;
  }
  spawnTerminal(spawner, configuration, cwd2) {
    const execPromise = configuration.linuxExec ? Promise.resolve(configuration.linuxExec) : _$wkc.getDefaultTerminalLinuxReady();
    return new Promise((c, e) => {
      execPromise.then((exec4) => {
        const env2 = getSanitizedEnvironment(process);
        const child = spawner.spawn(exec4, [], { cwd: cwd2, env: env2 });
        child.on("error", e);
        child.on("exit", () => c());
      });
    });
  }
};
function getSanitizedEnvironment(process2) {
  const env2 = { ...process2.env };
  $Fm(env2);
  return env2;
}
function improveError(err) {
  if ("errno" in err && err["errno"] === "ENOENT" && "path" in err && typeof err["path"] === "string") {
    return new Error(localize(1870, null, err["path"]));
  }
  return err;
}
function quote(args) {
  let r = "";
  for (const a of args) {
    if (a.indexOf(" ") >= 0) {
      r += '"' + a + '"';
    } else {
      r += a;
    }
    r += " ";
  }
  return r;
}

// out-build/vs/base/common/glob.js
var $Qk = "**";
var $Rk = "/";
var PATH_REGEX = "[/\\\\]";
var NO_PATH_REGEX = "[^/\\\\]";
var ALL_FORWARD_SLASHES = /\//g;
function starsToRegExp(starCount, isLastPattern) {
  switch (starCount) {
    case 0:
      return "";
    case 1:
      return `${NO_PATH_REGEX}*?`;
    default:
      return `(?:${PATH_REGEX}|${NO_PATH_REGEX}+${PATH_REGEX}${isLastPattern ? `|${PATH_REGEX}${NO_PATH_REGEX}+` : ""})*?`;
  }
}
function $Sk(pattern, splitChar) {
  if (!pattern) {
    return [];
  }
  const segments = [];
  let inBraces = false;
  let inBrackets = false;
  let curVal = "";
  for (const char of pattern) {
    switch (char) {
      case splitChar:
        if (!inBraces && !inBrackets) {
          segments.push(curVal);
          curVal = "";
          continue;
        }
        break;
      case "{":
        inBraces = true;
        break;
      case "}":
        inBraces = false;
        break;
      case "[":
        inBrackets = true;
        break;
      case "]":
        inBrackets = false;
        break;
    }
    curVal += char;
  }
  if (curVal) {
    segments.push(curVal);
  }
  return segments;
}
function parseRegExp(pattern) {
  if (!pattern) {
    return "";
  }
  let regEx = "";
  const segments = $Sk(pattern, $Rk);
  if (segments.every((segment) => segment === $Qk)) {
    regEx = ".*";
  } else {
    let previousSegmentWasGlobStar = false;
    segments.forEach((segment, index) => {
      if (segment === $Qk) {
        if (previousSegmentWasGlobStar) {
          return;
        }
        regEx += starsToRegExp(2, index === segments.length - 1);
      } else {
        let inBraces = false;
        let braceVal = "";
        let inBrackets = false;
        let bracketVal = "";
        for (const char of segment) {
          if (char !== "}" && inBraces) {
            braceVal += char;
            continue;
          }
          if (inBrackets && (char !== "]" || !bracketVal)) {
            let res;
            if (char === "-") {
              res = char;
            } else if ((char === "^" || char === "!") && !bracketVal) {
              res = "^";
            } else if (char === $Rk) {
              res = "";
            } else {
              res = $Af(char);
            }
            bracketVal += res;
            continue;
          }
          switch (char) {
            case "{":
              inBraces = true;
              continue;
            case "[":
              inBrackets = true;
              continue;
            case "}": {
              const choices = $Sk(braceVal, ",");
              const braceRegExp = `(?:${choices.map((choice) => parseRegExp(choice)).join("|")})`;
              regEx += braceRegExp;
              inBraces = false;
              braceVal = "";
              break;
            }
            case "]": {
              regEx += "[" + bracketVal + "]";
              inBrackets = false;
              bracketVal = "";
              break;
            }
            case "?":
              regEx += NO_PATH_REGEX;
              continue;
            case "*":
              regEx += starsToRegExp(1);
              continue;
            default:
              regEx += $Af(char);
          }
        }
        if (index < segments.length - 1 && // more segments to come after this
        (segments[index + 1] !== $Qk || // next segment is not **, or...
        index + 2 < segments.length)) {
          regEx += PATH_REGEX;
        }
      }
      previousSegmentWasGlobStar = segment === $Qk;
    });
  }
  return regEx;
}
var T1 = /^\*\*\/\*\.[\w\.-]+$/;
var T2 = /^\*\*\/([\w\.-]+)\/?$/;
var T3 = /^{\*\*\/\*?[\w\.-]+\/?(,\*\*\/\*?[\w\.-]+\/?)*}$/;
var T3_2 = /^{\*\*\/\*?[\w\.-]+(\/(\*\*)?)?(,\*\*\/\*?[\w\.-]+(\/(\*\*)?)?)*}$/;
var T4 = /^\*\*((\/[\w\.-]+)+)\/?$/;
var T5 = /^([\w\.-]+(\/[\w\.-]+)*)\/?$/;
var CACHE = new $Pc(1e4);
var FALSE = function() {
  return false;
};
var NULL = function() {
  return null;
};
function parsePattern(arg1, options) {
  if (!arg1) {
    return NULL;
  }
  let pattern;
  if (typeof arg1 !== "string") {
    pattern = arg1.pattern;
  } else {
    pattern = arg1;
  }
  pattern = pattern.trim();
  const patternKey = `${pattern}_${!!options.trimForExclusions}`;
  let parsedPattern = CACHE.get(patternKey);
  if (parsedPattern) {
    return wrapRelativePattern(parsedPattern, arg1);
  }
  let match;
  if (T1.test(pattern)) {
    parsedPattern = trivia1(pattern.substr(4), pattern);
  } else if (match = T2.exec(trimForExclusions(pattern, options))) {
    parsedPattern = trivia2(match[1], pattern);
  } else if ((options.trimForExclusions ? T3_2 : T3).test(pattern)) {
    parsedPattern = trivia3(pattern, options);
  } else if (match = T4.exec(trimForExclusions(pattern, options))) {
    parsedPattern = trivia4and5(match[1].substr(1), pattern, true);
  } else if (match = T5.exec(trimForExclusions(pattern, options))) {
    parsedPattern = trivia4and5(match[1], pattern, false);
  } else {
    parsedPattern = toRegExp(pattern);
  }
  CACHE.set(patternKey, parsedPattern);
  return wrapRelativePattern(parsedPattern, arg1);
}
function wrapRelativePattern(parsedPattern, arg2) {
  if (typeof arg2 === "string") {
    return parsedPattern;
  }
  const wrappedPattern = function(path3, basename) {
    if (!$Yg(path3, arg2.base, !$n)) {
      return null;
    }
    return parsedPattern($Ff(path3.substr(arg2.base.length), sep), basename);
  };
  wrappedPattern.allBasenames = parsedPattern.allBasenames;
  wrappedPattern.allPaths = parsedPattern.allPaths;
  wrappedPattern.basenames = parsedPattern.basenames;
  wrappedPattern.patterns = parsedPattern.patterns;
  return wrappedPattern;
}
function trimForExclusions(pattern, options) {
  return options.trimForExclusions && pattern.endsWith("/**") ? pattern.substr(0, pattern.length - 2) : pattern;
}
function trivia1(base, pattern) {
  return function(path3, basename) {
    return typeof path3 === "string" && path3.endsWith(base) ? pattern : null;
  };
}
function trivia2(base, pattern) {
  const slashBase = `/${base}`;
  const backslashBase = `\\${base}`;
  const parsedPattern = function(path3, basename) {
    if (typeof path3 !== "string") {
      return null;
    }
    if (basename) {
      return basename === base ? pattern : null;
    }
    return path3 === base || path3.endsWith(slashBase) || path3.endsWith(backslashBase) ? pattern : null;
  };
  const basenames = [base];
  parsedPattern.basenames = basenames;
  parsedPattern.patterns = [pattern];
  parsedPattern.allBasenames = basenames;
  return parsedPattern;
}
function trivia3(pattern, options) {
  const parsedPatterns = aggregateBasenameMatches(pattern.slice(1, -1).split(",").map((pattern2) => parsePattern(pattern2, options)).filter((pattern2) => pattern2 !== NULL), pattern);
  const patternsLength = parsedPatterns.length;
  if (!patternsLength) {
    return NULL;
  }
  if (patternsLength === 1) {
    return parsedPatterns[0];
  }
  const parsedPattern = function(path3, basename) {
    for (let i = 0, n = parsedPatterns.length; i < n; i++) {
      if (parsedPatterns[i](path3, basename)) {
        return pattern;
      }
    }
    return null;
  };
  const withBasenames = parsedPatterns.find((pattern2) => !!pattern2.allBasenames);
  if (withBasenames) {
    parsedPattern.allBasenames = withBasenames.allBasenames;
  }
  const allPaths = parsedPatterns.reduce((all, current) => current.allPaths ? all.concat(current.allPaths) : all, []);
  if (allPaths.length) {
    parsedPattern.allPaths = allPaths;
  }
  return parsedPattern;
}
function trivia4and5(targetPath, pattern, matchPathEnds) {
  const usingPosixSep = sep === $sc.sep;
  const nativePath = usingPosixSep ? targetPath : targetPath.replace(ALL_FORWARD_SLASHES, sep);
  const nativePathEnd = sep + nativePath;
  const targetPathEnd = $sc.sep + targetPath;
  let parsedPattern;
  if (matchPathEnds) {
    parsedPattern = function(path3, basename) {
      return typeof path3 === "string" && (path3 === nativePath || path3.endsWith(nativePathEnd) || !usingPosixSep && (path3 === targetPath || path3.endsWith(targetPathEnd))) ? pattern : null;
    };
  } else {
    parsedPattern = function(path3, basename) {
      return typeof path3 === "string" && (path3 === nativePath || !usingPosixSep && path3 === targetPath) ? pattern : null;
    };
  }
  parsedPattern.allPaths = [(matchPathEnds ? "*/" : "./") + targetPath];
  return parsedPattern;
}
function toRegExp(pattern) {
  try {
    const regExp = new RegExp(`^${parseRegExp(pattern)}$`);
    return function(path3) {
      regExp.lastIndex = 0;
      return typeof path3 === "string" && regExp.test(path3) ? pattern : null;
    };
  } catch (error) {
    return NULL;
  }
}
function $Uk(arg1, options = {}) {
  if (!arg1) {
    return FALSE;
  }
  if (typeof arg1 === "string" || $Vk(arg1)) {
    const parsedPattern = parsePattern(arg1, options);
    if (parsedPattern === NULL) {
      return FALSE;
    }
    const resultPattern = function(path3, basename) {
      return !!parsedPattern(path3, basename);
    };
    if (parsedPattern.allBasenames) {
      resultPattern.allBasenames = parsedPattern.allBasenames;
    }
    if (parsedPattern.allPaths) {
      resultPattern.allPaths = parsedPattern.allPaths;
    }
    return resultPattern;
  }
  return parsedExpression(arg1, options);
}
function $Vk(obj) {
  const rp = obj;
  if (!rp) {
    return false;
  }
  return typeof rp.base === "string" && typeof rp.pattern === "string";
}
function parsedExpression(expression, options) {
  const parsedPatterns = aggregateBasenameMatches(Object.getOwnPropertyNames(expression).map((pattern) => parseExpressionPattern(pattern, expression[pattern], options)).filter((pattern) => pattern !== NULL));
  const patternsLength = parsedPatterns.length;
  if (!patternsLength) {
    return NULL;
  }
  if (!parsedPatterns.some((parsedPattern) => !!parsedPattern.requiresSiblings)) {
    if (patternsLength === 1) {
      return parsedPatterns[0];
    }
    const resultExpression2 = function(path3, basename) {
      let resultPromises = void 0;
      for (let i = 0, n = parsedPatterns.length; i < n; i++) {
        const result = parsedPatterns[i](path3, basename);
        if (typeof result === "string") {
          return result;
        }
        if ($Lh(result)) {
          if (!resultPromises) {
            resultPromises = [];
          }
          resultPromises.push(result);
        }
      }
      if (resultPromises) {
        return (async () => {
          for (const resultPromise of resultPromises) {
            const result = await resultPromise;
            if (typeof result === "string") {
              return result;
            }
          }
          return null;
        })();
      }
      return null;
    };
    const withBasenames2 = parsedPatterns.find((pattern) => !!pattern.allBasenames);
    if (withBasenames2) {
      resultExpression2.allBasenames = withBasenames2.allBasenames;
    }
    const allPaths2 = parsedPatterns.reduce((all, current) => current.allPaths ? all.concat(current.allPaths) : all, []);
    if (allPaths2.length) {
      resultExpression2.allPaths = allPaths2;
    }
    return resultExpression2;
  }
  const resultExpression = function(path3, base, hasSibling) {
    let name = void 0;
    let resultPromises = void 0;
    for (let i = 0, n = parsedPatterns.length; i < n; i++) {
      const parsedPattern = parsedPatterns[i];
      if (parsedPattern.requiresSiblings && hasSibling) {
        if (!base) {
          base = $zc(path3);
        }
        if (!name) {
          name = base.substr(0, base.length - $Ac(path3).length);
        }
      }
      const result = parsedPattern(path3, base, name, hasSibling);
      if (typeof result === "string") {
        return result;
      }
      if ($Lh(result)) {
        if (!resultPromises) {
          resultPromises = [];
        }
        resultPromises.push(result);
      }
    }
    if (resultPromises) {
      return (async () => {
        for (const resultPromise of resultPromises) {
          const result = await resultPromise;
          if (typeof result === "string") {
            return result;
          }
        }
        return null;
      })();
    }
    return null;
  };
  const withBasenames = parsedPatterns.find((pattern) => !!pattern.allBasenames);
  if (withBasenames) {
    resultExpression.allBasenames = withBasenames.allBasenames;
  }
  const allPaths = parsedPatterns.reduce((all, current) => current.allPaths ? all.concat(current.allPaths) : all, []);
  if (allPaths.length) {
    resultExpression.allPaths = allPaths;
  }
  return resultExpression;
}
function parseExpressionPattern(pattern, value, options) {
  if (value === false) {
    return NULL;
  }
  const parsedPattern = parsePattern(pattern, options);
  if (parsedPattern === NULL) {
    return NULL;
  }
  if (typeof value === "boolean") {
    return parsedPattern;
  }
  if (value) {
    const when = value.when;
    if (typeof when === "string") {
      const result = (path3, basename, name, hasSibling) => {
        if (!hasSibling || !parsedPattern(path3, basename)) {
          return null;
        }
        const clausePattern = when.replace("$(basename)", () => name);
        const matched = hasSibling(clausePattern);
        return $Lh(matched) ? matched.then((match) => match ? pattern : null) : matched ? pattern : null;
      };
      result.requiresSiblings = true;
      return result;
    }
  }
  return parsedPattern;
}
function aggregateBasenameMatches(parsedPatterns, result) {
  const basenamePatterns = parsedPatterns.filter((parsedPattern) => !!parsedPattern.basenames);
  if (basenamePatterns.length < 2) {
    return parsedPatterns;
  }
  const basenames = basenamePatterns.reduce((all, current) => {
    const basenames2 = current.basenames;
    return basenames2 ? all.concat(basenames2) : all;
  }, []);
  let patterns;
  if (result) {
    patterns = [];
    for (let i = 0, n = basenames.length; i < n; i++) {
      patterns.push(result);
    }
  } else {
    patterns = basenamePatterns.reduce((all, current) => {
      const patterns2 = current.patterns;
      return patterns2 ? all.concat(patterns2) : all;
    }, []);
  }
  const aggregate = function(path3, basename) {
    if (typeof path3 !== "string") {
      return null;
    }
    if (!basename) {
      let i;
      for (i = path3.length; i > 0; i--) {
        const ch = path3.charCodeAt(i - 1);
        if (ch === 47 || ch === 92) {
          break;
        }
      }
      basename = path3.substr(i);
    }
    const index = basenames.indexOf(basename);
    return index !== -1 ? patterns[index] : null;
  };
  aggregate.basenames = basenames;
  aggregate.patterns = patterns;
  aggregate.allBasenames = basenames;
  const aggregatedPatterns = parsedPatterns.filter((parsedPattern) => !parsedPattern.basenames);
  aggregatedPatterns.push(aggregate);
  return aggregatedPatterns;
}
function $Yk(patternsA, patternsB) {
  return $Hb(patternsA, patternsB, (a, b) => {
    if (typeof a === "string" && typeof b === "string") {
      return a === b;
    }
    if (typeof a !== "string" && typeof b !== "string") {
      return a.base === b.base && a.pattern === b.pattern;
    }
    return false;
  });
}

// out-build/vs/platform/files/common/watcher.js
function $nr(request) {
  return typeof request.correlationId === "number";
}
function $or(request) {
  return request.recursive === true;
}
var $pr = class _$pr extends $0c {
  static {
    this.a = 5;
  }
  constructor(h, j, m, n) {
    super();
    this.h = h;
    this.j = j;
    this.m = m;
    this.n = n;
    this.c = this.B(new $$c());
    this.f = void 0;
    this.g = 0;
  }
  s() {
    const disposables = new $9c();
    this.c.value = disposables;
    this.b = this.r(disposables);
    this.b.setVerboseLogging(this.m);
    disposables.add(this.b.onDidChangeFile((changes) => this.h(changes)));
    disposables.add(this.b.onDidLogMessage((msg) => this.j(msg)));
    disposables.add(this.b.onDidError((e) => this.t(e.error, e.request)));
  }
  t(error, failedRequest) {
    if (this.u(error, failedRequest)) {
      if (this.g < _$pr.a && this.f) {
        this.y(`restarting watcher after unexpected error: ${error}`);
        this.w(this.f);
      } else {
        this.y(`gave up attempting to restart watcher after unexpected error: ${error}`);
      }
    } else {
      this.y(error);
    }
  }
  u(error, failedRequest) {
    if (!this.n.restartOnError) {
      return false;
    }
    if (failedRequest) {
      return false;
    }
    if (error.indexOf("No space left on device") !== -1 || error.indexOf("EMFILE") !== -1) {
      return false;
    }
    return true;
  }
  w(requests) {
    this.g++;
    this.s();
    this.watch(requests);
  }
  async watch(requests) {
    this.f = requests;
    await this.b?.watch(requests);
  }
  async setVerboseLogging(verboseLogging) {
    this.m = verboseLogging;
    await this.b?.setVerboseLogging(verboseLogging);
  }
  y(message) {
    this.j({ type: "error", message: `[File Watcher (${this.n.type})] ${message}` });
  }
  z(message) {
    this.j({ type: "trace", message: `[File Watcher (${this.n.type})] ${message}` });
  }
  dispose() {
    this.b = void 0;
    return super.dispose();
  }
};
var $qr = class extends $pr {
  constructor(onFileChanges, onLogMessage, verboseLogging) {
    super(onFileChanges, onLogMessage, verboseLogging, { type: "node.js", restartOnError: false });
  }
};
var $rr = class extends $pr {
  constructor(onFileChanges, onLogMessage, verboseLogging) {
    super(onFileChanges, onLogMessage, verboseLogging, { type: "universal", restartOnError: true });
  }
};
function $sr(changes) {
  return changes.map((change) => ({
    type: change.type,
    resource: URI.revive(change.resource),
    cId: change.cId
  }));
}
function $tr(changes) {
  const coalescer = new EventCoalescer();
  for (const event of changes) {
    coalescer.processEvent(event);
  }
  return coalescer.coalesce();
}
function $ur(path3, pattern) {
  if (typeof pattern === "string" && !pattern.startsWith($Qk) && !$uc(pattern)) {
    return { base: path3, pattern };
  }
  return pattern;
}
function $vr(path3, patterns) {
  const parsedPatterns = [];
  for (const pattern of patterns) {
    parsedPatterns.push($Uk($ur(path3, pattern)));
  }
  return parsedPatterns;
}
var EventCoalescer = class {
  constructor() {
    this.a = /* @__PURE__ */ new Set();
    this.b = /* @__PURE__ */ new Map();
  }
  c(event) {
    if ($n) {
      return event.resource.fsPath;
    }
    return event.resource.fsPath.toLowerCase();
  }
  processEvent(event) {
    const existingEvent = this.b.get(this.c(event));
    let keepEvent = false;
    if (existingEvent) {
      const currentChangeType = existingEvent.type;
      const newChangeType = event.type;
      if (existingEvent.resource.fsPath !== event.resource.fsPath && (event.type === 2 || event.type === 1)) {
        keepEvent = true;
      } else if (currentChangeType === 1 && newChangeType === 2) {
        this.b.delete(this.c(event));
        this.a.delete(existingEvent);
      } else if (currentChangeType === 2 && newChangeType === 1) {
        existingEvent.type = 0;
      } else if (currentChangeType === 1 && newChangeType === 0) {
      } else {
        existingEvent.type = newChangeType;
      }
    } else {
      keepEvent = true;
    }
    if (keepEvent) {
      this.a.add(event);
      this.b.set(this.c(event), event);
    }
  }
  coalesce() {
    const addOrChangeEvents = [];
    const deletedPaths = [];
    return Array.from(this.a).filter((e) => {
      if (e.type !== 2) {
        addOrChangeEvents.push(e);
        return false;
      }
      return true;
    }).sort((e1, e2) => {
      return e1.resource.fsPath.length - e2.resource.fsPath.length;
    }).filter((e) => {
      if (deletedPaths.some((deletedPath) => $Ol(
        e.resource.fsPath,
        deletedPath,
        !$n
        /* ignorecase */
      ))) {
        return false;
      }
      deletedPaths.push(e.resource.fsPath);
      return true;
    }).concat(addOrChangeEvents);
  }
};
function $wr(event, filter) {
  if (typeof filter === "number") {
    switch (event.type) {
      case 1:
        return (filter & 4) === 0;
      case 2:
        return (filter & 8) === 0;
      case 0:
        return (filter & 2) === 0;
    }
  }
  return false;
}
function $xr(filter) {
  if (typeof filter === "number") {
    const filters = [];
    if (filter & 4) {
      filters.push("Added");
    }
    if (filter & 8) {
      filters.push("Deleted");
    }
    if (filter & 2) {
      filters.push("Updated");
    }
    if (filters.length === 0) {
      return "<all>";
    }
    return `[${filters.join(", ")}]`;
  }
  return "<none>";
}

// out-build/vs/platform/files/common/diskFileSystemProviderClient.js
var $rS = "localFilesystem";

// out-build/vs/platform/files/electron-main/diskFileSystemProviderServer.js
import { shell } from "electron";

// out-build/vs/platform/files/node/diskFileSystemProvider.js
import { promises as promises8 } from "fs";

// out-build/vs/platform/files/common/io.js
async function $lr(provider, resource, target, transformer, options, token) {
  let error = void 0;
  try {
    await doReadFileIntoStream(provider, resource, target, transformer, options, token);
  } catch (err) {
    error = err;
  } finally {
    if (error && options.errorTransformer) {
      error = options.errorTransformer(error);
    }
    if (typeof error !== "undefined") {
      target.error(error);
    }
    target.end();
  }
}
async function doReadFileIntoStream(provider, resource, target, transformer, options, token) {
  throwIfCancelled(token);
  const handle = await provider.open(resource, { create: false });
  try {
    throwIfCancelled(token);
    let totalBytesRead = 0;
    let bytesRead = 0;
    let allowedRemainingBytes = options && typeof options.length === "number" ? options.length : void 0;
    let buffer = $7e.alloc(Math.min(options.bufferSize, typeof allowedRemainingBytes === "number" ? allowedRemainingBytes : options.bufferSize));
    let posInFile = options && typeof options.position === "number" ? options.position : 0;
    let posInBuffer = 0;
    do {
      bytesRead = await provider.read(handle, posInFile, buffer.buffer, posInBuffer, buffer.byteLength - posInBuffer);
      posInFile += bytesRead;
      posInBuffer += bytesRead;
      totalBytesRead += bytesRead;
      if (typeof allowedRemainingBytes === "number") {
        allowedRemainingBytes -= bytesRead;
      }
      if (posInBuffer === buffer.byteLength) {
        await target.write(transformer(buffer));
        buffer = $7e.alloc(Math.min(options.bufferSize, typeof allowedRemainingBytes === "number" ? allowedRemainingBytes : options.bufferSize));
        posInBuffer = 0;
      }
    } while (bytesRead > 0 && (typeof allowedRemainingBytes !== "number" || allowedRemainingBytes > 0) && throwIfCancelled(token) && throwIfTooLarge(totalBytesRead, options));
    if (posInBuffer > 0) {
      let lastChunkLength = posInBuffer;
      if (typeof allowedRemainingBytes === "number") {
        lastChunkLength = Math.min(posInBuffer, allowedRemainingBytes);
      }
      target.write(transformer(buffer.slice(0, lastChunkLength)));
    }
  } catch (error) {
    throw $Il(error);
  } finally {
    await provider.close(handle);
  }
}
function throwIfCancelled(token) {
  if (token.isCancellationRequested) {
    throw $gb();
  }
  return true;
}
function throwIfTooLarge(totalBytesRead, options) {
  if (typeof options?.limits?.size === "number" && totalBytesRead > options.limits.size) {
    throw $Hl(localize(1912, null), FileSystemProviderErrorCode.FileTooLarge);
  }
  return true;
}

// out-build/vs/platform/files/common/diskFileSystemProvider.js
var $yr = class extends $0c {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.c = this.B(new $De());
    this.onDidChangeFile = this.c.event;
    this.g = this.B(new $De());
    this.onDidWatchError = this.g.event;
    this.j = [];
    this.m = this.B(new $Xh(0));
    this.y = [];
    this.z = this.B(new $Xh(0));
  }
  watch(resource, opts) {
    if (opts.recursive || this.b?.watcher?.forceUniversal) {
      return this.n(resource, opts);
    }
    return this.C(resource, opts);
  }
  n(resource, opts) {
    const request = this.r(resource, opts);
    const remove = $5b(this.j, request);
    this.s();
    return $8c(() => {
      remove();
      this.s();
    });
  }
  r(resource, opts) {
    const request = {
      path: this.L(resource),
      excludes: opts.excludes,
      includes: opts.includes,
      recursive: opts.recursive,
      filter: opts.filter,
      correlationId: opts.correlationId
    };
    if ($or(request)) {
      const usePolling = this.b?.watcher?.recursive?.usePolling;
      if (usePolling === true) {
        request.pollingInterval = this.b?.watcher?.recursive?.pollingInterval ?? 5e3;
      } else if (Array.isArray(usePolling)) {
        if (usePolling.includes(request.path)) {
          request.pollingInterval = this.b?.watcher?.recursive?.pollingInterval ?? 5e3;
        }
      }
    }
    return request;
  }
  s() {
    this.m.trigger(() => {
      return this.t();
    }).catch((error) => $ab(error));
  }
  t() {
    if (!this.h) {
      this.h = this.B(this.u((changes) => this.c.fire($sr(changes)), (msg) => this.H(msg), this.a.getLevel() === LogLevel.Trace));
      this.B(this.a.onDidChangeLogLevel(() => {
        this.h?.setVerboseLogging(this.a.getLevel() === LogLevel.Trace);
      }));
    }
    return this.h.watch(this.j);
  }
  C(resource, opts) {
    const request = {
      path: this.L(resource),
      excludes: opts.excludes,
      includes: opts.includes,
      recursive: false,
      filter: opts.filter,
      correlationId: opts.correlationId
    };
    const remove = $5b(this.y, request);
    this.D();
    return $8c(() => {
      remove();
      this.D();
    });
  }
  D() {
    this.z.trigger(() => {
      return this.F();
    }).catch((error) => $ab(error));
  }
  F() {
    if (!this.w) {
      this.w = this.B(this.G((changes) => this.c.fire($sr(changes)), (msg) => this.H(msg), this.a.getLevel() === LogLevel.Trace));
      this.B(this.a.onDidChangeLogLevel(() => {
        this.w?.setVerboseLogging(this.a.getLevel() === LogLevel.Trace);
      }));
    }
    return this.w.watch(this.y);
  }
  //#endregion
  H(msg) {
    if (msg.type === "error") {
      this.g.fire(msg.message);
    }
    this.I(msg);
  }
  I(msg) {
    this.a[msg.type](msg.message);
  }
  J(resource) {
    return $tc(resource.fsPath);
  }
  L(resource) {
    const filePath = this.J(resource);
    return $2g(filePath);
  }
};

// out-build/vs/base/parts/ipc/node/ipc.cp.js
import { fork } from "child_process";

// out-build/vs/base/common/console.js
function $zr(obj) {
  const entry = obj;
  return entry && typeof entry.type === "string" && typeof entry.severity === "string";
}
function $Ar(entry) {
  const args = [];
  let stack;
  try {
    const parsedArguments = JSON.parse(entry.arguments);
    const stackArgument = parsedArguments[parsedArguments.length - 1];
    if (stackArgument && stackArgument.__$stack) {
      parsedArguments.pop();
      stack = stackArgument.__$stack;
    }
    args.push(...parsedArguments);
  } catch (error) {
    args.push("Unable to log remote console arguments", entry.arguments);
  }
  return { args, stack };
}
function findFirstFrame(stack) {
  if (!stack) {
    return stack;
  }
  const newlineIndex = stack.indexOf("\n");
  if (newlineIndex === -1) {
    return stack;
  }
  return stack.substring(0, newlineIndex);
}
function log2(entry, label) {
  const { args, stack } = $Ar(entry);
  const isOneStringArg = typeof args[0] === "string" && args.length === 1;
  let topFrame = findFirstFrame(stack);
  if (topFrame) {
    topFrame = `(${topFrame.trim()})`;
  }
  let consoleArgs = [];
  if (typeof args[0] === "string") {
    if (topFrame && isOneStringArg) {
      consoleArgs = [`%c[${label}] %c${args[0]} %c${topFrame}`, color("blue"), color(""), color("grey")];
    } else {
      consoleArgs = [`%c[${label}] %c${args[0]}`, color("blue"), color(""), ...args.slice(1)];
    }
  } else {
    consoleArgs = [`%c[${label}]%`, color("blue"), ...args];
  }
  if (topFrame && !isOneStringArg) {
    consoleArgs.push(topFrame);
  }
  if (typeof console[entry.severity] !== "function") {
    throw new Error("Unknown console method");
  }
  console[entry.severity].apply(console, consoleArgs);
}
function color(color2) {
  return `color: ${color2}`;
}

// out-build/vs/base/parts/ipc/node/ipc.cp.js
var $Er = class {
  constructor(i, j) {
    this.i = i;
    this.j = j;
    this.c = /* @__PURE__ */ new Set();
    this.g = /* @__PURE__ */ new Map();
    this.h = new $De();
    this.onDidProcessExit = this.h.event;
    const timeout = j && j.timeout ? j.timeout : 6e4;
    this.b = new $Wh(timeout);
    this.d = null;
    this.f = null;
  }
  getChannel(channelName) {
    const that = this;
    return {
      call(command, arg, cancellationToken) {
        return that.k(channelName, command, arg, cancellationToken);
      },
      listen(event, arg) {
        return that.l(channelName, event, arg);
      }
    };
  }
  k(channelName, name, arg, cancellationToken = CancellationToken.None) {
    if (!this.b) {
      return Promise.reject(new Error("disposed"));
    }
    if (cancellationToken.isCancellationRequested) {
      return Promise.reject($gb());
    }
    this.b.cancel();
    const channel = this.n(channelName);
    const result = $Mh((token) => channel.call(name, arg, token));
    const cancellationTokenListener = cancellationToken.onCancellationRequested(() => result.cancel());
    const disposable = $8c(() => result.cancel());
    this.c.add(disposable);
    result.finally(() => {
      cancellationTokenListener.dispose();
      this.c.delete(disposable);
      if (this.c.size === 0 && this.b) {
        this.b.trigger(() => this.o());
      }
    });
    return result;
  }
  l(channelName, name, arg) {
    if (!this.b) {
      return Event.None;
    }
    this.b.cancel();
    let listener;
    const emitter = new $De({
      onWillAddFirstListener: () => {
        const channel = this.n(channelName);
        const event = channel.listen(name, arg);
        listener = event(emitter.fire, emitter);
        this.c.add(listener);
      },
      onDidRemoveLastListener: () => {
        this.c.delete(listener);
        listener.dispose();
        if (this.c.size === 0 && this.b) {
          this.b.trigger(() => this.o());
        }
      }
    });
    return emitter.event;
  }
  get m() {
    if (!this.f) {
      const args = this.j && this.j.args ? this.j.args : [];
      const forkOpts = /* @__PURE__ */ Object.create(null);
      forkOpts.env = { ...$zo(process.env), "VSCODE_PARENT_PID": String(process.pid) };
      if (this.j && this.j.env) {
        forkOpts.env = { ...forkOpts.env, ...this.j.env };
      }
      if (this.j && this.j.freshExecArgv) {
        forkOpts.execArgv = [];
      }
      if (this.j && typeof this.j.debug === "number") {
        forkOpts.execArgv = ["--nolazy", "--inspect=" + this.j.debug];
      }
      if (this.j && typeof this.j.debugBrk === "number") {
        forkOpts.execArgv = ["--nolazy", "--inspect-brk=" + this.j.debugBrk];
      }
      if (forkOpts.execArgv === void 0) {
        forkOpts.execArgv = process.execArgv.filter((a) => !/^--inspect(-brk)?=/.test(a)).filter((a) => !a.startsWith("--vscode-"));
      }
      $Gm(forkOpts.env);
      this.d = fork(this.i, args, forkOpts);
      const onMessageEmitter = new $De();
      const onRawMessage = Event.fromNodeEventEmitter(this.d, "message", (msg) => msg);
      const rawMessageDisposable = onRawMessage((msg) => {
        if ($zr(msg)) {
          log2(msg, `IPC Library: ${this.j.serverName}`);
          return;
        }
        onMessageEmitter.fire($7e.wrap(Buffer.from(msg, "base64")));
      });
      const sender = this.j.useQueue ? $Tm(this.d) : this.d;
      const send = (r) => this.d && this.d.connected && sender.send(r.buffer.toString("base64"));
      const onMessage = onMessageEmitter.event;
      const protocol3 = { send, onMessage };
      this.f = new $Ci(protocol3);
      const onExit = () => this.o();
      process.once("exit", onExit);
      this.d.on("error", (err) => console.warn('IPC "' + this.j.serverName + '" errored with ' + err));
      this.d.on("exit", (code2, signal) => {
        process.removeListener("exit", onExit);
        rawMessageDisposable.dispose();
        this.c.forEach((r) => $5c(r));
        this.c.clear();
        if (code2 !== 0 && signal !== "SIGTERM") {
          console.warn('IPC "' + this.j.serverName + '" crashed with exit code ' + code2 + " and signal " + signal);
        }
        this.b?.cancel();
        this.o();
        this.h.fire({ code: code2, signal });
      });
    }
    return this.f;
  }
  n(name) {
    let channel = this.g.get(name);
    if (!channel) {
      channel = this.m.getChannel(name);
      this.g.set(name, channel);
    }
    return channel;
  }
  o() {
    if (this.f) {
      if (this.d) {
        this.d.kill();
        this.d = null;
      }
      this.f = null;
      this.g.clear();
    }
  }
  dispose() {
    this.h.dispose();
    this.b?.cancel();
    this.b = void 0;
    this.o();
    this.c.clear();
  }
};

// out-build/vs/platform/files/node/watcher/watcherClient.js
var $Fr = class extends $rr {
  constructor(onFileChanges, onLogMessage, verboseLogging) {
    super(onFileChanges, onLogMessage, verboseLogging);
    this.s();
  }
  r(disposables) {
    const client = disposables.add(new $Er($hh.asFileUri("bootstrap-fork").fsPath, {
      serverName: "File Watcher",
      args: ["--type=fileWatcher"],
      env: {
        VSCODE_AMD_ENTRYPOINT: "vs/platform/files/node/watcher/watcherMain",
        VSCODE_PIPE_LOGGING: "true",
        VSCODE_VERBOSE_LOGGING: "true"
        // transmit console logs from server to client
      }
    }));
    disposables.add(client.onDidProcessExit(({ code: code2, signal }) => this.t(`terminated by itself with code ${code2}, signal: ${signal} (ETERM)`)));
    return ProxyChannel.toService($Gi(client.getChannel("watcher")));
  }
};

// out-build/vs/platform/files/node/watcher/baseWatcher.js
import { watchFile, unwatchFile } from "fs";
var $Gr = class extends $0c {
  constructor() {
    super();
    this.a = this.B(new $De());
    this.onDidChangeFile = this.a.event;
    this.b = this.B(new $De());
    this.onDidLogMessage = this.b.event;
    this.c = this.B(new $De());
    this.f = this.c.event;
    this.g = /* @__PURE__ */ new Map();
    this.h = /* @__PURE__ */ new Map();
    this.j = this.B(new $gd());
    this.m = /* @__PURE__ */ new Set();
    this.n = this.B(new $Xh(this.y()));
    this.r = 5007;
    this.s = new $ki();
    this.R = false;
    this.B(this.f((request) => this.z({
      id: this.u(request),
      correlationId: this.t(request) ? request.correlationId : void 0,
      path: request.path
    })));
  }
  t(request) {
    return $nr(request);
  }
  u(request) {
    if (this.t(request)) {
      return request.correlationId;
    } else {
      return $Nj(request);
    }
  }
  async watch(requests) {
    if (!this.s.isSettled) {
      this.s.complete();
    }
    this.s = new $ki();
    try {
      this.g.clear();
      this.h.clear();
      for (const request of requests) {
        if (this.t(request)) {
          this.g.set(request.correlationId, request);
        } else {
          this.h.set(this.u(request), request);
        }
      }
      for (const [id2] of this.j) {
        if (!this.h.has(id2) && !this.g.has(id2)) {
          this.j.deleteAndDispose(id2);
          this.m.delete(id2);
        }
      }
      return await this.w(
        false
        /* not delayed */
      );
    } finally {
      this.s.complete();
    }
  }
  w(delayed) {
    const nonSuspendedRequests = [];
    for (const [id2, request] of [...this.h, ...this.g]) {
      if (!this.j.has(id2)) {
        nonSuspendedRequests.push(request);
      }
    }
    return this.n.trigger(() => this.N(nonSuspendedRequests), delayed ? this.y() : 0);
  }
  y() {
    return 800;
  }
  isSuspended(request) {
    const id2 = this.u(request);
    return this.m.has(id2) ? "polling" : this.j.has(id2);
  }
  async z(request) {
    if (this.j.has(request.id)) {
      return;
    }
    const disposables = new $9c();
    this.j.set(request.id, disposables);
    await this.s.p;
    if (disposables.isDisposed) {
      return;
    }
    this.D(request, disposables);
    this.w(
      true
      /* delay this call as we might accumulate many failing watch requests on startup */
    );
  }
  C(request) {
    this.j.deleteAndDispose(request.id);
    this.m.delete(request.id);
    this.w(false);
  }
  D(request, disposables) {
    if (this.F(request, disposables)) {
      this.P(`reusing an existing recursive watcher to monitor ${request.path}`);
      this.m.delete(request.id);
    } else {
      this.G(request, disposables);
      this.m.add(request.id);
    }
  }
  F(request, disposables) {
    const subscription = this.O?.subscribe(request.path, (error, change) => {
      if (disposables.isDisposed) {
        return;
      }
      if (error) {
        this.D(request, disposables);
      } else if (change?.type === 1) {
        this.H(request);
      }
    });
    if (subscription) {
      disposables.add(subscription);
      return true;
    }
    return false;
  }
  G(request, disposables) {
    let pathNotFound = false;
    const watchFileCallback = (curr, prev) => {
      if (disposables.isDisposed) {
        return;
      }
      const currentPathNotFound = this.I(curr);
      const previousPathNotFound = this.I(prev);
      const oldPathNotFound = pathNotFound;
      pathNotFound = currentPathNotFound;
      if (!currentPathNotFound && (previousPathNotFound || oldPathNotFound)) {
        this.H(request);
      }
    };
    this.P(`starting fs.watchFile() on ${request.path} (correlationId: ${request.correlationId})`);
    try {
      watchFile(request.path, { persistent: false, interval: this.r }, watchFileCallback);
    } catch (error) {
      this.Q(`fs.watchFile() failed with error ${error} on path ${request.path} (correlationId: ${request.correlationId})`);
    }
    disposables.add($8c(() => {
      this.P(`stopping fs.watchFile() on ${request.path} (correlationId: ${request.correlationId})`);
      try {
        unwatchFile(request.path, watchFileCallback);
      } catch (error) {
        this.Q(`fs.unwatchFile() failed with error ${error} on path ${request.path} (correlationId: ${request.correlationId})`);
      }
    }));
  }
  H(request) {
    this.P(`detected ${request.path} exists again, resuming watcher (correlationId: ${request.correlationId})`);
    const event = { resource: URI.file(request.path), type: 1, cId: request.correlationId };
    this.a.fire([event]);
    this.J(event, request);
    this.C(request);
  }
  I(stats) {
    return stats.ctimeMs === 0 && stats.ino === 0;
  }
  async stop() {
    this.j.clearAndDisposeAll();
    this.m.clear();
  }
  J(event, request) {
    if (this.R) {
      const traceMsg = ` >> normalized ${event.type === 1 ? "[ADDED]" : event.type === 2 ? "[DELETED]" : "[CHANGED]"} ${event.resource.fsPath}`;
      this.L(traceMsg, request);
    }
  }
  L(message, request) {
    if (this.R) {
      this.P(`${message}${typeof request.correlationId === "number" ? ` <${request.correlationId}> ` : ``}`);
    }
  }
  M(request) {
    return `${request.path} (excludes: ${request.excludes.length > 0 ? request.excludes : "<none>"}, includes: ${request.includes && request.includes.length > 0 ? JSON.stringify(request.includes) : "<all>"}, filter: ${$xr(request.filter)}, correlationId: ${typeof request.correlationId === "number" ? request.correlationId : "<none>"})`;
  }
  async setVerboseLogging(enabled) {
    this.R = enabled;
  }
};

// out-build/vs/platform/files/node/watcher/nodejs/nodejsWatcherLib.js
import { watch, promises as promises7 } from "fs";

// out-build/vs/base/node/extpath.js
import * as fs5 from "fs";
async function $Ir(path3, token) {
  if ($n) {
    return path3;
  }
  const dir = $yc(path3);
  if (path3 === dir) {
    return path3;
  }
  const name = ($zc(path3) || path3).toLowerCase();
  try {
    if (token?.isCancellationRequested) {
      return null;
    }
    const entries = await Promises2.readdir(dir);
    const found = entries.filter((e) => e.toLowerCase() === name);
    if (found.length === 1) {
      const prefix = await $Ir(dir, token);
      if (prefix) {
        return $vc(prefix, found[0]);
      }
    } else if (found.length > 1) {
      const ix = found.indexOf(name);
      if (ix >= 0) {
        const prefix = await $Ir(dir, token);
        if (prefix) {
          return $vc(prefix, found[ix]);
        }
      }
    }
  } catch (error) {
  }
  return null;
}
async function $Jr(path3) {
  try {
    return await Promises2.realpath(path3);
  } catch (error) {
    const normalizedPath = normalizePath(path3);
    await fs5.promises.access(normalizedPath, fs5.constants.R_OK);
    return normalizedPath;
  }
}
function normalizePath(path3) {
  return $Gf($tc(path3), sep);
}

// out-build/vs/platform/files/node/watcher/nodejs/nodejsWatcherLib.js
var $Lr = class _$Lr extends $0c {
  static {
    this.a = 100;
  }
  static {
    this.b = 75;
  }
  get isReusingRecursiveWatcher() {
    return this.n;
  }
  get failed() {
    return this.r;
  }
  constructor(s, t, u, w, y, z) {
    super();
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.c = this.B(new $ci({
      maxWorkChunkSize: 100,
      // only process up to 100 changes at once before...
      throttleDelay: 200,
      // ...resting for 200ms until we process events again...
      maxBufferedWork: 1e4
      // ...but never buffering more than 10000 events in memory
    }, (events) => this.u(events)));
    this.f = this.B(new $bi((events) => this.M(events), _$Lr.b));
    this.g = $vr(this.s.path, this.s.excludes);
    this.h = this.s.includes ? $vr(this.s.path, this.s.includes) : void 0;
    this.j = $nr(this.s) ? this.s.filter : void 0;
    this.m = new $Pe();
    this.ready = this.C();
    this.n = false;
    this.r = false;
  }
  async C() {
    try {
      const realPath = await this.F(this.s);
      if (this.m.token.isCancellationRequested) {
        return;
      }
      const stat = await promises7.stat(realPath);
      if (this.m.token.isCancellationRequested) {
        return;
      }
      this.B(await this.G(realPath, stat.isDirectory()));
    } catch (error) {
      if (error.code !== "ENOENT") {
        this.O(error);
      } else {
        this.Q(`ignoring a path for watching who's stat info failed to resolve: ${this.s.path} (error: ${error})`);
      }
      this.D();
    }
  }
  D() {
    this.r = true;
    this.w?.();
  }
  async F(request) {
    let realPath = request.path;
    try {
      realPath = await Promises2.realpath(request.path);
      if (request.path === realPath) {
        realPath = await $Ir(request.path, this.m.token) ?? request.path;
      }
      if (request.path !== realPath) {
        this.Q(`correcting a path to watch that seems to be a symbolic link or wrong casing (original: ${request.path}, real: ${realPath})`);
      }
    } catch (error) {
    }
    return realPath;
  }
  async G(realPath, isDirectory) {
    const disposables = new $9c();
    if (this.H(realPath, isDirectory, disposables)) {
      this.Q(`reusing an existing recursive watcher for ${this.s.path}`);
      this.n = true;
    } else {
      this.n = false;
      await this.I(realPath, isDirectory, disposables);
    }
    return disposables;
  }
  H(realPath, isDirectory, disposables) {
    if (isDirectory) {
      return false;
    }
    const resource = URI.file(this.s.path);
    const subscription = this.t?.subscribe(this.s.path, async (error, change) => {
      if (disposables.isDisposed) {
        return;
      }
      if (error) {
        const watchDisposable = await this.G(realPath, isDirectory);
        if (!disposables.isDisposed) {
          disposables.add(watchDisposable);
        } else {
          watchDisposable.dispose();
        }
      } else if (change) {
        if (typeof change.cId === "number" || typeof this.s.correlationId === "number") {
          this.L(
            { resource, type: change.type, cId: this.s.correlationId },
            true
            /* skip excludes/includes (file is explicitly watched) */
          );
        }
      }
    });
    if (subscription) {
      disposables.add(subscription);
      return true;
    }
    return false;
  }
  async I(realPath, isDirectory, disposables) {
    if ($m && $Yg(realPath, "/Volumes/", true)) {
      this.O(`Refusing to watch ${realPath} for changes using fs.watch() for possibly being a network share where watching is unreliable and unstable.`);
      return;
    }
    const cts = new $Pe(this.m.token);
    disposables.add($8c(() => cts.dispose(true)));
    const watcherDisposables = new $9c();
    disposables.add(watcherDisposables);
    try {
      const requestResource = URI.file(this.s.path);
      const pathBasename = $zc(realPath);
      const watcher = watch(realPath);
      watcherDisposables.add($8c(() => {
        watcher.removeAllListeners();
        watcher.close();
      }));
      this.Q(`Started watching: '${realPath}'`);
      const folderChildren = /* @__PURE__ */ new Set();
      if (isDirectory) {
        try {
          for (const child of await Promises2.readdir(realPath)) {
            folderChildren.add(child);
          }
        } catch (error) {
          this.O(error);
        }
      }
      if (cts.token.isCancellationRequested) {
        return;
      }
      const mapPathToStatDisposable = /* @__PURE__ */ new Map();
      watcherDisposables.add($8c(() => {
        for (const [, disposable] of mapPathToStatDisposable) {
          disposable.dispose();
        }
        mapPathToStatDisposable.clear();
      }));
      watcher.on("error", (code2, signal) => {
        if (cts.token.isCancellationRequested) {
          return;
        }
        this.O(`Failed to watch ${realPath} for changes using fs.watch() (${code2}, ${signal})`);
        this.D();
      });
      watcher.on("change", (type4, raw) => {
        if (cts.token.isCancellationRequested) {
          return;
        }
        if (this.z) {
          this.R(`[raw] ["${type4}"] ${raw}`);
        }
        let changedFileName = "";
        if (raw) {
          changedFileName = raw.toString();
          if ($m) {
            changedFileName = $Hm(changedFileName);
          }
        }
        if (!changedFileName || type4 !== "change" && type4 !== "rename") {
          return;
        }
        if (isDirectory) {
          if (type4 === "rename") {
            mapPathToStatDisposable.get(changedFileName)?.dispose();
            const timeoutHandle = setTimeout(async () => {
              mapPathToStatDisposable.delete(changedFileName);
              if (changedFileName === pathBasename && !await Promises2.exists(realPath)) {
                this.J(requestResource);
                return;
              }
              if (cts.token.isCancellationRequested) {
                return;
              }
              const fileExists = await this.N($vc(realPath, changedFileName));
              if (cts.token.isCancellationRequested) {
                return;
              }
              let type5;
              if (fileExists) {
                if (folderChildren.has(changedFileName)) {
                  type5 = 0;
                } else {
                  type5 = 1;
                  folderChildren.add(changedFileName);
                }
              } else {
                folderChildren.delete(changedFileName);
                type5 = 2;
              }
              this.L({ resource: $Ah(requestResource, changedFileName), type: type5, cId: this.s.correlationId });
            }, _$Lr.a);
            mapPathToStatDisposable.set(changedFileName, $8c(() => clearTimeout(timeoutHandle)));
          } else {
            let type5;
            if (folderChildren.has(changedFileName)) {
              type5 = 0;
            } else {
              type5 = 1;
              folderChildren.add(changedFileName);
            }
            this.L({ resource: $Ah(requestResource, changedFileName), type: type5, cId: this.s.correlationId });
          }
        } else {
          if (type4 === "rename" || changedFileName !== pathBasename) {
            const timeoutHandle = setTimeout(async () => {
              const fileExists = await Promises2.exists(realPath);
              if (cts.token.isCancellationRequested) {
                return;
              }
              if (fileExists) {
                this.L(
                  { resource: requestResource, type: 0, cId: this.s.correlationId },
                  true
                  /* skip excludes/includes (file is explicitly watched) */
                );
                watcherDisposables.add(await this.G(realPath, false));
              } else {
                this.J(requestResource);
              }
            }, _$Lr.a);
            watcherDisposables.clear();
            watcherDisposables.add($8c(() => clearTimeout(timeoutHandle)));
          } else {
            this.L(
              { resource: requestResource, type: 0, cId: this.s.correlationId },
              true
              /* skip excludes/includes (file is explicitly watched) */
            );
          }
        }
      });
    } catch (error) {
      if (!cts.token.isCancellationRequested) {
        this.O(`Failed to watch ${realPath} for changes using fs.watch() (${error.toString()})`);
      }
      this.D();
    }
  }
  J(resource) {
    this.P("Watcher shutdown because watched path got deleted");
    this.L(
      { resource, type: 2, cId: this.s.correlationId },
      true
      /* skip excludes/includes (file is explicitly watched) */
    );
    this.f.flush();
    this.D();
  }
  L(event, skipIncludeExcludeChecks = false) {
    if (this.m.token.isCancellationRequested) {
      return;
    }
    if (this.z) {
      this.R(`${event.type === 1 ? "[ADDED]" : event.type === 2 ? "[DELETED]" : "[CHANGED]"} ${event.resource.fsPath}`);
    }
    if (!skipIncludeExcludeChecks && this.g.some((exclude) => exclude(event.resource.fsPath))) {
      if (this.z) {
        this.R(` >> ignored (excluded) ${event.resource.fsPath}`);
      }
    } else if (!skipIncludeExcludeChecks && this.h && this.h.length > 0 && !this.h.some((include) => include(event.resource.fsPath))) {
      if (this.z) {
        this.R(` >> ignored (not included) ${event.resource.fsPath}`);
      }
    } else {
      this.f.work(event);
    }
  }
  M(fileChanges) {
    const coalescedFileChanges = $tr(fileChanges);
    const filteredEvents = [];
    for (const event of coalescedFileChanges) {
      if ($wr(event, this.j)) {
        if (this.z) {
          this.R(` >> ignored (filtered) ${event.resource.fsPath}`);
        }
        continue;
      }
      filteredEvents.push(event);
    }
    if (filteredEvents.length === 0) {
      return;
    }
    if (this.z) {
      for (const event of filteredEvents) {
        this.R(` >> normalized ${event.type === 1 ? "[ADDED]" : event.type === 2 ? "[DELETED]" : "[CHANGED]"} ${event.resource.fsPath}`);
      }
    }
    const worked = this.c.work(filteredEvents);
    if (!worked) {
      this.P(`started ignoring events due to too many file change events at once (incoming: ${filteredEvents.length}, most recent change: ${filteredEvents[0].resource.fsPath}). Use 'files.watcherExclude' setting to exclude folders with lots of changing files (e.g. compilation output).`);
    } else {
      if (this.c.pending > 0) {
        this.Q(`started throttling events due to large amount of file change events at once (pending: ${this.c.pending}, most recent change: ${filteredEvents[0].resource.fsPath}). Use 'files.watcherExclude' setting to exclude folders with lots of changing files (e.g. compilation output).`);
      }
    }
  }
  async N(path3) {
    if ($n) {
      return Promises2.exists(path3);
    }
    try {
      const pathBasename = $zc(path3);
      const children = await Promises2.readdir($yc(path3));
      return children.some((child) => child === pathBasename);
    } catch (error) {
      this.Q(error);
      return false;
    }
  }
  setVerboseLogging(verboseLogging) {
    this.z = verboseLogging;
  }
  O(error) {
    if (!this.m.token.isCancellationRequested) {
      this.y?.({ type: "error", message: `[File Watcher (node.js)] ${error}` });
    }
  }
  P(message) {
    if (!this.m.token.isCancellationRequested) {
      this.y?.({ type: "warn", message: `[File Watcher (node.js)] ${message}` });
    }
  }
  Q(message) {
    if (!this.m.token.isCancellationRequested && this.z) {
      this.y?.({ type: "trace", message: `[File Watcher (node.js)] ${message}` });
    }
  }
  R(message) {
    if (!this.m.token.isCancellationRequested && this.z) {
      this.Q(`${message}${typeof this.s.correlationId === "number" ? ` <${this.s.correlationId}> ` : ``}`);
    }
  }
  dispose() {
    this.m.dispose(true);
    super.dispose();
  }
};

// out-build/vs/platform/files/node/watcher/nodejs/nodejsWatcher.js
var $Nr = class extends $Gr {
  constructor(O) {
    super();
    this.O = O;
    this.onDidError = Event.None;
    this.watchers = /* @__PURE__ */ new Set();
  }
  async N(requests) {
    requests = this.Z(requests);
    const requestsToStart = [];
    const watchersToStop = new Set(Array.from(this.watchers));
    for (const request of requests) {
      const watcher = this.W(request);
      if (watcher && $Yk(watcher.request.excludes, request.excludes) && $Yk(watcher.request.includes, request.includes)) {
        watchersToStop.delete(watcher);
      } else {
        requestsToStart.push(request);
      }
    }
    if (requestsToStart.length) {
      this.P(`Request to start watching: ${requestsToStart.map((request) => this.M(request)).join(",")}`);
    }
    if (watchersToStop.size) {
      this.P(`Request to stop watching: ${Array.from(watchersToStop).map((watcher) => this.M(watcher.request)).join(",")}`);
    }
    for (const watcher of watchersToStop) {
      this.Y(watcher);
    }
    for (const request of requestsToStart) {
      this.X(request);
    }
  }
  W(request) {
    for (const watcher of this.watchers) {
      if (typeof request.correlationId === "number" || typeof watcher.request.correlationId === "number") {
        if (watcher.request.correlationId === request.correlationId) {
          return watcher;
        }
      } else {
        if ($Xg(
          watcher.request.path,
          request.path,
          !$n
          /* ignorecase */
        )) {
          return watcher;
        }
      }
    }
    return void 0;
  }
  X(request) {
    const instance = new $Lr(request, this.O, (changes) => this.a.fire(changes), () => this.c.fire(request), (msg) => this.b.fire(msg), this.R);
    const watcher = { request, instance };
    this.watchers.add(watcher);
  }
  async stop() {
    await super.stop();
    for (const watcher of this.watchers) {
      this.Y(watcher);
    }
  }
  Y(watcher) {
    this.P(`stopping file watcher`, watcher);
    this.watchers.delete(watcher);
    watcher.instance.dispose();
  }
  Z(requests) {
    const mapCorrelationtoRequests = /* @__PURE__ */ new Map();
    for (const request of requests) {
      const path3 = $n ? request.path : request.path.toLowerCase();
      let requestsForCorrelation = mapCorrelationtoRequests.get(request.correlationId);
      if (!requestsForCorrelation) {
        requestsForCorrelation = /* @__PURE__ */ new Map();
        mapCorrelationtoRequests.set(request.correlationId, requestsForCorrelation);
      }
      if (requestsForCorrelation.has(path3)) {
        this.P(`ignoring a request for watching who's path is already watched: ${this.M(request)}`);
      }
      requestsForCorrelation.set(path3, request);
    }
    return Array.from(mapCorrelationtoRequests.values()).map((requests2) => Array.from(requests2.values())).flat();
  }
  async setVerboseLogging(enabled) {
    super.setVerboseLogging(enabled);
    for (const watcher of this.watchers) {
      watcher.instance.setVerboseLogging(enabled);
    }
  }
  P(message, watcher) {
    if (this.R) {
      this.b.fire({ type: "trace", message: this.bb(message, watcher) });
    }
  }
  Q(message) {
    this.b.fire({ type: "warn", message: this.bb(message) });
  }
  bb(message, watcher) {
    return watcher ? `[File Watcher (node.js)] ${message} (${this.M(watcher.request)})` : `[File Watcher (node.js)] ${message}`;
  }
};

// out-build/vs/platform/files/node/watcher/nodejs/nodejsClient.js
var $Or = class extends $qr {
  constructor(onFileChanges, onLogMessage, verboseLogging) {
    super(onFileChanges, onLogMessage, verboseLogging);
    this.s();
  }
  r(disposables) {
    return disposables.add(new $Nr(
      void 0
      /* no recursive watching support here */
    ));
  }
};

// out-build/vs/platform/files/node/diskFileSystemProvider.js
var $Pr = class _$Pr extends $yr {
  static {
    this.M = false;
  }
  // not enabled by default because very spammy
  constructor(logService, options) {
    super(logService, options);
    this.onDidChangeCapabilities = Event.None;
    this.Q = new $Mc((resource) => $rh.getComparisonKey(resource));
    this.Y = /* @__PURE__ */ new Map();
    this.Z = /* @__PURE__ */ new Map();
    this.$ = /* @__PURE__ */ new Map();
  }
  get capabilities() {
    if (!this.N) {
      this.N = 2 | 4 | 16 | 8 | 8192 | 16384 | 32768 | 65536 | 131072;
      if ($n) {
        this.N |= 1024;
      }
    }
    return this.N;
  }
  //#endregion
  //#region File Metadata Resolving
  async stat(resource) {
    try {
      const { stat, symbolicLink } = await SymlinkSupport.stat(this.J(resource));
      return {
        type: this.P(stat, symbolicLink),
        ctime: stat.birthtime.getTime(),
        // intentionally not using ctime here, we want the creation time
        mtime: stat.mtime.getTime(),
        size: stat.size,
        permissions: (stat.mode & 128) === 0 ? FilePermission.Locked : void 0
      };
    } catch (error) {
      throw this.ib(error);
    }
  }
  async O(resource) {
    try {
      return await this.stat(resource);
    } catch (error) {
      return void 0;
    }
  }
  async readdir(resource) {
    try {
      const children = await Promises2.readdir(this.J(resource), { withFileTypes: true });
      const result = [];
      await Promise.all(children.map(async (child) => {
        try {
          let type4;
          if (child.isSymbolicLink()) {
            type4 = (await this.stat($Ah(resource, child.name))).type;
          } else {
            type4 = this.P(child);
          }
          result.push([child.name, type4]);
        } catch (error) {
          this.a.trace(error);
        }
      }));
      return result;
    } catch (error) {
      throw this.ib(error);
    }
  }
  P(entry, symbolicLink) {
    let type4;
    if (symbolicLink?.dangling) {
      type4 = FileType.Unknown;
    } else if (entry.isFile()) {
      type4 = FileType.File;
    } else if (entry.isDirectory()) {
      type4 = FileType.Directory;
    } else {
      type4 = FileType.Unknown;
    }
    if (symbolicLink) {
      type4 |= FileType.SymbolicLink;
    }
    return type4;
  }
  async R(resource) {
    const filePath = this.J(resource);
    this.S(`[Disk FileSystemProvider]: createResourceLock() - request to acquire resource lock (${filePath})`);
    let existingLock = void 0;
    while (existingLock = this.Q.get(resource)) {
      this.S(`[Disk FileSystemProvider]: createResourceLock() - waiting for resource lock to be released (${filePath})`);
      await existingLock.wait();
    }
    const newLock = new $Yh();
    this.Q.set(resource, newLock);
    this.S(`[Disk FileSystemProvider]: createResourceLock() - new resource lock created (${filePath})`);
    return $8c(() => {
      this.S(`[Disk FileSystemProvider]: createResourceLock() - resource lock dispose() (${filePath})`);
      if (this.Q.get(resource) === newLock) {
        this.S(`[Disk FileSystemProvider]: createResourceLock() - resource lock removed from resource-lock map (${filePath})`);
        this.Q.delete(resource);
      }
      this.S(`[Disk FileSystemProvider]: createResourceLock() - resource lock barrier open() (${filePath})`);
      newLock.open();
    });
  }
  async readFile(resource, options) {
    let lock = void 0;
    try {
      if (options?.atomic) {
        this.S(`[Disk FileSystemProvider]: atomic read operation started (${this.J(resource)})`);
        lock = await this.R(resource);
      }
      const filePath = this.J(resource);
      return await promises8.readFile(filePath);
    } catch (error) {
      throw this.ib(error);
    } finally {
      lock?.dispose();
    }
  }
  S(msg) {
    if (_$Pr.M) {
      this.a.trace(msg);
    }
  }
  readFileStream(resource, opts, token) {
    const stream = $Ue((data) => $7e.concat(data.map((data2) => $7e.wrap(data2))).buffer);
    $lr(this, resource, stream, (data) => data.buffer, {
      ...opts,
      bufferSize: 256 * 1024
      // read into chunks of 256kb each to reduce IPC overhead
    }, token);
    return stream;
  }
  async writeFile(resource, content, opts) {
    if (opts?.atomic !== false && opts?.atomic?.postfix && await this.U(resource)) {
      return this.W(resource, $Ah($zh(resource), `${$xh(resource)}${opts.atomic.postfix}`), content, opts);
    } else {
      return this.X(resource, content, opts);
    }
  }
  async U(resource) {
    try {
      const filePath = this.J(resource);
      const { symbolicLink } = await SymlinkSupport.stat(filePath);
      if (symbolicLink) {
        return false;
      }
    } catch (error) {
    }
    return true;
  }
  async W(resource, tempResource, content, opts) {
    const locks = new $9c();
    try {
      locks.add(await this.R(resource));
      locks.add(await this.R(tempResource));
      await this.X(
        tempResource,
        content,
        opts,
        true
        /* disable write lock */
      );
      try {
        await this.rename(tempResource, resource, { overwrite: true });
      } catch (error) {
        try {
          await this.delete(tempResource, { recursive: false, useTrash: false, atomic: false });
        } catch (error2) {
        }
        throw error;
      }
    } finally {
      locks.dispose();
    }
  }
  async X(resource, content, opts, disableWriteLock) {
    let handle = void 0;
    try {
      const filePath = this.J(resource);
      if (!opts.create || !opts.overwrite) {
        const fileExists = await Promises2.exists(filePath);
        if (fileExists) {
          if (!opts.overwrite) {
            throw $Hl(localize(1915, null), FileSystemProviderErrorCode.FileExists);
          }
        } else {
          if (!opts.create) {
            throw $Hl(localize(1916, null), FileSystemProviderErrorCode.FileNotFound);
          }
        }
      }
      handle = await this.open(resource, { create: true, unlock: opts.unlock }, disableWriteLock);
      await this.write(handle, 0, content, 0, content.byteLength);
    } catch (error) {
      throw await this.jb(resource, error);
    } finally {
      if (typeof handle === "number") {
        await this.close(handle);
      }
    }
  }
  static {
    this.ab = true;
  }
  static configureFlushOnWrite(enabled) {
    _$Pr.ab = enabled;
  }
  async open(resource, opts, disableWriteLock) {
    const filePath = this.J(resource);
    let lock = void 0;
    if ($vl(opts) && !disableWriteLock) {
      lock = await this.R(resource);
    }
    let fd = void 0;
    try {
      if ($vl(opts) && opts.unlock) {
        try {
          const { stat } = await SymlinkSupport.stat(filePath);
          if (!(stat.mode & 128)) {
            await promises8.chmod(filePath, stat.mode | 128);
          }
        } catch (error) {
          if (error.code !== "ENOENT") {
            this.a.trace(error);
          }
        }
      }
      let flags = void 0;
      if ($vl(opts)) {
        if ($l) {
          try {
            await promises8.truncate(filePath, 0);
            flags = "r+";
          } catch (error) {
            if (error.code !== "ENOENT") {
              this.a.trace(error);
            }
          }
        }
        if (!flags) {
          flags = "w";
        }
      } else {
        flags = "r";
      }
      fd = await Promises2.open(filePath, flags);
    } catch (error) {
      lock?.dispose();
      if ($vl(opts)) {
        throw await this.jb(resource, error);
      } else {
        throw this.ib(error);
      }
    }
    this.Y.set(fd, 0);
    if ($vl(opts)) {
      this.$.set(fd, resource);
    }
    if (lock) {
      const previousLock = this.Z.get(fd);
      this.S(`[Disk FileSystemProvider]: open() - storing lock for handle ${fd} (${filePath})`);
      this.Z.set(fd, lock);
      if (previousLock) {
        this.S(`[Disk FileSystemProvider]: open() - disposing a previous lock that was still stored on same handle ${fd} (${filePath})`);
        previousLock.dispose();
      }
    }
    return fd;
  }
  async close(fd) {
    const lockForHandle = this.Z.get(fd);
    try {
      this.Y.delete(fd);
      if (this.$.delete(fd) && _$Pr.ab) {
        try {
          await Promises2.fdatasync(fd);
        } catch (error) {
          _$Pr.configureFlushOnWrite(false);
          this.a.error(error);
        }
      }
      return await Promises2.close(fd);
    } catch (error) {
      throw this.ib(error);
    } finally {
      if (lockForHandle) {
        if (this.Z.get(fd) === lockForHandle) {
          this.S(`[Disk FileSystemProvider]: close() - resource lock removed from handle-lock map ${fd}`);
          this.Z.delete(fd);
        }
        this.S(`[Disk FileSystemProvider]: close() - disposing lock for handle ${fd}`);
        lockForHandle.dispose();
      }
    }
  }
  async read(fd, pos, data, offset, length) {
    const normalizedPos = this.bb(fd, pos);
    let bytesRead = null;
    try {
      bytesRead = (await Promises2.read(fd, data, offset, length, normalizedPos)).bytesRead;
    } catch (error) {
      throw this.ib(error);
    } finally {
      this.cb(fd, normalizedPos, bytesRead);
    }
    return bytesRead;
  }
  bb(fd, pos) {
    if (pos === this.Y.get(fd)) {
      return null;
    }
    return pos;
  }
  cb(fd, pos, bytesLength) {
    const lastKnownPos = this.Y.get(fd);
    if (typeof lastKnownPos === "number") {
      if (typeof pos === "number") {
      } else if (typeof bytesLength === "number") {
        this.Y.set(fd, lastKnownPos + bytesLength);
      } else {
        this.Y.delete(fd);
      }
    }
  }
  async write(fd, pos, data, offset, length) {
    return $hi(
      () => this.db(fd, pos, data, offset, length),
      100,
      3
      /* retries */
    );
  }
  async db(fd, pos, data, offset, length) {
    const normalizedPos = this.bb(fd, pos);
    let bytesWritten = null;
    try {
      bytesWritten = (await Promises2.write(fd, data, offset, length, normalizedPos)).bytesWritten;
    } catch (error) {
      throw await this.jb(this.$.get(fd), error);
    } finally {
      this.cb(fd, normalizedPos, bytesWritten);
    }
    return bytesWritten;
  }
  //#endregion
  //#region Move/Copy/Delete/Create Folder
  async mkdir(resource) {
    try {
      await promises8.mkdir(this.J(resource));
    } catch (error) {
      throw this.ib(error);
    }
  }
  async delete(resource, opts) {
    try {
      const filePath = this.J(resource);
      if (opts.recursive) {
        let rmMoveToPath = void 0;
        if (opts?.atomic !== false && opts.atomic.postfix) {
          rmMoveToPath = $vc($yc(filePath), `${$zc(filePath)}${opts.atomic.postfix}`);
        }
        await Promises2.rm(filePath, RimRafMode.MOVE, rmMoveToPath);
      } else {
        try {
          await promises8.unlink(filePath);
        } catch (unlinkError) {
          if (unlinkError.code === "EPERM" || unlinkError.code === "EISDIR") {
            let isDirectory = false;
            try {
              const { stat, symbolicLink } = await SymlinkSupport.stat(filePath);
              isDirectory = stat.isDirectory() && !symbolicLink;
            } catch (statError) {
            }
            if (isDirectory) {
              await promises8.rmdir(filePath);
            } else {
              throw unlinkError;
            }
          } else {
            throw unlinkError;
          }
        }
      }
    } catch (error) {
      throw this.ib(error);
    }
  }
  async rename(from, to, opts) {
    const fromFilePath = this.J(from);
    const toFilePath = this.J(to);
    if (fromFilePath === toFilePath) {
      return;
    }
    try {
      await this.eb(from, to, "move", opts.overwrite);
      await Promises2.rename(fromFilePath, toFilePath);
    } catch (error) {
      if (error.code === "EINVAL" || error.code === "EBUSY" || error.code === "ENAMETOOLONG") {
        error = new Error(localize(1917, null, $zc(fromFilePath), $zc($yc(toFilePath)), error.toString()));
      }
      throw this.ib(error);
    }
  }
  async copy(from, to, opts) {
    const fromFilePath = this.J(from);
    const toFilePath = this.J(to);
    if (fromFilePath === toFilePath) {
      return;
    }
    try {
      await this.eb(from, to, "copy", opts.overwrite);
      await Promises2.copy(fromFilePath, toFilePath, { preserveSymlinks: true });
    } catch (error) {
      if (error.code === "EINVAL" || error.code === "EBUSY" || error.code === "ENAMETOOLONG") {
        error = new Error(localize(1918, null, $zc(fromFilePath), $zc($yc(toFilePath)), error.toString()));
      }
      throw this.ib(error);
    }
  }
  async eb(from, to, mode, overwrite) {
    const fromFilePath = this.J(from);
    const toFilePath = this.J(to);
    let isSameResourceWithDifferentPathCase = false;
    const isPathCaseSensitive = !!(this.capabilities & 1024);
    if (!isPathCaseSensitive) {
      isSameResourceWithDifferentPathCase = $Xg(
        fromFilePath,
        toFilePath,
        true
        /* ignore case */
      );
    }
    if (isSameResourceWithDifferentPathCase) {
      if (mode === "copy") {
        throw $Hl(localize(1919, null), FileSystemProviderErrorCode.FileExists);
      } else if (mode === "move") {
        return;
      }
    }
    const fromStat = await this.O(from);
    if (!fromStat) {
      throw $Hl(localize(1920, null), FileSystemProviderErrorCode.FileNotFound);
    }
    const toStat = await this.O(to);
    if (!toStat) {
      return;
    }
    if (!overwrite) {
      throw $Hl(localize(1921, null), FileSystemProviderErrorCode.FileExists);
    }
    if ((fromStat.type & FileType.File) !== 0 && (toStat.type & FileType.File) !== 0) {
      return;
    } else {
      await this.delete(to, { recursive: true, useTrash: false, atomic: false });
    }
  }
  //#endregion
  //#region Clone File
  async cloneFile(from, to) {
    return this.fb(
      from,
      to,
      false
      /* optimistically assume parent folders exist */
    );
  }
  async fb(from, to, mkdir) {
    const fromFilePath = this.J(from);
    const toFilePath = this.J(to);
    const isPathCaseSensitive = !!(this.capabilities & 1024);
    if ($Xg(fromFilePath, toFilePath, !isPathCaseSensitive)) {
      return;
    }
    const locks = new $9c();
    try {
      locks.add(await this.R(from));
      locks.add(await this.R(to));
      if (mkdir) {
        await promises8.mkdir($yc(toFilePath), { recursive: true });
      }
      await promises8.copyFile(fromFilePath, toFilePath);
    } catch (error) {
      if (error.code === "ENOENT" && !mkdir) {
        return this.fb(from, to, true);
      }
      throw this.ib(error);
    } finally {
      locks.dispose();
    }
  }
  //#endregion
  //#region File Watching
  u(onChange, onLogMessage, verboseLogging) {
    return new $Fr((changes) => onChange(changes), (msg) => onLogMessage(msg), verboseLogging);
  }
  G(onChange, onLogMessage, verboseLogging) {
    return new $Or((changes) => onChange(changes), (msg) => onLogMessage(msg), verboseLogging);
  }
  //#endregion
  //#region Helpers
  ib(error) {
    if (error instanceof $Gl) {
      return error;
    }
    let resultError = error;
    let code2;
    switch (error.code) {
      case "ENOENT":
        code2 = FileSystemProviderErrorCode.FileNotFound;
        break;
      case "EISDIR":
        code2 = FileSystemProviderErrorCode.FileIsADirectory;
        break;
      case "ENOTDIR":
        code2 = FileSystemProviderErrorCode.FileNotADirectory;
        break;
      case "EEXIST":
        code2 = FileSystemProviderErrorCode.FileExists;
        break;
      case "EPERM":
      case "EACCES":
        code2 = FileSystemProviderErrorCode.NoPermissions;
        break;
      case "ERR_UNC_HOST_NOT_ALLOWED":
        resultError = `${error.message}. Please update the 'security.allowedUNCHosts' setting if you want to allow this host.`;
        code2 = FileSystemProviderErrorCode.Unknown;
        break;
      default:
        code2 = FileSystemProviderErrorCode.Unknown;
    }
    return $Hl(resultError, code2);
  }
  async jb(resource, error) {
    let fileSystemProviderWriteError = this.ib(error);
    if (resource && fileSystemProviderWriteError.code === FileSystemProviderErrorCode.NoPermissions) {
      try {
        const { stat } = await SymlinkSupport.stat(this.J(resource));
        if (!(stat.mode & 128)) {
          fileSystemProviderWriteError = $Hl(error, FileSystemProviderErrorCode.FileWriteLocked);
        }
      } catch (error2) {
        this.a.trace(error2);
      }
    }
    return fileSystemProviderWriteError;
  }
};

// out-build/vs/platform/files/node/diskFileSystemProviderServer.js
var $nt = class extends $0c {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.F = /* @__PURE__ */ new Map();
    this.G = /* @__PURE__ */ new Map();
  }
  call(ctx, command, arg) {
    const uriTransformer = this.c(ctx);
    switch (command) {
      case "stat":
        return this.g(uriTransformer, arg[0]);
      case "readdir":
        return this.h(uriTransformer, arg[0]);
      case "open":
        return this.r(uriTransformer, arg[0], arg[1]);
      case "close":
        return this.s(arg[0]);
      case "read":
        return this.t(arg[0], arg[1], arg[2]);
      case "readFile":
        return this.j(uriTransformer, arg[0], arg[1]);
      case "write":
        return this.u(arg[0], arg[1], arg[2], arg[3], arg[4]);
      case "writeFile":
        return this.n(uriTransformer, arg[0], arg[1], arg[2]);
      case "rename":
        return this.z(uriTransformer, arg[0], arg[1], arg[2]);
      case "copy":
        return this.C(uriTransformer, arg[0], arg[1], arg[2]);
      case "cloneFile":
        return this.D(uriTransformer, arg[0], arg[1]);
      case "mkdir":
        return this.w(uriTransformer, arg[0]);
      case "delete":
        return this.y(uriTransformer, arg[0], arg[1]);
      case "watch":
        return this.I(uriTransformer, arg[0], arg[1], arg[2], arg[3]);
      case "unwatch":
        return this.J(arg[0], arg[1]);
    }
    throw new Error(`IPC Command ${command} not found`);
  }
  listen(ctx, event, arg) {
    const uriTransformer = this.c(ctx);
    switch (event) {
      case "fileChange":
        return this.H(uriTransformer, arg[0]);
      case "readFileStream":
        return this.m(uriTransformer, arg[0], arg[1]);
    }
    throw new Error(`Unknown event ${event}`);
  }
  //#region File Metadata Resolving
  g(uriTransformer, _resource) {
    const resource = this.f(uriTransformer, _resource, true);
    return this.a.stat(resource);
  }
  h(uriTransformer, _resource) {
    const resource = this.f(uriTransformer, _resource);
    return this.a.readdir(resource);
  }
  //#endregion
  //#region File Reading/Writing
  async j(uriTransformer, _resource, opts) {
    const resource = this.f(uriTransformer, _resource, true);
    const buffer = await this.a.readFile(resource, opts);
    return $7e.wrap(buffer);
  }
  m(uriTransformer, _resource, opts) {
    const resource = this.f(uriTransformer, _resource, true);
    const cts = new $Pe();
    const emitter = new $De({
      onDidRemoveLastListener: () => {
        cts.cancel();
      }
    });
    const fileStream = this.a.readFileStream(resource, opts, cts.token);
    $Ye(fileStream, {
      onData: (chunk) => emitter.fire($7e.wrap(chunk)),
      onError: (error) => emitter.fire(error),
      onEnd: () => {
        emitter.fire("end");
        emitter.dispose();
        cts.dispose();
      }
    });
    return emitter.event;
  }
  n(uriTransformer, _resource, content, opts) {
    const resource = this.f(uriTransformer, _resource);
    return this.a.writeFile(resource, content.buffer, opts);
  }
  r(uriTransformer, _resource, opts) {
    const resource = this.f(uriTransformer, _resource, true);
    return this.a.open(resource, opts);
  }
  s(fd) {
    return this.a.close(fd);
  }
  async t(fd, pos, length) {
    const buffer = $7e.alloc(length);
    const bufferOffset = 0;
    const bytesRead = await this.a.read(fd, pos, buffer.buffer, bufferOffset, length);
    return [buffer, bytesRead];
  }
  u(fd, pos, data, offset, length) {
    return this.a.write(fd, pos, data.buffer, offset, length);
  }
  //#endregion
  //#region Move/Copy/Delete/Create Folder
  w(uriTransformer, _resource) {
    const resource = this.f(uriTransformer, _resource);
    return this.a.mkdir(resource);
  }
  y(uriTransformer, _resource, opts) {
    const resource = this.f(uriTransformer, _resource);
    return this.a.delete(resource, opts);
  }
  z(uriTransformer, _source, _target, opts) {
    const source = this.f(uriTransformer, _source);
    const target = this.f(uriTransformer, _target);
    return this.a.rename(source, target, opts);
  }
  C(uriTransformer, _source, _target, opts) {
    const source = this.f(uriTransformer, _source);
    const target = this.f(uriTransformer, _target);
    return this.a.copy(source, target, opts);
  }
  //#endregion
  //#region Clone File
  D(uriTransformer, _source, _target) {
    const source = this.f(uriTransformer, _source);
    const target = this.f(uriTransformer, _target);
    return this.a.cloneFile(source, target);
  }
  H(uriTransformer, sessionId) {
    const emitter = new $De({
      onWillAddFirstListener: () => {
        this.F.set(sessionId, this.L(uriTransformer, emitter));
      },
      onDidRemoveLastListener: () => {
        $5c(this.F.get(sessionId));
        this.F.delete(sessionId);
      }
    });
    return emitter.event;
  }
  async I(uriTransformer, sessionId, req, _resource, opts) {
    const watcher = this.F.get(sessionId);
    if (watcher) {
      const resource = this.f(uriTransformer, _resource);
      const disposable = watcher.watch(req, resource, opts);
      this.G.set(sessionId + req, disposable);
    }
  }
  async J(sessionId, req) {
    const id2 = sessionId + req;
    const disposable = this.G.get(id2);
    if (disposable) {
      $5c(disposable);
      this.G.delete(id2);
    }
  }
  //#endregion
  dispose() {
    super.dispose();
    for (const [, disposable] of this.G) {
      disposable.dispose();
    }
    this.G.clear();
    for (const [, disposable] of this.F) {
      disposable.dispose();
    }
    this.F.clear();
  }
};
var $ot = class extends $0c {
  constructor(c, sessionEmitter, f, g) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = /* @__PURE__ */ new Map();
    this.b = this.B(new $Pr(this.f));
    this.h(sessionEmitter);
  }
  h(sessionEmitter) {
    const localChangeEmitter = this.B(new $De());
    this.B(localChangeEmitter.event((events) => {
      sessionEmitter.fire(events.map((e) => ({
        resource: this.c.transformOutgoingURI(e.resource),
        type: e.type,
        cId: e.cId
      })));
    }));
    this.B(this.b.onDidChangeFile((events) => localChangeEmitter.fire(events)));
    this.B(this.b.onDidWatchError((error) => sessionEmitter.fire(error)));
  }
  j(environmentService) {
    return void 0;
  }
  m(environmentService) {
    return void 0;
  }
  watch(req, resource, opts) {
    const extraExcludes = this.m(this.g);
    if (Array.isArray(extraExcludes)) {
      opts.excludes = [...opts.excludes, ...extraExcludes];
    }
    this.a.set(req, this.b.watch(resource, opts));
    return $8c(() => {
      $5c(this.a.get(req));
      this.a.delete(req);
    });
  }
  dispose() {
    for (const [, disposable] of this.a) {
      disposable.dispose();
    }
    this.a.clear();
    super.dispose();
  }
};

// out-build/vs/base/common/uriIpc.js
var $9n = new class {
  transformIncoming(uri) {
    return uri;
  }
  transformOutgoing(uri) {
    return uri;
  }
  transformOutgoingURI(uri) {
    return uri;
  }
  transformOutgoingScheme(scheme) {
    return scheme;
  }
}();

// out-build/vs/platform/files/electron-main/diskFileSystemProviderServer.js
var $xkc = class extends $nt {
  constructor(provider, logService, M) {
    super(provider, logService);
    this.M = M;
  }
  c(ctx) {
    return $9n;
  }
  f(uriTransformer, _resource) {
    return URI.revive(_resource);
  }
  //#region Delete: override to support Electron's trash support
  async y(uriTransformer, _resource, opts) {
    if (!opts.useTrash) {
      return super.y(uriTransformer, _resource, opts);
    }
    const resource = this.f(uriTransformer, _resource);
    const filePath = $tc(resource.fsPath);
    try {
      await shell.trashItem(filePath);
    } catch (error) {
      throw $Hl($l ? localize(1913, null, $zc(filePath), $Kj(error)) : localize(1914, null, $zc(filePath), $Kj(error)), FileSystemProviderErrorCode.Unknown);
    }
  }
  //#endregion
  //#region File Watching
  L(uriTransformer, emitter) {
    return new SessionFileWatcher(uriTransformer, emitter, this.b, this.M);
  }
};
var SessionFileWatcher = class extends $ot {
  watch(req, resource, opts) {
    if (opts.recursive) {
      throw $Hl("Recursive file watching is not supported from main process for performance reasons.", FileSystemProviderErrorCode.Unavailable);
    }
    return super.watch(req, resource, opts);
  }
};

// out-build/vs/platform/instantiation/common/descriptors.js
var $Wi = class {
  constructor(ctor, staticArguments = [], supportsDelayedInstantiation = false) {
    this.ctor = ctor;
    this.staticArguments = staticArguments;
    this.supportsDelayedInstantiation = supportsDelayedInstantiation;
  }
};

// out-build/vs/platform/instantiation/common/serviceCollection.js
var $Xi = class {
  constructor(...entries) {
    this.a = /* @__PURE__ */ new Map();
    for (const [id2, service] of entries) {
      this.set(id2, service);
    }
  }
  set(id2, instanceOrDescriptor) {
    const result = this.a.get(id2);
    this.a.set(id2, instanceOrDescriptor);
    return result;
  }
  has(id2) {
    return this.a.has(id2);
  }
  get(id2) {
    return this.a.get(id2);
  }
};

// out-build/vs/platform/issue/common/issue.js
var OldIssueType;
(function(OldIssueType2) {
  OldIssueType2[OldIssueType2["Bug"] = 0] = "Bug";
  OldIssueType2[OldIssueType2["PerformanceIssue"] = 1] = "PerformanceIssue";
  OldIssueType2[OldIssueType2["FeatureRequest"] = 2] = "FeatureRequest";
})(OldIssueType || (OldIssueType = {}));
var IssueSource;
(function(IssueSource2) {
  IssueSource2["VSCode"] = "vscode";
  IssueSource2["Extension"] = "extension";
  IssueSource2["Marketplace"] = "marketplace";
})(IssueSource || (IssueSource = {}));
var $Eqb = $Zi("issueService");
var $Fqb = $Zi("processService");

// out-build/vs/platform/issue/electron-main/issueMainService.js
import { BrowserWindow as BrowserWindow2, screen as screen2 } from "electron";
import { arch as arch2, release as release3, type as type2 } from "os";

// out-build/vs/platform/native/electron-main/nativeHostMainService.js
import * as fs7 from "fs";
import { exec } from "child_process";
import { app as app5, clipboard, Menu as Menu2, powerMonitor, screen, shell as shell2, webContents } from "electron";
import { arch, cpus, freemem, loadavg, platform, release as release2, totalmem, type } from "os";
import { promisify as promisify2 } from "util";

// out-build/vs/base/node/id.js
import { networkInterfaces as networkInterfaces2 } from "os";

// out-build/vs/base/node/macAddress.js
import { networkInterfaces } from "os";
var invalidMacAddresses = /* @__PURE__ */ new Set([
  "00:00:00:00:00:00",
  "ff:ff:ff:ff:ff:ff",
  "ac:de:48:00:11:22"
]);
function validateMacAddress(candidate) {
  const tempCandidate = candidate.replace(/\-/g, ":").toLowerCase();
  return !invalidMacAddresses.has(tempCandidate);
}
function $ao() {
  const ifaces = networkInterfaces();
  for (const name in ifaces) {
    const networkInterface = ifaces[name];
    if (networkInterface) {
      for (const { mac } of networkInterface) {
        if (validateMacAddress(mac)) {
          return mac;
        }
      }
    }
  }
  throw new Error("Unable to retrieve mac address (unexpected format)");
}

// out-build/vs/base/node/id.js
var $bo = new class {
  c(mac) {
    if (!this.a) {
      this.a = $6i.forStrings();
      this.a.set("00-50-56", true);
      this.a.set("00-0C-29", true);
      this.a.set("00-05-69", true);
      this.a.set("00-03-FF", true);
      this.a.set("00-1C-42", true);
      this.a.set("00-16-3E", true);
      this.a.set("08-00-27", true);
      this.a.set("00:50:56", true);
      this.a.set("00:0C:29", true);
      this.a.set("00:05:69", true);
      this.a.set("00:03:FF", true);
      this.a.set("00:1C:42", true);
      this.a.set("00:16:3E", true);
      this.a.set("08:00:27", true);
    }
    return !!this.a.findSubstr(mac);
  }
  value() {
    if (this.b === void 0) {
      let vmOui = 0;
      let interfaceCount = 0;
      const interfaces = networkInterfaces2();
      for (const name in interfaces) {
        const networkInterface = interfaces[name];
        if (networkInterface) {
          for (const { mac, internal } of networkInterface) {
            if (!internal) {
              interfaceCount += 1;
              if (this.c(mac.toUpperCase())) {
                vmOui += 1;
              }
            }
          }
        }
      }
      this.b = interfaceCount > 0 ? vmOui / interfaceCount : 0;
    }
    return this.b;
  }
}();
var machineId;
async function $co(errorLogger) {
  if (!machineId) {
    machineId = (async () => {
      const id2 = await getMacMachineId(errorLogger);
      return id2 || $jh();
    })();
  }
  return machineId;
}
async function getMacMachineId(errorLogger) {
  try {
    const crypto3 = await import("crypto");
    const macAddress = $ao();
    return crypto3.createHash("sha256").update(macAddress, "utf8").digest("hex");
  } catch (err) {
    errorLogger(err);
    return void 0;
  }
}
var SQM_KEY = "Software\\Microsoft\\SQMClient";
async function $do(errorLogger) {
  if ($l) {
    const Registry = await import("@vscode/windows-registry");
    try {
      return Registry.GetStringRegKey("HKEY_LOCAL_MACHINE", SQM_KEY, "MachineId") || "";
    } catch (err) {
      errorLogger(err);
      return "";
    }
  }
  return "";
}
async function $eo(errorLogger) {
  try {
    const deviceIdPackage = await import("@vscode/deviceid");
    const id2 = await deviceIdPackage.getDeviceId();
    return id2;
  } catch (err) {
    errorLogger(err);
    return "";
  }
}

// out-build/vs/base/node/ports.js
import * as net from "net";
function $lh(startPort, giveUpAfter, timeout, stride = 1) {
  let done = false;
  return new Promise((resolve2) => {
    const timeoutHandle = setTimeout(() => {
      if (!done) {
        done = true;
        return resolve2(0);
      }
    }, timeout);
    doFindFreePort(startPort, giveUpAfter, stride, (port) => {
      if (!done) {
        done = true;
        clearTimeout(timeoutHandle);
        return resolve2(port);
      }
    });
  });
}
function doFindFreePort(startPort, giveUpAfter, stride, clb) {
  if (giveUpAfter === 0) {
    return clb(0);
  }
  const client = new net.Socket();
  client.once("connect", () => {
    dispose(client);
    return doFindFreePort(startPort + stride, giveUpAfter - 1, stride, clb);
  });
  client.once("data", () => {
  });
  client.once("error", (err) => {
    dispose(client);
    if (err.code !== "ECONNREFUSED") {
      return doFindFreePort(startPort + stride, giveUpAfter - 1, stride, clb);
    }
    return clb(startPort);
  });
  client.connect(startPort, "127.0.0.1");
}
var $mh = {
  1: true,
  // tcpmux
  7: true,
  // echo
  9: true,
  // discard
  11: true,
  // systat
  13: true,
  // daytime
  15: true,
  // netstat
  17: true,
  // qotd
  19: true,
  // chargen
  20: true,
  // ftp data
  21: true,
  // ftp access
  22: true,
  // ssh
  23: true,
  // telnet
  25: true,
  // smtp
  37: true,
  // time
  42: true,
  // name
  43: true,
  // nicname
  53: true,
  // domain
  69: true,
  // tftp
  77: true,
  // priv-rjs
  79: true,
  // finger
  87: true,
  // ttylink
  95: true,
  // supdup
  101: true,
  // hostriame
  102: true,
  // iso-tsap
  103: true,
  // gppitnp
  104: true,
  // acr-nema
  109: true,
  // pop2
  110: true,
  // pop3
  111: true,
  // sunrpc
  113: true,
  // auth
  115: true,
  // sftp
  117: true,
  // uucp-path
  119: true,
  // nntp
  123: true,
  // NTP
  135: true,
  // loc-srv /epmap
  137: true,
  // netbios
  139: true,
  // netbios
  143: true,
  // imap2
  161: true,
  // snmp
  179: true,
  // BGP
  389: true,
  // ldap
  427: true,
  // SLP (Also used by Apple Filing Protocol)
  465: true,
  // smtp+ssl
  512: true,
  // print / exec
  513: true,
  // login
  514: true,
  // shell
  515: true,
  // printer
  526: true,
  // tempo
  530: true,
  // courier
  531: true,
  // chat
  532: true,
  // netnews
  540: true,
  // uucp
  548: true,
  // AFP (Apple Filing Protocol)
  554: true,
  // rtsp
  556: true,
  // remotefs
  563: true,
  // nntp+ssl
  587: true,
  // smtp (rfc6409)
  601: true,
  // syslog-conn (rfc3195)
  636: true,
  // ldap+ssl
  989: true,
  // ftps-data
  990: true,
  // ftps
  993: true,
  // ldap+ssl
  995: true,
  // pop3+ssl
  1719: true,
  // h323gatestat
  1720: true,
  // h323hostcall
  1723: true,
  // pptp
  2049: true,
  // nfs
  3659: true,
  // apple-sasl / PasswordServer
  4045: true,
  // lockd
  5060: true,
  // sip
  5061: true,
  // sips
  6e3: true,
  // X11
  6566: true,
  // sane-port
  6665: true,
  // Alternate IRC [Apple addition]
  6666: true,
  // Alternate IRC [Apple addition]
  6667: true,
  // Standard IRC [Apple addition]
  6668: true,
  // Alternate IRC [Apple addition]
  6669: true,
  // Alternate IRC [Apple addition]
  6697: true,
  // IRC + TLS
  10080: true
  // Amanda
};
function $nh(startPort, giveUpAfter, timeout, hostname3 = "127.0.0.1") {
  let resolved = false;
  let timeoutHandle = void 0;
  let countTried = 1;
  const server = net.createServer({ pauseOnConnect: true });
  function doResolve(port, resolve2) {
    if (!resolved) {
      resolved = true;
      server.removeAllListeners();
      server.close();
      if (timeoutHandle) {
        clearTimeout(timeoutHandle);
      }
      resolve2(port);
    }
  }
  return new Promise((resolve2) => {
    timeoutHandle = setTimeout(() => {
      doResolve(0, resolve2);
    }, timeout);
    server.on("listening", () => {
      doResolve(startPort, resolve2);
    });
    server.on("error", (err) => {
      if (err && (err.code === "EADDRINUSE" || err.code === "EACCES") && countTried < giveUpAfter) {
        startPort++;
        countTried++;
        server.listen(startPort, hostname3);
      } else {
        doResolve(0, resolve2);
      }
    });
    server.on("close", () => {
      doResolve(0, resolve2);
    });
    server.listen(startPort, hostname3);
  });
}
function dispose(socket) {
  try {
    socket.removeAllListeners("connect");
    socket.removeAllListeners("error");
    socket.end();
    socket.destroy();
    socket.unref();
  } catch (error) {
    console.error(error);
  }
}

// out-build/vs/platform/remote/node/wsl.js
import * as fs6 from "fs";
import * as os3 from "os";
import * as cp2 from "child_process";
import * as path2 from "path";
var hasWSLFeaturePromise;
async function $zkc(refresh = false) {
  if (hasWSLFeaturePromise === void 0 || refresh) {
    hasWSLFeaturePromise = testWSLFeatureInstalled();
  }
  return hasWSLFeaturePromise;
}
async function testWSLFeatureInstalled() {
  const windowsBuildNumber = getWindowsBuildNumber();
  if (windowsBuildNumber === void 0) {
    return false;
  }
  if (windowsBuildNumber >= 22e3) {
    const wslExePath = getWSLExecutablePath();
    if (wslExePath) {
      return new Promise((s) => {
        try {
          cp2.execFile(wslExePath, ["--status"], (err) => s(!err));
        } catch (e) {
          s(false);
        }
      });
    }
  } else {
    const dllPath = getLxssManagerDllPath();
    if (dllPath) {
      try {
        if ((await fs6.promises.stat(dllPath)).isFile()) {
          return true;
        }
      } catch (e) {
      }
    }
  }
  return false;
}
function getWindowsBuildNumber() {
  const osVersion = /(\d+)\.(\d+)\.(\d+)/g.exec(os3.release());
  if (osVersion) {
    return parseInt(osVersion[3]);
  }
  return void 0;
}
function getSystem32Path(subPath) {
  const systemRoot = process.env["SystemRoot"];
  if (systemRoot) {
    const is32ProcessOn64Windows = process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432");
    return path2.join(systemRoot, is32ProcessOn64Windows ? "Sysnative" : "System32", subPath);
  }
  return void 0;
}
function getWSLExecutablePath() {
  return getSystem32Path("wsl.exe");
}
function getLxssManagerDllPath() {
  return getSystem32Path("lxss\\LxssManager.dll");
}

// out-build/vs/platform/profiling/electron-main/windowProfiling.js
var $Akc = class $Akc2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  async inspect(duration) {
    await this.d();
    const inspector = this.a.webContents.debugger;
    await inspector.sendCommand("Profiler.start");
    this.c.warn("[perf] profiling STARTED", this.b);
    await $1h(duration);
    const data = await inspector.sendCommand("Profiler.stop");
    this.c.warn("[perf] profiling DONE", this.b);
    await this.e();
    return data.profile;
  }
  async d() {
    const inspector = this.a.webContents.debugger;
    inspector.attach();
    await inspector.sendCommand("Profiler.enable");
  }
  async e() {
    const inspector = this.a.webContents.debugger;
    await inspector.sendCommand("Profiler.disable");
    inspector.detach();
  }
};
$Akc = __decorate([
  __param(2, $uk)
], $Akc);

// out-build/vs/platform/auxiliaryWindow/electron-main/auxiliaryWindows.js
var $Bkc = $Zi("auxiliaryWindowsMainService");

// out-build/vs/platform/request/common/request.js
var $qq = $Zi("requestService");
var LoggableHeaders = class {
  constructor(b) {
    this.b = b;
  }
  toJSON() {
    if (!this.a) {
      const headers = /* @__PURE__ */ Object.create(null);
      for (const key in this.b) {
        if (key.toLowerCase() === "authorization" || key.toLowerCase() === "proxy-authorization") {
          headers[key] = "*****";
        } else {
          headers[key] = this.b[key];
        }
      }
      this.a = headers;
    }
    return this.a;
  }
};
var $rq = class extends $0c {
  constructor(b) {
    super();
    this.b = b;
    this.a = 0;
  }
  async c(options, request) {
    const prefix = `[network] #${++this.a}: ${options.url}`;
    this.b.trace(`${prefix} - begin`, options.type, new LoggableHeaders(options.headers ?? {}));
    try {
      const result = await request();
      this.b.trace(`${prefix} - end`, options.type, result.res.statusCode, result.res.headers);
      return result;
    } catch (error) {
      this.b.error(`${prefix} - error`, options.type, $kb(error));
      throw error;
    }
  }
};
function $sq(context) {
  return context.res.statusCode && context.res.statusCode >= 200 && context.res.statusCode < 300 || context.res.statusCode === 1223;
}
function $tq(context) {
  return context.res.statusCode === 204;
}
async function $wq(context) {
  if (!$sq(context)) {
    throw new Error("Server returned " + context.res.statusCode);
  }
  if ($tq(context)) {
    return null;
  }
  const buffer = await $gf(context.stream);
  const str = buffer.toString();
  try {
    return JSON.parse(str);
  } catch (err) {
    err.message += ":\n" + str;
    throw err;
  }
}
var proxyConfiguration;
function registerProxyConfigurations(scope) {
  const configurationRegistry3 = $Mo.as($Ro.Configuration);
  const oldProxyConfiguration = proxyConfiguration;
  proxyConfiguration = {
    id: "http",
    order: 15,
    title: localize(2064, null),
    type: "object",
    scope,
    properties: {
      "http.proxy": {
        type: "string",
        pattern: "^(https?|socks|socks4a?|socks5h?)://([^:]*(:[^@]*)?@)?([^:]+|\\[[:0-9a-fA-F]+\\])(:\\d+)?/?$|^$",
        markdownDescription: localize(2065, null),
        restricted: true
      },
      "http.proxyStrictSSL": {
        type: "boolean",
        default: true,
        description: localize(2066, null),
        restricted: true
      },
      "http.proxyKerberosServicePrincipal": {
        type: "string",
        markdownDescription: localize(2067, null),
        restricted: true
      },
      "http.noProxy": {
        type: "array",
        items: { type: "string" },
        markdownDescription: localize(2068, null),
        restricted: true
      },
      "http.proxyAuthorization": {
        type: ["null", "string"],
        default: null,
        markdownDescription: localize(2069, null),
        restricted: true
      },
      "http.proxySupport": {
        type: "string",
        enum: ["off", "on", "fallback", "override"],
        enumDescriptions: [
          localize(2070, null),
          localize(2071, null),
          localize(2072, null),
          localize(2073, null)
        ],
        default: "override",
        description: localize(2074, null),
        restricted: true
      },
      "http.systemCertificates": {
        type: "boolean",
        default: true,
        description: localize(2075, null),
        restricted: true
      },
      "http.experimental.systemCertificatesV2": {
        type: "boolean",
        tags: ["experimental"],
        default: false,
        description: localize(2076, null),
        restricted: true
      },
      "http.electronFetch": {
        type: "boolean",
        default: false,
        description: localize(2077, null),
        restricted: true
      }
    }
  };
  configurationRegistry3.updateConfigurations({ add: [proxyConfiguration], remove: oldProxyConfiguration ? [oldProxyConfiguration] : [] });
}
registerProxyConfigurations(
  1
  /* ConfigurationScope.APPLICATION */
);

// out-build/vs/platform/native/electron-main/nativeHostMainService.js
var $Ckc = $Zi("nativeHostMainService");
var $Dkc = class $Dkc2 extends $0c {
  constructor(a, b, c, f, g, h, j, m, n, r, s, t) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r;
    this.s = s;
    this.t = t;
    this.onDidOpenMainWindow = Event.map(this.a.onDidOpenWindow, (window2) => window2.id);
    this.onDidTriggerWindowSystemContextMenu = Event.any(Event.map(this.a.onDidTriggerSystemContextMenu, ({ window: window2, x, y }) => ({ windowId: window2.id, x, y })), Event.map(this.b.onDidTriggerSystemContextMenu, ({ window: window2, x, y }) => ({ windowId: window2.id, x, y })));
    this.onDidMaximizeWindow = Event.any(Event.map(this.a.onDidMaximizeWindow, (window2) => window2.id), Event.map(this.b.onDidMaximizeWindow, (window2) => window2.id));
    this.onDidUnmaximizeWindow = Event.any(Event.map(this.a.onDidUnmaximizeWindow, (window2) => window2.id), Event.map(this.b.onDidUnmaximizeWindow, (window2) => window2.id));
    this.onDidChangeWindowFullScreen = Event.any(Event.map(this.a.onDidChangeFullScreen, (e) => ({ windowId: e.window.id, fullscreen: e.fullscreen })), Event.map(this.b.onDidChangeFullScreen, (e) => ({ windowId: e.window.id, fullscreen: e.fullscreen })));
    this.onDidBlurMainWindow = Event.filter(Event.fromNodeEventEmitter(app5, "browser-window-blur", (event, window2) => window2.id), (windowId) => !!this.a.getWindowById(windowId));
    this.onDidFocusMainWindow = Event.any(Event.map(Event.filter(Event.map(this.a.onDidChangeWindowsCount, () => this.a.getLastActiveWindow()), (window2) => !!window2), (window2) => window2.id), Event.filter(Event.fromNodeEventEmitter(app5, "browser-window-focus", (event, window2) => window2.id), (windowId) => !!this.a.getWindowById(windowId)));
    this.onDidBlurMainOrAuxiliaryWindow = Event.any(this.onDidBlurMainWindow, Event.map(Event.filter(Event.fromNodeEventEmitter(app5, "browser-window-blur", (event, window2) => this.b.getWindowByWebContents(window2.webContents)), (window2) => !!window2), (window2) => window2.id));
    this.onDidFocusMainOrAuxiliaryWindow = Event.any(this.onDidFocusMainWindow, Event.map(Event.filter(Event.fromNodeEventEmitter(app5, "browser-window-focus", (event, window2) => this.b.getWindowByWebContents(window2.webContents)), (window2) => !!window2), (window2) => window2.id));
    this.onDidResumeOS = Event.fromNodeEventEmitter(powerMonitor, "resume");
    this.onDidChangeColorScheme = this.m.onDidChangeColorScheme;
    this.u = this.B(new $De());
    this.onDidChangePassword = this.u.event;
    this.onDidChangeDisplay = Event.debounce(Event.any(Event.filter(Event.fromNodeEventEmitter(screen, "display-metrics-changed", (event, display, changedMetrics) => changedMetrics), (changedMetrics) => {
      return !(Array.isArray(changedMetrics) && changedMetrics.length === 1 && changedMetrics[0] === "workArea");
    }), Event.fromNodeEventEmitter(screen, "display-added"), Event.fromNodeEventEmitter(screen, "display-removed")), () => {
    }, 100);
  }
  //#region Properties
  get windowId() {
    throw new Error("Not implemented in electron-main");
  }
  async getWindows(windowId, options) {
    const mainWindows = this.a.getWindows().map((window2) => ({
      id: window2.id,
      workspace: window2.openedWorkspace ?? $bj(window2.backupPath, window2.isExtensionDevelopmentHost),
      title: window2.win?.getTitle() ?? "",
      filename: window2.getRepresentedFilename(),
      dirty: window2.isDocumentEdited()
    }));
    const auxiliaryWindows = [];
    if (options.includeAuxiliaryWindows) {
      auxiliaryWindows.push(...this.b.getWindows().map((window2) => ({
        id: window2.id,
        parentId: window2.parentId,
        title: window2.win?.getTitle() ?? "",
        filename: window2.getRepresentedFilename()
      })));
    }
    return [...mainWindows, ...auxiliaryWindows];
  }
  async getWindowCount(windowId) {
    return this.a.getWindowCount();
  }
  async getActiveWindowId(windowId) {
    const activeWindow = this.a.getFocusedWindow() || this.a.getLastActiveWindow();
    if (activeWindow) {
      return activeWindow.id;
    }
    return void 0;
  }
  async getActiveWindowPosition() {
    const activeWindow = this.a.getFocusedWindow() || this.a.getLastActiveWindow();
    if (activeWindow) {
      return activeWindow.getBounds();
    }
    return void 0;
  }
  openWindow(windowId, arg1, arg2) {
    if (Array.isArray(arg1)) {
      return this.w(windowId, arg1, arg2);
    }
    return this.z(windowId, arg1);
  }
  async w(windowId, toOpen, options = /* @__PURE__ */ Object.create(null)) {
    if (toOpen.length > 0) {
      await this.a.open({
        context: 5,
        contextWindowId: windowId,
        urisToOpen: toOpen,
        cli: this.g.args,
        forceNewWindow: options.forceNewWindow,
        forceReuseWindow: options.forceReuseWindow,
        preferNewWindow: options.preferNewWindow,
        diffMode: options.diffMode,
        mergeMode: options.mergeMode,
        addMode: options.addMode,
        gotoLineMode: options.gotoLineMode,
        noRecentEntry: options.noRecentEntry,
        waitMarkerFileURI: options.waitMarkerFileURI,
        remoteAuthority: options.remoteAuthority || void 0,
        forceProfile: options.forceProfile,
        forceTempProfile: options.forceTempProfile
      });
    }
  }
  async z(windowId, options) {
    await this.a.openEmptyWindow({
      context: 5,
      contextWindowId: windowId
    }, options);
  }
  async isFullScreen(windowId, options) {
    const window2 = this.H(options?.targetWindowId, windowId);
    return window2?.isFullScreen ?? false;
  }
  async toggleFullScreen(windowId, options) {
    const window2 = this.H(options?.targetWindowId, windowId);
    window2?.toggleFullScreen();
  }
  async handleTitleDoubleClick(windowId, options) {
    const window2 = this.H(options?.targetWindowId, windowId);
    window2?.handleTitleDoubleClick();
  }
  async getCursorScreenPoint(windowId) {
    const point = screen.getCursorScreenPoint();
    const display = screen.getDisplayNearestPoint(point);
    return { point, display: display.bounds };
  }
  async isMaximized(windowId, options) {
    const window2 = this.H(options?.targetWindowId, windowId);
    return window2?.win?.isMaximized() ?? false;
  }
  async maximizeWindow(windowId, options) {
    const window2 = this.H(options?.targetWindowId, windowId);
    window2?.win?.maximize();
  }
  async unmaximizeWindow(windowId, options) {
    const window2 = this.H(options?.targetWindowId, windowId);
    window2?.win?.unmaximize();
  }
  async minimizeWindow(windowId, options) {
    const window2 = this.H(options?.targetWindowId, windowId);
    window2?.win?.minimize();
  }
  async moveWindowTop(windowId, options) {
    const window2 = this.H(options?.targetWindowId, windowId);
    window2?.win?.moveTop();
  }
  async positionWindow(windowId, position, options) {
    const window2 = this.H(options?.targetWindowId, windowId);
    if (window2?.win) {
      if (window2.win.isFullScreen()) {
        const fullscreenLeftFuture = Event.toPromise(Event.once(Event.fromNodeEventEmitter(window2.win, "leave-full-screen")));
        window2.win.setFullScreen(false);
        await fullscreenLeftFuture;
      }
      window2.win.setBounds(position);
    }
  }
  async updateWindowControls(windowId, options) {
    const window2 = this.H(options?.targetWindowId, windowId);
    window2?.updateWindowControls(options);
  }
  async focusWindow(windowId, options) {
    const window2 = this.H(options?.targetWindowId, windowId);
    window2?.focus({ force: options?.force ?? false });
  }
  async setMinimumSize(windowId, width, height) {
    const window2 = this.I(windowId);
    if (window2?.win) {
      const [windowWidth, windowHeight] = window2.win.getSize();
      const [minWindowWidth, minWindowHeight] = window2.win.getMinimumSize();
      const [newMinWindowWidth, newMinWindowHeight] = [width ?? minWindowWidth, height ?? minWindowHeight];
      const [newWindowWidth, newWindowHeight] = [Math.max(windowWidth, newMinWindowWidth), Math.max(windowHeight, newMinWindowHeight)];
      if (minWindowWidth !== newMinWindowWidth || minWindowHeight !== newMinWindowHeight) {
        window2.win.setMinimumSize(newMinWindowWidth, newMinWindowHeight);
      }
      if (windowWidth !== newWindowWidth || windowHeight !== newWindowHeight) {
        window2.win.setSize(newWindowWidth, newWindowHeight);
      }
    }
  }
  async saveWindowSplash(windowId, splash) {
    this.m.saveWindowSplash(windowId, splash);
  }
  //#endregion
  //#region macOS Shell Command
  async installShellCommand(windowId) {
    const { source, target } = await this.C();
    try {
      const { symbolicLink } = await SymlinkSupport.stat(source);
      if (symbolicLink && !symbolicLink.dangling) {
        const linkTargetRealPath = await $Jr(source);
        if (target === linkTargetRealPath) {
          return;
        }
      }
      await fs7.promises.unlink(source);
    } catch (error) {
      if (error.code !== "ENOENT") {
        throw error;
      }
    }
    try {
      await fs7.promises.symlink(target, source);
    } catch (error) {
      if (error.code !== "EACCES" && error.code !== "ENOENT") {
        throw error;
      }
      const { response } = await this.showMessageBox(windowId, {
        type: "info",
        message: localize(2018, null, this.j.nameShort),
        buttons: [
          localize(2019, null),
          localize(2020, null)
        ]
      });
      if (response === 1) {
        throw new $fb();
      }
      try {
        const command = `osascript -e "do shell script \\"mkdir -p /usr/local/bin && ln -sf '${target}' '${source}'\\" with administrator privileges"`;
        await promisify2(exec)(command);
      } catch (error2) {
        throw new Error(localize(2021, null, source));
      }
    }
  }
  async uninstallShellCommand(windowId) {
    const { source } = await this.C();
    try {
      await fs7.promises.unlink(source);
    } catch (error) {
      switch (error.code) {
        case "EACCES": {
          const { response } = await this.showMessageBox(windowId, {
            type: "info",
            message: localize(2022, null, this.j.nameShort),
            buttons: [
              localize(2023, null),
              localize(2024, null)
            ]
          });
          if (response === 1) {
            throw new $fb();
          }
          try {
            const command = `osascript -e "do shell script \\"rm '${source}'\\" with administrator privileges"`;
            await promisify2(exec)(command);
          } catch (error2) {
            throw new Error(localize(2025, null, source));
          }
          break;
        }
        case "ENOENT":
          break;
        default:
          throw error;
      }
    }
  }
  async C() {
    const target = $wc(this.g.appRoot, "bin", "code");
    const source = `/usr/local/bin/${this.j.applicationName}`;
    const sourceExists = await Promises2.exists(target);
    if (!sourceExists) {
      throw new Error(localize(2026, null, target));
    }
    return { source, target };
  }
  //#endregion
  //#region Dialog
  async showMessageBox(windowId, options) {
    const window2 = this.H(options?.targetWindowId, windowId);
    return this.c.showMessageBox(options, window2?.win ?? void 0);
  }
  async showSaveDialog(windowId, options) {
    const window2 = this.H(options?.targetWindowId, windowId);
    return this.c.showSaveDialog(options, window2?.win ?? void 0);
  }
  async showOpenDialog(windowId, options) {
    const window2 = this.H(options?.targetWindowId, windowId);
    return this.c.showOpenDialog(options, window2?.win ?? void 0);
  }
  async pickFileFolderAndOpen(windowId, options) {
    const paths = await this.c.pickFileFolder(options);
    if (paths) {
      await this.D(await Promise.all(paths.map(async (path3) => await SymlinkSupport.existsDirectory(path3) ? { folderUri: URI.file(path3) } : { fileUri: URI.file(path3) })), options, windowId);
    }
  }
  async pickFolderAndOpen(windowId, options) {
    const paths = await this.c.pickFolder(options);
    if (paths) {
      await this.D(paths.map((path3) => ({ folderUri: URI.file(path3) })), options, windowId);
    }
  }
  async pickFileAndOpen(windowId, options) {
    const paths = await this.c.pickFile(options);
    if (paths) {
      await this.D(paths.map((path3) => ({ fileUri: URI.file(path3) })), options, windowId);
    }
  }
  async pickWorkspaceAndOpen(windowId, options) {
    const paths = await this.c.pickWorkspace(options);
    if (paths) {
      await this.D(paths.map((path3) => ({ workspaceUri: URI.file(path3) })), options, windowId);
    }
  }
  async D(openable, options, windowId) {
    await this.a.open({
      context: 3,
      contextWindowId: windowId,
      cli: this.g.args,
      urisToOpen: openable,
      forceNewWindow: options.forceNewWindow
      /* remoteAuthority will be determined based on openable */
    });
  }
  //#endregion
  //#region OS
  async showItemInFolder(windowId, path3) {
    shell2.showItemInFolder(path3);
  }
  async setRepresentedFilename(windowId, path3, options) {
    const window2 = this.H(options?.targetWindowId, windowId);
    window2?.setRepresentedFilename(path3);
  }
  async setDocumentEdited(windowId, edited, options) {
    const window2 = this.H(options?.targetWindowId, windowId);
    window2?.setDocumentEdited(edited);
  }
  async openExternal(windowId, url, defaultApplication) {
    this.g.unsetSnapExportedVariables();
    try {
      if ($0g(url, Schemas.http, Schemas.https)) {
        this.F(url, defaultApplication);
      } else {
        shell2.openExternal(url);
      }
    } finally {
      this.g.restoreSnapExportedVariables();
    }
    return true;
  }
  async F(url, defaultApplication) {
    const configuredBrowser = defaultApplication ?? this.r.getValue("workbench.externalBrowser");
    if (!configuredBrowser) {
      return shell2.openExternal(url);
    }
    if (configuredBrowser.includes($sc.sep) || configuredBrowser.includes($rc.sep)) {
      const browserPathExists = await Promises2.exists(configuredBrowser);
      if (!browserPathExists) {
        this.h.error(`Configured external browser path does not exist: ${configuredBrowser}`);
        return shell2.openExternal(url);
      }
    }
    try {
      const { default: open2 } = await import("open");
      const res = await open2(url, {
        app: {
          // Use `open.apps` helper to allow cross-platform browser
          // aliases to be looked up properly. Fallback to the
          // configured value if not found.
          name: Object.hasOwn(open2.apps, configuredBrowser) ? open2.apps[configuredBrowser] : configuredBrowser
        }
      });
      res.stderr?.once("data", (data) => {
        this.h.error(`Error openening external URL '${url}' using browser '${configuredBrowser}': ${data.toString()}`);
        return shell2.openExternal(url);
      });
    } catch (error) {
      this.h.error(`Unable to open external URL '${url}' using browser '${configuredBrowser}' due to ${error}.`);
      return shell2.openExternal(url);
    }
  }
  moveItemToTrash(windowId, fullPath) {
    return shell2.trashItem(fullPath);
  }
  async isAdmin() {
    let isAdmin;
    if ($l) {
      isAdmin = (await import("native-is-elevated")).default();
    } else {
      isAdmin = process.getuid?.() === 0;
    }
    return isAdmin;
  }
  async writeElevated(windowId, source, target, options) {
    const sudoPrompt = await import("@vscode/sudo-prompt");
    return new Promise((resolve2, reject) => {
      const sudoCommand = [`"${this.G}"`];
      if (options?.unlock) {
        sudoCommand.push("--file-chmod");
      }
      sudoCommand.push("--file-write", `"${source.fsPath}"`, `"${target.fsPath}"`);
      const promptOptions = {
        name: this.j.nameLong.replace("-", ""),
        icns: $m && this.g.isBuilt ? $vc($yc(this.g.appRoot), `${this.j.nameShort}.icns`) : void 0
      };
      sudoPrompt.exec(sudoCommand.join(" "), promptOptions, (error, stdout, stderr) => {
        if (stdout) {
          this.h.trace(`[sudo-prompt] received stdout: ${stdout}`);
        }
        if (stderr) {
          this.h.trace(`[sudo-prompt] received stderr: ${stderr}`);
        }
        if (error) {
          reject(error);
        } else {
          resolve2(void 0);
        }
      });
    });
  }
  async isRunningUnderARM64Translation() {
    if ($n || $l) {
      return false;
    }
    return app5.runningUnderARM64Translation;
  }
  get G() {
    if ($l) {
      if (this.g.isBuilt) {
        return $vc($yc(process.execPath), "bin", `${this.j.applicationName}.cmd`);
      }
      return $vc(this.g.appRoot, "scripts", "code-cli.bat");
    }
    if ($n) {
      if (this.g.isBuilt) {
        return $vc($yc(process.execPath), "bin", `${this.j.applicationName}`);
      }
      return $vc(this.g.appRoot, "scripts", "code-cli.sh");
    }
    if (this.g.isBuilt) {
      return $vc(this.g.appRoot, "bin", "code");
    }
    return $vc(this.g.appRoot, "scripts", "code-cli.sh");
  }
  async getOSStatistics() {
    return {
      totalmem: totalmem(),
      freemem: freemem(),
      loadavg: loadavg()
    };
  }
  async getOSProperties() {
    return {
      arch: arch(),
      platform: platform(),
      release: release2(),
      type: type(),
      cpus: cpus()
    };
  }
  async getOSVirtualMachineHint() {
    return $bo.value();
  }
  async getOSColorScheme() {
    return this.m.getColorScheme();
  }
  // WSL
  async hasWSLFeatureInstalled() {
    return $l && $zkc();
  }
  //#endregion
  //#region Process
  async getProcessId(windowId) {
    const window2 = this.H(void 0, windowId);
    return window2?.win?.webContents.getOSProcessId();
  }
  async killProcess(windowId, pid, code2) {
    process.kill(pid, code2);
  }
  //#endregion
  //#region Clipboard
  async readClipboardText(windowId, type4) {
    return clipboard.readText(type4);
  }
  async readImage() {
    return clipboard.readImage().toPNG();
  }
  async writeClipboardText(windowId, text, type4) {
    return clipboard.writeText(text, type4);
  }
  async readClipboardFindText(windowId) {
    return clipboard.readFindText();
  }
  async writeClipboardFindText(windowId, text) {
    return clipboard.writeFindText(text);
  }
  async writeClipboardBuffer(windowId, format2, buffer, type4) {
    return clipboard.writeBuffer(format2, Buffer.from(buffer.buffer), type4);
  }
  async readClipboardBuffer(windowId, format2) {
    return $7e.wrap(clipboard.readBuffer(format2));
  }
  async hasClipboard(windowId, format2, type4) {
    return clipboard.has(format2, type4);
  }
  //#endregion
  //#region macOS Touchbar
  async newWindowTab() {
    await this.a.open({
      context: 5,
      cli: this.g.args,
      forceNewTabbedWindow: true,
      forceEmpty: true,
      remoteAuthority: this.g.args.remote || void 0
    });
  }
  async showPreviousWindowTab() {
    Menu2.sendActionToFirstResponder("selectPreviousTab:");
  }
  async showNextWindowTab() {
    Menu2.sendActionToFirstResponder("selectNextTab:");
  }
  async moveWindowTabToNewWindow() {
    Menu2.sendActionToFirstResponder("moveTabToNewWindow:");
  }
  async mergeAllWindowTabs() {
    Menu2.sendActionToFirstResponder("mergeAllWindows:");
  }
  async toggleWindowTabsBar() {
    Menu2.sendActionToFirstResponder("toggleTabBar:");
  }
  async updateTouchBar(windowId, items) {
    const window2 = this.I(windowId);
    window2?.updateTouchBar(items);
  }
  //#endregion
  //#region Lifecycle
  async notifyReady(windowId) {
    const window2 = this.I(windowId);
    window2?.setReady();
  }
  async relaunch(windowId, options) {
    return this.f.relaunch(options);
  }
  async reload(windowId, options) {
    const window2 = this.I(windowId);
    if (window2) {
      if ($cj(window2.openedWorkspace)) {
        const configPath = window2.openedWorkspace.configPath;
        if (configPath.scheme === Schemas.file) {
          const workspace = await this.n.resolveLocalWorkspace(configPath);
          if (workspace?.transient) {
            return this.openWindow(window2.id, { forceReuseWindow: true });
          }
        }
      }
      return this.f.reload(window2, options?.disableExtensions !== void 0 ? { _: [], "disable-extensions": options.disableExtensions } : void 0);
    }
  }
  async closeWindow(windowId, options) {
    const window2 = this.H(options?.targetWindowId, windowId);
    return window2?.win?.close();
  }
  async quit(windowId) {
    const window2 = this.a.getLastActiveWindow();
    if (window2?.isExtensionDevelopmentHost && this.a.getWindowCount() > 1 && window2.win) {
      window2.win.close();
    } else {
      this.f.quit();
    }
  }
  async exit(windowId, code2) {
    await this.f.kill(code2);
  }
  //#endregion
  //#region Connectivity
  async resolveProxy(windowId, url) {
    if (this.g.extensionTestsLocationURI) {
      const testProxy = this.r.getValue("integration-test.http.proxy");
      if (testProxy) {
        return testProxy;
      }
    }
    const window2 = this.I(windowId);
    const session3 = window2?.win?.webContents?.session;
    return session3?.resolveProxy(url);
  }
  async lookupAuthorization(_windowId, authInfo) {
    return this.t.lookupAuthorization(authInfo);
  }
  async lookupKerberosAuthorization(_windowId, url) {
    return this.s.lookupKerberosAuthorization(url);
  }
  async loadCertificates(_windowId) {
    return this.s.loadCertificates();
  }
  findFreePort(windowId, startPort, giveUpAfter, timeout, stride = 1) {
    return $lh(startPort, giveUpAfter, timeout, stride);
  }
  //#endregion
  //#region Development
  async openDevTools(windowId, options) {
    const window2 = this.H(options?.targetWindowId, windowId);
    let mode = void 0;
    if ($n && $TE(this.r)) {
      mode = "bottom";
    }
    window2?.win?.webContents.openDevTools(mode ? { mode } : void 0);
  }
  async toggleDevTools(windowId, options) {
    const window2 = this.H(options?.targetWindowId, windowId);
    const webContents3 = window2?.win?.webContents;
    if (!webContents3) {
      return;
    }
    if ($n && $TE(this.r) && !webContents3.isDevToolsOpened()) {
      webContents3.openDevTools({ mode: "bottom" });
    } else {
      webContents3.toggleDevTools();
    }
  }
  //#endregion
  // #region Performance
  async profileRenderer(windowId, session3, duration) {
    const window2 = this.I(windowId);
    if (!window2 || !window2.win) {
      throw new Error();
    }
    const profiler = new $Akc(window2.win, session3, this.h);
    const result = await profiler.inspect(duration);
    return result;
  }
  // #endregion
  //#region Registry (windows)
  async windowsGetStringRegKey(windowId, hive, path3, name) {
    if (!$l) {
      return void 0;
    }
    const Registry = await import("@vscode/windows-registry");
    try {
      return Registry.GetStringRegKey(hive, path3, name);
    } catch {
      return void 0;
    }
  }
  //#endregion
  H(windowId, fallbackCodeWindowId) {
    return this.I(windowId) ?? this.J(windowId) ?? this.I(fallbackCodeWindowId);
  }
  I(windowId) {
    if (typeof windowId !== "number") {
      return void 0;
    }
    return this.a.getWindowById(windowId);
  }
  J(windowId) {
    if (typeof windowId !== "number") {
      return void 0;
    }
    const contents = webContents.fromId(windowId);
    if (!contents) {
      return void 0;
    }
    return this.b.getWindowByWebContents(contents);
  }
};
__decorate([
  $ri
], $Dkc.prototype, "G", null);
$Dkc = __decorate([
  __param(0, $Pjc),
  __param(1, $Bkc),
  __param(2, $Kjc),
  __param(3, $9jc),
  __param(4, $Cjc),
  __param(5, $uk),
  __param(6, $Nk),
  __param(7, $Njc),
  __param(8, $2jc),
  __param(9, $tj),
  __param(10, $qq),
  __param(11, $gkc)
], $Dkc);

// out-build/vs/platform/product/common/product.js
var product;
var vscodeGlobal2 = globalThis.vscode;
if (typeof vscodeGlobal2 !== "undefined" && typeof vscodeGlobal2.context !== "undefined") {
  const configuration = vscodeGlobal2.context.configuration();
  if (configuration) {
    product = configuration.product;
  } else {
    throw new Error("Sandbox: unable to resolve product configuration from preload script.");
  }
} else if (globalThis._VSCODE_PRODUCT_JSON && globalThis._VSCODE_PACKAGE_JSON) {
  product = globalThis._VSCODE_PRODUCT_JSON;
  if (env["VSCODE_DEV"]) {
    Object.assign(product, {
      nameShort: `${product.nameShort} Dev`,
      nameLong: `${product.nameLong} Dev`,
      dataFolderName: `${product.dataFolderName}-dev`,
      serverDataFolderName: product.serverDataFolderName ? `${product.serverDataFolderName}-dev` : void 0
    });
  }
  if (!product.version) {
    const pkg = globalThis._VSCODE_PACKAGE_JSON;
    Object.assign(product, {
      version: pkg.version
    });
  }
} else {
  product = {
    /*BUILD->INSERT_PRODUCT_CONFIGURATION*/
  };
  if (Object.keys(product).length === 0) {
    Object.assign(product, {
      version: "1.94.0-dev",
      nameShort: "Code - OSS Dev",
      nameLong: "Code - OSS Dev",
      applicationName: "code-oss",
      dataFolderName: ".vscode-oss",
      urlProtocol: "code-oss",
      reportIssueUrl: "https://github.com/microsoft/vscode/issues/new",
      licenseName: "MIT",
      licenseUrl: "https://github.com/microsoft/vscode/blob/main/LICENSE.txt",
      serverLicenseUrl: "https://github.com/microsoft/vscode/blob/main/LICENSE.txt"
    });
  }
}
var product_default = product;

// out-build/vs/platform/protocol/electron-main/protocol.js
var $Mjc = $Zi("protocolMainService");

// out-build/vs/base/common/amd.js
var $4 = true;
var $5 = false;
var LoaderEventType;
(function(LoaderEventType2) {
  LoaderEventType2[LoaderEventType2["LoaderAvailable"] = 1] = "LoaderAvailable";
  LoaderEventType2[LoaderEventType2["BeginLoadingScript"] = 10] = "BeginLoadingScript";
  LoaderEventType2[LoaderEventType2["EndLoadingScriptOK"] = 11] = "EndLoadingScriptOK";
  LoaderEventType2[LoaderEventType2["EndLoadingScriptError"] = 12] = "EndLoadingScriptError";
  LoaderEventType2[LoaderEventType2["BeginInvokeFactory"] = 21] = "BeginInvokeFactory";
  LoaderEventType2[LoaderEventType2["EndInvokeFactory"] = 22] = "EndInvokeFactory";
  LoaderEventType2[LoaderEventType2["NodeBeginEvaluatingScript"] = 31] = "NodeBeginEvaluatingScript";
  LoaderEventType2[LoaderEventType2["NodeEndEvaluatingScript"] = 32] = "NodeEndEvaluatingScript";
  LoaderEventType2[LoaderEventType2["NodeBeginNativeRequire"] = 33] = "NodeBeginNativeRequire";
  LoaderEventType2[LoaderEventType2["NodeEndNativeRequire"] = 34] = "NodeEndNativeRequire";
  LoaderEventType2[LoaderEventType2["CachedDataFound"] = 60] = "CachedDataFound";
  LoaderEventType2[LoaderEventType2["CachedDataMissed"] = 61] = "CachedDataMissed";
  LoaderEventType2[LoaderEventType2["CachedDataRejected"] = 62] = "CachedDataRejected";
  LoaderEventType2[LoaderEventType2["CachedDataCreated"] = 63] = "CachedDataCreated";
})(LoaderEventType || (LoaderEventType = {}));

// out-build/vs/platform/cssDev/node/cssDevService.js
import { spawn as spawn3 } from "child_process";
import { relative } from "path";
var $SS = $Zi("ICSSDevelopmentService");
var $TS = class $TS2 {
  constructor(b, c) {
    this.b = b;
    this.c = c;
  }
  get isEnabled() {
    return !this.b.isBuilt && $4;
  }
  getCssModules() {
    this.a ??= this.d();
    return this.a;
  }
  async d() {
    if (!this.isEnabled) {
      return [];
    }
    const rg = await import("@vscode/ripgrep");
    return await new Promise((resolve2) => {
      const sw = $xe.create();
      const chunks = [];
      const decoder = new TextDecoder();
      const basePath = $hh.asFileUri("").fsPath;
      const process2 = spawn3(rg.rgPath, ["-g", "**/*.css", "--files", "--no-ignore", basePath], {});
      process2.stdout.on("data", (data) => {
        const chunk = decoder.decode(data, { stream: true });
        chunks.push(chunk.split("\n").filter(Boolean));
      });
      process2.on("error", (err) => {
        this.c.error("[CSS_DEV] FAILED to compute CSS data", err);
        resolve2([]);
      });
      process2.on("close", () => {
        const result = chunks.flat().map((path3) => relative(basePath, path3).replace(/\\/g, "/")).filter(Boolean).sort();
        resolve2(result);
        this.c.info(`[CSS_DEV] DONE, ${result.length} css modules (${Math.round(sw.elapsed())}ms)`);
      });
    });
  }
};
$TS = __decorate([
  __param(0, $7i),
  __param(1, $uk)
], $TS);

// out-build/vs/platform/issue/electron-main/issueMainService.js
var $Ekc_1;
var $Ekc = class $Ekc2 {
  static {
    $Ekc_1 = this;
  }
  static {
    this.a = "#1E1E1E";
  }
  constructor(d, e, f, g, h, i, j, k) {
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h;
    this.i = i;
    this.j = j;
    this.k = k;
    this.b = null;
    this.c = null;
  }
  //#region Used by renderer
  async openReporter(data) {
    if (!this.b) {
      this.c = BrowserWindow2.getFocusedWindow();
      if (this.c) {
        const issueReporterDisposables = new $9c();
        const issueReporterWindowConfigUrl = issueReporterDisposables.add(this.i.createIPCObjectUrl());
        const position = this.n(this.c, 700, 800);
        this.b = this.m(position, issueReporterWindowConfigUrl, {
          backgroundColor: data.styles.backgroundColor,
          title: localize(1923, null),
          zoomLevel: data.zoomLevel,
          alwaysOnTop: false
        }, "issue-reporter");
        issueReporterWindowConfigUrl.update({
          appRoot: this.e.appRoot,
          windowId: this.b.id,
          userEnv: this.d,
          data,
          disableExtensions: !!this.e.disableExtensions,
          os: {
            type: type2(),
            arch: arch2(),
            release: release3()
          },
          product: product_default,
          nls: {
            messages: $f(),
            language: $g()
          },
          cssModules: this.k.isEnabled ? await this.k.getCssModules() : void 0
        });
        this.b.loadURL($hh.asBrowserUri(`vs/workbench/contrib/issue/electron-sandbox/issueReporter${this.e.isBuilt ? "" : "-dev"}.${$4 ? "esm." : ""}html`).toString(true));
        this.b.on("close", () => {
          this.b = null;
          issueReporterDisposables.dispose();
        });
        this.c.on("closed", () => {
          if (this.b) {
            this.b.close();
            this.b = null;
            issueReporterDisposables.dispose();
          }
        });
      }
    } else if (this.b) {
      this.l(this.b);
    }
  }
  //#endregion
  //#region used by issue reporter window
  async $reloadWithExtensionsDisabled() {
    if (this.c) {
      try {
        await this.h.reload(this.c.id, { disableExtensions: true });
      } catch (error) {
        this.f.error(error);
      }
    }
  }
  async $showConfirmCloseDialog() {
    if (this.b) {
      const { response } = await this.g.showMessageBox({
        type: "warning",
        message: localize(1924, null),
        buttons: [
          localize(1925, null),
          localize(1926, null)
        ]
      }, this.b);
      if (response === 0) {
        if (this.b) {
          this.b.destroy();
          this.b = null;
        }
      }
    }
  }
  async $showClipboardDialog() {
    if (this.b) {
      const { response } = await this.g.showMessageBox({
        type: "warning",
        message: localize(1927, null),
        buttons: [
          localize(1928, null),
          localize(1929, null)
        ]
      }, this.b);
      return response === 0;
    }
    return false;
  }
  issueReporterWindowCheck() {
    if (!this.c) {
      throw new Error("Issue reporter window not available");
    }
    const window2 = this.j.getWindowById(this.c.id);
    if (!window2) {
      throw new Error("Window not found");
    }
    return window2;
  }
  async $sendReporterMenu(extensionId, extensionName) {
    const window2 = this.issueReporterWindowCheck();
    const replyChannel = `vscode:triggerReporterMenu`;
    const cts = new $Pe();
    window2.sendWhenReady(replyChannel, cts.token, { replyChannel, extensionId, extensionName });
    const result = await $Qh(new Promise((resolve2) => $ZY.once(`vscode:triggerReporterMenuResponse:${extensionId}`, (_, data) => resolve2(data))), 5e3, () => {
      this.f.error(`Error: Extension ${extensionId} timed out waiting for menu response`);
      cts.cancel();
    });
    return result;
  }
  async $closeReporter() {
    this.b?.close();
  }
  //#endregion
  l(window2) {
    if (window2.isMinimized()) {
      window2.restore();
    }
    window2.focus();
  }
  m(position, ipcObjectUrl, options, windowKind) {
    const window2 = new BrowserWindow2({
      fullscreen: false,
      skipTaskbar: false,
      resizable: true,
      width: position.width,
      height: position.height,
      minWidth: 300,
      minHeight: 200,
      x: position.x,
      y: position.y,
      title: options.title,
      backgroundColor: options.backgroundColor || $Ekc_1.a,
      webPreferences: {
        preload: $hh.asFileUri("vs/base/parts/sandbox/electron-sandbox/preload.js").fsPath,
        additionalArguments: [`--vscode-window-config=${ipcObjectUrl.resource.toString()}`],
        v8CacheOptions: this.e.useCodeCache ? "bypassHeatCheck" : "none",
        enableWebSQL: false,
        spellcheck: false,
        zoomFactor: $VE(options.zoomLevel),
        sandbox: true
      },
      alwaysOnTop: options.alwaysOnTop,
      experimentalDarkMode: true
    });
    window2.setMenuBarVisibility(false);
    return window2;
  }
  n(parentWindow, defaultWidth, defaultHeight) {
    let displayToUse;
    const displays = screen2.getAllDisplays();
    if (displays.length === 1) {
      displayToUse = displays[0];
    } else {
      if ($m) {
        const cursorPoint = screen2.getCursorScreenPoint();
        displayToUse = screen2.getDisplayNearestPoint(cursorPoint);
      }
      if (!displayToUse && parentWindow) {
        displayToUse = screen2.getDisplayMatching(parentWindow.getBounds());
      }
      if (!displayToUse) {
        displayToUse = screen2.getPrimaryDisplay() || displays[0];
      }
    }
    const displayBounds = displayToUse.bounds;
    const state = {
      width: defaultWidth,
      height: defaultHeight,
      x: displayBounds.x + displayBounds.width / 2 - defaultWidth / 2,
      y: displayBounds.y + displayBounds.height / 2 - defaultHeight / 2
    };
    if (displayBounds.width > 0 && displayBounds.height > 0) {
      if (state.x < displayBounds.x) {
        state.x = displayBounds.x;
      }
      if (state.y < displayBounds.y) {
        state.y = displayBounds.y;
      }
      if (state.x > displayBounds.x + displayBounds.width) {
        state.x = displayBounds.x;
      }
      if (state.y > displayBounds.y + displayBounds.height) {
        state.y = displayBounds.y;
      }
      if (state.width > displayBounds.width) {
        state.width = displayBounds.width;
      }
      if (state.height > displayBounds.height) {
        state.height = displayBounds.height;
      }
    }
    return state;
  }
};
$Ekc = $Ekc_1 = __decorate([
  __param(1, $Cjc),
  __param(2, $uk),
  __param(3, $Kjc),
  __param(4, $Ckc),
  __param(5, $Mjc),
  __param(6, $Pjc),
  __param(7, $SS)
], $Ekc);

// out-build/vs/platform/issue/electron-main/processMainService.js
import { BrowserWindow as BrowserWindow3, contentTracing, screen as screen3 } from "electron";

// out-build/vs/base/node/ps.js
import { exec as exec2 } from "child_process";
function $ht(rootPid) {
  return new Promise((resolve2, reject) => {
    let rootItem;
    const map = /* @__PURE__ */ new Map();
    function addToTree(pid, ppid, cmd, load, mem) {
      const parent = map.get(ppid);
      if (pid === rootPid || parent) {
        const item = {
          name: findName(cmd),
          cmd,
          pid,
          ppid,
          load,
          mem
        };
        map.set(pid, item);
        if (pid === rootPid) {
          rootItem = item;
        }
        if (parent) {
          if (!parent.children) {
            parent.children = [];
          }
          parent.children.push(item);
          if (parent.children.length > 1) {
            parent.children = parent.children.sort((a, b) => a.pid - b.pid);
          }
        }
      }
    }
    function findName(cmd) {
      const UTILITY_NETWORK_HINT = /--utility-sub-type=network/i;
      const WINDOWS_CRASH_REPORTER = /--crashes-directory/i;
      const WINPTY = /\\pipe\\winpty-control/i;
      const CONPTY = /conhost\.exe.+--headless/i;
      const TYPE = /--type=([a-zA-Z-]+)/;
      if (WINDOWS_CRASH_REPORTER.exec(cmd)) {
        return "electron-crash-reporter";
      }
      if (WINPTY.exec(cmd)) {
        return "winpty-agent";
      }
      if (CONPTY.exec(cmd)) {
        return "conpty-agent";
      }
      let matches = TYPE.exec(cmd);
      if (matches && matches.length === 2) {
        if (matches[1] === "renderer") {
          return `window`;
        } else if (matches[1] === "utility") {
          if (UTILITY_NETWORK_HINT.exec(cmd)) {
            return "utility-network-service";
          }
          return "utility-process";
        } else if (matches[1] === "extensionHost") {
          return "extension-host";
        }
        return matches[1];
      }
      const JS = /[a-zA-Z-]+\.js/g;
      let result = "";
      do {
        matches = JS.exec(cmd);
        if (matches) {
          result += matches + " ";
        }
      } while (matches);
      if (result) {
        if (cmd.indexOf("node ") < 0 && cmd.indexOf("node.exe") < 0) {
          return `electron-nodejs (${result})`;
        }
      }
      return cmd;
    }
    if (process.platform === "win32") {
      const cleanUNCPrefix = (value) => {
        if (value.indexOf("\\\\?\\") === 0) {
          return value.substring(4);
        } else if (value.indexOf("\\??\\") === 0) {
          return value.substring(4);
        } else if (value.indexOf('"\\\\?\\') === 0) {
          return '"' + value.substring(5);
        } else if (value.indexOf('"\\??\\') === 0) {
          return '"' + value.substring(5);
        } else {
          return value;
        }
      };
      import("@vscode/windows-process-tree").then((windowsProcessTree) => {
        windowsProcessTree.getProcessList(rootPid, (processList) => {
          if (!processList) {
            reject(new Error(`Root process ${rootPid} not found`));
            return;
          }
          windowsProcessTree.getProcessCpuUsage(processList, (completeProcessList) => {
            const processItems = /* @__PURE__ */ new Map();
            completeProcessList.forEach((process2) => {
              const commandLine = cleanUNCPrefix(process2.commandLine || "");
              processItems.set(process2.pid, {
                name: findName(commandLine),
                cmd: commandLine,
                pid: process2.pid,
                ppid: process2.ppid,
                load: process2.cpu || 0,
                mem: process2.memory || 0
              });
            });
            rootItem = processItems.get(rootPid);
            if (rootItem) {
              processItems.forEach((item) => {
                const parent = processItems.get(item.ppid);
                if (parent) {
                  if (!parent.children) {
                    parent.children = [];
                  }
                  parent.children.push(item);
                }
              });
              processItems.forEach((item) => {
                if (item.children) {
                  item.children = item.children.sort((a, b) => a.pid - b.pid);
                }
              });
              resolve2(rootItem);
            } else {
              reject(new Error(`Root process ${rootPid} not found`));
            }
          });
        }, windowsProcessTree.ProcessDataFlag.CommandLine | windowsProcessTree.ProcessDataFlag.Memory);
      });
    } else {
      let calculateLinuxCpuUsage2 = function() {
        let processes = [rootItem];
        const pids = [];
        while (processes.length) {
          const process2 = processes.shift();
          if (process2) {
            pids.push(process2.pid);
            if (process2.children) {
              processes = processes.concat(process2.children);
            }
          }
        }
        let cmd = JSON.stringify($hh.asFileUri("vs/base/node/cpuUsage.sh").fsPath);
        cmd += " " + pids.join(" ");
        exec2(cmd, {}, (err, stdout, stderr) => {
          if (err || stderr) {
            reject(err || new Error(stderr.toString()));
          } else {
            const cpuUsage = stdout.toString().split("\n");
            for (let i = 0; i < pids.length; i++) {
              const processInfo = map.get(pids[i]);
              processInfo.load = parseFloat(cpuUsage[i]);
            }
            if (!rootItem) {
              reject(new Error(`Root process ${rootPid} not found`));
              return;
            }
            resolve2(rootItem);
          }
        });
      };
      var calculateLinuxCpuUsage = calculateLinuxCpuUsage2;
      exec2("which ps", {}, (err, stdout, stderr) => {
        if (err || stderr) {
          if (process.platform !== "linux") {
            reject(err || new Error(stderr.toString()));
          } else {
            const cmd = JSON.stringify($hh.asFileUri("vs/base/node/ps.sh").fsPath);
            exec2(cmd, {}, (err2, stdout2, stderr2) => {
              if (err2 || stderr2) {
                reject(err2 || new Error(stderr2.toString()));
              } else {
                parsePsOutput(stdout2, addToTree);
                calculateLinuxCpuUsage2();
              }
            });
          }
        } else {
          const ps = stdout.toString().trim();
          const args = "-ax -o pid=,ppid=,pcpu=,pmem=,command=";
          exec2(`${ps} ${args}`, { maxBuffer: 1e3 * 1024, env: { LC_NUMERIC: "en_US.UTF-8" } }, (err2, stdout2, stderr2) => {
            if (err2 || stderr2 && !stderr2.includes("screen size is bogus")) {
              reject(err2 || new Error(stderr2.toString()));
            } else {
              parsePsOutput(stdout2, addToTree);
              if (process.platform === "linux") {
                calculateLinuxCpuUsage2();
              } else {
                if (!rootItem) {
                  reject(new Error(`Root process ${rootPid} not found`));
                } else {
                  resolve2(rootItem);
                }
              }
            }
          });
        }
      });
    }
  });
}
function parsePsOutput(stdout, addToTree) {
  const PID_CMD = /^\s*([0-9]+)\s+([0-9]+)\s+([0-9]+\.[0-9]+)\s+([0-9]+\.[0-9]+)\s+(.+)$/;
  const lines = stdout.toString().split("\n");
  for (const line of lines) {
    const matches = PID_CMD.exec(line.trim());
    if (matches && matches.length === 6) {
      addToTree(parseInt(matches[1]), parseInt(matches[2]), matches[5], parseFloat(matches[3]), parseFloat(matches[4]));
    }
  }
}

// out-build/vs/platform/issue/electron-main/processMainService.js
var $Fkc_1;
var processExplorerWindowState = "issue.processExplorerWindowState";
var $Fkc = class $Fkc2 {
  static {
    $Fkc_1 = this;
  }
  static {
    this.a = "#1E1E1E";
  }
  constructor(d, f, g, h, i, j, k, l, m, n, o) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h;
    this.i = i;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.b = null;
    this.c = null;
    this.p();
  }
  //#region Register Listeners
  p() {
    $ZY.on("vscode:listProcesses", async (event) => {
      const processes = [];
      try {
        processes.push({ name: localize(1930, null), rootProcess: await $ht(process.pid) });
        const remoteDiagnostics = await this.i.getRemoteDiagnostics({ includeProcesses: true });
        remoteDiagnostics.forEach((data) => {
          if ($cn(data)) {
            processes.push({
              name: data.hostName,
              rootProcess: data
            });
          } else {
            if (data.processes) {
              processes.push({
                name: data.hostName,
                rootProcess: data.processes
              });
            }
          }
        });
      } catch (e) {
        this.g.error(`Listing processes failed: ${e}`);
      }
      this.t(event, "vscode:listProcessesResponse", processes);
    });
    $ZY.on("vscode:workbenchCommand", (_, commandInfo) => {
      const { id: id2, from, args } = commandInfo;
      let parentWindow;
      switch (from) {
        case "processExplorer":
          parentWindow = this.c;
          break;
        default:
          throw new Error(`Unexpected command source: ${from}`);
      }
      parentWindow?.webContents.send("vscode:runAction", { id: id2, from, args });
    });
    $ZY.on("vscode:closeProcessExplorer", (event) => {
      this.b?.close();
    });
    $ZY.on("vscode:pidToNameRequest", async (event) => {
      const mainProcessInfo = await this.i.getMainDiagnostics();
      const pidToNames = [];
      for (const window2 of mainProcessInfo.windows) {
        pidToNames.push([window2.pid, `window [${window2.id}] (${window2.title})`]);
      }
      for (const { pid, name } of $kkc.getAll()) {
        pidToNames.push([pid, name]);
      }
      this.t(event, "vscode:pidToNameResponse", pidToNames);
    });
  }
  async openProcessExplorer(data) {
    if (!this.b) {
      this.c = BrowserWindow3.getFocusedWindow();
      if (this.c) {
        const processExplorerDisposables = new $9c();
        const processExplorerWindowConfigUrl = processExplorerDisposables.add(this.l.createIPCObjectUrl());
        const savedPosition = this.n.getItem(processExplorerWindowState, void 0);
        const position = isStrictWindowState(savedPosition) ? savedPosition : this.r(this.c, 800, 500);
        this.b = this.s(position, processExplorerWindowConfigUrl, {
          backgroundColor: data.styles.backgroundColor,
          title: localize(1931, null),
          zoomLevel: data.zoomLevel,
          alwaysOnTop: true
        }, "process-explorer");
        processExplorerWindowConfigUrl.update({
          appRoot: this.f.appRoot,
          windowId: this.b.id,
          userEnv: this.d,
          data,
          product: product_default,
          nls: {
            messages: $f(),
            language: $g()
          },
          cssModules: this.o.isEnabled ? await this.o.getCssModules() : void 0
        });
        this.b.loadURL($hh.asBrowserUri(`vs/code/electron-sandbox/processExplorer/processExplorer${this.f.isBuilt ? "" : "-dev"}.${$4 ? "esm." : ""}html`).toString(true));
        this.b.on("close", () => {
          this.b = null;
          processExplorerDisposables.dispose();
        });
        this.c.on("close", () => {
          if (this.b) {
            this.b.close();
            this.b = null;
            processExplorerDisposables.dispose();
          }
        });
        const storeState = () => {
          if (!this.b) {
            return;
          }
          const size = this.b.getSize();
          const position2 = this.b.getPosition();
          if (!size || !position2) {
            return;
          }
          const state = {
            width: size[0],
            height: size[1],
            x: position2[0],
            y: position2[1]
          };
          this.n.setItem(processExplorerWindowState, state);
        };
        this.b.on("moved", storeState);
        this.b.on("resized", storeState);
      }
    }
    if (this.b) {
      this.q(this.b);
    }
  }
  q(window2) {
    if (window2.isMinimized()) {
      window2.restore();
    }
    window2.focus();
  }
  r(parentWindow, defaultWidth, defaultHeight) {
    let displayToUse;
    const displays = screen3.getAllDisplays();
    if (displays.length === 1) {
      displayToUse = displays[0];
    } else {
      if ($m) {
        const cursorPoint = screen3.getCursorScreenPoint();
        displayToUse = screen3.getDisplayNearestPoint(cursorPoint);
      }
      if (!displayToUse && parentWindow) {
        displayToUse = screen3.getDisplayMatching(parentWindow.getBounds());
      }
      if (!displayToUse) {
        displayToUse = screen3.getPrimaryDisplay() || displays[0];
      }
    }
    const displayBounds = displayToUse.bounds;
    const state = {
      width: defaultWidth,
      height: defaultHeight,
      x: displayBounds.x + displayBounds.width / 2 - defaultWidth / 2,
      y: displayBounds.y + displayBounds.height / 2 - defaultHeight / 2
    };
    if (displayBounds.width > 0 && displayBounds.height > 0) {
      if (state.x < displayBounds.x) {
        state.x = displayBounds.x;
      }
      if (state.y < displayBounds.y) {
        state.y = displayBounds.y;
      }
      if (state.x > displayBounds.x + displayBounds.width) {
        state.x = displayBounds.x;
      }
      if (state.y > displayBounds.y + displayBounds.height) {
        state.y = displayBounds.y;
      }
      if (state.width > displayBounds.width) {
        state.width = displayBounds.width;
      }
      if (state.height > displayBounds.height) {
        state.height = displayBounds.height;
      }
    }
    return state;
  }
  async stopTracing() {
    if (!this.f.args.trace) {
      return;
    }
    const path3 = await contentTracing.stopRecording(`${$8g(this.f.userHome.fsPath, this.m.applicationName)}.trace.txt`);
    await this.j.showMessageBox({
      type: "info",
      message: localize(1932, null),
      detail: localize(1933, null, path3),
      buttons: [localize(1934, null)]
    }, BrowserWindow3.getFocusedWindow() ?? void 0);
    this.k.showItemInFolder(void 0, path3);
  }
  async getSystemStatus() {
    const [info, remoteData] = await Promise.all([this.i.getMainDiagnostics(), this.i.getRemoteDiagnostics({ includeProcesses: false, includeWorkspaceMetadata: false })]);
    return this.h.getDiagnostics(info, remoteData);
  }
  async $getSystemInfo() {
    const [info, remoteData] = await Promise.all([this.i.getMainDiagnostics(), this.i.getRemoteDiagnostics({ includeProcesses: false, includeWorkspaceMetadata: false })]);
    const msg = await this.h.getSystemInfo(info, remoteData);
    return msg;
  }
  async $getPerformanceInfo() {
    try {
      const [info, remoteData] = await Promise.all([this.i.getMainDiagnostics(), this.i.getRemoteDiagnostics({ includeProcesses: true, includeWorkspaceMetadata: true })]);
      return await this.h.getPerformanceInfo(info, remoteData);
    } catch (error) {
      this.g.warn("issueService#getPerformanceInfo ", error.message);
      throw error;
    }
  }
  s(position, ipcObjectUrl, options, windowKind) {
    const window2 = new BrowserWindow3({
      fullscreen: false,
      skipTaskbar: false,
      resizable: true,
      width: position.width,
      height: position.height,
      minWidth: 300,
      minHeight: 200,
      x: position.x,
      y: position.y,
      title: options.title,
      backgroundColor: options.backgroundColor || $Fkc_1.a,
      webPreferences: {
        preload: $hh.asFileUri("vs/base/parts/sandbox/electron-sandbox/preload.js").fsPath,
        additionalArguments: [`--vscode-window-config=${ipcObjectUrl.resource.toString()}`],
        v8CacheOptions: this.f.useCodeCache ? "bypassHeatCheck" : "none",
        enableWebSQL: false,
        spellcheck: false,
        zoomFactor: $VE(options.zoomLevel),
        sandbox: true
      },
      alwaysOnTop: options.alwaysOnTop,
      experimentalDarkMode: true
    });
    window2.setMenuBarVisibility(false);
    return window2;
  }
  t(event, channel, ...args) {
    if (!event.sender.isDestroyed()) {
      event.sender.send(channel, ...args);
    }
  }
  async closeProcessExplorer() {
    this.b?.close();
  }
};
$Fkc = $Fkc_1 = __decorate([
  __param(1, $Cjc),
  __param(2, $uk),
  __param(3, $bn),
  __param(4, $nkc),
  __param(5, $Kjc),
  __param(6, $Ckc),
  __param(7, $Mjc),
  __param(8, $Nk),
  __param(9, $BS),
  __param(10, $SS)
], $Fkc);
function isStrictWindowState(obj) {
  if (typeof obj !== "object" || obj === null) {
    return false;
  }
  return "x" in obj && "y" in obj && "width" in obj && "height" in obj;
}

// out-build/vs/platform/keyboardLayout/electron-main/keyboardLayoutMainService.js
var $Gkc = $Zi("keyboardLayoutMainService");
var $Hkc = class $Hkc2 extends $0c {
  constructor(lifecycleMainService) {
    super();
    this.a = this.B(new $De());
    this.onDidChangeKeyboardLayout = this.a.event;
    this.b = null;
    this.c = null;
    lifecycleMainService.when(
      3
      /* LifecycleMainPhase.AfterWindowOpen */
    ).then(() => this.f());
  }
  f() {
    if (!this.b) {
      this.b = this.g();
    }
    return this.b;
  }
  async g() {
    const nativeKeymapMod = await import("native-keymap");
    this.c = readKeyboardLayoutData(nativeKeymapMod);
    if (!$w) {
      nativeKeymapMod.onDidChangeKeyboardLayout(() => {
        this.c = readKeyboardLayoutData(nativeKeymapMod);
        this.a.fire(this.c);
      });
    }
  }
  async getKeyboardLayoutData() {
    await this.f();
    return this.c;
  }
};
$Hkc = __decorate([
  __param(0, $9jc)
], $Hkc);
function readKeyboardLayoutData(nativeKeymapMod) {
  const keyboardMapping = nativeKeymapMod.getKeyMap();
  const keyboardLayoutInfo = nativeKeymapMod.getCurrentKeyboardLayout();
  return { keyboardMapping, keyboardLayoutInfo };
}

// out-build/vs/platform/launch/electron-main/launchMainService.js
import { app as app6 } from "electron";

// out-build/vs/platform/url/common/url.js
var $OZ = $Zi("urlService");

// out-build/vs/platform/launch/electron-main/launchMainService.js
var ID3 = "launchMainService";
var $Jkc = $Zi(ID3);
var $Kkc = class $Kkc2 {
  constructor(a, b, c, d) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
  }
  async start(args, userEnv) {
    this.a.trace("Received data from other instance: ", args, userEnv);
    if ($m) {
      app6.focus({ steal: true });
    }
    const urlsToOpen = this.e(args);
    if (urlsToOpen.length) {
      let whenWindowReady = Promise.resolve();
      if (this.b.getWindowCount() === 0) {
        const window2 = (await this.b.openEmptyWindow({
          context: 4
          /* OpenContext.DESKTOP */
        })).at(0);
        if (window2) {
          whenWindowReady = window2.ready();
        }
      }
      whenWindowReady.then(() => {
        for (const { uri, originalUrl } of urlsToOpen) {
          this.c.open(uri, { originalUrl });
        }
      });
    } else {
      return this.f(args, userEnv);
    }
  }
  e(args) {
    if (args["open-url"] && args._urls && args._urls.length > 0) {
      return $Ub(args._urls.map((url) => {
        try {
          return { uri: URI.parse(url), originalUrl: url };
        } catch (err) {
          return null;
        }
      }));
    }
    return [];
  }
  async f(args, userEnv) {
    const context = $5m(userEnv) ? 0 : 4;
    let usedWindows = [];
    const waitMarkerFileURI = args.wait && args.waitMarkerFilePath ? URI.file(args.waitMarkerFilePath) : void 0;
    const remoteAuthority = args.remote || void 0;
    const baseConfig = {
      context,
      cli: args,
      /**
       * When opening a new window from a second instance that sent args and env
       * over to this instance, we want to preserve the environment only if that second
       * instance was spawned from the CLI or used the `--preserve-env` flag (example:
       * when using `open -n "VSCode.app" --args --preserve-env WORKSPACE_FOLDER`).
       *
       * This is done to ensure that the second window gets treated exactly the same
       * as the first window, for example, it gets the same resolved user shell environment.
       *
       * https://github.com/microsoft/vscode/issues/194736
       */
      userEnv: args["preserve-env"] || context === 0 ? userEnv : void 0,
      waitMarkerFileURI,
      remoteAuthority,
      forceProfile: args.profile,
      forceTempProfile: args["profile-temp"]
    };
    if (!!args.extensionDevelopmentPath) {
      await this.b.openExtensionDevelopmentHostWindow(args.extensionDevelopmentPath, baseConfig);
    } else if (!args._.length && !args["folder-uri"] && !args["file-uri"]) {
      let openNewWindow = false;
      if (args["new-window"] || baseConfig.forceProfile || baseConfig.forceTempProfile) {
        openNewWindow = true;
      } else if (args["reuse-window"]) {
        openNewWindow = false;
      } else {
        const windowConfig = this.d.getValue("window");
        const openWithoutArgumentsInNewWindowConfig = windowConfig?.openWithoutArgumentsInNewWindow || "default";
        switch (openWithoutArgumentsInNewWindowConfig) {
          case "on":
            openNewWindow = true;
            break;
          case "off":
            openNewWindow = false;
            break;
          default:
            openNewWindow = !$m;
        }
      }
      if (openNewWindow) {
        usedWindows = await this.b.open({
          ...baseConfig,
          forceNewWindow: true,
          forceEmpty: true
        });
      } else {
        const lastActive = this.b.getLastActiveWindow();
        if (lastActive) {
          this.b.openExistingWindow(lastActive, baseConfig);
          usedWindows = [lastActive];
        } else {
          usedWindows = await this.b.open({
            ...baseConfig,
            forceEmpty: true
          });
        }
      }
    } else {
      usedWindows = await this.b.open({
        ...baseConfig,
        forceNewWindow: args["new-window"],
        preferNewWindow: !args["reuse-window"] && !args.wait,
        forceReuseWindow: args["reuse-window"],
        diffMode: args.diff,
        mergeMode: args.merge,
        addMode: args.add,
        noRecentEntry: !!args["skip-add-to-recently-opened"],
        gotoLineMode: args.goto
      });
    }
    if (waitMarkerFileURI && usedWindows.length === 1 && usedWindows[0]) {
      return Promise.race([
        usedWindows[0].whenClosedOrLoaded,
        whenDeleted(waitMarkerFileURI.fsPath)
      ]).then(() => void 0, () => void 0);
    }
  }
  async getMainProcessId() {
    this.a.trace("Received request for process ID from other instance.");
    return process.pid;
  }
};
$Kkc = __decorate([
  __param(0, $uk),
  __param(1, $Pjc),
  __param(2, $OZ),
  __param(3, $tj)
], $Kkc);

// out-build/vs/platform/menubar/electron-main/menubar.js
import { app as app8, BrowserWindow as BrowserWindow4, Menu as Menu3, MenuItem as MenuItem2 } from "electron";

// out-build/vs/platform/menubar/common/menubar.js
function $Lkc(menuItem) {
  return menuItem.submenu !== void 0;
}
function $Mkc(menuItem) {
  return menuItem.id === "vscode.menubar.separator";
}
function $Nkc(menuItem) {
  return menuItem.uri !== void 0;
}
function $Okc(menuItem) {
  return !$Lkc(menuItem) && !$Mkc(menuItem) && !$Nkc(menuItem);
}

// out-build/vs/platform/update/common/update.js
var StateType;
(function(StateType2) {
  StateType2["Uninitialized"] = "uninitialized";
  StateType2["Idle"] = "idle";
  StateType2["Disabled"] = "disabled";
  StateType2["CheckingForUpdates"] = "checking for updates";
  StateType2["AvailableForDownload"] = "available for download";
  StateType2["Downloading"] = "downloading";
  StateType2["Downloaded"] = "downloaded";
  StateType2["Updating"] = "updating";
  StateType2["Ready"] = "ready";
})(StateType || (StateType = {}));
var UpdateType;
(function(UpdateType2) {
  UpdateType2[UpdateType2["Setup"] = 0] = "Setup";
  UpdateType2[UpdateType2["Archive"] = 1] = "Archive";
  UpdateType2[UpdateType2["Snap"] = 2] = "Snap";
})(UpdateType || (UpdateType = {}));
var DisablementReason;
(function(DisablementReason2) {
  DisablementReason2[DisablementReason2["NotBuilt"] = 0] = "NotBuilt";
  DisablementReason2[DisablementReason2["DisabledByEnvironment"] = 1] = "DisabledByEnvironment";
  DisablementReason2[DisablementReason2["ManuallyDisabled"] = 2] = "ManuallyDisabled";
  DisablementReason2[DisablementReason2["MissingConfiguration"] = 3] = "MissingConfiguration";
  DisablementReason2[DisablementReason2["InvalidConfiguration"] = 4] = "InvalidConfiguration";
  DisablementReason2[DisablementReason2["RunningAsAdmin"] = 5] = "RunningAsAdmin";
})(DisablementReason || (DisablementReason = {}));
var $XZ = {
  Uninitialized: {
    type: "uninitialized"
    /* StateType.Uninitialized */
  },
  Disabled: (reason) => ({ type: "disabled", reason }),
  Idle: (updateType, error) => ({ type: "idle", updateType, error }),
  CheckingForUpdates: (explicit) => ({ type: "checking for updates", explicit }),
  AvailableForDownload: (update) => ({ type: "available for download", update }),
  Downloading: {
    type: "downloading"
    /* StateType.Downloading */
  },
  Downloaded: (update) => ({ type: "downloaded", update }),
  Updating: (update) => ({ type: "updating", update }),
  Ready: (update) => ({ type: "ready", update })
};
var $YZ = $Zi("updateService");

// out-build/vs/platform/workspaces/electron-main/workspacesHistoryMainService.js
import { app as app7 } from "electron";
var $Qkc_1;
var $Pkc = $Zi("workspacesHistoryMainService");
var $Qkc = class $Qkc2 extends $0c {
  static {
    $Qkc_1 = this;
  }
  static {
    this.a = 500;
  }
  static {
    this.b = "history.recentlyOpenedPathsList";
  }
  constructor(f, g, h, j, m) {
    super();
    this.f = f;
    this.g = g;
    this.h = h;
    this.j = j;
    this.m = m;
    this.c = this.B(new $De());
    this.onDidChangeRecentlyOpened = this.c.event;
    this.H = this.B(new $Xh(800));
    this.n();
  }
  n() {
    this.h.when(
      4
      /* LifecycleMainPhase.Eventually */
    ).then(() => this.I());
    this.B(this.g.onDidEnterWorkspace((event) => this.addRecentlyOpened([{ workspace: event.workspace, remoteAuthority: event.window.remoteAuthority }])));
  }
  //#region Workspaces History
  async addRecentlyOpened(recentToAdd) {
    let workspaces = [];
    let files = [];
    for (const recent of recentToAdd) {
      if ($9jb(recent)) {
        if (!this.g.isUntitledWorkspace(recent.workspace) && !this.w(workspaces, recent.workspace)) {
          workspaces.push(recent);
        }
      } else if ($0jb(recent)) {
        if (!this.y(workspaces, recent.folderUri)) {
          workspaces.push(recent);
        }
      } else {
        const alreadyExistsInHistory = this.z(files, recent.fileUri);
        const shouldBeFiltered = recent.fileUri.scheme === Schemas.file && $Qkc_1.G.indexOf($xh(recent.fileUri)) >= 0;
        if (!alreadyExistsInHistory && !shouldBeFiltered) {
          files.push(recent);
          if ($l && recent.fileUri.scheme === Schemas.file) {
            app7.addRecentDocument(recent.fileUri.fsPath);
          }
        }
      }
    }
    const mergedEntries = await this.r({ workspaces, files });
    workspaces = mergedEntries.workspaces;
    files = mergedEntries.files;
    if (workspaces.length > $Qkc_1.a) {
      workspaces.length = $Qkc_1.a;
    }
    if (files.length > $Qkc_1.a) {
      files.length = $Qkc_1.a;
    }
    await this.t({ workspaces, files });
    this.c.fire();
    if ($m) {
      this.H.trigger(() => this.N());
    }
  }
  async removeRecentlyOpened(recentToRemove) {
    const keep = (recent) => {
      const uri = this.u(recent);
      for (const resourceToRemove of recentToRemove) {
        if ($rh.isEqual(resourceToRemove, uri)) {
          return false;
        }
      }
      return true;
    };
    const mru = await this.getRecentlyOpened();
    const workspaces = mru.workspaces.filter(keep);
    const files = mru.files.filter(keep);
    if (workspaces.length !== mru.workspaces.length || files.length !== mru.files.length) {
      await this.t({ files, workspaces });
      this.c.fire();
      if ($m) {
        this.H.trigger(() => this.N());
      }
    }
  }
  async clearRecentlyOpened(options) {
    if (options?.confirm) {
      const { response } = await this.m.showMessageBox({
        type: "warning",
        buttons: [
          localize(2504, null),
          localize(2505, null)
        ],
        message: localize(2506, null),
        detail: localize(2507, null),
        cancelId: 1
      });
      if (response !== 0) {
        return;
      }
    }
    await this.t({ workspaces: [], files: [] });
    app7.clearRecentDocuments();
    this.c.fire();
  }
  async getRecentlyOpened() {
    return this.r();
  }
  async r(existingEntries) {
    const mapWorkspaceIdToWorkspace = new $Mc((uri) => $rh.getComparisonKey(uri));
    if (existingEntries?.workspaces) {
      for (const workspace of existingEntries.workspaces) {
        mapWorkspaceIdToWorkspace.set(this.u(workspace), workspace);
      }
    }
    const mapFileIdToFile = new $Mc((uri) => $rh.getComparisonKey(uri));
    if (existingEntries?.files) {
      for (const file of existingEntries.files) {
        mapFileIdToFile.set(this.u(file), file);
      }
    }
    const recentFromStorage = await this.s();
    for (const recentWorkspaceFromStorage of recentFromStorage.workspaces) {
      const existingRecentWorkspace = mapWorkspaceIdToWorkspace.get(this.u(recentWorkspaceFromStorage));
      if (existingRecentWorkspace) {
        existingRecentWorkspace.label = existingRecentWorkspace.label ?? recentWorkspaceFromStorage.label;
      } else {
        mapWorkspaceIdToWorkspace.set(this.u(recentWorkspaceFromStorage), recentWorkspaceFromStorage);
      }
    }
    for (const recentFileFromStorage of recentFromStorage.files) {
      const existingRecentFile = mapFileIdToFile.get(this.u(recentFileFromStorage));
      if (existingRecentFile) {
        existingRecentFile.label = existingRecentFile.label ?? recentFileFromStorage.label;
      } else {
        mapFileIdToFile.set(this.u(recentFileFromStorage), recentFileFromStorage);
      }
    }
    return {
      workspaces: [...mapWorkspaceIdToWorkspace.values()],
      files: [...mapFileIdToFile.values()]
    };
  }
  async s() {
    await this.j.whenReady;
    let storedRecentlyOpened = void 0;
    const storedRecentlyOpenedRaw = this.j.get(
      $Qkc_1.b,
      -1
      /* StorageScope.APPLICATION */
    );
    if (typeof storedRecentlyOpenedRaw === "string") {
      try {
        storedRecentlyOpened = JSON.parse(storedRecentlyOpenedRaw);
      } catch (error) {
        this.f.error("Unexpected error parsing opened paths list", error);
      }
    }
    return $dkb(storedRecentlyOpened, this.f);
  }
  async t(recent) {
    await this.j.whenReady;
    this.j.store(
      $Qkc_1.b,
      JSON.stringify($ekb(recent)),
      -1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  u(recent) {
    if ($0jb(recent)) {
      return recent.folderUri;
    }
    if ($$jb(recent)) {
      return recent.fileUri;
    }
    return recent.workspace.configPath;
  }
  w(recents, candidate) {
    return !!recents.find((recent) => $9jb(recent) && recent.workspace.id === candidate.id);
  }
  y(recents, candidate) {
    return !!recents.find((recent) => $0jb(recent) && $rh.isEqual(recent.folderUri, candidate));
  }
  z(recents, candidate) {
    return !!recents.find((recent) => $rh.isEqual(recent.fileUri, candidate));
  }
  static {
    this.C = 7;
  }
  static {
    this.D = 10;
  }
  static {
    this.F = 7;
  }
  static {
    this.G = [
      "COMMIT_EDITMSG",
      "MERGE_MSG",
      "git-rebase-todo"
    ];
  }
  async I() {
    if (!$l) {
      return;
    }
    await this.J();
    this.B(this.onDidChangeRecentlyOpened(() => this.J()));
  }
  async J() {
    if (!$l) {
      return;
    }
    const jumpList = [];
    jumpList.push({
      type: "tasks",
      items: [
        {
          type: "task",
          title: localize(2508, null),
          description: localize(2509, null),
          program: process.execPath,
          args: "-n",
          // force new window
          iconPath: process.execPath,
          iconIndex: 0
        }
      ]
    });
    if ((await this.getRecentlyOpened()).workspaces.length > 0) {
      const toRemove = [];
      for (const item of app7.getJumpListSettings().removedItems) {
        const args = item.args;
        if (args) {
          const match = /^--(folder|file)-uri\s+"([^"]+)"$/.exec(args);
          if (match) {
            toRemove.push(URI.parse(match[2]));
          }
        }
      }
      await this.removeRecentlyOpened(toRemove);
      let hasWorkspaces = false;
      const items = $Ub((await this.getRecentlyOpened()).workspaces.slice(0, $Qkc_1.F).map((recent) => {
        const workspace = $9jb(recent) ? recent.workspace : recent.folderUri;
        const { title, description } = this.L(workspace, recent.label);
        let args;
        if (URI.isUri(workspace)) {
          args = `--folder-uri "${workspace.toString()}"`;
        } else {
          hasWorkspaces = true;
          args = `--file-uri "${workspace.configPath.toString()}"`;
        }
        return {
          type: "task",
          title: title.substr(0, 255),
          // Windows seems to be picky around the length of entries
          description: description.substr(0, 255),
          // (see https://github.com/microsoft/vscode/issues/111177)
          program: process.execPath,
          args,
          iconPath: "explorer.exe",
          // simulate folder icon
          iconIndex: 0
        };
      }));
      if (items.length > 0) {
        jumpList.push({
          type: "custom",
          name: hasWorkspaces ? localize(2510, null) : localize(2511, null),
          items
        });
      }
    }
    jumpList.push({
      type: "recent"
      // this enables to show files in the "recent" category
    });
    try {
      const res = app7.setJumpList(jumpList);
      if (res && res !== "ok") {
        this.f.warn(`updateWindowsJumpList#setJumpList unexpected result: ${res}`);
      }
    } catch (error) {
      this.f.warn("updateWindowsJumpList#setJumpList", error);
    }
  }
  L(workspace, recentLabel) {
    if (recentLabel) {
      return { title: $Ax(recentLabel).name, description: recentLabel };
    }
    if (URI.isUri(workspace)) {
      return { title: $xh(workspace), description: this.M(workspace) };
    }
    if (this.g.isUntitledWorkspace(workspace)) {
      return { title: localize(2512, null), description: "" };
    }
    let filename = $xh(workspace.configPath);
    if (filename.endsWith($jj)) {
      filename = filename.substr(0, filename.length - $jj.length - 1);
    }
    return { title: localize(2513, null, filename), description: this.M(workspace.configPath) };
  }
  M(uri) {
    return uri.scheme === "file" ? $sx(uri.fsPath) : uri.toString();
  }
  async N() {
    if (!$m) {
      return;
    }
    app7.clearRecentDocuments();
    const mru = await this.getRecentlyOpened();
    const workspaceEntries = [];
    let entries = 0;
    for (let i = 0; i < mru.workspaces.length && entries < $Qkc_1.C; i++) {
      const loc = this.u(mru.workspaces[i]);
      if (loc.scheme === Schemas.file) {
        const workspacePath = $oh(loc);
        if (await Promises2.exists(workspacePath)) {
          workspaceEntries.push(workspacePath);
          entries++;
        }
      }
    }
    const fileEntries = [];
    for (let i = 0; i < mru.files.length && entries < $Qkc_1.D; i++) {
      const loc = this.u(mru.files[i]);
      if (loc.scheme === Schemas.file) {
        const filePath = $oh(loc);
        if ($Qkc_1.G.includes($xh(loc)) || // skip some well known file entries
        workspaceEntries.includes(filePath)) {
          continue;
        }
        if (await Promises2.exists(filePath)) {
          fileEntries.push(filePath);
          entries++;
        }
      }
    }
    fileEntries.reverse().forEach((fileEntry) => app7.addRecentDocument(fileEntry));
    workspaceEntries.reverse().forEach((workspaceEntry) => app7.addRecentDocument(workspaceEntry));
  }
};
$Qkc = $Qkc_1 = __decorate([
  __param(0, $uk),
  __param(1, $2jc),
  __param(2, $9jc),
  __param(3, $ekc),
  __param(4, $Kjc)
], $Qkc);

// out-build/vs/platform/menubar/electron-main/menubar.js
var $Rkc_1;
var telemetryFrom = "menu";
var $Rkc = class $Rkc2 extends $0c {
  static {
    $Rkc_1 = this;
  }
  static {
    this.a = "lastKnownMenubarData";
  }
  constructor(t, u, w, y, z, C, D, F, G, H, I, J) {
    super();
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.s = /* @__PURE__ */ Object.create(null);
    this.h = new $_h(() => this.R(), 0);
    this.j = new $_h(() => {
      this.m = [];
    }, 1e4);
    this.n = /* @__PURE__ */ Object.create(null);
    this.r = /* @__PURE__ */ Object.create(null);
    if ($m || $QE(u)) {
      this.L();
    }
    this.M();
    this.f = false;
    this.g = false;
    this.m = [];
    this.W();
    this.N();
  }
  L() {
    const menubarData = this.D.getItem($Rkc_1.a);
    if (menubarData) {
      if (menubarData.menus) {
        this.n = menubarData.menus;
      }
      if (menubarData.keybindings) {
        this.r = menubarData.keybindings;
      }
    }
  }
  M() {
    this.s["workbench.action.files.newUntitledFile"] = (menuItem, win, event) => {
      if (!this.lb({ type: "commandId", commandId: "workbench.action.files.newUntitledFile" })) {
        this.w.openEmptyWindow({ context: 2, contextWindowId: win?.id });
      }
    };
    this.s["workbench.action.newWindow"] = (menuItem, win, event) => this.w.openEmptyWindow({ context: 2, contextWindowId: win?.id });
    this.s["workbench.action.files.openFileFolder"] = (menuItem, win, event) => this.H.pickFileFolderAndOpen(void 0, { forceNewWindow: this.eb(event), telemetryExtraData: { from: telemetryFrom } });
    this.s["workbench.action.files.openFolder"] = (menuItem, win, event) => this.H.pickFolderAndOpen(void 0, { forceNewWindow: this.eb(event), telemetryExtraData: { from: telemetryFrom } });
    this.s["workbench.action.openWorkspace"] = (menuItem, win, event) => this.H.pickWorkspaceAndOpen(void 0, { forceNewWindow: this.eb(event), telemetryExtraData: { from: telemetryFrom } });
    this.s["workbench.action.clearRecentFiles"] = () => this.C.clearRecentlyOpened({
      confirm: true
      /* ask for confirmation */
    });
    const youTubeUrl = this.I.youTubeUrl;
    if (youTubeUrl) {
      this.s["workbench.action.openYouTubeUrl"] = () => this.ob(youTubeUrl, "openYouTubeUrl");
    }
    const requestFeatureUrl = this.I.requestFeatureUrl;
    if (requestFeatureUrl) {
      this.s["workbench.action.openRequestFeatureUrl"] = () => this.ob(requestFeatureUrl, "openUserVoiceUrl");
    }
    const reportIssueUrl = this.I.reportIssueUrl;
    if (reportIssueUrl) {
      this.s["workbench.action.openIssueReporter"] = () => this.ob(reportIssueUrl, "openReportIssues");
    }
    const licenseUrl = this.I.licenseUrl;
    if (licenseUrl) {
      this.s["workbench.action.openLicenseUrl"] = () => {
        if ($z) {
          const queryArgChar = licenseUrl.indexOf("?") > 0 ? "&" : "?";
          this.ob(`${licenseUrl}${queryArgChar}lang=${$z}`, "openLicenseUrl");
        } else {
          this.ob(licenseUrl, "openLicenseUrl");
        }
      };
    }
    const privacyStatementUrl = this.I.privacyStatementUrl;
    if (privacyStatementUrl && licenseUrl) {
      this.s["workbench.action.openPrivacyStatementUrl"] = () => {
        this.ob(privacyStatementUrl, "openPrivacyStatement");
      };
    }
  }
  N() {
    this.B(this.F.onWillShutdown(() => this.b = true));
    this.B(this.w.onDidChangeWindowsCount((e) => this.S(e)));
    this.B(this.H.onDidBlurMainWindow(() => this.U()));
    this.B(this.H.onDidFocusMainWindow(() => this.U()));
  }
  get O() {
    const enableMenuBarMnemonics = this.u.getValue("window.enableMenuBarMnemonics");
    if (typeof enableMenuBarMnemonics !== "boolean") {
      return true;
    }
    return enableMenuBarMnemonics;
  }
  get P() {
    if (!$m) {
      return false;
    }
    const enableNativeTabs = this.u.getValue("window.nativeTabs");
    if (typeof enableNativeTabs !== "boolean") {
      return false;
    }
    return enableNativeTabs;
  }
  updateMenu(menubarData, windowId) {
    this.n = menubarData.menus;
    this.r = menubarData.keybindings;
    this.D.setItem($Rkc_1.a, menubarData);
    this.Q();
  }
  Q() {
    this.h.schedule();
  }
  R() {
    if (!this.b) {
      setTimeout(
        () => {
          if (!this.b) {
            this.W();
          }
        },
        10
        /* delay this because there is an issue with updating a menu when it is open */
      );
    }
  }
  S(e) {
    if (!$m) {
      return;
    }
    if (e.oldCount === 0 && e.newCount > 0 || e.oldCount > 0 && e.newCount === 0) {
      this.f = e.newCount === 0;
      this.Q();
    }
  }
  U() {
    if (!$m) {
      return;
    }
    const focusedWindow = BrowserWindow4.getFocusedWindow();
    this.g = !focusedWindow || !!this.J.getWindowByWebContents(focusedWindow.webContents);
    this.Q();
  }
  W() {
    const oldMenu = Menu3.getApplicationMenu();
    if (oldMenu) {
      this.m.push(oldMenu);
    }
    if (Object.keys(this.n).length === 0) {
      this.X($m ? new Menu3() : null);
      return;
    }
    const menubar = new Menu3();
    let macApplicationMenuItem;
    if ($m) {
      const applicationMenu = new Menu3();
      macApplicationMenuItem = new MenuItem2({ label: this.I.nameShort, submenu: applicationMenu });
      this.Y(applicationMenu);
      menubar.append(macApplicationMenuItem);
    }
    if ($m && !this.c) {
      this.c = true;
      const dockMenu = new Menu3();
      dockMenu.append(new MenuItem2({ label: this.qb(localize(1982, null)), click: () => this.w.openEmptyWindow({
        context: 1
        /* OpenContext.DOCK */
      }) }));
      app8.dock.setMenu(dockMenu);
    }
    if (this.$("File")) {
      const fileMenu = new Menu3();
      const fileMenuItem = new MenuItem2({ label: this.qb(localize(1983, null)), submenu: fileMenu });
      this.bb(fileMenu, "File");
      menubar.append(fileMenuItem);
    }
    if (this.$("Edit")) {
      const editMenu = new Menu3();
      const editMenuItem = new MenuItem2({ label: this.qb(localize(1984, null)), submenu: editMenu });
      this.bb(editMenu, "Edit");
      menubar.append(editMenuItem);
    }
    if (this.$("Selection")) {
      const selectionMenu = new Menu3();
      const selectionMenuItem = new MenuItem2({ label: this.qb(localize(1985, null)), submenu: selectionMenu });
      this.bb(selectionMenu, "Selection");
      menubar.append(selectionMenuItem);
    }
    if (this.$("View")) {
      const viewMenu = new Menu3();
      const viewMenuItem = new MenuItem2({ label: this.qb(localize(1986, null)), submenu: viewMenu });
      this.bb(viewMenu, "View");
      menubar.append(viewMenuItem);
    }
    if (this.$("Go")) {
      const gotoMenu = new Menu3();
      const gotoMenuItem = new MenuItem2({ label: this.qb(localize(1987, null)), submenu: gotoMenu });
      this.bb(gotoMenu, "Go");
      menubar.append(gotoMenuItem);
    }
    if (this.$("Run")) {
      const debugMenu = new Menu3();
      const debugMenuItem = new MenuItem2({ label: this.qb(localize(1988, null)), submenu: debugMenu });
      this.bb(debugMenu, "Run");
      menubar.append(debugMenuItem);
    }
    if (this.$("Terminal")) {
      const terminalMenu = new Menu3();
      const terminalMenuItem = new MenuItem2({ label: this.qb(localize(1989, null)), submenu: terminalMenu });
      this.bb(terminalMenu, "Terminal");
      menubar.append(terminalMenuItem);
    }
    let macWindowMenuItem;
    if (this.$("Window")) {
      const windowMenu = new Menu3();
      macWindowMenuItem = new MenuItem2({ label: this.qb(localize(1990, null)), submenu: windowMenu, role: "window" });
      this.hb(windowMenu);
    }
    if (macWindowMenuItem) {
      menubar.append(macWindowMenuItem);
    }
    if (this.$("Help")) {
      const helpMenu = new Menu3();
      const helpMenuItem = new MenuItem2({ label: this.qb(localize(1991, null)), submenu: helpMenu, role: "help" });
      this.bb(helpMenu, "Help");
      menubar.append(helpMenuItem);
    }
    if (menubar.items && menubar.items.length > 0) {
      this.X(menubar);
    } else {
      this.X(null);
    }
    this.j.schedule();
  }
  X(menu) {
    Menu3.setApplicationMenu(menu);
    if (menu) {
      for (const window2 of this.J.getWindows()) {
        window2.win?.setMenu(null);
      }
    }
  }
  Y(macApplicationMenu) {
    const about = this.jb(localize(1992, null, this.I.nameLong), "workbench.action.showAboutDialog");
    const checkForUpdates = this.ib();
    let preferences;
    if (this.$("Preferences")) {
      const preferencesMenu = new Menu3();
      this.bb(preferencesMenu, "Preferences");
      preferences = new MenuItem2({ label: this.qb(localize(1993, null)), submenu: preferencesMenu });
    }
    const servicesMenu = new Menu3();
    const services = new MenuItem2({ label: localize(1994, null), role: "services", submenu: servicesMenu });
    const hide = new MenuItem2({ label: localize(1995, null, this.I.nameLong), role: "hide", accelerator: "Command+H" });
    const hideOthers = new MenuItem2({ label: localize(1996, null), role: "hideOthers", accelerator: "Command+Alt+H" });
    const showAll = new MenuItem2({ label: localize(1997, null), role: "unhide" });
    const quit = new MenuItem2(this.nb("workbench.action.quit", {
      label: localize(1998, null, this.I.nameLong),
      click: async (item, window2, event) => {
        const lastActiveWindow = this.w.getLastActiveWindow();
        if (this.w.getWindowCount() === 0 || // allow to quit when no more windows are open
        !!BrowserWindow4.getFocusedWindow() || // allow to quit when window has focus (fix for https://github.com/microsoft/vscode/issues/39191)
        lastActiveWindow?.win?.isMinimized()) {
          const confirmed = await this.Z(event);
          if (confirmed) {
            this.H.quit(void 0);
          }
        }
      }
    }));
    const actions = [about];
    actions.push(...checkForUpdates);
    if (preferences) {
      actions.push(...[
        __separator__(),
        preferences
      ]);
    }
    actions.push(...[
      __separator__(),
      services,
      __separator__(),
      hide,
      hideOthers,
      showAll,
      __separator__(),
      quit
    ]);
    actions.forEach((i) => macApplicationMenu.append(i));
  }
  async Z(event) {
    if (this.w.getWindowCount() === 0) {
      return true;
    }
    const confirmBeforeClose = this.u.getValue("window.confirmBeforeClose");
    if (confirmBeforeClose === "always" || confirmBeforeClose === "keyboardOnly" && this.fb(event)) {
      const { response } = await this.H.showMessageBox(this.w.getFocusedWindow()?.id, {
        type: "question",
        buttons: [
          localize(1999, null),
          localize(2e3, null)
        ],
        message: localize(2001, null)
      });
      return response === 0;
    }
    return true;
  }
  $(menuId) {
    if (!$m && !$QE(this.u)) {
      return false;
    }
    switch (menuId) {
      case "File":
      case "Help":
        if ($m) {
          return this.w.getWindowCount() === 0 && this.f || this.w.getWindowCount() > 0 && this.g || !!this.n && !!this.n[menuId];
        }
      case "Window":
        if ($m) {
          return this.w.getWindowCount() === 0 && this.f || this.w.getWindowCount() > 0 && this.g || !!this.n;
        }
      default:
        return this.w.getWindowCount() > 0 && (!!this.n && !!this.n[menuId]);
    }
  }
  ab(menu, items) {
    items.forEach((item) => {
      if ($Mkc(item)) {
        menu.append(__separator__());
      } else if ($Lkc(item)) {
        const submenu = new Menu3();
        const submenuItem = new MenuItem2({ label: this.qb(item.label), submenu });
        this.ab(submenu, item.submenu.items);
        menu.append(submenuItem);
      } else if ($Nkc(item)) {
        menu.append(this.db(item));
      } else if ($Okc(item)) {
        if (item.id === "workbench.action.showAboutDialog") {
          this.cb(menu);
        }
        if ($m) {
          if (this.w.getWindowCount() === 0 && this.f || this.w.getWindowCount() > 0 && this.g) {
            if (this.s[item.id]) {
              menu.append(new MenuItem2(this.nb(item.id, { label: this.qb(item.label), click: this.s[item.id] })));
            } else {
              menu.append(this.jb(item.label, item.id, false, item.checked));
            }
          } else {
            menu.append(this.jb(item.label, item.id, item.enabled === false ? false : true, !!item.checked));
          }
        } else {
          menu.append(this.jb(item.label, item.id, item.enabled === false ? false : true, !!item.checked));
        }
      }
    });
  }
  bb(menu, menuId) {
    if (this.n && this.n[menuId]) {
      this.ab(menu, this.n[menuId].items);
    }
  }
  cb(menu) {
    const updateItems = this.ib();
    if (updateItems.length) {
      updateItems.forEach((i) => menu.append(i));
      menu.append(__separator__());
    }
  }
  db(item) {
    const revivedUri = URI.revive(item.uri);
    const commandId = item.id;
    const openable = commandId === "openRecentFile" ? { fileUri: revivedUri } : commandId === "openRecentWorkspace" ? { workspaceUri: revivedUri } : { folderUri: revivedUri };
    return new MenuItem2(this.nb(commandId, {
      label: item.label,
      click: async (menuItem, win, event) => {
        const openInNewWindow = this.eb(event);
        const success = (await this.w.open({
          context: 2,
          cli: this.y.args,
          urisToOpen: [openable],
          forceNewWindow: openInNewWindow,
          gotoLineMode: false,
          remoteAuthority: item.remoteAuthority
        })).length > 0;
        if (!success) {
          await this.C.removeRecentlyOpened([revivedUri]);
        }
      }
    }, false));
  }
  eb(event) {
    return !!(event && (!$m && (event.ctrlKey || event.shiftKey) || $m && (event.metaKey || event.altKey)));
  }
  fb(event) {
    return !!(event.triggeredByAccelerator || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey);
  }
  gb(label, commandId, role) {
    const options = {
      label: this.qb(label),
      role,
      enabled: true
    };
    return new MenuItem2(this.mb(commandId, options));
  }
  hb(macWindowMenu) {
    const minimize = new MenuItem2({ label: localize(2002, null), role: "minimize", accelerator: "Command+M", enabled: this.w.getWindowCount() > 0 });
    const zoom = new MenuItem2({ label: localize(2003, null), role: "zoom", enabled: this.w.getWindowCount() > 0 });
    const bringAllToFront = new MenuItem2({ label: localize(2004, null), role: "front", enabled: this.w.getWindowCount() > 0 });
    const switchWindow = this.jb(localize(2005, null), "workbench.action.switchWindow");
    const nativeTabMenuItems = [];
    if (this.P) {
      nativeTabMenuItems.push(__separator__());
      nativeTabMenuItems.push(this.jb(localize(2006, null), "workbench.action.newWindowTab"));
      nativeTabMenuItems.push(this.gb(localize(2007, null), "workbench.action.showPreviousWindowTab", "selectPreviousTab"));
      nativeTabMenuItems.push(this.gb(localize(2008, null), "workbench.action.showNextWindowTab", "selectNextTab"));
      nativeTabMenuItems.push(this.gb(localize(2009, null), "workbench.action.moveWindowTabToNewWindow", "moveTabToNewWindow"));
      nativeTabMenuItems.push(this.gb(localize(2010, null), "workbench.action.mergeAllWindowTabs", "mergeAllWindows"));
    }
    [
      minimize,
      zoom,
      __separator__(),
      switchWindow,
      ...nativeTabMenuItems,
      __separator__(),
      bringAllToFront
    ].forEach((item) => macWindowMenu.append(item));
  }
  ib() {
    const state = this.t.state;
    switch (state.type) {
      case "idle":
        return [new MenuItem2({
          label: this.qb(localize(2011, null)),
          click: () => setTimeout(() => {
            this.pb("CheckForUpdate");
            this.t.checkForUpdates(true);
          }, 0)
        })];
      case "checking for updates":
        return [new MenuItem2({ label: localize(2012, null), enabled: false })];
      case "available for download":
        return [new MenuItem2({
          label: this.qb(localize(2013, null)),
          click: () => {
            this.t.downloadUpdate();
          }
        })];
      case "downloading":
        return [new MenuItem2({ label: localize(2014, null), enabled: false })];
      case "downloaded":
        return $m ? [] : [new MenuItem2({
          label: this.qb(localize(2015, null)),
          click: () => {
            this.pb("InstallUpdate");
            this.t.applyUpdate();
          }
        })];
      case "updating":
        return [new MenuItem2({ label: localize(2016, null), enabled: false })];
      case "ready":
        return [new MenuItem2({
          label: this.qb(localize(2017, null)),
          click: () => {
            this.pb("RestartToUpdate");
            this.t.quitAndInstall();
          }
        })];
      default:
        return [];
    }
  }
  jb(arg1, arg2, arg3, arg4) {
    const label = this.qb(arg1);
    const click = typeof arg2 === "function" ? arg2 : (menuItem, win, event) => {
      const userSettingsLabel = menuItem ? menuItem.userSettingsLabel : null;
      let commandId2 = arg2;
      if (Array.isArray(arg2)) {
        commandId2 = this.eb(event) ? arg2[1] : arg2[0];
      }
      if (userSettingsLabel && event.triggeredByAccelerator) {
        this.lb({ type: "keybinding", userSettingsLabel });
      } else {
        this.lb({ type: "commandId", commandId: commandId2 });
      }
    };
    const enabled = typeof arg3 === "boolean" ? arg3 : this.w.getWindowCount() > 0;
    const checked = typeof arg4 === "boolean" ? arg4 : false;
    const options = {
      label,
      click,
      enabled
    };
    if (checked) {
      options.type = "checkbox";
      options.checked = checked;
    }
    let commandId;
    if (typeof arg2 === "string") {
      commandId = arg2;
    } else if (Array.isArray(arg2)) {
      commandId = arg2[0];
    }
    if ($m) {
      if (commandId === "editor.action.clipboardCutAction") {
        options.role = "cut";
      } else if (commandId === "editor.action.clipboardCopyAction") {
        options.role = "copy";
      } else if (commandId === "editor.action.clipboardPasteAction") {
        options.role = "paste";
      }
      if (commandId === "undo") {
        options.click = this.kb(click, {
          inDevTools: (devTools) => devTools.undo(),
          inNoWindow: () => Menu3.sendActionToFirstResponder("undo:")
        });
      } else if (commandId === "redo") {
        options.click = this.kb(click, {
          inDevTools: (devTools) => devTools.redo(),
          inNoWindow: () => Menu3.sendActionToFirstResponder("redo:")
        });
      } else if (commandId === "editor.action.selectAll") {
        options.click = this.kb(click, {
          inDevTools: (devTools) => devTools.selectAll(),
          inNoWindow: () => Menu3.sendActionToFirstResponder("selectAll:")
        });
      }
    }
    return new MenuItem2(this.mb(commandId, options));
  }
  kb(click, contextSpecificHandlers) {
    return (menuItem, win, event) => {
      const activeWindow = BrowserWindow4.getFocusedWindow();
      if (!activeWindow) {
        return contextSpecificHandlers.inNoWindow();
      }
      if (activeWindow.webContents.isDevToolsFocused() && activeWindow.webContents.devToolsWebContents) {
        return contextSpecificHandlers.inDevTools(activeWindow.webContents.devToolsWebContents);
      }
      click(menuItem, win || activeWindow, event);
    };
  }
  lb(invocation) {
    let activeBrowserWindow = BrowserWindow4.getFocusedWindow();
    if (activeBrowserWindow) {
      const auxiliaryWindowCandidate = this.J.getWindowByWebContents(activeBrowserWindow.webContents);
      if (auxiliaryWindowCandidate) {
        activeBrowserWindow = this.w.getWindowById(auxiliaryWindowCandidate.parentId)?.win ?? null;
      }
    }
    if (!activeBrowserWindow) {
      const lastActiveWindow = this.w.getLastActiveWindow();
      if (lastActiveWindow?.win?.isMinimized()) {
        activeBrowserWindow = lastActiveWindow.win;
      }
    }
    const activeWindow = activeBrowserWindow ? this.w.getWindowById(activeBrowserWindow.id) : void 0;
    if (activeWindow) {
      this.G.trace("menubar#runActionInRenderer", invocation);
      if ($m && !this.y.isBuilt && !activeWindow.isReady) {
        if (invocation.type === "commandId" && invocation.commandId === "workbench.action.toggleDevTools" || invocation.type !== "commandId" && invocation.userSettingsLabel === "alt+cmd+i") {
          return false;
        }
      }
      if (invocation.type === "commandId") {
        const runActionPayload = { id: invocation.commandId, from: "menu" };
        activeWindow.sendWhenReady("vscode:runAction", CancellationToken.None, runActionPayload);
      } else {
        const runKeybindingPayload = { userSettingsLabel: invocation.userSettingsLabel };
        activeWindow.sendWhenReady("vscode:runKeybinding", CancellationToken.None, runKeybindingPayload);
      }
      return true;
    } else {
      this.G.trace("menubar#runActionInRenderer: no active window found", invocation);
      return false;
    }
  }
  mb(commandId, options) {
    const binding = typeof commandId === "string" ? this.r[commandId] : void 0;
    if (binding?.label) {
      if (binding.isNative !== false) {
        options.accelerator = binding.label;
        options.userSettingsLabel = binding.userSettingsLabel;
      } else if (typeof options.label === "string") {
        const bindingIndex = options.label.indexOf("[");
        if (bindingIndex >= 0) {
          options.label = `${options.label.substr(0, bindingIndex)} [${binding.label}]`;
        } else {
          options.label = `${options.label} [${binding.label}]`;
        }
      }
    } else {
      options.accelerator = void 0;
    }
    return options;
  }
  nb(commandId, options, setAccelerator = !options.accelerator) {
    if (setAccelerator) {
      options = this.mb(commandId, options);
    }
    const originalClick = options.click;
    options.click = (item, window2, event) => {
      this.pb(commandId);
      originalClick?.(item, window2, event);
    };
    return options;
  }
  ob(url, id2) {
    this.H.openExternal(void 0, url);
    this.pb(id2);
  }
  pb(id2) {
    this.z.publicLog2("workbenchActionExecuted", { id: id2, from: telemetryFrom });
  }
  qb(label) {
    return $xx(label, !this.O);
  }
};
$Rkc = $Rkc_1 = __decorate([
  __param(0, $YZ),
  __param(1, $tj),
  __param(2, $Pjc),
  __param(3, $Cjc),
  __param(4, $tm),
  __param(5, $Pkc),
  __param(6, $BS),
  __param(7, $9jc),
  __param(8, $uk),
  __param(9, $Ckc),
  __param(10, $Nk),
  __param(11, $Bkc)
], $Rkc);
function __separator__() {
  return new MenuItem2({ type: "separator" });
}

// out-build/vs/platform/menubar/electron-main/menubarMainService.js
var $Skc = $Zi("menubarMainService");
var $Tkc = class $Tkc2 extends $0c {
  constructor(b, c, f) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.a = this.g();
  }
  async g() {
    await this.c.when(
      3
      /* LifecycleMainPhase.AfterWindowOpen */
    );
    return this.B(this.b.createInstance($Rkc));
  }
  async updateMenubar(windowId, menus) {
    this.f.trace("menubarService#updateMenubar", windowId);
    const menubar = await this.a;
    menubar.updateMenu(menus, windowId);
  }
};
$Tkc = __decorate([
  __param(0, $Yi),
  __param(1, $9jc),
  __param(2, $uk)
], $Tkc);

// out-build/vs/platform/policy/common/policy.js
var $Oo = $Zi("policy");
var $Po = class extends $0c {
  constructor() {
    super(...arguments);
    this.f = {};
    this.g = /* @__PURE__ */ new Map();
    this.h = this.B(new $De());
    this.onDidChange = this.h.event;
  }
  async updatePolicyDefinitions(policyDefinitions) {
    const size = Object.keys(this.f).length;
    this.f = { ...policyDefinitions, ...this.f };
    if (size !== Object.keys(this.f).length) {
      await this.j(policyDefinitions);
    }
    return Iterable.reduce(this.g.entries(), (r, [name, value]) => ({ ...r, [name]: value }), {});
  }
  getPolicyValue(name) {
    return this.g.get(name);
  }
  serialize() {
    return Iterable.reduce(Object.entries(this.f), (r, [name, definition]) => ({ ...r, [name]: { definition, value: this.g.get(name) } }), {});
  }
};
var $Qo = class {
  constructor() {
    this.onDidChange = Event.None;
  }
  async updatePolicyDefinitions() {
    return {};
  }
  getPolicyValue() {
    return void 0;
  }
  serialize() {
    return void 0;
  }
};

// out-build/vs/platform/log/node/spdlogLog.js
var SpdLogLevel;
(function(SpdLogLevel2) {
  SpdLogLevel2[SpdLogLevel2["Trace"] = 0] = "Trace";
  SpdLogLevel2[SpdLogLevel2["Debug"] = 1] = "Debug";
  SpdLogLevel2[SpdLogLevel2["Info"] = 2] = "Info";
  SpdLogLevel2[SpdLogLevel2["Warning"] = 3] = "Warning";
  SpdLogLevel2[SpdLogLevel2["Error"] = 4] = "Error";
  SpdLogLevel2[SpdLogLevel2["Critical"] = 5] = "Critical";
  SpdLogLevel2[SpdLogLevel2["Off"] = 6] = "Off";
})(SpdLogLevel || (SpdLogLevel = {}));
async function createSpdLogLogger(name, logfilePath, filesize, filecount, donotUseFormatters) {
  try {
    const _spdlog = await import("@vscode/spdlog");
    _spdlog.setFlushOn(SpdLogLevel.Trace);
    const logger = await _spdlog.createAsyncRotatingLogger(name, logfilePath, filesize, filecount);
    if (donotUseFormatters) {
      logger.clearFormatters();
    } else {
      logger.setPattern("%Y-%m-%d %H:%M:%S.%e [%l] %v");
    }
    return logger;
  } catch (e) {
    console.error(e);
  }
  return null;
}
function log3(logger, level, message) {
  switch (level) {
    case LogLevel.Trace:
      logger.trace(message);
      break;
    case LogLevel.Debug:
      logger.debug(message);
      break;
    case LogLevel.Info:
      logger.info(message);
      break;
    case LogLevel.Warning:
      logger.warn(message);
      break;
    case LogLevel.Error:
      logger.error(message);
      break;
    case LogLevel.Off:
      break;
    default:
      throw new Error(`Invalid log level ${level}`);
  }
}
function setLogLevel(logger, level) {
  switch (level) {
    case LogLevel.Trace:
      logger.setLevel(SpdLogLevel.Trace);
      break;
    case LogLevel.Debug:
      logger.setLevel(SpdLogLevel.Debug);
      break;
    case LogLevel.Info:
      logger.setLevel(SpdLogLevel.Info);
      break;
    case LogLevel.Warning:
      logger.setLevel(SpdLogLevel.Warning);
      break;
    case LogLevel.Error:
      logger.setLevel(SpdLogLevel.Error);
      break;
    case LogLevel.Off:
      logger.setLevel(SpdLogLevel.Off);
      break;
    default:
      throw new Error(`Invalid log level ${level}`);
  }
}
var $yS = class extends $Ak {
  constructor(name, filepath, rotating, donotUseFormatters, level) {
    super();
    this.m = [];
    this.setLevel(level);
    this.n = this.s(name, filepath, rotating, donotUseFormatters);
    this.B(this.onDidChangeLogLevel((level2) => {
      if (this.r) {
        setLogLevel(this.r, level2);
      }
    }));
  }
  async s(name, filepath, rotating, donotUseFormatters) {
    const filecount = rotating ? 6 : 1;
    const filesize = 30 / filecount * $3l.MB;
    const logger = await createSpdLogLogger(name, filepath, filesize, filecount, donotUseFormatters);
    if (logger) {
      this.r = logger;
      setLogLevel(this.r, this.getLevel());
      for (const { level, message } of this.m) {
        log3(this.r, level, message);
      }
      this.m = [];
    }
  }
  g(level, message) {
    if (this.r) {
      log3(this.r, level, message);
    } else if (this.getLevel() <= level) {
      this.m.push({ level, message });
    }
  }
  flush() {
    if (this.r) {
      this.r.flush();
    } else {
      this.n.then(() => this.flush());
    }
  }
  dispose() {
    if (this.r) {
      this.u();
    } else {
      this.n.then(() => this.u());
    }
    super.dispose();
  }
  u() {
    if (this.r) {
      this.r.drop();
      this.r = void 0;
    }
  }
};

// out-build/vs/platform/log/node/loggerService.js
var $zS = class extends $Fk {
  s(resource, logLevel, options) {
    return new $yS($jh(), resource.fsPath, !options?.donotRotate, !!options?.donotUseFormatters, logLevel);
  }
};

// out-build/vs/platform/log/electron-main/loggerService.js
var $4jc = $1i($vk);
var $5jc = class extends $zS {
  constructor() {
    super(...arguments);
    this.u = new $Mc();
  }
  createLogger(idOrResource, options, windowId) {
    if (windowId !== void 0) {
      this.u.set(this.n(idOrResource), windowId);
    }
    try {
      return super.createLogger(idOrResource, options);
    } catch (error) {
      this.u.delete(this.n(idOrResource));
      throw error;
    }
  }
  registerLogger(resource, windowId) {
    if (windowId !== void 0) {
      this.u.set(resource.resource, windowId);
    }
    super.registerLogger(resource);
  }
  deregisterLogger(resource) {
    this.u.delete(resource);
    super.deregisterLogger(resource);
  }
  getRegisteredLoggers(windowId) {
    const resources = [];
    for (const resource of super.getRegisteredLoggers()) {
      if (windowId === this.u.get(resource.resource)) {
        resources.push(resource);
      }
    }
    return resources;
  }
  getOnDidChangeLogLevelEvent(windowId) {
    return Event.filter(this.onDidChangeLogLevel, (arg) => $wk(arg) || this.w(arg[0], windowId));
  }
  getOnDidChangeVisibilityEvent(windowId) {
    return Event.filter(this.onDidChangeVisibility, ([resource]) => this.w(resource, windowId));
  }
  getOnDidChangeLoggersEvent(windowId) {
    return Event.filter(Event.map(this.onDidChangeLoggers, (e) => {
      const r = {
        added: [...e.added].filter((loggerResource) => this.w(loggerResource.resource, windowId)),
        removed: [...e.removed].filter((loggerResource) => this.w(loggerResource.resource, windowId))
      };
      return r;
    }), (e) => e.added.length > 0 || e.removed.length > 0);
  }
  deregisterLoggers(windowId) {
    for (const [resource, resourceWindow] of this.u) {
      if (resourceWindow === windowId) {
        this.deregisterLogger(resource);
      }
    }
  }
  w(resource, windowId) {
    const loggerWindowId = this.u.get(resource);
    return loggerWindowId === void 0 || loggerWindowId === windowId;
  }
  dispose() {
    super.dispose();
    this.u.clear();
  }
};

// out-build/vs/platform/telemetry/common/commonProperties.js
function getPlatformDetail(hostname3) {
  if ($x === 2 && /^penguin(\.|$)/i.test(hostname3)) {
    return "chromebook";
  }
  return void 0;
}
function $Qp(release10, hostname3, arch5, commit, version, machineId2, sqmId, devDeviceId, isInternalTelemetry, product2) {
  const result = /* @__PURE__ */ Object.create(null);
  result["common.machineId"] = machineId2;
  result["common.sqmId"] = sqmId;
  result["common.devDeviceId"] = devDeviceId;
  result["sessionID"] = $jh() + Date.now();
  result["commitHash"] = commit;
  result["version"] = version;
  result["common.platformVersion"] = (release10 || "").replace(/^(\d+)(\.\d+)?(\.\d+)?(.*)/, "$1$2$3");
  result["common.platform"] = $k($x);
  result["common.nodePlatform"] = $pc;
  result["common.nodeArch"] = arch5;
  result["common.product"] = product2 || "desktop";
  if (isInternalTelemetry) {
    result["common.msftInternal"] = isInternalTelemetry;
  }
  let seq = 0;
  const startTime = Date.now();
  Object.defineProperties(result, {
    // __GDPR__COMMON__ "timestamp" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
    "timestamp": {
      get: () => /* @__PURE__ */ 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
    }
  });
  if ($o) {
    result["common.snap"] = "true";
  }
  const platformDetail = getPlatformDetail(hostname3);
  if (platformDetail) {
    result["common.platformDetail"] = platformDetail;
  }
  return result;
}
function $Rp(domainList) {
  const userDnsDomain = env["USERDNSDOMAIN"];
  if (!userDnsDomain) {
    return false;
  }
  const domain = userDnsDomain.toLowerCase();
  return domainList.some((msftDomain) => domain === msftDomain);
}

// out-build/vs/platform/telemetry/common/telemetryUtils.js
var $Sp = class {
  constructor(value) {
    this.value = value;
    this.isTrustedTelemetryValue = true;
  }
};
var $Tp = class {
  constructor() {
    this.telemetryLevel = 0;
    this.sessionId = "someValue.sessionId";
    this.machineId = "someValue.machineId";
    this.sqmId = "someValue.sqmId";
    this.devDeviceId = "someValue.devDeviceId";
    this.firstSessionDate = "someValue.firstSessionDate";
    this.sendErrorTelemetry = false;
  }
  publicLog() {
  }
  publicLog2() {
  }
  publicLogError() {
  }
  publicLogError2() {
  }
  setExperimentProperty() {
  }
};
var $Up = new $Tp();
function $Zp(productService, environmentService) {
  if (!environmentService.isBuilt && !environmentService.disableTelemetry) {
    return true;
  }
  return !(environmentService.disableTelemetry || !productService.enableTelemetry);
}
function $2p(configurationService) {
  const newConfig = configurationService.getValue($Cm);
  const crashReporterConfig = configurationService.getValue($Dm);
  const oldConfig = configurationService.getValue($Em);
  if (oldConfig === false || crashReporterConfig === false) {
    return 0;
  }
  switch (newConfig ?? "all") {
    case "all":
      return 3;
    case "error":
      return 2;
    case "crash":
      return 1;
    case "off":
      return 0;
  }
}
function $5p(productService, configService) {
  const msftInternalDomains = productService.msftInternalDomains || [];
  const internalTesting = configService.getValue("telemetry.internalTesting");
  return $Rp(msftInternalDomains) || internalTesting;
}
function $6p(paths) {
  return [paths.appRoot, paths.extensionsPath, paths.userHome.fsPath, paths.tmpDir.fsPath, paths.userDataPath];
}
function anonymizeFilePaths(stack, cleanupPatterns) {
  if (!stack || !stack.includes("/") && !stack.includes("\\")) {
    return stack;
  }
  let updatedStack = stack;
  const cleanUpIndexes = [];
  for (const regexp of 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;
    }
    const overlappingRange = cleanUpIndexes.some(([start, end]) => result.index < end && start < fileRegex.lastIndex);
    if (!nodeModulesRegex.test(result[0]) && !overlappingRange) {
      updatedStack += stack.substring(lastIndex, result.index) + "<REDACTED: user-file-path>";
      lastIndex = fileRegex.lastIndex;
    }
  }
  if (lastIndex < stack.length) {
    updatedStack += stack.substr(lastIndex);
  }
  return updatedStack;
}
function removePropertiesWithPossibleUserInfo(property) {
  if (!property) {
    return property;
  }
  const userDataRegexes = [
    { label: "Google API Key", regex: /AIza[A-Za-z0-9_\\\-]{35}/ },
    { label: "Slack Token", regex: /xox[pbar]\-[A-Za-z0-9]/ },
    { label: "GitHub Token", regex: /(gh[psuro]_[a-zA-Z0-9]{36}|github_pat_[a-zA-Z0-9]{22}_[a-zA-Z0-9]{59})/ },
    { label: "Generic Secret", regex: /(key|token|sig|secret|signature|password|passwd|pwd|android:value)[^a-zA-Z0-9]/i },
    { label: "CLI Credentials", regex: /((login|psexec|(certutil|psexec)\.exe).{1,50}(\s-u(ser(name)?)?\s+.{3,100})?\s-(admin|user|vm|root)?p(ass(word)?)?\s+["']?[^$\-\/\s]|(^|[\s\r\n\\])net(\.exe)?.{1,5}(user\s+|share\s+\/user:| user -? secrets ? set) \s + [^ $\s \/])/ },
    { label: "Email", regex: /@[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+/ }
    // Regex which matches @*.site
  ];
  for (const secretRegex of userDataRegexes) {
    if (secretRegex.regex.test(property)) {
      return `<REDACTED: ${secretRegex.label}>`;
    }
  }
  return property;
}
function $7p(data, cleanUpPatterns) {
  return $Bo(data, (value) => {
    if (value instanceof $Sp || Object.hasOwnProperty.call(value, "isTrustedTelemetryValue")) {
      return value.value;
    }
    if (typeof value === "string") {
      let updatedProperty = value.replaceAll("%20", " ");
      updatedProperty = anonymizeFilePaths(updatedProperty, cleanUpPatterns);
      for (const regexp of cleanUpPatterns) {
        updatedProperty = updatedProperty.replace(regexp, "");
      }
      updatedProperty = removePropertiesWithPossibleUserInfo(updatedProperty);
      return updatedProperty;
    }
    return void 0;
  });
}

// out-build/vs/platform/sharedProcess/common/sharedProcess.js
var $Ukc = {
  exit: "vscode:electron-main->shared-process=exit",
  ipcReady: "vscode:shared-process->electron-main=ipc-ready",
  initDone: "vscode:shared-process->electron-main=init-done"
};
var $Vkc = {
  request: "vscode:createSharedProcessChannelConnection",
  response: "vscode:createSharedProcessChannelConnectionResult"
};
var $Wkc = {
  request: "vscode:createSharedProcessRawConnection",
  response: "vscode:createSharedProcessRawConnectionResult"
};

// out-build/vs/platform/sharedProcess/electron-main/sharedProcess.js
var $Xkc = class $Xkc2 extends $0c {
  constructor(g, h, j, m, n, r, s, t, u) {
    super();
    this.g = g;
    this.h = h;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r;
    this.s = s;
    this.t = t;
    this.u = u;
    this.a = new $Yh();
    this.b = void 0;
    this.c = void 0;
    this.f = this.B(new $De());
    this.onDidCrash = this.f.event;
    this.C = void 0;
    this.D = void 0;
    this.w();
  }
  w() {
    $ZY.on($Vkc.request, (e, nonce) => this.y(e, nonce, $Vkc.response));
    $ZY.on($Wkc.request, (e, nonce) => this.y(e, nonce, $Wkc.response));
    this.B(this.r.onWillShutdown(() => this.z()));
  }
  async y(e, nonce, responseChannel) {
    this.s.trace(`[SharedProcess] onWindowConnection for: ${responseChannel}`);
    if (!this.a.isOpen()) {
      this.a.open();
    }
    await this.whenReady();
    const port = await this.connect(responseChannel);
    if (e.sender.isDestroyed()) {
      return port.close();
    }
    e.sender.postMessage(responseChannel, nonce, [port]);
  }
  z() {
    this.s.trace("[SharedProcess] onWillShutdown");
    this.b?.postMessage($Ukc.exit);
    this.b = void 0;
  }
  whenReady() {
    if (!this.C) {
      this.C = (async () => {
        await this.F;
        const whenReady = new $ki();
        this.b?.once($Ukc.initDone, () => whenReady.complete());
        await whenReady.p;
        this.c?.dispose();
        this.s.trace("[SharedProcess] Overall ready");
      })();
    }
    return this.C;
  }
  get F() {
    if (!this.D) {
      this.D = (async () => {
        await this.a.wait();
        this.G();
        const sharedProcessIpcReady = new $ki();
        this.b?.once($Ukc.ipcReady, () => sharedProcessIpcReady.complete());
        await sharedProcessIpcReady.p;
        this.s.trace("[SharedProcess] IPC ready");
      })();
    }
    return this.D;
  }
  G() {
    this.b = this.B(new $kkc(this.s, $Up, this.r));
    this.c = this.b.onMessage((e) => {
      if (typeof e.warning === "string") {
        this.s.warn(e.warning);
      } else if (typeof e.error === "string") {
        this.s.error(e.error);
      }
    });
    const inspectParams = $tn(this.m.args, this.m.isBuilt);
    let execArgv = void 0;
    if (inspectParams.port) {
      execArgv = ["--nolazy"];
      if (inspectParams.break) {
        execArgv.push(`--inspect-brk=${inspectParams.port}`);
      } else {
        execArgv.push(`--inspect=${inspectParams.port}`);
      }
    }
    this.b.start({
      type: "shared-process",
      entryPoint: "vs/code/electron-utility/sharedProcess/sharedProcessMain",
      payload: this.H(),
      respondToAuthRequestsFromMainProcess: true,
      execArgv
    });
    this.B(this.b.onCrash(() => this.f.fire()));
  }
  H() {
    return {
      machineId: this.g,
      sqmId: this.h,
      devDeviceId: this.j,
      codeCachePath: this.m.codeCachePath,
      profiles: {
        home: this.n.profilesHome,
        all: this.n.profiles
      },
      args: this.m.args,
      logLevel: this.t.getLogLevel(),
      loggers: this.t.getRegisteredLoggers(),
      policiesData: this.u.serialize()
    };
  }
  async connect(payload) {
    await this.F;
    const utilityProcess2 = $Jg(this.b);
    return utilityProcess2.connect(payload);
  }
};
$Xkc = __decorate([
  __param(3, $Cjc),
  __param(4, $7l),
  __param(5, $9jc),
  __param(6, $uk),
  __param(7, $4jc),
  __param(8, $Oo)
], $Xkc);

// out-build/vs/platform/sign/common/sign.js
var $gm = "signService";
var $hm = $Zi($gm);

// out-build/vs/platform/storage/electron-main/storageIpc.js
var $Ykc = class _$Ykc extends $0c {
  static {
    this.a = 100;
  }
  constructor(f, g) {
    super();
    this.f = f;
    this.g = g;
    this.b = this.B(new $De());
    this.c = /* @__PURE__ */ new Map();
    this.h(g.applicationStorage, this.b);
  }
  //#region Storage Change Events
  h(storage, emitter) {
    this.B(Event.debounce(storage.onDidChangeStorage, (prev, cur) => {
      if (!prev) {
        prev = [cur];
      } else {
        prev.push(cur);
      }
      return prev;
    }, _$Ykc.a)((events) => {
      if (events.length) {
        emitter.fire(this.j(events, storage));
      }
    }));
  }
  j(events, storage) {
    const changed = /* @__PURE__ */ new Map();
    const deleted = /* @__PURE__ */ new Set();
    events.forEach((event) => {
      const existing = storage.get(event.key);
      if (typeof existing === "string") {
        changed.set(event.key, existing);
      } else {
        deleted.add(event.key);
      }
    });
    return {
      changed: Array.from(changed.entries()),
      deleted: Array.from(deleted.values())
    };
  }
  listen(_, event, arg) {
    switch (event) {
      case "onDidChangeStorage": {
        const profile = arg.profile ? $wi(arg.profile) : void 0;
        if (!profile) {
          return this.b.event;
        }
        let profileStorageChangeEmitter = this.c.get(profile.id);
        if (!profileStorageChangeEmitter) {
          profileStorageChangeEmitter = this.B(new $De());
          this.h(this.g.profileStorage(profile), profileStorageChangeEmitter);
          this.c.set(profile.id, profileStorageChangeEmitter);
        }
        return profileStorageChangeEmitter.event;
      }
    }
    throw new Error(`Event not found: ${event}`);
  }
  //#endregion
  async call(_, command, arg) {
    const profile = arg.profile ? $wi(arg.profile) : void 0;
    const workspace = $dj(arg.workspace);
    const storage = await this.m(profile, workspace);
    switch (command) {
      case "getItems": {
        return Array.from(storage.items.entries());
      }
      case "updateItems": {
        const items = arg;
        if (items.insert) {
          for (const [key, value] of items.insert) {
            storage.set(key, value);
          }
        }
        items.delete?.forEach((key) => storage.delete(key));
        break;
      }
      case "optimize": {
        return storage.optimize();
      }
      case "isUsed": {
        const path3 = arg.payload;
        if (typeof path3 === "string") {
          return this.g.isUsed(path3);
        }
      }
      default:
        throw new Error(`Call not found: ${command}`);
    }
  }
  async m(profile, workspace) {
    let storage;
    if (workspace) {
      storage = this.g.workspaceStorage(workspace);
    } else if (profile) {
      storage = this.g.profileStorage(profile);
    } else {
      storage = this.g.applicationStorage;
    }
    try {
      await storage.init();
    } catch (error) {
      this.f.error(`StorageIPC#init: Unable to init ${workspace ? "workspace" : profile ? "profile" : "application"} storage due to ${error}`);
    }
    return storage;
  }
};

// out-build/vs/platform/telemetry/common/telemetryIpc.js
var $1kc = class {
  constructor(b) {
    this.b = b;
  }
  log(eventName, data) {
    this.b.call("log", { eventName, data }).then(void 0, (err) => `Failed to log telemetry: ${console.warn(err)}`);
    return Promise.resolve(null);
  }
  flush() {
    return Promise.resolve();
  }
};

// out-build/vs/platform/telemetry/common/telemetryService.js
var $Ds = class $Ds2 {
  static {
    this.IDLE_START_EVENT_NAME = "UserIdleStart";
  }
  static {
    this.IDLE_STOP_EVENT_NAME = "UserIdleStop";
  }
  constructor(config, k, l) {
    this.k = k;
    this.l = l;
    this.d = {};
    this.i = new $9c();
    this.j = [];
    this.b = config.appenders;
    this.c = config.commonProperties ?? /* @__PURE__ */ Object.create(null);
    this.sessionId = this.c["sessionID"];
    this.machineId = this.c["common.machineId"];
    this.sqmId = this.c["common.sqmId"];
    this.devDeviceId = this.c["common.devDeviceId"];
    this.firstSessionDate = this.c["common.firstSessionDate"];
    this.msftInternal = this.c["common.msftInternal"];
    this.f = config.piiPaths || [];
    this.g = 3;
    this.h = !!config.sendErrorTelemetry;
    this.j = [/(vscode-)?file:\/\/\/.*?\/resources\/app\//gi];
    for (const piiPath of this.f) {
      this.j.push(new RegExp($Af(piiPath), "gi"));
      if (piiPath.indexOf("\\") >= 0) {
        this.j.push(new RegExp($Af(piiPath.replace(/\\/g, "/")), "gi"));
      }
    }
    this.m();
    this.i.add(this.k.onDidChangeConfiguration((e) => {
      const affectsTelemetryConfig = e.affectsConfiguration($Cm) || e.affectsConfiguration($Em) || e.affectsConfiguration($Dm);
      if (affectsTelemetryConfig) {
        this.m();
      }
    }));
  }
  setExperimentProperty(name, value) {
    this.d[name] = value;
  }
  m() {
    let level = $2p(this.k);
    const collectableTelemetry = this.l.enabledTelemetryLevels;
    if (collectableTelemetry) {
      this.h = this.sendErrorTelemetry ? collectableTelemetry.error : false;
      const maxCollectableTelemetryLevel = collectableTelemetry.usage ? 3 : collectableTelemetry.error ? 2 : 0;
      level = Math.min(level, maxCollectableTelemetryLevel);
    }
    this.g = level;
  }
  get sendErrorTelemetry() {
    return this.h;
  }
  get telemetryLevel() {
    return this.g;
  }
  dispose() {
    this.i.dispose();
  }
  n(eventName, eventLevel, data) {
    if (this.g < eventLevel) {
      return;
    }
    data = $Co(data, this.d);
    data = $7p(data, this.j);
    data = $Co(data, this.c);
    this.b.forEach((a) => a.log(eventName, data));
  }
  publicLog(eventName, data) {
    this.n(eventName, 3, data);
  }
  publicLog2(eventName, data) {
    this.publicLog(eventName, data);
  }
  publicLogError(errorEventName, data) {
    if (!this.h) {
      return;
    }
    this.n(errorEventName, 2, data);
  }
  publicLogError2(eventName, data) {
    this.publicLogError(eventName, data);
  }
};
$Ds = __decorate([
  __param(1, $tj),
  __param(2, $Nk)
], $Ds);
function getTelemetryLevelSettingDescription() {
  const telemetryText = localize(2082, null, product_default.nameLong);
  const externalLinksStatement = !product_default.privacyStatementUrl ? localize(2083, null, "https://aka.ms/vscode-telemetry") : localize(2084, null, "https://aka.ms/vscode-telemetry", product_default.privacyStatementUrl);
  const restartString = !$r ? localize(2085, null) : "";
  const crashReportsHeader = localize(2086, null);
  const errorsHeader = localize(2087, null);
  const usageHeader = localize(2088, null);
  const telemetryTableDescription = localize(2089, null);
  const telemetryTable = `
|       | ${crashReportsHeader} | ${errorsHeader} | ${usageHeader} |
|:------|:---------------------:|:---------------:|:--------------:|
| all   |            \u2713          |        \u2713        |        \u2713       |
| error |            \u2713          |        \u2713        |        -       |
| crash |            \u2713          |        -        |        -       |
| off   |            -          |        -        |        -       |
`;
  const deprecatedSettingNote = localize(2090, null);
  const telemetryDescription = `
${telemetryText} ${externalLinksStatement} ${restartString}

&nbsp;

${telemetryTableDescription}
${telemetryTable}

&nbsp;

${deprecatedSettingNote}
`;
  return telemetryDescription;
}
$Mo.as($Ro.Configuration).registerConfiguration({
  "id": $Bm,
  "order": 1,
  "type": "object",
  "title": localize(2091, null),
  "properties": {
    [$Cm]: {
      "type": "string",
      "enum": [
        "all",
        "error",
        "crash",
        "off"
        /* TelemetryConfiguration.OFF */
      ],
      "enumDescriptions": [
        localize(2092, null),
        localize(2093, null),
        localize(2094, null),
        localize(2095, null)
      ],
      "markdownDescription": getTelemetryLevelSettingDescription(),
      "default": "all",
      "restricted": true,
      "scope": 1,
      "tags": ["usesOnlineServices", "telemetry"]
    }
  }
});
$Mo.as($Ro.Configuration).registerConfiguration({
  "id": $Bm,
  "order": 110,
  "type": "object",
  "title": localize(2096, null),
  "properties": {
    [$Em]: {
      "type": "boolean",
      "markdownDescription": !product_default.privacyStatementUrl ? localize(2097, null, product_default.nameLong) : localize(2098, null, product_default.nameLong, product_default.privacyStatementUrl),
      "default": true,
      "restricted": true,
      "markdownDeprecationMessage": localize(2099, null, `\`#${$Cm}#\``),
      "scope": 1,
      "tags": ["usesOnlineServices", "telemetry"]
    }
  }
});

// out-build/vs/platform/update/common/updateIpc.js
var $2kc = class {
  constructor(a) {
    this.a = a;
  }
  listen(_, event) {
    switch (event) {
      case "onStateChange":
        return this.a.onStateChange;
    }
    throw new Error(`Event not found: ${event}`);
  }
  call(_, command, arg) {
    switch (command) {
      case "checkForUpdates":
        return this.a.checkForUpdates(arg);
      case "downloadUpdate":
        return this.a.downloadUpdate();
      case "applyUpdate":
        return this.a.applyUpdate();
      case "quitAndInstall":
        return this.a.quitAndInstall();
      case "_getInitialState":
        return Promise.resolve(this.a.state);
      case "isLatestVersion":
        return this.a.isLatestVersion();
      case "_applySpecificUpdate":
        return this.a._applySpecificUpdate(arg);
    }
    throw new Error(`Call not found: ${command}`);
  }
};

// out-build/vs/platform/update/electron-main/updateService.darwin.js
import * as electron8 from "electron";

// out-build/vs/platform/update/electron-main/abstractUpdateService.js
function $4kc(platform2, quality, productService) {
  return `${productService.updateUrl}/api/update/${platform2}/${quality}/${productService.commit}`;
}
var $5kc = class $5kc2 {
  get state() {
    return this.b;
  }
  d(state) {
    this.j.info("update#setState", state.type);
    this.b = state;
    this.c.fire(state);
  }
  constructor(f, g, h, i, j, k) {
    this.f = f;
    this.g = g;
    this.h = h;
    this.i = i;
    this.j = j;
    this.k = k;
    this.b = $XZ.Uninitialized;
    this.c = new $De();
    this.onStateChange = this.c.event;
    f.when(
      3
      /* LifecycleMainPhase.AfterWindowOpen */
    ).finally(() => this.l());
  }
  /**
   * This must be called before any other call. This is a performance
   * optimization, to avoid using extra CPU cycles before first window open.
   * https://github.com/microsoft/vscode/issues/89784
   */
  async l() {
    if (!this.h.isBuilt) {
      this.d($XZ.Disabled(
        0
        /* DisablementReason.NotBuilt */
      ));
      return;
    }
    if (this.h.disableUpdates) {
      this.d($XZ.Disabled(
        1
        /* DisablementReason.DisabledByEnvironment */
      ));
      this.j.info("update#ctor - updates are disabled by the environment");
      return;
    }
    if (!this.k.updateUrl || !this.k.commit) {
      this.d($XZ.Disabled(
        3
        /* DisablementReason.MissingConfiguration */
      ));
      this.j.info("update#ctor - updates are disabled as there is no update URL");
      return;
    }
    const updateMode = this.g.getValue("update.mode");
    const quality = this.m(updateMode);
    if (!quality) {
      this.d($XZ.Disabled(
        2
        /* DisablementReason.ManuallyDisabled */
      ));
      this.j.info("update#ctor - updates are disabled by user preference");
      return;
    }
    this.a = this.s(quality);
    if (!this.a) {
      this.d($XZ.Disabled(
        4
        /* DisablementReason.InvalidConfiguration */
      ));
      this.j.info("update#ctor - updates are disabled as the update URL is badly formed");
      return;
    }
    if (this.g.getValue("_update.prss")) {
      const url = new URL(this.a);
      url.searchParams.set("prss", "true");
      this.a = url.toString();
    }
    this.d($XZ.Idle(this.q()));
    if (updateMode === "manual") {
      this.j.info("update#ctor - manual checks only; automatic updates are disabled by user preference");
      return;
    }
    if (updateMode === "start") {
      this.j.info("update#ctor - startup checks only; automatic updates are disabled by user preference");
      setTimeout(() => this.checkForUpdates(false), 30 * 1e3);
    } else {
      this.n(30 * 1e3).then(void 0, (err) => this.j.error(err));
    }
  }
  m(updateMode) {
    return updateMode === "none" ? void 0 : this.k.quality;
  }
  n(delay = 60 * 60 * 1e3) {
    return $1h(delay).then(() => this.checkForUpdates(false)).then(() => {
      return this.n(60 * 60 * 1e3);
    });
  }
  async checkForUpdates(explicit) {
    this.j.trace("update#checkForUpdates, state = ", this.state.type);
    if (this.state.type !== "idle") {
      return;
    }
    this.t(explicit);
  }
  async downloadUpdate() {
    this.j.trace("update#downloadUpdate, state = ", this.state.type);
    if (this.state.type !== "available for download") {
      return;
    }
    await this.o(this.state);
  }
  async o(state) {
  }
  async applyUpdate() {
    this.j.trace("update#applyUpdate, state = ", this.state.type);
    if (this.state.type !== "downloaded") {
      return;
    }
    await this.p();
  }
  async p() {
  }
  quitAndInstall() {
    this.j.trace("update#quitAndInstall, state = ", this.state.type);
    if (this.state.type !== "ready") {
      return Promise.resolve(void 0);
    }
    this.j.trace("update#quitAndInstall(): before lifecycle quit()");
    this.f.quit(
      true
      /* will restart */
    ).then((vetod) => {
      this.j.trace(`update#quitAndInstall(): after lifecycle quit() with veto: ${vetod}`);
      if (vetod) {
        return;
      }
      this.j.trace("update#quitAndInstall(): running raw#quitAndInstall()");
      this.r();
    });
    return Promise.resolve(void 0);
  }
  async isLatestVersion() {
    if (!this.a) {
      return void 0;
    }
    const mode = this.g.getValue("update.mode");
    if (mode === "none") {
      return false;
    }
    try {
      const context = await this.i.request({ url: this.a }, CancellationToken.None);
      return context.res.statusCode === 204;
    } catch (error) {
      this.j.error("update#isLatestVersion(): failed to check for updates");
      this.j.error(error);
      return void 0;
    }
  }
  async _applySpecificUpdate(packagePath) {
  }
  q() {
    return 1;
  }
  r() {
  }
};
$5kc = __decorate([
  __param(0, $9jc),
  __param(1, $tj),
  __param(2, $Cjc),
  __param(3, $qq),
  __param(4, $uk),
  __param(5, $Nk)
], $5kc);

// out-build/vs/platform/update/electron-main/updateService.darwin.js
var $6kc = class $6kc2 extends $5kc {
  get v() {
    return Event.fromNodeEventEmitter(electron8.autoUpdater, "error", (_, message) => message);
  }
  get w() {
    return Event.fromNodeEventEmitter(electron8.autoUpdater, "update-not-available");
  }
  get x() {
    return Event.fromNodeEventEmitter(electron8.autoUpdater, "update-available");
  }
  get y() {
    return Event.fromNodeEventEmitter(electron8.autoUpdater, "update-downloaded", (_, releaseNotes, version, timestamp) => ({ version, productVersion: version, timestamp }));
  }
  constructor(lifecycleMainService, configurationService, z, environmentMainService, requestService, logService, productService) {
    super(lifecycleMainService, configurationService, environmentMainService, requestService, logService, productService);
    this.z = z;
    this.u = new $9c();
    lifecycleMainService.setRelaunchHandler(this);
  }
  handleRelaunch(options) {
    if (options?.addArgs || options?.removeArgs) {
      return false;
    }
    if (this.state.type !== "ready") {
      return false;
    }
    this.j.trace("update#handleRelaunch(): running raw#quitAndInstall()");
    this.r();
    return true;
  }
  async l() {
    await super.l();
    this.v(this.B, this, this.u);
    this.x(this.E, this, this.u);
    this.y(this.F, this, this.u);
    this.w(this.G, this, this.u);
  }
  B(err) {
    this.z.publicLog2("update:error", { messageHash: String($Nj(String(err))) });
    this.j.error("UpdateService error:", err);
    const message = this.state.type === "checking for updates" && this.state.explicit ? err : void 0;
    this.d($XZ.Idle(1, message));
  }
  s(quality) {
    let assetID;
    if (!this.k.darwinUniversalAssetId) {
      assetID = process.arch === "x64" ? "darwin" : "darwin-arm64";
    } else {
      assetID = this.k.darwinUniversalAssetId;
    }
    const url = $4kc(assetID, quality, this.k);
    try {
      electron8.autoUpdater.setFeedURL({ url });
    } catch (e) {
      this.j.error("Failed to set update feed URL", e);
      return void 0;
    }
    return url;
  }
  t(context) {
    this.d($XZ.CheckingForUpdates(context));
    electron8.autoUpdater.checkForUpdates();
  }
  E() {
    if (this.state.type !== "checking for updates") {
      return;
    }
    this.d($XZ.Downloading);
  }
  F(update) {
    if (this.state.type !== "downloading") {
      return;
    }
    this.d($XZ.Downloaded(update));
    this.z.publicLog2("update:downloaded", { version: update.version });
    this.d($XZ.Ready(update));
  }
  G() {
    if (this.state.type !== "checking for updates") {
      return;
    }
    this.z.publicLog2("update:notAvailable", { explicit: this.state.explicit });
    this.d($XZ.Idle(
      1
      /* UpdateType.Archive */
    ));
  }
  r() {
    this.j.trace("update#quitAndInstall(): running raw#quitAndInstall()");
    electron8.autoUpdater.quitAndInstall();
  }
  dispose() {
    this.u.dispose();
  }
};
__decorate([
  $ri
], $6kc.prototype, "v", null);
__decorate([
  $ri
], $6kc.prototype, "w", null);
__decorate([
  $ri
], $6kc.prototype, "x", null);
__decorate([
  $ri
], $6kc.prototype, "y", null);
$6kc = __decorate([
  __param(0, $9jc),
  __param(1, $tj),
  __param(2, $tm),
  __param(3, $Cjc),
  __param(4, $qq),
  __param(5, $uk),
  __param(6, $Nk)
], $6kc);

// out-build/vs/platform/update/electron-main/updateService.linux.js
var $7kc = class $7kc2 extends $5kc {
  constructor(lifecycleMainService, configurationService, e, environmentMainService, requestService, logService, u, productService) {
    super(lifecycleMainService, configurationService, environmentMainService, requestService, logService, productService);
    this.e = e;
    this.u = u;
  }
  s(quality) {
    return $4kc(`linux-${process.arch}`, quality, this.k);
  }
  t(context) {
    if (!this.a) {
      return;
    }
    this.d($XZ.CheckingForUpdates(context));
    this.i.request({ url: this.a }, CancellationToken.None).then($wq).then((update) => {
      if (!update || !update.url || !update.version || !update.productVersion) {
        this.e.publicLog2("update:notAvailable", { explicit: !!context });
        this.d($XZ.Idle(
          1
          /* UpdateType.Archive */
        ));
      } else {
        this.d($XZ.AvailableForDownload(update));
      }
    }).then(void 0, (err) => {
      this.j.error(err);
      const message = !!context ? err.message || err : void 0;
      this.d($XZ.Idle(1, message));
    });
  }
  async o(state) {
    if (this.k.downloadUrl && this.k.downloadUrl.length > 0) {
      this.u.openExternal(void 0, this.k.downloadUrl);
    } else if (state.update.url) {
      this.u.openExternal(void 0, state.update.url);
    }
    this.d($XZ.Idle(
      1
      /* UpdateType.Archive */
    ));
  }
};
$7kc = __decorate([
  __param(0, $9jc),
  __param(1, $tj),
  __param(2, $tm),
  __param(3, $Cjc),
  __param(4, $qq),
  __param(5, $uk),
  __param(6, $Ckc),
  __param(7, $Nk)
], $7kc);

// out-build/vs/platform/update/electron-main/updateService.snap.js
import { spawn as spawn4 } from "child_process";
import { realpath as realpath2, watch as watch2 } from "fs";
var AbstractUpdateService = class AbstractUpdateService2 {
  get state() {
    return this.a;
  }
  d(state) {
    this.g.info("update#setState", state.type);
    this.a = state;
    this.b.fire(state);
  }
  constructor(f, environmentMainService, g) {
    this.f = f;
    this.g = g;
    this.a = $XZ.Uninitialized;
    this.b = new $De();
    this.onStateChange = this.b.event;
    if (environmentMainService.disableUpdates) {
      this.g.info("update#ctor - updates are disabled");
      return;
    }
    this.d($XZ.Idle(this.k()));
    this.h(30 * 1e3).then(void 0, (err) => this.g.error(err));
  }
  h(delay = 60 * 60 * 1e3) {
    return $1h(delay).then(() => this.checkForUpdates(false)).then(() => {
      return this.h(60 * 60 * 1e3);
    });
  }
  async checkForUpdates(explicit) {
    this.g.trace("update#checkForUpdates, state = ", this.state.type);
    if (this.state.type !== "idle") {
      return;
    }
    this.m(explicit);
  }
  async downloadUpdate() {
    this.g.trace("update#downloadUpdate, state = ", this.state.type);
    if (this.state.type !== "available for download") {
      return;
    }
    await this.i(this.state);
  }
  i(state) {
    return Promise.resolve(void 0);
  }
  async applyUpdate() {
    this.g.trace("update#applyUpdate, state = ", this.state.type);
    if (this.state.type !== "downloaded") {
      return;
    }
    await this.j();
  }
  j() {
    return Promise.resolve(void 0);
  }
  quitAndInstall() {
    this.g.trace("update#quitAndInstall, state = ", this.state.type);
    if (this.state.type !== "ready") {
      return Promise.resolve(void 0);
    }
    this.g.trace("update#quitAndInstall(): before lifecycle quit()");
    this.f.quit(
      true
      /* will restart */
    ).then((vetod) => {
      this.g.trace(`update#quitAndInstall(): after lifecycle quit() with veto: ${vetod}`);
      if (vetod) {
        return;
      }
      this.g.trace("update#quitAndInstall(): running raw#quitAndInstall()");
      this.l();
    });
    return Promise.resolve(void 0);
  }
  k() {
    return 2;
  }
  l() {
  }
  async _applySpecificUpdate(packagePath) {
  }
};
AbstractUpdateService = __decorate([
  __param(0, $9jc),
  __param(1, $Cjc),
  __param(2, $uk)
], AbstractUpdateService);
var $8kc = class $8kc2 extends AbstractUpdateService {
  constructor(o, p, lifecycleMainService, environmentMainService, logService, q) {
    super(lifecycleMainService, environmentMainService, logService);
    this.o = o;
    this.p = p;
    this.q = q;
    const watcher = watch2($yc(this.o));
    const onChange = Event.fromNodeEventEmitter(watcher, "change", (_, fileName) => fileName);
    const onCurrentChange = Event.filter(onChange, (n) => n === "current");
    const onDebouncedCurrentChange = Event.debounce(onCurrentChange, (_, e) => e, 2e3);
    const listener = onDebouncedCurrentChange(() => this.checkForUpdates(false));
    lifecycleMainService.onWillShutdown(() => {
      listener.dispose();
      watcher.close();
    });
  }
  m() {
    this.d($XZ.CheckingForUpdates(false));
    this.u().then((result) => {
      if (result) {
        this.d($XZ.Ready({ version: "something" }));
      } else {
        this.q.publicLog2("update:notAvailable", { explicit: false });
        this.d($XZ.Idle(
          2
          /* UpdateType.Snap */
        ));
      }
    }, (err) => {
      this.g.error(err);
      this.q.publicLog2("update:notAvailable", { explicit: false });
      this.d($XZ.Idle(2, err.message || err));
    });
  }
  l() {
    this.g.trace("update#quitAndInstall(): running raw#quitAndInstall()");
    spawn4("sleep 3 && " + $zc(process.argv[0]), {
      shell: true,
      detached: true,
      stdio: "ignore"
    });
  }
  async u() {
    const resolvedCurrentSnapPath = await new Promise((c, e) => realpath2(`${$yc(this.o)}/current`, (err, r) => err ? e(err) : c(r)));
    const currentRevision = $zc(resolvedCurrentSnapPath);
    return this.p !== currentRevision;
  }
  isLatestVersion() {
    return this.u().then(void 0, (err) => {
      this.g.error("update#checkForSnapUpdate(): Could not get realpath of application.");
      return void 0;
    });
  }
};
$8kc = __decorate([
  __param(2, $9jc),
  __param(3, $Cjc),
  __param(4, $uk),
  __param(5, $tm)
], $8kc);

// out-build/vs/platform/update/electron-main/updateService.win32.js
import { spawn as spawn5 } from "child_process";
import * as fs9 from "fs";
import { tmpdir as tmpdir4 } from "os";

// out-build/vs/base/node/crypto.js
import * as crypto2 from "crypto";
import * as fs8 from "fs";
async function $SY(path3, sha256hash) {
  const checksumPromise = new Promise((resolve2, reject) => {
    const input = fs8.createReadStream(path3);
    const hash2 = crypto2.createHash("sha256");
    input.pipe(hash2);
    const done = $qb((err, result) => {
      input.removeAllListeners();
      hash2.removeAllListeners();
      if (err) {
        reject(err);
      } else {
        resolve2(result);
      }
    });
    input.once("error", done);
    input.once("end", done);
    hash2.once("error", done);
    hash2.once("data", (data) => done(void 0, data.toString("hex")));
  });
  const hash = await checksumPromise;
  if (hash !== sha256hash) {
    throw new Error("Hash mismatch");
  }
}

// out-build/vs/platform/update/electron-main/updateService.win32.js
async function pollUntil(fn, millis = 1e3) {
  while (!fn()) {
    await $1h(millis);
  }
}
var _updateType = void 0;
function getUpdateType() {
  if (typeof _updateType === "undefined") {
    _updateType = fs9.existsSync($vc($yc(process.execPath), "unins000.exe")) ? 0 : 1;
  }
  return _updateType;
}
var $9kc = class $9kc2 extends $5kc {
  get cachePath() {
    const result = $vc(tmpdir4(), `vscode-${this.k.quality}-${this.k.target}-${process.arch}`);
    return fs9.promises.mkdir(result, { recursive: true }).then(() => result);
  }
  constructor(lifecycleMainService, configurationService, u, environmentMainService, requestService, logService, v, w, productService) {
    super(lifecycleMainService, configurationService, environmentMainService, requestService, logService, productService);
    this.u = u;
    this.v = v;
    this.w = w;
    lifecycleMainService.setRelaunchHandler(this);
  }
  handleRelaunch(options) {
    if (options?.addArgs || options?.removeArgs) {
      return false;
    }
    if (this.state.type !== "ready" || !this.e) {
      return false;
    }
    this.j.trace("update#handleRelaunch(): running raw#quitAndInstall()");
    this.r();
    return true;
  }
  async l() {
    if (this.k.target === "user" && await this.w.isAdmin(void 0)) {
      this.d($XZ.Disabled(
        5
        /* DisablementReason.RunningAsAdmin */
      ));
      this.j.info("update#ctor - updates are disabled due to running as Admin in user setup");
      return;
    }
    await super.l();
  }
  s(quality) {
    let platform2 = `win32-${process.arch}`;
    if (getUpdateType() === 1) {
      platform2 += "-archive";
    } else if (this.k.target === "user") {
      platform2 += "-user";
    }
    return $4kc(platform2, quality, this.k);
  }
  t(context) {
    if (!this.a) {
      return;
    }
    this.d($XZ.CheckingForUpdates(context));
    this.i.request({ url: this.a }, CancellationToken.None).then($wq).then((update) => {
      const updateType = getUpdateType();
      if (!update || !update.url || !update.version || !update.productVersion) {
        this.u.publicLog2("update:notAvailable", { explicit: !!context });
        this.d($XZ.Idle(updateType));
        return Promise.resolve(null);
      }
      if (updateType === 1) {
        this.d($XZ.AvailableForDownload(update));
        return Promise.resolve(null);
      }
      this.d($XZ.Downloading);
      return this.C(update.version).then(() => {
        return this.B(update.version).then((updatePackagePath) => {
          return Promises2.exists(updatePackagePath).then((exists) => {
            if (exists) {
              return Promise.resolve(updatePackagePath);
            }
            const downloadPath = `${updatePackagePath}.tmp`;
            return this.i.request({ url: update.url }, CancellationToken.None).then((context2) => this.v.writeFile(URI.file(downloadPath), context2.stream)).then(update.sha256hash ? () => $SY(downloadPath, update.sha256hash) : () => void 0).then(() => Promises2.rename(
              downloadPath,
              updatePackagePath,
              false
              /* no retry */
            )).then(() => updatePackagePath);
          });
        }).then((packagePath) => {
          this.e = { packagePath };
          this.d($XZ.Downloaded(update));
          const fastUpdatesEnabled = this.g.getValue("update.enableWindowsBackgroundUpdates");
          if (fastUpdatesEnabled) {
            if (this.k.target === "user") {
              this.p();
            }
          } else {
            this.d($XZ.Ready(update));
          }
        });
      });
    }).then(void 0, (err) => {
      this.u.publicLog2("update:error", { messageHash: String($Nj(String(err))) });
      this.j.error(err);
      const message = !!context ? err.message || err : void 0;
      this.d($XZ.Idle(getUpdateType(), message));
    });
  }
  async o(state) {
    if (state.update.url) {
      this.w.openExternal(void 0, state.update.url);
    }
    this.d($XZ.Idle(getUpdateType()));
  }
  async B(version) {
    const cachePath = await this.cachePath;
    return $vc(cachePath, `CodeSetup-${this.k.quality}-${version}.exe`);
  }
  async C(exceptVersion = null) {
    const filter = exceptVersion ? (one) => !new RegExp(`${this.k.quality}-${exceptVersion}\\.exe$`).test(one) : () => true;
    const cachePath = await this.cachePath;
    const versions = await Promises2.readdir(cachePath);
    const promises16 = versions.filter(filter).map(async (one) => {
      try {
        await fs9.promises.unlink($vc(cachePath, one));
      } catch (err) {
      }
    });
    await Promise.all(promises16);
  }
  async p() {
    if (this.state.type !== "downloaded") {
      return Promise.resolve(void 0);
    }
    if (!this.e) {
      return Promise.resolve(void 0);
    }
    const update = this.state.update;
    this.d($XZ.Updating(update));
    const cachePath = await this.cachePath;
    this.e.updateFilePath = $vc(cachePath, `CodeSetup-${this.k.quality}-${update.version}.flag`);
    await Promises2.writeFile(this.e.updateFilePath, "flag");
    const child = spawn5(this.e.packagePath, ["/verysilent", "/log", `/update="${this.e.updateFilePath}"`, "/nocloseapplications", "/mergetasks=runcode,!desktopicon,!quicklaunchicon"], {
      detached: true,
      stdio: ["ignore", "ignore", "ignore"],
      windowsVerbatimArguments: true
    });
    child.once("exit", () => {
      this.e = void 0;
      this.d($XZ.Idle(getUpdateType()));
    });
    const readyMutexName = `${this.k.win32MutexName}-ready`;
    const mutex = await import("@vscode/windows-mutex");
    pollUntil(() => mutex.isActive(readyMutexName)).then(() => this.d($XZ.Ready(update)));
  }
  r() {
    if (this.state.type !== "ready" || !this.e) {
      return;
    }
    this.j.trace("update#quitAndInstall(): running raw#quitAndInstall()");
    if (this.e.updateFilePath) {
      fs9.unlinkSync(this.e.updateFilePath);
    } else {
      spawn5(this.e.packagePath, ["/silent", "/log", "/mergetasks=runcode,!desktopicon,!quicklaunchicon"], {
        detached: true,
        stdio: ["ignore", "ignore", "ignore"]
      });
    }
  }
  q() {
    return getUpdateType();
  }
  async _applySpecificUpdate(packagePath) {
    if (this.state.type !== "idle") {
      return;
    }
    const fastUpdatesEnabled = this.g.getValue("update.enableWindowsBackgroundUpdates");
    const update = { version: "unknown", productVersion: "unknown" };
    this.d($XZ.Downloading);
    this.e = { packagePath };
    this.d($XZ.Downloaded(update));
    if (fastUpdatesEnabled) {
      if (this.k.target === "user") {
        this.p();
      }
    } else {
      this.d($XZ.Ready(update));
    }
  }
};
__decorate([
  $ri
], $9kc.prototype, "cachePath", null);
$9kc = __decorate([
  __param(0, $9jc),
  __param(1, $tj),
  __param(2, $tm),
  __param(3, $Cjc),
  __param(4, $qq),
  __param(5, $uk),
  __param(6, $ul),
  __param(7, $Ckc),
  __param(8, $Nk)
], $9kc);

// out-build/vs/platform/url/common/urlIpc.js
var $$kc = class {
  constructor(a) {
    this.a = a;
  }
  handleURL(uri, options) {
    return this.a.call("handleURL", [uri.toJSON(), options]);
  }
};
var $_kc = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  async routeCall(hub, command, arg, cancellationToken) {
    if (command !== "handleURL") {
      throw new Error(`Call not found: ${command}`);
    }
    if (Array.isArray(arg) && arg.length > 0) {
      const uri = URI.revive(arg[0]);
      this.b.trace("URLHandlerRouter#routeCall() with URI argument", uri.toString(true));
      if (uri.query) {
        const match = /\bwindowId=(\d+)/.exec(uri.query);
        if (match) {
          const windowId = match[1];
          this.b.trace(`URLHandlerRouter#routeCall(): found windowId query parameter with value "${windowId}"`, uri.toString(true));
          const regex = new RegExp(`window:${windowId}`);
          const connection = hub.connections.find((c) => {
            this.b.trace("URLHandlerRouter#routeCall(): testing connection", c.ctx);
            return regex.test(c.ctx);
          });
          if (connection) {
            this.b.trace("URLHandlerRouter#routeCall(): found a connection to route", uri.toString(true));
            return connection;
          } else {
            this.b.trace("URLHandlerRouter#routeCall(): did not find a connection to route", uri.toString(true));
          }
        } else {
          this.b.trace("URLHandlerRouter#routeCall(): did not find windowId query parameter", uri.toString(true));
        }
      }
    } else {
      this.b.trace("URLHandlerRouter#routeCall() without URI argument");
    }
    return this.a.routeCall(hub, command, arg, cancellationToken);
  }
  routeEvent(_, event) {
    throw new Error(`Event not found: ${event}`);
  }
};

// out-build/vs/platform/url/common/urlService.js
var $PZ = class extends $0c {
  constructor() {
    super(...arguments);
    this.a = /* @__PURE__ */ new Set();
  }
  open(uri, options) {
    const handlers = [...this.a.values()];
    return $4h(handlers.map((h) => () => h.handleURL(uri, options)), void 0, false).then((val) => val || false);
  }
  registerHandler(handler) {
    this.a.add(handler);
    return $8c(() => this.a.delete(handler));
  }
};
var $QZ = class $QZ2 extends $PZ {
  constructor(b) {
    super();
    this.b = b;
  }
  create(options) {
    let { authority, path: path3, query, fragment } = options ? options : { authority: void 0, path: void 0, query: void 0, fragment: void 0 };
    if (authority && path3 && path3.indexOf("/") !== 0) {
      path3 = `/${path3}`;
    }
    return URI.from({ scheme: this.b.urlProtocol, authority, path: path3, query, fragment });
  }
};
$QZ = __decorate([
  __param(0, $Nk)
], $QZ);

// out-build/vs/platform/url/electron-main/electronUrlListener.js
import { app as app9 } from "electron";
var $alc = class extends $0c {
  constructor(initialProtocolUrls, c, windowsMainService, environmentMainService, productService, f) {
    super();
    this.c = c;
    this.f = f;
    this.a = [];
    this.b = 0;
    if (initialProtocolUrls) {
      f.trace("ElectronURLListener initialUrisToHandle:", initialProtocolUrls.map((url) => url.originalUrl));
      this.a = initialProtocolUrls;
    }
    if ($l) {
      const windowsParameters = environmentMainService.isBuilt ? [] : [`"${environmentMainService.appRoot}"`];
      windowsParameters.push("--open-url", "--");
      app9.setAsDefaultProtocolClient(productService.urlProtocol, process.execPath, windowsParameters);
    }
    const onOpenElectronUrl = Event.map(Event.fromNodeEventEmitter(app9, "open-url", (event, url) => ({ event, url })), ({ event, url }) => {
      event.preventDefault();
      return url;
    });
    this.B(onOpenElectronUrl((url) => {
      const uri = this.g(url);
      if (!uri) {
        return;
      }
      this.c.open(uri, { originalUrl: url });
    }));
    const isWindowReady = windowsMainService.getWindows().filter((window2) => window2.isReady).length > 0;
    if (isWindowReady) {
      f.trace("ElectronURLListener: window is ready to handle URLs");
      this.h();
    } else {
      f.trace("ElectronURLListener: waiting for window to be ready to handle URLs...");
      this.B(Event.once(windowsMainService.onDidSignalReadyWindow)(() => this.h()));
    }
  }
  g(url) {
    try {
      return URI.parse(url);
    } catch (e) {
      return void 0;
    }
  }
  async h() {
    if (this.b++ > 10) {
      this.f.trace("ElectronURLListener#flush(): giving up after 10 retries");
      return;
    }
    this.f.trace("ElectronURLListener#flush(): flushing URLs");
    const uris = [];
    for (const obj of this.a) {
      const handled = await this.c.open(obj.uri, { originalUrl: obj.originalUrl });
      if (handled) {
        this.f.trace("ElectronURLListener#flush(): URL was handled", obj.originalUrl);
      } else {
        this.f.trace("ElectronURLListener#flush(): URL was not yet handled", obj.originalUrl);
        uris.push(obj);
      }
    }
    if (uris.length === 0) {
      return;
    }
    this.a = uris;
    $2h(() => this.h(), 500, this.q);
  }
};

// out-build/vs/platform/webview/common/webviewManagerService.js
var $blc = $Zi("webviewManagerService");

// out-build/vs/platform/webview/electron-main/webviewMainService.js
import { webContents as webContents2 } from "electron";

// out-build/vs/platform/webview/electron-main/webviewProtocolProvider.js
import { protocol } from "electron";
var $clc = class _$clc extends $0c {
  static {
    this.a = /* @__PURE__ */ new Map([
      ["/index.html", "index.html"],
      ["/fake.html", "fake.html"],
      ["/service-worker.js", "service-worker.js"]
    ]);
  }
  constructor() {
    super();
    const webviewHandler = this.b.bind(this);
    protocol.registerFileProtocol(Schemas.vscodeWebview, webviewHandler);
  }
  b(request, callback) {
    try {
      const uri = URI.parse(request.url);
      const entry = _$clc.a.get(uri.path);
      if (typeof entry === "string") {
        const relativeResourcePath = `vs/workbench/contrib/webview/browser/pre/${entry}`;
        const url = $hh.asFileUri(relativeResourcePath);
        return callback({
          path: url.fsPath,
          headers: {
            ...COI.getHeadersFromQuery(request.url),
            "Cross-Origin-Resource-Policy": "cross-origin"
          }
        });
      } else {
        return callback({
          error: -10
          /* ACCESS_DENIED - https://cs.chromium.org/chromium/src/net/base/net_error_list.h?l=32 */
        });
      }
    } catch {
    }
    return callback({
      error: -2
      /* FAILED - https://cs.chromium.org/chromium/src/net/base/net_error_list.h?l=32 */
    });
  }
};

// out-build/vs/platform/webview/electron-main/webviewMainService.js
var $dlc = class $dlc2 extends $0c {
  constructor(b) {
    super();
    this.b = b;
    this.a = this.B(new $De());
    this.onFoundInFrame = this.a.event;
    this.B(new $clc());
  }
  async setIgnoreMenuShortcuts(id2, enabled) {
    let contents;
    if (typeof id2.windowId === "number") {
      const { windowId } = id2;
      const window2 = this.b.getWindowById(windowId);
      if (!window2?.win) {
        throw new Error(`Invalid windowId: ${windowId}`);
      }
      contents = window2.win.webContents;
    } else {
      const { webContentsId } = id2;
      contents = webContents2.fromId(webContentsId);
      if (!contents) {
        throw new Error(`Invalid webContentsId: ${webContentsId}`);
      }
    }
    if (!contents.isDestroyed()) {
      contents.setIgnoreMenuShortcuts(enabled);
    }
  }
  async findInFrame(windowId, frameName, text, options) {
    const initialFrame = this.c(windowId, frameName);
    const frame = initialFrame;
    if (typeof frame.findInFrame === "function") {
      frame.findInFrame(text, {
        findNext: options.findNext,
        forward: options.forward
      });
      const foundInFrameHandler = (_, result) => {
        if (result.finalUpdate) {
          this.a.fire(result);
          frame.removeListener("found-in-frame", foundInFrameHandler);
        }
      };
      frame.on("found-in-frame", foundInFrameHandler);
    }
  }
  async stopFindInFrame(windowId, frameName, options) {
    const initialFrame = this.c(windowId, frameName);
    const frame = initialFrame;
    if (typeof frame.stopFindInFrame === "function") {
      frame.stopFindInFrame(options.keepSelection ? "keepSelection" : "clearSelection");
    }
  }
  c(windowId, frameName) {
    const window2 = this.b.getWindowById(windowId.windowId);
    if (!window2?.win) {
      throw new Error(`Invalid windowId: ${windowId}`);
    }
    const frame = window2.win.webContents.mainFrame.framesInSubtree.find((frame2) => {
      return frame2.name === frameName;
    });
    if (!frame) {
      throw new Error(`Unknown frame: ${frameName}`);
    }
    return frame;
  }
};
$dlc = __decorate([
  __param(0, $Pjc)
], $dlc);

// out-build/vs/platform/windows/electron-main/windowsMainService.js
import * as fs10 from "fs";
import { app as app10, BrowserWindow as BrowserWindow5, shell as shell3 } from "electron";
import { hostname, release as release5, arch as arch3 } from "os";

// out-build/vs/platform/windows/electron-main/windowImpl.js
import electron9 from "electron";
import { release as release4 } from "os";

// out-build/vs/platform/externalServices/common/serviceMachineId.js
async function $Jq(environmentService, fileService, storageService) {
  let uuid = storageService ? storageService.get(
    "storage.serviceMachineId",
    -1
    /* StorageScope.APPLICATION */
  ) || null : null;
  if (uuid) {
    return uuid;
  }
  try {
    const contents = await fileService.readFile(environmentService.serviceMachineIdResource);
    const value = contents.value.toString();
    uuid = $ih(value) ? value : null;
  } catch (e) {
    uuid = null;
  }
  if (!uuid) {
    uuid = $jh();
    try {
      await fileService.writeFile(environmentService.serviceMachineIdResource, $7e.fromString(uuid));
    } catch (error) {
    }
  }
  storageService?.store(
    "storage.serviceMachineId",
    uuid,
    -1,
    1
    /* StorageTarget.MACHINE */
  );
  return uuid;
}

// out-build/vs/platform/externalServices/common/marketplace.js
async function $Kq(version, productService, environmentService, configurationService, fileService, storageService, telemetryService) {
  const headers = {
    "X-Market-Client-Id": `VSCode ${version}`,
    "User-Agent": `VSCode ${version} (${productService.nameShort})`
  };
  if ($Zp(productService, environmentService) && $2p(configurationService) === 3) {
    const serviceMachineId = await $Jq(environmentService, fileService, storageService);
    headers["X-Market-User-Id"] = serviceMachineId;
    headers["VSCode-SessionId"] = telemetryService.machineId || serviceMachineId;
  }
  return headers;
}

// out-build/vs/base/common/codiconsUtil.js
var _codiconFontCharacters = /* @__PURE__ */ Object.create(null);
function $hk(id2, fontCharacter) {
  if ($yg(fontCharacter)) {
    const val = _codiconFontCharacters[fontCharacter];
    if (val === void 0) {
      throw new Error(`${id2} references an unknown codicon: ${fontCharacter}`);
    }
    fontCharacter = val;
  }
  _codiconFontCharacters[id2] = fontCharacter;
  return { id: id2 };
}

// out-build/vs/base/common/codiconsLibrary.js
var $jk = {
  add: $hk("add", 6e4),
  plus: $hk("plus", 6e4),
  gistNew: $hk("gist-new", 6e4),
  repoCreate: $hk("repo-create", 6e4),
  lightbulb: $hk("lightbulb", 60001),
  lightBulb: $hk("light-bulb", 60001),
  repo: $hk("repo", 60002),
  repoDelete: $hk("repo-delete", 60002),
  gistFork: $hk("gist-fork", 60003),
  repoForked: $hk("repo-forked", 60003),
  gitPullRequest: $hk("git-pull-request", 60004),
  gitPullRequestAbandoned: $hk("git-pull-request-abandoned", 60004),
  recordKeys: $hk("record-keys", 60005),
  keyboard: $hk("keyboard", 60005),
  tag: $hk("tag", 60006),
  gitPullRequestLabel: $hk("git-pull-request-label", 60006),
  tagAdd: $hk("tag-add", 60006),
  tagRemove: $hk("tag-remove", 60006),
  person: $hk("person", 60007),
  personFollow: $hk("person-follow", 60007),
  personOutline: $hk("person-outline", 60007),
  personFilled: $hk("person-filled", 60007),
  gitBranch: $hk("git-branch", 60008),
  gitBranchCreate: $hk("git-branch-create", 60008),
  gitBranchDelete: $hk("git-branch-delete", 60008),
  sourceControl: $hk("source-control", 60008),
  mirror: $hk("mirror", 60009),
  mirrorPublic: $hk("mirror-public", 60009),
  star: $hk("star", 60010),
  starAdd: $hk("star-add", 60010),
  starDelete: $hk("star-delete", 60010),
  starEmpty: $hk("star-empty", 60010),
  comment: $hk("comment", 60011),
  commentAdd: $hk("comment-add", 60011),
  alert: $hk("alert", 60012),
  warning: $hk("warning", 60012),
  search: $hk("search", 60013),
  searchSave: $hk("search-save", 60013),
  logOut: $hk("log-out", 60014),
  signOut: $hk("sign-out", 60014),
  logIn: $hk("log-in", 60015),
  signIn: $hk("sign-in", 60015),
  eye: $hk("eye", 60016),
  eyeUnwatch: $hk("eye-unwatch", 60016),
  eyeWatch: $hk("eye-watch", 60016),
  circleFilled: $hk("circle-filled", 60017),
  primitiveDot: $hk("primitive-dot", 60017),
  closeDirty: $hk("close-dirty", 60017),
  debugBreakpoint: $hk("debug-breakpoint", 60017),
  debugBreakpointDisabled: $hk("debug-breakpoint-disabled", 60017),
  debugHint: $hk("debug-hint", 60017),
  terminalDecorationSuccess: $hk("terminal-decoration-success", 60017),
  primitiveSquare: $hk("primitive-square", 60018),
  edit: $hk("edit", 60019),
  pencil: $hk("pencil", 60019),
  info: $hk("info", 60020),
  issueOpened: $hk("issue-opened", 60020),
  gistPrivate: $hk("gist-private", 60021),
  gitForkPrivate: $hk("git-fork-private", 60021),
  lock: $hk("lock", 60021),
  mirrorPrivate: $hk("mirror-private", 60021),
  close: $hk("close", 60022),
  removeClose: $hk("remove-close", 60022),
  x: $hk("x", 60022),
  repoSync: $hk("repo-sync", 60023),
  sync: $hk("sync", 60023),
  clone: $hk("clone", 60024),
  desktopDownload: $hk("desktop-download", 60024),
  beaker: $hk("beaker", 60025),
  microscope: $hk("microscope", 60025),
  vm: $hk("vm", 60026),
  deviceDesktop: $hk("device-desktop", 60026),
  file: $hk("file", 60027),
  fileText: $hk("file-text", 60027),
  more: $hk("more", 60028),
  ellipsis: $hk("ellipsis", 60028),
  kebabHorizontal: $hk("kebab-horizontal", 60028),
  mailReply: $hk("mail-reply", 60029),
  reply: $hk("reply", 60029),
  organization: $hk("organization", 60030),
  organizationFilled: $hk("organization-filled", 60030),
  organizationOutline: $hk("organization-outline", 60030),
  newFile: $hk("new-file", 60031),
  fileAdd: $hk("file-add", 60031),
  newFolder: $hk("new-folder", 60032),
  fileDirectoryCreate: $hk("file-directory-create", 60032),
  trash: $hk("trash", 60033),
  trashcan: $hk("trashcan", 60033),
  history: $hk("history", 60034),
  clock: $hk("clock", 60034),
  folder: $hk("folder", 60035),
  fileDirectory: $hk("file-directory", 60035),
  symbolFolder: $hk("symbol-folder", 60035),
  logoGithub: $hk("logo-github", 60036),
  markGithub: $hk("mark-github", 60036),
  github: $hk("github", 60036),
  terminal: $hk("terminal", 60037),
  console: $hk("console", 60037),
  repl: $hk("repl", 60037),
  zap: $hk("zap", 60038),
  symbolEvent: $hk("symbol-event", 60038),
  error: $hk("error", 60039),
  stop: $hk("stop", 60039),
  variable: $hk("variable", 60040),
  symbolVariable: $hk("symbol-variable", 60040),
  array: $hk("array", 60042),
  symbolArray: $hk("symbol-array", 60042),
  symbolModule: $hk("symbol-module", 60043),
  symbolPackage: $hk("symbol-package", 60043),
  symbolNamespace: $hk("symbol-namespace", 60043),
  symbolObject: $hk("symbol-object", 60043),
  symbolMethod: $hk("symbol-method", 60044),
  symbolFunction: $hk("symbol-function", 60044),
  symbolConstructor: $hk("symbol-constructor", 60044),
  symbolBoolean: $hk("symbol-boolean", 60047),
  symbolNull: $hk("symbol-null", 60047),
  symbolNumeric: $hk("symbol-numeric", 60048),
  symbolNumber: $hk("symbol-number", 60048),
  symbolStructure: $hk("symbol-structure", 60049),
  symbolStruct: $hk("symbol-struct", 60049),
  symbolParameter: $hk("symbol-parameter", 60050),
  symbolTypeParameter: $hk("symbol-type-parameter", 60050),
  symbolKey: $hk("symbol-key", 60051),
  symbolText: $hk("symbol-text", 60051),
  symbolReference: $hk("symbol-reference", 60052),
  goToFile: $hk("go-to-file", 60052),
  symbolEnum: $hk("symbol-enum", 60053),
  symbolValue: $hk("symbol-value", 60053),
  symbolRuler: $hk("symbol-ruler", 60054),
  symbolUnit: $hk("symbol-unit", 60054),
  activateBreakpoints: $hk("activate-breakpoints", 60055),
  archive: $hk("archive", 60056),
  arrowBoth: $hk("arrow-both", 60057),
  arrowDown: $hk("arrow-down", 60058),
  arrowLeft: $hk("arrow-left", 60059),
  arrowRight: $hk("arrow-right", 60060),
  arrowSmallDown: $hk("arrow-small-down", 60061),
  arrowSmallLeft: $hk("arrow-small-left", 60062),
  arrowSmallRight: $hk("arrow-small-right", 60063),
  arrowSmallUp: $hk("arrow-small-up", 60064),
  arrowUp: $hk("arrow-up", 60065),
  bell: $hk("bell", 60066),
  bold: $hk("bold", 60067),
  book: $hk("book", 60068),
  bookmark: $hk("bookmark", 60069),
  debugBreakpointConditionalUnverified: $hk("debug-breakpoint-conditional-unverified", 60070),
  debugBreakpointConditional: $hk("debug-breakpoint-conditional", 60071),
  debugBreakpointConditionalDisabled: $hk("debug-breakpoint-conditional-disabled", 60071),
  debugBreakpointDataUnverified: $hk("debug-breakpoint-data-unverified", 60072),
  debugBreakpointData: $hk("debug-breakpoint-data", 60073),
  debugBreakpointDataDisabled: $hk("debug-breakpoint-data-disabled", 60073),
  debugBreakpointLogUnverified: $hk("debug-breakpoint-log-unverified", 60074),
  debugBreakpointLog: $hk("debug-breakpoint-log", 60075),
  debugBreakpointLogDisabled: $hk("debug-breakpoint-log-disabled", 60075),
  briefcase: $hk("briefcase", 60076),
  broadcast: $hk("broadcast", 60077),
  browser: $hk("browser", 60078),
  bug: $hk("bug", 60079),
  calendar: $hk("calendar", 60080),
  caseSensitive: $hk("case-sensitive", 60081),
  check: $hk("check", 60082),
  checklist: $hk("checklist", 60083),
  chevronDown: $hk("chevron-down", 60084),
  chevronLeft: $hk("chevron-left", 60085),
  chevronRight: $hk("chevron-right", 60086),
  chevronUp: $hk("chevron-up", 60087),
  chromeClose: $hk("chrome-close", 60088),
  chromeMaximize: $hk("chrome-maximize", 60089),
  chromeMinimize: $hk("chrome-minimize", 60090),
  chromeRestore: $hk("chrome-restore", 60091),
  circleOutline: $hk("circle-outline", 60092),
  circle: $hk("circle", 60092),
  debugBreakpointUnverified: $hk("debug-breakpoint-unverified", 60092),
  terminalDecorationIncomplete: $hk("terminal-decoration-incomplete", 60092),
  circleSlash: $hk("circle-slash", 60093),
  circuitBoard: $hk("circuit-board", 60094),
  clearAll: $hk("clear-all", 60095),
  clippy: $hk("clippy", 60096),
  closeAll: $hk("close-all", 60097),
  cloudDownload: $hk("cloud-download", 60098),
  cloudUpload: $hk("cloud-upload", 60099),
  code: $hk("code", 60100),
  collapseAll: $hk("collapse-all", 60101),
  colorMode: $hk("color-mode", 60102),
  commentDiscussion: $hk("comment-discussion", 60103),
  creditCard: $hk("credit-card", 60105),
  dash: $hk("dash", 60108),
  dashboard: $hk("dashboard", 60109),
  database: $hk("database", 60110),
  debugContinue: $hk("debug-continue", 60111),
  debugDisconnect: $hk("debug-disconnect", 60112),
  debugPause: $hk("debug-pause", 60113),
  debugRestart: $hk("debug-restart", 60114),
  debugStart: $hk("debug-start", 60115),
  debugStepInto: $hk("debug-step-into", 60116),
  debugStepOut: $hk("debug-step-out", 60117),
  debugStepOver: $hk("debug-step-over", 60118),
  debugStop: $hk("debug-stop", 60119),
  debug: $hk("debug", 60120),
  deviceCameraVideo: $hk("device-camera-video", 60121),
  deviceCamera: $hk("device-camera", 60122),
  deviceMobile: $hk("device-mobile", 60123),
  diffAdded: $hk("diff-added", 60124),
  diffIgnored: $hk("diff-ignored", 60125),
  diffModified: $hk("diff-modified", 60126),
  diffRemoved: $hk("diff-removed", 60127),
  diffRenamed: $hk("diff-renamed", 60128),
  diff: $hk("diff", 60129),
  diffSidebyside: $hk("diff-sidebyside", 60129),
  discard: $hk("discard", 60130),
  editorLayout: $hk("editor-layout", 60131),
  emptyWindow: $hk("empty-window", 60132),
  exclude: $hk("exclude", 60133),
  extensions: $hk("extensions", 60134),
  eyeClosed: $hk("eye-closed", 60135),
  fileBinary: $hk("file-binary", 60136),
  fileCode: $hk("file-code", 60137),
  fileMedia: $hk("file-media", 60138),
  filePdf: $hk("file-pdf", 60139),
  fileSubmodule: $hk("file-submodule", 60140),
  fileSymlinkDirectory: $hk("file-symlink-directory", 60141),
  fileSymlinkFile: $hk("file-symlink-file", 60142),
  fileZip: $hk("file-zip", 60143),
  files: $hk("files", 60144),
  filter: $hk("filter", 60145),
  flame: $hk("flame", 60146),
  foldDown: $hk("fold-down", 60147),
  foldUp: $hk("fold-up", 60148),
  fold: $hk("fold", 60149),
  folderActive: $hk("folder-active", 60150),
  folderOpened: $hk("folder-opened", 60151),
  gear: $hk("gear", 60152),
  gift: $hk("gift", 60153),
  gistSecret: $hk("gist-secret", 60154),
  gist: $hk("gist", 60155),
  gitCommit: $hk("git-commit", 60156),
  gitCompare: $hk("git-compare", 60157),
  compareChanges: $hk("compare-changes", 60157),
  gitMerge: $hk("git-merge", 60158),
  githubAction: $hk("github-action", 60159),
  githubAlt: $hk("github-alt", 60160),
  globe: $hk("globe", 60161),
  grabber: $hk("grabber", 60162),
  graph: $hk("graph", 60163),
  gripper: $hk("gripper", 60164),
  heart: $hk("heart", 60165),
  home: $hk("home", 60166),
  horizontalRule: $hk("horizontal-rule", 60167),
  hubot: $hk("hubot", 60168),
  inbox: $hk("inbox", 60169),
  issueReopened: $hk("issue-reopened", 60171),
  issues: $hk("issues", 60172),
  italic: $hk("italic", 60173),
  jersey: $hk("jersey", 60174),
  json: $hk("json", 60175),
  kebabVertical: $hk("kebab-vertical", 60176),
  key: $hk("key", 60177),
  law: $hk("law", 60178),
  lightbulbAutofix: $hk("lightbulb-autofix", 60179),
  linkExternal: $hk("link-external", 60180),
  link: $hk("link", 60181),
  listOrdered: $hk("list-ordered", 60182),
  listUnordered: $hk("list-unordered", 60183),
  liveShare: $hk("live-share", 60184),
  loading: $hk("loading", 60185),
  location: $hk("location", 60186),
  mailRead: $hk("mail-read", 60187),
  mail: $hk("mail", 60188),
  markdown: $hk("markdown", 60189),
  megaphone: $hk("megaphone", 60190),
  mention: $hk("mention", 60191),
  milestone: $hk("milestone", 60192),
  gitPullRequestMilestone: $hk("git-pull-request-milestone", 60192),
  mortarBoard: $hk("mortar-board", 60193),
  move: $hk("move", 60194),
  multipleWindows: $hk("multiple-windows", 60195),
  mute: $hk("mute", 60196),
  noNewline: $hk("no-newline", 60197),
  note: $hk("note", 60198),
  octoface: $hk("octoface", 60199),
  openPreview: $hk("open-preview", 60200),
  package: $hk("package", 60201),
  paintcan: $hk("paintcan", 60202),
  pin: $hk("pin", 60203),
  play: $hk("play", 60204),
  run: $hk("run", 60204),
  plug: $hk("plug", 60205),
  preserveCase: $hk("preserve-case", 60206),
  preview: $hk("preview", 60207),
  project: $hk("project", 60208),
  pulse: $hk("pulse", 60209),
  question: $hk("question", 60210),
  quote: $hk("quote", 60211),
  radioTower: $hk("radio-tower", 60212),
  reactions: $hk("reactions", 60213),
  references: $hk("references", 60214),
  refresh: $hk("refresh", 60215),
  regex: $hk("regex", 60216),
  remoteExplorer: $hk("remote-explorer", 60217),
  remote: $hk("remote", 60218),
  remove: $hk("remove", 60219),
  replaceAll: $hk("replace-all", 60220),
  replace: $hk("replace", 60221),
  repoClone: $hk("repo-clone", 60222),
  repoForcePush: $hk("repo-force-push", 60223),
  repoPull: $hk("repo-pull", 60224),
  repoPush: $hk("repo-push", 60225),
  report: $hk("report", 60226),
  requestChanges: $hk("request-changes", 60227),
  rocket: $hk("rocket", 60228),
  rootFolderOpened: $hk("root-folder-opened", 60229),
  rootFolder: $hk("root-folder", 60230),
  rss: $hk("rss", 60231),
  ruby: $hk("ruby", 60232),
  saveAll: $hk("save-all", 60233),
  saveAs: $hk("save-as", 60234),
  save: $hk("save", 60235),
  screenFull: $hk("screen-full", 60236),
  screenNormal: $hk("screen-normal", 60237),
  searchStop: $hk("search-stop", 60238),
  server: $hk("server", 60240),
  settingsGear: $hk("settings-gear", 60241),
  settings: $hk("settings", 60242),
  shield: $hk("shield", 60243),
  smiley: $hk("smiley", 60244),
  sortPrecedence: $hk("sort-precedence", 60245),
  splitHorizontal: $hk("split-horizontal", 60246),
  splitVertical: $hk("split-vertical", 60247),
  squirrel: $hk("squirrel", 60248),
  starFull: $hk("star-full", 60249),
  starHalf: $hk("star-half", 60250),
  symbolClass: $hk("symbol-class", 60251),
  symbolColor: $hk("symbol-color", 60252),
  symbolConstant: $hk("symbol-constant", 60253),
  symbolEnumMember: $hk("symbol-enum-member", 60254),
  symbolField: $hk("symbol-field", 60255),
  symbolFile: $hk("symbol-file", 60256),
  symbolInterface: $hk("symbol-interface", 60257),
  symbolKeyword: $hk("symbol-keyword", 60258),
  symbolMisc: $hk("symbol-misc", 60259),
  symbolOperator: $hk("symbol-operator", 60260),
  symbolProperty: $hk("symbol-property", 60261),
  wrench: $hk("wrench", 60261),
  wrenchSubaction: $hk("wrench-subaction", 60261),
  symbolSnippet: $hk("symbol-snippet", 60262),
  tasklist: $hk("tasklist", 60263),
  telescope: $hk("telescope", 60264),
  textSize: $hk("text-size", 60265),
  threeBars: $hk("three-bars", 60266),
  thumbsdown: $hk("thumbsdown", 60267),
  thumbsup: $hk("thumbsup", 60268),
  tools: $hk("tools", 60269),
  triangleDown: $hk("triangle-down", 60270),
  triangleLeft: $hk("triangle-left", 60271),
  triangleRight: $hk("triangle-right", 60272),
  triangleUp: $hk("triangle-up", 60273),
  twitter: $hk("twitter", 60274),
  unfold: $hk("unfold", 60275),
  unlock: $hk("unlock", 60276),
  unmute: $hk("unmute", 60277),
  unverified: $hk("unverified", 60278),
  verified: $hk("verified", 60279),
  versions: $hk("versions", 60280),
  vmActive: $hk("vm-active", 60281),
  vmOutline: $hk("vm-outline", 60282),
  vmRunning: $hk("vm-running", 60283),
  watch: $hk("watch", 60284),
  whitespace: $hk("whitespace", 60285),
  wholeWord: $hk("whole-word", 60286),
  window: $hk("window", 60287),
  wordWrap: $hk("word-wrap", 60288),
  zoomIn: $hk("zoom-in", 60289),
  zoomOut: $hk("zoom-out", 60290),
  listFilter: $hk("list-filter", 60291),
  listFlat: $hk("list-flat", 60292),
  listSelection: $hk("list-selection", 60293),
  selection: $hk("selection", 60293),
  listTree: $hk("list-tree", 60294),
  debugBreakpointFunctionUnverified: $hk("debug-breakpoint-function-unverified", 60295),
  debugBreakpointFunction: $hk("debug-breakpoint-function", 60296),
  debugBreakpointFunctionDisabled: $hk("debug-breakpoint-function-disabled", 60296),
  debugStackframeActive: $hk("debug-stackframe-active", 60297),
  circleSmallFilled: $hk("circle-small-filled", 60298),
  debugStackframeDot: $hk("debug-stackframe-dot", 60298),
  terminalDecorationMark: $hk("terminal-decoration-mark", 60298),
  debugStackframe: $hk("debug-stackframe", 60299),
  debugStackframeFocused: $hk("debug-stackframe-focused", 60299),
  debugBreakpointUnsupported: $hk("debug-breakpoint-unsupported", 60300),
  symbolString: $hk("symbol-string", 60301),
  debugReverseContinue: $hk("debug-reverse-continue", 60302),
  debugStepBack: $hk("debug-step-back", 60303),
  debugRestartFrame: $hk("debug-restart-frame", 60304),
  debugAlt: $hk("debug-alt", 60305),
  callIncoming: $hk("call-incoming", 60306),
  callOutgoing: $hk("call-outgoing", 60307),
  menu: $hk("menu", 60308),
  expandAll: $hk("expand-all", 60309),
  feedback: $hk("feedback", 60310),
  gitPullRequestReviewer: $hk("git-pull-request-reviewer", 60310),
  groupByRefType: $hk("group-by-ref-type", 60311),
  ungroupByRefType: $hk("ungroup-by-ref-type", 60312),
  account: $hk("account", 60313),
  gitPullRequestAssignee: $hk("git-pull-request-assignee", 60313),
  bellDot: $hk("bell-dot", 60314),
  debugConsole: $hk("debug-console", 60315),
  library: $hk("library", 60316),
  output: $hk("output", 60317),
  runAll: $hk("run-all", 60318),
  syncIgnored: $hk("sync-ignored", 60319),
  pinned: $hk("pinned", 60320),
  githubInverted: $hk("github-inverted", 60321),
  serverProcess: $hk("server-process", 60322),
  serverEnvironment: $hk("server-environment", 60323),
  pass: $hk("pass", 60324),
  issueClosed: $hk("issue-closed", 60324),
  stopCircle: $hk("stop-circle", 60325),
  playCircle: $hk("play-circle", 60326),
  record: $hk("record", 60327),
  debugAltSmall: $hk("debug-alt-small", 60328),
  vmConnect: $hk("vm-connect", 60329),
  cloud: $hk("cloud", 60330),
  merge: $hk("merge", 60331),
  export: $hk("export", 60332),
  graphLeft: $hk("graph-left", 60333),
  magnet: $hk("magnet", 60334),
  notebook: $hk("notebook", 60335),
  redo: $hk("redo", 60336),
  checkAll: $hk("check-all", 60337),
  pinnedDirty: $hk("pinned-dirty", 60338),
  passFilled: $hk("pass-filled", 60339),
  circleLargeFilled: $hk("circle-large-filled", 60340),
  circleLarge: $hk("circle-large", 60341),
  circleLargeOutline: $hk("circle-large-outline", 60341),
  combine: $hk("combine", 60342),
  gather: $hk("gather", 60342),
  table: $hk("table", 60343),
  variableGroup: $hk("variable-group", 60344),
  typeHierarchy: $hk("type-hierarchy", 60345),
  typeHierarchySub: $hk("type-hierarchy-sub", 60346),
  typeHierarchySuper: $hk("type-hierarchy-super", 60347),
  gitPullRequestCreate: $hk("git-pull-request-create", 60348),
  runAbove: $hk("run-above", 60349),
  runBelow: $hk("run-below", 60350),
  notebookTemplate: $hk("notebook-template", 60351),
  debugRerun: $hk("debug-rerun", 60352),
  workspaceTrusted: $hk("workspace-trusted", 60353),
  workspaceUntrusted: $hk("workspace-untrusted", 60354),
  workspaceUnknown: $hk("workspace-unknown", 60355),
  terminalCmd: $hk("terminal-cmd", 60356),
  terminalDebian: $hk("terminal-debian", 60357),
  terminalLinux: $hk("terminal-linux", 60358),
  terminalPowershell: $hk("terminal-powershell", 60359),
  terminalTmux: $hk("terminal-tmux", 60360),
  terminalUbuntu: $hk("terminal-ubuntu", 60361),
  terminalBash: $hk("terminal-bash", 60362),
  arrowSwap: $hk("arrow-swap", 60363),
  copy: $hk("copy", 60364),
  personAdd: $hk("person-add", 60365),
  filterFilled: $hk("filter-filled", 60366),
  wand: $hk("wand", 60367),
  debugLineByLine: $hk("debug-line-by-line", 60368),
  inspect: $hk("inspect", 60369),
  layers: $hk("layers", 60370),
  layersDot: $hk("layers-dot", 60371),
  layersActive: $hk("layers-active", 60372),
  compass: $hk("compass", 60373),
  compassDot: $hk("compass-dot", 60374),
  compassActive: $hk("compass-active", 60375),
  azure: $hk("azure", 60376),
  issueDraft: $hk("issue-draft", 60377),
  gitPullRequestClosed: $hk("git-pull-request-closed", 60378),
  gitPullRequestDraft: $hk("git-pull-request-draft", 60379),
  debugAll: $hk("debug-all", 60380),
  debugCoverage: $hk("debug-coverage", 60381),
  runErrors: $hk("run-errors", 60382),
  folderLibrary: $hk("folder-library", 60383),
  debugContinueSmall: $hk("debug-continue-small", 60384),
  beakerStop: $hk("beaker-stop", 60385),
  graphLine: $hk("graph-line", 60386),
  graphScatter: $hk("graph-scatter", 60387),
  pieChart: $hk("pie-chart", 60388),
  bracket: $hk("bracket", 60175),
  bracketDot: $hk("bracket-dot", 60389),
  bracketError: $hk("bracket-error", 60390),
  lockSmall: $hk("lock-small", 60391),
  azureDevops: $hk("azure-devops", 60392),
  verifiedFilled: $hk("verified-filled", 60393),
  newline: $hk("newline", 60394),
  layout: $hk("layout", 60395),
  layoutActivitybarLeft: $hk("layout-activitybar-left", 60396),
  layoutActivitybarRight: $hk("layout-activitybar-right", 60397),
  layoutPanelLeft: $hk("layout-panel-left", 60398),
  layoutPanelCenter: $hk("layout-panel-center", 60399),
  layoutPanelJustify: $hk("layout-panel-justify", 60400),
  layoutPanelRight: $hk("layout-panel-right", 60401),
  layoutPanel: $hk("layout-panel", 60402),
  layoutSidebarLeft: $hk("layout-sidebar-left", 60403),
  layoutSidebarRight: $hk("layout-sidebar-right", 60404),
  layoutStatusbar: $hk("layout-statusbar", 60405),
  layoutMenubar: $hk("layout-menubar", 60406),
  layoutCentered: $hk("layout-centered", 60407),
  target: $hk("target", 60408),
  indent: $hk("indent", 60409),
  recordSmall: $hk("record-small", 60410),
  errorSmall: $hk("error-small", 60411),
  terminalDecorationError: $hk("terminal-decoration-error", 60411),
  arrowCircleDown: $hk("arrow-circle-down", 60412),
  arrowCircleLeft: $hk("arrow-circle-left", 60413),
  arrowCircleRight: $hk("arrow-circle-right", 60414),
  arrowCircleUp: $hk("arrow-circle-up", 60415),
  layoutSidebarRightOff: $hk("layout-sidebar-right-off", 60416),
  layoutPanelOff: $hk("layout-panel-off", 60417),
  layoutSidebarLeftOff: $hk("layout-sidebar-left-off", 60418),
  blank: $hk("blank", 60419),
  heartFilled: $hk("heart-filled", 60420),
  map: $hk("map", 60421),
  mapHorizontal: $hk("map-horizontal", 60421),
  foldHorizontal: $hk("fold-horizontal", 60421),
  mapFilled: $hk("map-filled", 60422),
  mapHorizontalFilled: $hk("map-horizontal-filled", 60422),
  foldHorizontalFilled: $hk("fold-horizontal-filled", 60422),
  circleSmall: $hk("circle-small", 60423),
  bellSlash: $hk("bell-slash", 60424),
  bellSlashDot: $hk("bell-slash-dot", 60425),
  commentUnresolved: $hk("comment-unresolved", 60426),
  gitPullRequestGoToChanges: $hk("git-pull-request-go-to-changes", 60427),
  gitPullRequestNewChanges: $hk("git-pull-request-new-changes", 60428),
  searchFuzzy: $hk("search-fuzzy", 60429),
  commentDraft: $hk("comment-draft", 60430),
  send: $hk("send", 60431),
  sparkle: $hk("sparkle", 60432),
  insert: $hk("insert", 60433),
  mic: $hk("mic", 60434),
  thumbsdownFilled: $hk("thumbsdown-filled", 60435),
  thumbsupFilled: $hk("thumbsup-filled", 60436),
  coffee: $hk("coffee", 60437),
  snake: $hk("snake", 60438),
  game: $hk("game", 60439),
  vr: $hk("vr", 60440),
  chip: $hk("chip", 60441),
  piano: $hk("piano", 60442),
  music: $hk("music", 60443),
  micFilled: $hk("mic-filled", 60444),
  repoFetch: $hk("repo-fetch", 60445),
  copilot: $hk("copilot", 60446),
  lightbulbSparkle: $hk("lightbulb-sparkle", 60447),
  robot: $hk("robot", 60448),
  sparkleFilled: $hk("sparkle-filled", 60449),
  diffSingle: $hk("diff-single", 60450),
  diffMultiple: $hk("diff-multiple", 60451),
  surroundWith: $hk("surround-with", 60452),
  share: $hk("share", 60453),
  gitStash: $hk("git-stash", 60454),
  gitStashApply: $hk("git-stash-apply", 60455),
  gitStashPop: $hk("git-stash-pop", 60456),
  vscode: $hk("vscode", 60457),
  vscodeInsiders: $hk("vscode-insiders", 60458),
  codeOss: $hk("code-oss", 60459),
  runCoverage: $hk("run-coverage", 60460),
  runAllCoverage: $hk("run-all-coverage", 60461),
  coverage: $hk("coverage", 60462),
  githubProject: $hk("github-project", 60463),
  mapVertical: $hk("map-vertical", 60464),
  foldVertical: $hk("fold-vertical", 60464),
  mapVerticalFilled: $hk("map-vertical-filled", 60465),
  foldVerticalFilled: $hk("fold-vertical-filled", 60465),
  goToSearch: $hk("go-to-search", 60466),
  percentage: $hk("percentage", 60467),
  sortPercentage: $hk("sort-percentage", 60467),
  attach: $hk("attach", 60468)
};

// out-build/vs/base/common/codicons.js
function $kk() {
  return Object.values($mk);
}
var $lk = {
  dialogError: $hk("dialog-error", "error"),
  dialogWarning: $hk("dialog-warning", "warning"),
  dialogInfo: $hk("dialog-info", "info"),
  dialogClose: $hk("dialog-close", "close"),
  treeItemExpanded: $hk("tree-item-expanded", "chevron-down"),
  // collapsed is done with rotation
  treeFilterOnTypeOn: $hk("tree-filter-on-type-on", "list-filter"),
  treeFilterOnTypeOff: $hk("tree-filter-on-type-off", "list-selection"),
  treeFilterClear: $hk("tree-filter-clear", "close"),
  treeItemLoading: $hk("tree-item-loading", "loading"),
  menuSelection: $hk("menu-selection", "check"),
  menuSubmenu: $hk("menu-submenu", "chevron-right"),
  menuBarMore: $hk("menubar-more", "more"),
  scrollbarButtonLeft: $hk("scrollbar-button-left", "triangle-left"),
  scrollbarButtonRight: $hk("scrollbar-button-right", "triangle-right"),
  scrollbarButtonUp: $hk("scrollbar-button-up", "triangle-up"),
  scrollbarButtonDown: $hk("scrollbar-button-down", "triangle-down"),
  toolBarMore: $hk("toolbar-more", "more"),
  quickInputBack: $hk("quick-input-back", "arrow-left"),
  dropDownButton: $hk("drop-down-button", 60084),
  symbolCustomColor: $hk("symbol-customcolor", 60252),
  exportIcon: $hk("export", 60332),
  workspaceUnspecified: $hk("workspace-unspecified", 60355),
  newLine: $hk("newline", 60394),
  thumbsDownFilled: $hk("thumbsdown-filled", 60435),
  thumbsUpFilled: $hk("thumbsup-filled", 60436),
  gitFetch: $hk("git-fetch", 60445),
  lightbulbSparkleAutofix: $hk("lightbulb-sparkle-autofix", 60447),
  debugBreakpointPending: $hk("debug-breakpoint-pending", 60377)
};
var $mk = {
  ...$jk,
  ...$lk
};

// out-build/vs/base/common/themables.js
var ThemeColor;
(function(ThemeColor2) {
  function isThemeColor(obj) {
    return obj && typeof obj === "object" && typeof obj.id === "string";
  }
  ThemeColor2.isThemeColor = isThemeColor;
})(ThemeColor || (ThemeColor = {}));
var ThemeIcon;
(function(ThemeIcon2) {
  ThemeIcon2.iconNameSegment = "[A-Za-z0-9]+";
  ThemeIcon2.iconNameExpression = "[A-Za-z0-9-]+";
  ThemeIcon2.iconModifierExpression = "~[A-Za-z]+";
  ThemeIcon2.iconNameCharacter = "[A-Za-z0-9~-]";
  const ThemeIconIdRegex = new RegExp(`^(${ThemeIcon2.iconNameExpression})(${ThemeIcon2.iconModifierExpression})?$`);
  function asClassNameArray(icon) {
    const match = ThemeIconIdRegex.exec(icon.id);
    if (!match) {
      return asClassNameArray($mk.error);
    }
    const [, id2, modifier] = match;
    const classNames = ["codicon", "codicon-" + id2];
    if (modifier) {
      classNames.push("codicon-modifier-" + modifier.substring(1));
    }
    return classNames;
  }
  ThemeIcon2.asClassNameArray = asClassNameArray;
  function asClassName(icon) {
    return asClassNameArray(icon).join(" ");
  }
  ThemeIcon2.asClassName = asClassName;
  function asCSSSelector(icon) {
    return "." + asClassNameArray(icon).join(".");
  }
  ThemeIcon2.asCSSSelector = asCSSSelector;
  function isThemeIcon(obj) {
    return obj && typeof obj === "object" && typeof obj.id === "string" && (typeof obj.color === "undefined" || ThemeColor.isThemeColor(obj.color));
  }
  ThemeIcon2.isThemeIcon = isThemeIcon;
  const _regexFromString = new RegExp(`^\\$\\((${ThemeIcon2.iconNameExpression}(?:${ThemeIcon2.iconModifierExpression})?)\\)$`);
  function fromString(str) {
    const match = _regexFromString.exec(str);
    if (!match) {
      return void 0;
    }
    const [, name] = match;
    return { id: name };
  }
  ThemeIcon2.fromString = fromString;
  function fromId(id2) {
    return { id: id2 };
  }
  ThemeIcon2.fromId = fromId;
  function modify(icon, modifier) {
    let id2 = icon.id;
    const tildeIndex = id2.lastIndexOf("~");
    if (tildeIndex !== -1) {
      id2 = id2.substring(0, tildeIndex);
    }
    if (modifier) {
      id2 = `${id2}~${modifier}`;
    }
    return { id: id2 };
  }
  ThemeIcon2.modify = modify;
  function getModifier(icon) {
    const tildeIndex = icon.id.lastIndexOf("~");
    if (tildeIndex !== -1) {
      return icon.id.substring(tildeIndex + 1);
    }
    return void 0;
  }
  ThemeIcon2.getModifier = getModifier;
  function isEqual(ti1, ti2) {
    return ti1.id === ti2.id && ti1.color?.id === ti2.color?.id;
  }
  ThemeIcon2.isEqual = isEqual;
})(ThemeIcon || (ThemeIcon = {}));

// out-build/vs/platform/windows/electron-main/windowImpl.js
var ReadyState;
(function(ReadyState2) {
  ReadyState2[ReadyState2["NONE"] = 0] = "NONE";
  ReadyState2[ReadyState2["NAVIGATING"] = 1] = "NAVIGATING";
  ReadyState2[ReadyState2["READY"] = 2] = "READY";
})(ReadyState || (ReadyState = {}));
var $6jc = class _$6jc extends $0c {
  get lastFocusTime() {
    return this.j;
  }
  get win() {
    return this.m;
  }
  n(win, options) {
    this.m = win;
    this.B(Event.fromNodeEventEmitter(win, "maximize")(() => this.b.fire()));
    this.B(Event.fromNodeEventEmitter(win, "unmaximize")(() => this.c.fire()));
    this.B(Event.fromNodeEventEmitter(win, "closed")(() => {
      this.a.fire();
      this.dispose();
    }));
    this.B(Event.fromNodeEventEmitter(win, "focus")(() => {
      this.j = Date.now();
    }));
    this.B(Event.fromNodeEventEmitter(this.m, "enter-full-screen")(() => this.g.fire()));
    this.B(Event.fromNodeEventEmitter(this.m, "leave-full-screen")(() => this.h.fire()));
    const useCustomTitleStyle = !$QE(
      this.r,
      options?.titleBarStyle === "hidden" ? "custom" : void 0
      /* unknown */
    );
    if ($m && useCustomTitleStyle) {
      win.setSheetOffset($M(release4()) ? 28 : 22);
    }
    if (useCustomTitleStyle && ($TE(this.r) || $m)) {
      const cachedWindowControlHeight = this.s.getItem(_$6jc.D);
      if (cachedWindowControlHeight) {
        this.updateWindowControls({ height: cachedWindowControlHeight });
      } else {
        this.updateWindowControls({ height: $SE });
      }
    }
    if ($l && useCustomTitleStyle) {
      const WM_INITMENU = 278;
      win.hookWindowMessage(WM_INITMENU, () => {
        const [x, y] = win.getPosition();
        const cursorPos = electron9.screen.getCursorScreenPoint();
        const cx = cursorPos.x - x;
        const cy = cursorPos.y - y;
        const shouldTriggerDefaultSystemContextMenu = () => {
          if (cx > 30 && cy >= 0 && cy <= Math.max(win.getBounds().height * 0.15, 35)) {
            return false;
          }
          return true;
        };
        if (!shouldTriggerDefaultSystemContextMenu()) {
          win.setEnabled(false);
          win.setEnabled(true);
          this.f.fire({ x: cx, y: cy });
        }
        return 0;
      });
    }
    if (this.t.args["open-devtools"] === true) {
      win.webContents.openDevTools();
    }
    if ($m) {
      this.B(this.onDidEnterFullScreen(() => {
        this.H?.complete(true);
      }));
      this.B(this.onDidLeaveFullScreen(() => {
        this.H?.complete(true);
      }));
    }
  }
  constructor(r, s, t, u) {
    super();
    this.r = r;
    this.s = s;
    this.t = t;
    this.u = u;
    this.a = this.B(new $De());
    this.onDidClose = this.a.event;
    this.b = this.B(new $De());
    this.onDidMaximize = this.b.event;
    this.c = this.B(new $De());
    this.onDidUnmaximize = this.c.event;
    this.f = this.B(new $De());
    this.onDidTriggerSystemContextMenu = this.f.event;
    this.g = this.B(new $De());
    this.onDidEnterFullScreen = this.g.event;
    this.h = this.B(new $De());
    this.onDidLeaveFullScreen = this.h.event;
    this.j = Date.now();
    this.m = null;
    this.F = $TE(this.r);
    this.G = void 0;
    this.H = void 0;
  }
  w(state, hasMultipleDisplays = electron9.screen.getAllDisplays().length > 0) {
    const windowSettings = this.r.getValue("window");
    const useNativeTabs = $m && windowSettings?.nativeTabs === true;
    if (($m || $l) && hasMultipleDisplays && (!useNativeTabs || electron9.BrowserWindow.getAllWindows().length === 1)) {
      if ([state.width, state.height, state.x, state.y].every((value) => typeof value === "number")) {
        this.m?.setBounds({
          width: state.width,
          height: state.height,
          x: state.x,
          y: state.y
        });
      }
    }
    if (state.mode === 0 || state.mode === 3) {
      this.m?.maximize();
      if (state.mode === 3) {
        this.I(true, true);
      }
      this.m?.show();
    }
  }
  setRepresentedFilename(filename) {
    if ($m) {
      this.win?.setRepresentedFilename(filename);
    } else {
      this.z = filename;
    }
  }
  getRepresentedFilename() {
    if ($m) {
      return this.win?.getRepresentedFilename();
    }
    return this.z;
  }
  setDocumentEdited(edited) {
    if ($m) {
      this.win?.setDocumentEdited(edited);
    }
    this.C = edited;
  }
  isDocumentEdited() {
    if ($m) {
      return Boolean(this.win?.isDocumentEdited());
    }
    return !!this.C;
  }
  focus(options) {
    if ($m && options?.force) {
      electron9.app.focus({ steal: true });
    }
    const win = this.win;
    if (!win) {
      return;
    }
    if (win.isMinimized()) {
      win.restore();
    }
    win.focus();
  }
  handleTitleDoubleClick() {
    const win = this.win;
    if (!win) {
      return;
    }
    if ($m) {
      const action = electron9.systemPreferences.getUserDefault("AppleActionOnDoubleClick", "string");
      switch (action) {
        case "Minimize":
          win.minimize();
          break;
        case "None":
          break;
        case "Maximize":
        default:
          if (win.isMaximized()) {
            win.unmaximize();
          } else {
            win.maximize();
          }
      }
    } else {
      if (win.isMaximized()) {
        win.unmaximize();
      } else {
        win.maximize();
      }
    }
  }
  static {
    this.D = "windowControlHeight";
  }
  updateWindowControls(options) {
    const win = this.win;
    if (!win) {
      return;
    }
    if (options.height) {
      this.s.setItem($7jc.D, options.height);
    }
    if (this.F) {
      win.setTitleBarOverlay({
        color: options.backgroundColor?.trim() === "" ? void 0 : options.backgroundColor,
        symbolColor: options.foregroundColor?.trim() === "" ? void 0 : options.foregroundColor,
        height: options.height ? options.height - 1 : void 0
        // account for window border
      });
    } else if ($m && options.height !== void 0) {
      const verticalOffset = (options.height - 15) / 2;
      if (!verticalOffset) {
        win.setWindowButtonPosition(null);
      } else {
        win.setWindowButtonPosition({ x: verticalOffset, y: verticalOffset });
      }
    }
  }
  toggleFullScreen() {
    this.I(!this.isFullScreen, false);
  }
  I(fullscreen, fromRestore) {
    if ($UE(this.r)) {
      this.J(fullscreen, fromRestore);
    } else {
      this.M(fullscreen);
    }
  }
  get isFullScreen() {
    if ($m && typeof this.G === "boolean") {
      return this.G;
    }
    const win = this.win;
    const isFullScreen = win?.isFullScreen();
    const isSimpleFullScreen = win?.isSimpleFullScreen();
    return Boolean(isFullScreen || isSimpleFullScreen);
  }
  J(fullscreen, fromRestore) {
    const win = this.win;
    if (win?.isSimpleFullScreen()) {
      win?.setSimpleFullScreen(false);
    }
    this.L(fullscreen, fromRestore);
  }
  L(fullscreen, fromRestore) {
    if ($m) {
      this.G = fullscreen;
      const joinNativeFullScreenTransition = this.H = new $ki();
      (async () => {
        const transitioned = await Promise.race([
          joinNativeFullScreenTransition.p,
          $1h(1e4).then(() => false)
        ]);
        if (this.H !== joinNativeFullScreenTransition) {
          return;
        }
        this.G = void 0;
        this.H = void 0;
        if (!transitioned && fullscreen && fromRestore && this.win && !this.win.isFullScreen()) {
          this.u.warn("window: native macOS fullscreen transition did not happen within 10s from restoring");
          this.h.fire();
        }
      })();
    }
    const win = this.win;
    win?.setFullScreen(fullscreen);
  }
  M(fullscreen) {
    const win = this.win;
    if (win?.isFullScreen()) {
      this.L(false, false);
    }
    win?.setSimpleFullScreen(fullscreen);
    win?.webContents.focus();
  }
  dispose() {
    super.dispose();
    this.m = null;
  }
};
var $7jc = class $7jc2 extends $6jc {
  get id() {
    return this.Q;
  }
  get backupPath() {
    return this.S?.backupPath;
  }
  get openedWorkspace() {
    return this.S?.workspace;
  }
  get profile() {
    if (!this.config) {
      return void 0;
    }
    const profile = this.hb.profiles.find((profile2) => profile2.id === this.config?.profiles.profile.id);
    if (this.isExtensionDevelopmentHost && profile) {
      return profile;
    }
    return this.hb.getProfileForWorkspace(this.config.workspace ?? $bj(this.backupPath, this.isExtensionDevelopmentHost)) ?? this.hb.defaultProfile;
  }
  get remoteAuthority() {
    return this.S?.remoteAuthority;
  }
  get config() {
    return this.S;
  }
  get isExtensionDevelopmentHost() {
    return !!this.S?.extensionDevelopmentPath;
  }
  get isExtensionTestHost() {
    return !!this.S?.extensionTestsPath;
  }
  get isExtensionDevelopmentTestFromCli() {
    return this.isExtensionDevelopmentHost && this.isExtensionTestHost && !this.S?.debugId;
  }
  constructor(config, logService, fb, environmentMainService, gb, hb, ib, jb, kb, configurationService, lb, mb, nb, ob, pb, qb, rb, sb, tb, stateService, instantiationService) {
    super(configurationService, stateService, environmentMainService, logService);
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.jb = jb;
    this.kb = kb;
    this.lb = lb;
    this.mb = mb;
    this.nb = nb;
    this.ob = ob;
    this.pb = pb;
    this.qb = qb;
    this.rb = rb;
    this.sb = sb;
    this.tb = tb;
    this.N = this.B(new $De());
    this.onWillLoad = this.N.event;
    this.O = this.B(new $De());
    this.onDidSignalReady = this.O.event;
    this.P = this.B(new $De());
    this.onDidDestroy = this.P.event;
    this.X = [];
    this.Y = [];
    this.Z = void 0;
    this.$ = void 0;
    this.ab = void 0;
    this.bb = this.B(this.sb.createIPCObjectUrl());
    this.eb = false;
    this.ub = 0;
    {
      const [state, hasMultipleDisplays] = this.Eb(config.state);
      this.U = state;
      this.u.trace("window#ctor: using window state", state);
      const options = instantiationService.invokeFunction($Qjc, this.U, void 0, {
        preload: $hh.asFileUri("vs/base/parts/sandbox/electron-sandbox/preload.js").fsPath,
        additionalArguments: [`--vscode-window-config=${this.bb.resource.toString()}`],
        v8CacheOptions: this.t.useCodeCache ? "bypassHeatCheck" : "none"
      });
      mark("code/willCreateCodeBrowserWindow");
      this.m = new electron9.BrowserWindow(options);
      mark("code/didCreateCodeBrowserWindow");
      this.Q = this.m.id;
      this.n(this.m, options);
      this.w(this.U, hasMultipleDisplays);
      this.j = Date.now();
    }
    this.Bb();
    this.Kb();
    this.vb();
  }
  setReady() {
    this.u.trace(`window#load: window reported ready (id: ${this.Q})`);
    this.ub = 2;
    while (this.X.length) {
      this.X.pop()(this);
    }
    this.O.fire();
  }
  ready() {
    return new Promise((resolve2) => {
      if (this.isReady) {
        return resolve2(this);
      }
      this.X.push(resolve2);
    });
  }
  get isReady() {
    return this.ub === 2;
  }
  get whenClosedOrLoaded() {
    return new Promise((resolve2) => {
      function handle() {
        closeListener.dispose();
        loadListener.dispose();
        resolve2();
      }
      const closeListener = this.onDidClose(() => handle());
      const loadListener = this.onWillLoad(() => handle());
    });
  }
  vb() {
    this.B(Event.fromNodeEventEmitter(this.m, "unresponsive")(() => this.yb(
      1
      /* WindowError.UNRESPONSIVE */
    )));
    this.B(Event.fromNodeEventEmitter(this.m.webContents, "render-process-gone", (event, details) => details)((details) => this.yb(2, { ...details })));
    this.B(Event.fromNodeEventEmitter(this.m.webContents, "did-fail-load", (event, exitCode, reason) => ({ exitCode, reason }))(({ exitCode, reason }) => this.yb(3, { reason, exitCode })));
    this.B(Event.fromNodeEventEmitter(this.m.webContents, "will-prevent-unload")((event) => event.preventDefault()));
    this.B(Event.fromNodeEventEmitter(this.m.webContents, "did-finish-load")(() => {
      if (this.db) {
        this.S = this.db;
        this.db = void 0;
      }
    }));
    this.B(this.onDidMaximize(() => {
      if (this.S) {
        this.S.maximized = true;
      }
    }));
    this.B(this.onDidUnmaximize(() => {
      if (this.S) {
        this.S.maximized = false;
      }
    }));
    this.B(this.onDidEnterFullScreen(() => {
      this.sendWhenReady("vscode:enterFullScreen", CancellationToken.None);
    }));
    this.B(this.onDidLeaveFullScreen(() => {
      this.sendWhenReady("vscode:leaveFullScreen", CancellationToken.None);
    }));
    this.B(this.r.onDidChangeConfiguration((e) => this.Bb(e)));
    this.B(this.mb.onDidDeleteUntitledWorkspace((e) => this.Ab(e)));
    const urls = ["https://marketplace.visualstudio.com/*", "https://*.vsassets.io/*"];
    this.m.webContents.session.webRequest.onBeforeSendHeaders({ urls }, async (details, cb) => {
      const headers = await this.xb();
      cb({ cancel: false, requestHeaders: Object.assign(details.requestHeaders, headers) });
    });
  }
  xb() {
    if (!this.wb) {
      this.wb = $Kq(this.rb.version, this.rb, this.t, this.r, this.ib, this.jb, this.ob);
    }
    return this.wb;
  }
  async yb(type4, details) {
    switch (type4) {
      case 2:
        this.u.error(`CodeWindow: renderer process gone (reason: ${details?.reason || "<unknown>"}, code: ${details?.exitCode || "<unknown>"})`);
        break;
      case 1:
        this.u.error("CodeWindow: detected unresponsive");
        break;
      case 3:
        this.u.error(`CodeWindow: failed to load (reason: ${details?.reason || "<unknown>"}, code: ${details?.exitCode || "<unknown>"})`);
        break;
    }
    this.ob.publicLog2("windowerror", {
      type: type4,
      reason: details?.reason,
      code: details?.exitCode
    });
    switch (type4) {
      case 1:
      case 2:
        if (this.isExtensionDevelopmentTestFromCli) {
          this.qb.kill(1);
          return;
        }
        if (this.t.args["enable-smoke-test-driver"]) {
          await this.zb(false, false);
          this.qb.quit();
          return;
        }
        if (type4 === 1) {
          if (this.isExtensionDevelopmentHost || this.isExtensionTestHost || this.m && this.m.webContents && this.m.webContents.isDevToolsOpened()) {
            return;
          }
          const { response, checkboxChecked } = await this.pb.showMessageBox({
            type: "warning",
            buttons: [
              localize(2477, null),
              localize(2478, null),
              localize(2479, null)
            ],
            message: localize(2480, null),
            detail: localize(2481, null),
            checkboxLabel: this.S?.workspace ? localize(2482, null) : void 0
          }, this.m);
          if (response !== 2) {
            const reopen = response === 0;
            await this.zb(reopen, checkboxChecked);
          }
        } else if (type4 === 2) {
          let message;
          if (!details) {
            message = localize(2483, null);
          } else {
            message = localize(2484, null, details.reason, details.exitCode ?? "<unknown>");
          }
          const { response, checkboxChecked } = await this.pb.showMessageBox({
            type: "warning",
            buttons: [
              this.S?.workspace ? localize(2485, null) : localize(2486, null),
              localize(2487, null)
            ],
            message,
            detail: this.S?.workspace ? localize(2488, null) : localize(2489, null),
            checkboxLabel: this.S?.workspace ? localize(2490, null) : void 0
          }, this.m);
          const reopen = response === 0;
          await this.zb(reopen, checkboxChecked);
        }
        break;
    }
  }
  async zb(reopen, skipRestoreEditors) {
    const workspace = this.S?.workspace;
    if (skipRestoreEditors && workspace) {
      try {
        const workspaceStorage = this.kb.workspaceStorage(workspace);
        await workspaceStorage.init();
        workspaceStorage.delete("memento/workbench.parts.editor");
        await workspaceStorage.close();
      } catch (error) {
        this.u.error(error);
      }
    }
    this.P.fire();
    try {
      if (reopen && this.S) {
        let uriToOpen = void 0;
        let forceEmpty = void 0;
        if ($0i(workspace)) {
          uriToOpen = { folderUri: workspace.uri };
        } else if ($cj(workspace)) {
          uriToOpen = { workspaceUri: workspace.configPath };
        } else {
          forceEmpty = true;
        }
        const window2 = (await this.tb.open({
          context: 5,
          userEnv: this.S.userEnv,
          cli: {
            ...this.t.args,
            _: []
            // we pass in the workspace to open explicitly via `urisToOpen`
          },
          urisToOpen: uriToOpen ? [uriToOpen] : void 0,
          forceEmpty,
          forceNewWindow: true,
          remoteAuthority: this.remoteAuthority
        })).at(0);
        window2?.focus();
      }
    } finally {
      this.m?.destroy();
    }
  }
  Ab(workspace) {
    if (this.S?.workspace?.id === workspace.id) {
      this.S.workspace = void 0;
    }
  }
  Bb(e) {
    if (!e || e.affectsConfiguration("window.menuBarVisibility")) {
      const newMenuBarVisibility = this.Gb();
      if (newMenuBarVisibility !== this.W) {
        this.W = newMenuBarVisibility;
        this.Hb(newMenuBarVisibility);
      }
    }
    if (!e || e.affectsConfiguration("http.proxy") || e.affectsConfiguration("http.noProxy")) {
      let newHttpProxy = (this.r.getValue("http.proxy") || "").trim() || (process.env["https_proxy"] || process.env["HTTPS_PROXY"] || process.env["http_proxy"] || process.env["HTTP_PROXY"] || "").trim() || void 0;
      if (newHttpProxy?.indexOf("@") !== -1) {
        const uri = URI.parse(newHttpProxy);
        const i = uri.authority.indexOf("@");
        if (i !== -1) {
          newHttpProxy = uri.with({ authority: uri.authority.substring(i + 1) }).toString();
        }
      }
      if (newHttpProxy?.endsWith("/")) {
        newHttpProxy = newHttpProxy.substr(0, newHttpProxy.length - 1);
      }
      const newNoProxy = (this.r.getValue("http.noProxy") || []).map((item) => item.trim()).join(",") || (process.env["no_proxy"] || process.env["NO_PROXY"] || "").trim() || void 0;
      if ((newHttpProxy || "").indexOf("@") === -1 && (newHttpProxy !== this.Z || newNoProxy !== this.$)) {
        this.Z = newHttpProxy;
        this.$ = newNoProxy;
        const proxyRules = newHttpProxy || "";
        const proxyBypassRules = newNoProxy ? `${newNoProxy},<local>` : "<local>";
        this.u.trace(`Setting proxy to '${proxyRules}', bypassing '${proxyBypassRules}'`);
        this.m.webContents.session.setProxy({ proxyRules, proxyBypassRules, pacScript: "" });
        electron9.app.setProxy({ proxyRules, proxyBypassRules, pacScript: "" });
      }
    }
  }
  addTabbedWindow(window2) {
    if ($m && window2.win) {
      this.m.addTabbedWindow(window2.win);
    }
  }
  load(configuration, options = /* @__PURE__ */ Object.create(null)) {
    this.u.trace(`window#load: attempt to load window (id: ${this.Q})`);
    if (this.isDocumentEdited()) {
      if (!options.isReload || !this.nb.isHotExitEnabled()) {
        this.setDocumentEdited(false);
      }
    }
    if (!options.isReload) {
      if (this.getRepresentedFilename()) {
        this.setRepresentedFilename("");
      }
      this.m.setTitle(this.rb.nameLong);
    }
    this.Cb(configuration, options);
    if (this.ub === 0) {
      this.S = configuration;
    } else {
      this.db = configuration;
    }
    this.ub = 1;
    this.m.loadURL($hh.asBrowserUri(`vs/code/electron-sandbox/workbench/workbench${this.t.isBuilt ? "" : "-dev"}.${$4 ? "esm." : ""}html`).toString(true));
    const wasLoaded = this.eb;
    this.eb = true;
    if (!this.t.isBuilt && !this.t.extensionTestsLocationURI) {
      this.B(new $_h(() => {
        if (this.m && !this.m.isVisible() && !this.m.isMinimized()) {
          this.m.show();
          this.focus({ force: true });
          this.m.webContents.openDevTools();
        }
      }, 1e4)).schedule();
    }
    this.N.fire({
      workspace: configuration.workspace,
      reason: options.isReload ? 3 : wasLoaded ? 2 : 1
      /* LoadReason.INITIAL */
    });
  }
  Cb(configuration, options) {
    const currentUserEnv = (this.S ?? this.db)?.userEnv;
    if (currentUserEnv) {
      const shouldPreserveLaunchCliEnvironment = $5m(currentUserEnv) && !$5m(configuration.userEnv);
      const shouldPreserveDebugEnvironmnet = this.isExtensionDevelopmentHost;
      if (shouldPreserveLaunchCliEnvironment || shouldPreserveDebugEnvironmnet) {
        configuration.userEnv = { ...currentUserEnv, ...configuration.userEnv };
      }
    }
    if (process.env["CHROME_CRASHPAD_PIPE_NAME"]) {
      Object.assign(configuration.userEnv, {
        CHROME_CRASHPAD_PIPE_NAME: process.env["CHROME_CRASHPAD_PIPE_NAME"]
      });
    }
    if (options.disableExtensions !== void 0) {
      configuration["disable-extensions"] = options.disableExtensions;
    }
    configuration.fullscreen = this.isFullScreen;
    configuration.maximized = this.m.isMaximized();
    configuration.partsSplash = this.lb.getWindowSplash();
    configuration.zoomLevel = this.Jb();
    configuration.isCustomZoomLevel = typeof this.ab === "number";
    if (configuration.isCustomZoomLevel && configuration.partsSplash) {
      configuration.partsSplash.zoomLevel = configuration.zoomLevel;
    }
    mark("code/willOpenNewWindow");
    configuration.perfMarks = getMarks();
    this.bb.update(configuration);
  }
  async reload(cli) {
    const configuration = Object.assign({}, this.S);
    configuration.workspace = await this.Db(configuration);
    delete configuration.filesToOpenOrCreate;
    delete configuration.filesToDiff;
    delete configuration.filesToMerge;
    delete configuration.filesToWait;
    if (this.isExtensionDevelopmentHost && cli) {
      configuration.verbose = cli.verbose;
      configuration.debugId = cli.debugId;
      configuration.extensionEnvironment = cli.extensionEnvironment;
      configuration["inspect-extensions"] = cli["inspect-extensions"];
      configuration["inspect-brk-extensions"] = cli["inspect-brk-extensions"];
      configuration["extensions-dir"] = cli["extensions-dir"];
    }
    configuration.accessibilitySupport = electron9.app.isAccessibilitySupportEnabled();
    configuration.isInitialStartup = false;
    configuration.policiesData = this.gb.serialize();
    configuration.continueOn = this.t.continueOn;
    configuration.profiles = {
      all: this.hb.profiles,
      profile: this.profile || this.hb.defaultProfile,
      home: this.hb.profilesHome
    };
    configuration.logLevel = this.fb.getLogLevel();
    configuration.loggers = {
      window: this.fb.getRegisteredLoggers(this.id),
      global: this.fb.getRegisteredLoggers()
    };
    this.load(configuration, { isReload: true, disableExtensions: cli?.["disable-extensions"] });
  }
  async Db(configuration) {
    if ($cj(configuration.workspace)) {
      const configPath = configuration.workspace.configPath;
      if (configPath.scheme === Schemas.file) {
        const workspaceExists = await this.ib.exists(configPath);
        if (!workspaceExists) {
          return void 0;
        }
      }
    } else if ($0i(configuration.workspace)) {
      const uri = configuration.workspace.uri;
      if (uri.scheme === Schemas.file) {
        const folderExists = await this.ib.exists(uri);
        if (!folderExists) {
          return void 0;
        }
      }
    }
    return configuration.workspace;
  }
  serializeWindowState() {
    if (!this.m) {
      return $Ejc();
    }
    if (this.isFullScreen) {
      let display;
      try {
        display = electron9.screen.getDisplayMatching(this.getBounds());
      } catch (error) {
      }
      const defaultState = $Ejc();
      return {
        mode: 3,
        display: display ? display.id : void 0,
        // Still carry over window dimensions from previous sessions
        // if we can compute it in fullscreen state.
        // does not seem possible in all cases on Linux for example
        // (https://github.com/microsoft/vscode/issues/58218) so we
        // fallback to the defaults in that case.
        width: this.U.width || defaultState.width,
        height: this.U.height || defaultState.height,
        x: this.U.x || 0,
        y: this.U.y || 0,
        zoomLevel: this.ab
      };
    }
    const state = /* @__PURE__ */ Object.create(null);
    let mode;
    if (!$m && this.m.isMaximized()) {
      mode = 0;
    } else {
      mode = 1;
    }
    if (mode === 0) {
      state.mode = 0;
    } else {
      state.mode = 1;
    }
    if (mode === 1 || mode === 0) {
      let bounds;
      if (mode === 1) {
        bounds = this.getBounds();
      } else {
        bounds = this.m.getNormalBounds();
      }
      state.x = bounds.x;
      state.y = bounds.y;
      state.width = bounds.width;
      state.height = bounds.height;
    }
    state.zoomLevel = this.ab;
    return state;
  }
  Eb(state) {
    mark("code/willRestoreCodeWindowState");
    let hasMultipleDisplays = false;
    if (state) {
      this.ab = state.zoomLevel;
      try {
        const displays = electron9.screen.getAllDisplays();
        hasMultipleDisplays = displays.length > 1;
        state = WindowStateValidator.validateWindowState(this.u, state, displays);
      } catch (err) {
        this.u.warn(`Unexpected error validating window state: ${err}
${err.stack}`);
      }
    }
    mark("code/didRestoreCodeWindowState");
    return [state || $Ejc(), hasMultipleDisplays];
  }
  getBounds() {
    const [x, y] = this.m.getPosition();
    const [width, height] = this.m.getSize();
    return { x, y, width, height };
  }
  I(fullscreen, fromRestore) {
    super.I(fullscreen, fromRestore);
    this.sendWhenReady(fullscreen ? "vscode:enterFullScreen" : "vscode:leaveFullScreen", CancellationToken.None);
    if (this.W) {
      this.Hb(this.W, false);
    }
  }
  Gb() {
    let menuBarVisibility = $OE(this.r);
    if (["visible", "toggle", "hidden"].indexOf(menuBarVisibility) < 0) {
      menuBarVisibility = "classic";
    }
    return menuBarVisibility;
  }
  Hb(visibility, notify = true) {
    if ($m) {
      return;
    }
    if (visibility === "toggle") {
      if (notify) {
        this.send("vscode:showInfoMessage", localize(2491, null));
      }
    }
    if (visibility === "hidden") {
      setTimeout(() => {
        this.Ib(visibility);
      });
    } else {
      this.Ib(visibility);
    }
  }
  Ib(visibility) {
    const isFullscreen = this.isFullScreen;
    switch (visibility) {
      case "classic":
        this.m.setMenuBarVisibility(!isFullscreen);
        this.m.autoHideMenuBar = isFullscreen;
        break;
      case "visible":
        this.m.setMenuBarVisibility(true);
        this.m.autoHideMenuBar = false;
        break;
      case "toggle":
        this.m.setMenuBarVisibility(false);
        this.m.autoHideMenuBar = true;
        break;
      case "hidden":
        this.m.setMenuBarVisibility(false);
        this.m.autoHideMenuBar = false;
        break;
    }
  }
  notifyZoomLevel(zoomLevel) {
    this.ab = zoomLevel;
  }
  Jb() {
    if (typeof this.ab === "number") {
      return this.ab;
    }
    const windowSettings = this.r.getValue("window");
    return windowSettings?.zoomLevel;
  }
  close() {
    this.m?.close();
  }
  sendWhenReady(channel, token, ...args) {
    if (this.isReady) {
      this.send(channel, ...args);
    } else {
      this.ready().then(() => {
        if (!token.isCancellationRequested) {
          this.send(channel, ...args);
        }
      });
    }
  }
  send(channel, ...args) {
    if (this.m) {
      if (this.m.isDestroyed() || this.m.webContents.isDestroyed()) {
        this.u.warn(`Sending IPC message to channel '${channel}' for window that is destroyed`);
        return;
      }
      try {
        this.m.webContents.send(channel, ...args);
      } catch (error) {
        this.u.warn(`Error sending IPC message to channel '${channel}' of window ${this.Q}: ${$Kj(error)}`);
      }
    }
  }
  updateTouchBar(groups) {
    if (!$m) {
      return;
    }
    this.Y.forEach((touchBarGroup, index) => {
      const commands = groups[index];
      touchBarGroup.segments = this.Mb(commands);
    });
  }
  Kb() {
    if (!$m) {
      return;
    }
    for (let i = 0; i < 10; i++) {
      const groupTouchBar = this.Lb();
      this.Y.push(groupTouchBar);
    }
    this.m.setTouchBar(new electron9.TouchBar({ items: this.Y }));
  }
  Lb(items = []) {
    const segments = this.Mb(items);
    const control = new electron9.TouchBar.TouchBarSegmentedControl({
      segments,
      mode: "buttons",
      segmentStyle: "automatic",
      change: (selectedIndex) => {
        this.sendWhenReady("vscode:runAction", CancellationToken.None, { id: control.segments[selectedIndex].id, from: "touchbar" });
      }
    });
    return control;
  }
  Mb(items = []) {
    const segments = items.map((item) => {
      let icon;
      if (item.icon && !ThemeIcon.isThemeIcon(item.icon) && item.icon?.dark?.scheme === Schemas.file) {
        icon = electron9.nativeImage.createFromPath(URI.revive(item.icon.dark).fsPath);
        if (icon.isEmpty()) {
          icon = void 0;
        }
      }
      let title;
      if (typeof item.title === "string") {
        title = item.title;
      } else {
        title = item.title.value;
      }
      return {
        id: item.id,
        label: !icon ? title : void 0,
        icon
      };
    });
    return segments;
  }
  matches(webContents3) {
    return this.m?.webContents.id === webContents3.id;
  }
  dispose() {
    super.dispose();
    this.fb.deregisterLoggers(this.id);
  }
};
$7jc = __decorate([
  __param(1, $uk),
  __param(2, $4jc),
  __param(3, $Cjc),
  __param(4, $Oo),
  __param(5, $Sjc),
  __param(6, $ul),
  __param(7, $ekc),
  __param(8, $ckc),
  __param(9, $tj),
  __param(10, $Njc),
  __param(11, $2jc),
  __param(12, $Jjc),
  __param(13, $tm),
  __param(14, $Kjc),
  __param(15, $9jc),
  __param(16, $Nk),
  __param(17, $Mjc),
  __param(18, $Pjc),
  __param(19, $BS),
  __param(20, $Yi)
], $7jc);

// out-build/vs/platform/windows/electron-main/windowsStateHandler.js
import electron10 from "electron";
var $elc_1;
var $elc = class $elc2 extends $0c {
  static {
    $elc_1 = this;
  }
  static {
    this.a = "windowsState";
  }
  get state() {
    return this.b;
  }
  constructor(g, h, j, m, n) {
    super();
    this.g = g;
    this.h = h;
    this.j = j;
    this.m = m;
    this.n = n;
    this.b = $flc(this.h.getItem($elc_1.a));
    this.c = void 0;
    this.f = false;
    this.r();
  }
  r() {
    electron10.app.on("browser-window-blur", () => {
      if (!this.f) {
        this.t();
      }
    });
    this.B(this.j.onBeforeCloseWindow((window2) => this.u(window2)));
    this.B(this.j.onBeforeShutdown(() => this.s()));
    this.B(this.g.onDidChangeWindowsCount((e) => {
      if (e.newCount - e.oldCount > 0) {
        this.c = void 0;
      }
    }));
    this.B(this.g.onDidDestroyWindow((window2) => this.u(window2)));
  }
  // Note that onBeforeShutdown() and onBeforeCloseWindow() are fired in different order depending on the OS:
  // - macOS: since the app will not quit when closing the last window, you will always first get
  //          the onBeforeShutdown() event followed by N onBeforeCloseWindow() events for each window
  // - other: on other OS, closing the last window will quit the app so the order depends on the
  //          user interaction: closing the last window will first trigger onBeforeCloseWindow()
  //          and then onBeforeShutdown(). Using the quit action however will first issue onBeforeShutdown()
  //          and then onBeforeCloseWindow().
  //
  // Here is the behavior on different OS depending on action taken (Electron 1.7.x):
  //
  // Legend
  // -  quit(N): quit application with N windows opened
  // - close(1): close one window via the window close button
  // - closeAll: close all windows via the taskbar command
  // - onBeforeShutdown(N): number of windows reported in this event handler
  // - onBeforeCloseWindow(N, M): number of windows reported and quitRequested boolean in this event handler
  //
  // macOS
  // 	-     quit(1): onBeforeShutdown(1), onBeforeCloseWindow(1, true)
  // 	-     quit(2): onBeforeShutdown(2), onBeforeCloseWindow(2, true), onBeforeCloseWindow(2, true)
  // 	-     quit(0): onBeforeShutdown(0)
  // 	-    close(1): onBeforeCloseWindow(1, false)
  //
  // Windows
  // 	-     quit(1): onBeforeShutdown(1), onBeforeCloseWindow(1, true)
  // 	-     quit(2): onBeforeShutdown(2), onBeforeCloseWindow(2, true), onBeforeCloseWindow(2, true)
  // 	-    close(1): onBeforeCloseWindow(2, false)[not last window]
  // 	-    close(1): onBeforeCloseWindow(1, false), onBeforeShutdown(0)[last window]
  // 	- closeAll(2): onBeforeCloseWindow(2, false), onBeforeCloseWindow(2, false), onBeforeShutdown(0)
  //
  // Linux
  // 	-     quit(1): onBeforeShutdown(1), onBeforeCloseWindow(1, true)
  // 	-     quit(2): onBeforeShutdown(2), onBeforeCloseWindow(2, true), onBeforeCloseWindow(2, true)
  // 	-    close(1): onBeforeCloseWindow(2, false)[not last window]
  // 	-    close(1): onBeforeCloseWindow(1, false), onBeforeShutdown(0)[last window]
  // 	- closeAll(2): onBeforeCloseWindow(2, false), onBeforeCloseWindow(2, false), onBeforeShutdown(0)
  //
  s() {
    this.f = true;
    this.t();
  }
  t() {
    const displaysWithFullScreenWindow = /* @__PURE__ */ new Set();
    const currentWindowsState = {
      openedWindows: [],
      lastPluginDevelopmentHostWindow: this.b.lastPluginDevelopmentHostWindow,
      lastActiveWindow: this.c
    };
    if (!currentWindowsState.lastActiveWindow) {
      let activeWindow = this.g.getLastActiveWindow();
      if (!activeWindow || activeWindow.isExtensionDevelopmentHost) {
        activeWindow = this.g.getWindows().find((window2) => !window2.isExtensionDevelopmentHost);
      }
      if (activeWindow) {
        currentWindowsState.lastActiveWindow = this.w(activeWindow);
        if (currentWindowsState.lastActiveWindow.uiState.mode === 3) {
          displaysWithFullScreenWindow.add(currentWindowsState.lastActiveWindow.uiState.display);
        }
      }
    }
    const extensionHostWindow = this.g.getWindows().find((window2) => window2.isExtensionDevelopmentHost && !window2.isExtensionTestHost);
    if (extensionHostWindow) {
      currentWindowsState.lastPluginDevelopmentHostWindow = this.w(extensionHostWindow);
      if (currentWindowsState.lastPluginDevelopmentHostWindow.uiState.mode === 3) {
        if (displaysWithFullScreenWindow.has(currentWindowsState.lastPluginDevelopmentHostWindow.uiState.display)) {
          if ($m && !extensionHostWindow.win?.isSimpleFullScreen()) {
            currentWindowsState.lastPluginDevelopmentHostWindow.uiState.mode = 1;
          }
        } else {
          displaysWithFullScreenWindow.add(currentWindowsState.lastPluginDevelopmentHostWindow.uiState.display);
        }
      }
    }
    if (this.g.getWindowCount() > 1) {
      currentWindowsState.openedWindows = this.g.getWindows().filter((window2) => !window2.isExtensionDevelopmentHost).map((window2) => {
        const windowState = this.w(window2);
        if (windowState.uiState.mode === 3) {
          if (displaysWithFullScreenWindow.has(windowState.uiState.display)) {
            if ($m && windowState.windowId !== currentWindowsState.lastActiveWindow?.windowId && !window2.win?.isSimpleFullScreen()) {
              windowState.uiState.mode = 1;
            }
          } else {
            displaysWithFullScreenWindow.add(windowState.uiState.display);
          }
        }
        return windowState;
      });
    }
    const state = $glc(currentWindowsState);
    this.h.setItem($elc_1.a, state);
    if (this.f) {
      this.m.trace("[WindowsStateHandler] onBeforeShutdown", state);
    }
  }
  // See note on #onBeforeShutdown() for details how these events are flowing
  u(window2) {
    if (this.j.quitRequested) {
      return;
    }
    const state = this.w(window2);
    if (window2.isExtensionDevelopmentHost && !window2.isExtensionTestHost) {
      this.b.lastPluginDevelopmentHostWindow = state;
    } else if (!window2.isExtensionDevelopmentHost && window2.openedWorkspace) {
      this.b.openedWindows.forEach((openedWindow) => {
        const sameWorkspace = $cj(window2.openedWorkspace) && openedWindow.workspace?.id === window2.openedWorkspace.id;
        const sameFolder = $0i(window2.openedWorkspace) && openedWindow.folderUri && $rh.isEqual(openedWindow.folderUri, window2.openedWorkspace.uri);
        if (sameWorkspace || sameFolder) {
          openedWindow.uiState = state.uiState;
        }
      });
    }
    if (this.g.getWindowCount() === 1) {
      this.c = state;
    }
  }
  w(window2) {
    return {
      windowId: window2.id,
      workspace: $cj(window2.openedWorkspace) ? window2.openedWorkspace : void 0,
      folderUri: $0i(window2.openedWorkspace) ? window2.openedWorkspace.uri : void 0,
      backupPath: window2.backupPath,
      remoteAuthority: window2.remoteAuthority,
      uiState: window2.serializeWindowState()
    };
  }
  getNewWindowState(configuration) {
    const state = this.z(configuration);
    const windowConfig = this.n.getValue("window");
    if (state.mode === 3) {
      let allowFullscreen;
      if (state.hasDefaultState) {
        allowFullscreen = !!(windowConfig?.newWindowDimensions && ["fullscreen", "inherit", "offset"].indexOf(windowConfig.newWindowDimensions) >= 0);
      } else {
        allowFullscreen = !!(this.j.wasRestarted || windowConfig?.restoreFullscreen);
      }
      if (!allowFullscreen) {
        state.mode = 1;
      }
    }
    return state;
  }
  z(configuration) {
    const lastActive = this.g.getLastActiveWindow();
    if (!configuration.extensionTestsPath) {
      if (!!configuration.extensionDevelopmentPath && this.state.lastPluginDevelopmentHostWindow) {
        return this.state.lastPluginDevelopmentHostWindow.uiState;
      }
      const workspace = configuration.workspace;
      if ($cj(workspace)) {
        const stateForWorkspace = this.state.openedWindows.filter((openedWindow) => openedWindow.workspace && openedWindow.workspace.id === workspace.id).map((openedWindow) => openedWindow.uiState);
        if (stateForWorkspace.length) {
          return stateForWorkspace[0];
        }
      }
      if ($0i(workspace)) {
        const stateForFolder = this.state.openedWindows.filter((openedWindow) => openedWindow.folderUri && $rh.isEqual(openedWindow.folderUri, workspace.uri)).map((openedWindow) => openedWindow.uiState);
        if (stateForFolder.length) {
          return stateForFolder[0];
        }
      } else if (configuration.backupPath) {
        const stateForEmptyWindow = this.state.openedWindows.filter((openedWindow) => openedWindow.backupPath === configuration.backupPath).map((openedWindow) => openedWindow.uiState);
        if (stateForEmptyWindow.length) {
          return stateForEmptyWindow[0];
        }
      }
      const lastActiveState = this.c || this.state.lastActiveWindow;
      if (!lastActive && lastActiveState) {
        return lastActiveState.uiState;
      }
    }
    let displayToUse;
    const displays = electron10.screen.getAllDisplays();
    if (displays.length === 1) {
      displayToUse = displays[0];
    } else {
      if ($m) {
        const cursorPoint = electron10.screen.getCursorScreenPoint();
        displayToUse = electron10.screen.getDisplayNearestPoint(cursorPoint);
      }
      if (!displayToUse && lastActive) {
        displayToUse = electron10.screen.getDisplayMatching(lastActive.getBounds());
      }
      if (!displayToUse) {
        displayToUse = electron10.screen.getPrimaryDisplay() || displays[0];
      }
    }
    let state = $Ejc();
    state.x = Math.round(displayToUse.bounds.x + displayToUse.bounds.width / 2 - state.width / 2);
    state.y = Math.round(displayToUse.bounds.y + displayToUse.bounds.height / 2 - state.height / 2);
    const windowConfig = this.n.getValue("window");
    let ensureNoOverlap = true;
    if (windowConfig?.newWindowDimensions) {
      if (windowConfig.newWindowDimensions === "maximized") {
        state.mode = 0;
        ensureNoOverlap = false;
      } else if (windowConfig.newWindowDimensions === "fullscreen") {
        state.mode = 3;
        ensureNoOverlap = false;
      } else if ((windowConfig.newWindowDimensions === "inherit" || windowConfig.newWindowDimensions === "offset") && lastActive) {
        const lastActiveState = lastActive.serializeWindowState();
        if (lastActiveState.mode === 3) {
          state.mode = 3;
        } else {
          state = {
            ...lastActiveState,
            zoomLevel: void 0
            // do not inherit zoom level
          };
        }
        ensureNoOverlap = state.mode !== 3 && windowConfig.newWindowDimensions === "offset";
      }
    }
    if (ensureNoOverlap) {
      state = this.C(state);
    }
    state.hasDefaultState = true;
    return state;
  }
  C(state) {
    if (this.g.getWindows().length === 0) {
      return state;
    }
    state.x = typeof state.x === "number" ? state.x : 0;
    state.y = typeof state.y === "number" ? state.y : 0;
    const existingWindowBounds = this.g.getWindows().map((window2) => window2.getBounds());
    while (existingWindowBounds.some((bounds) => bounds.x === state.x || bounds.y === state.y)) {
      state.x += 30;
      state.y += 30;
    }
    return state;
  }
};
$elc = $elc_1 = __decorate([
  __param(0, $Pjc),
  __param(1, $BS),
  __param(2, $9jc),
  __param(3, $uk),
  __param(4, $tj)
], $elc);
function $flc(data) {
  const result = { openedWindows: [] };
  const windowsState = data || { openedWindows: [] };
  if (windowsState.lastActiveWindow) {
    result.lastActiveWindow = restoreWindowState(windowsState.lastActiveWindow);
  }
  if (windowsState.lastPluginDevelopmentHostWindow) {
    result.lastPluginDevelopmentHostWindow = restoreWindowState(windowsState.lastPluginDevelopmentHostWindow);
  }
  if (Array.isArray(windowsState.openedWindows)) {
    result.openedWindows = windowsState.openedWindows.map((windowState) => restoreWindowState(windowState));
  }
  return result;
}
function restoreWindowState(windowState) {
  const result = { uiState: windowState.uiState };
  if (windowState.backupPath) {
    result.backupPath = windowState.backupPath;
  }
  if (windowState.remoteAuthority) {
    result.remoteAuthority = windowState.remoteAuthority;
  }
  if (windowState.folder) {
    result.folderUri = URI.parse(windowState.folder);
  }
  if (windowState.workspaceIdentifier) {
    result.workspace = { id: windowState.workspaceIdentifier.id, configPath: URI.parse(windowState.workspaceIdentifier.configURIPath) };
  }
  return result;
}
function $glc(windowsState) {
  return {
    lastActiveWindow: windowsState.lastActiveWindow && serializeWindowState(windowsState.lastActiveWindow),
    lastPluginDevelopmentHostWindow: windowsState.lastPluginDevelopmentHostWindow && serializeWindowState(windowsState.lastPluginDevelopmentHostWindow),
    openedWindows: windowsState.openedWindows.map((ws) => serializeWindowState(ws))
  };
}
function serializeWindowState(windowState) {
  return {
    workspaceIdentifier: windowState.workspace && { id: windowState.workspace.id, configURIPath: windowState.workspace.configPath.toString() },
    folder: windowState.folderUri && windowState.folderUri.toString(),
    backupPath: windowState.backupPath,
    remoteAuthority: windowState.remoteAuthority,
    uiState: windowState.uiState
  };
}

// out-build/vs/platform/windows/electron-main/windowsMainService.js
function isWorkspacePathToOpen(path3) {
  return $cj(path3?.workspace);
}
function isSingleFolderWorkspacePathToOpen(path3) {
  return $0i(path3?.workspace);
}
var $hlc = class $hlc2 extends $0c {
  constructor(s, t, u, w, z, C, D, F, G, H, I, J, L, M, N, O, P, Q, R, S, U, W) {
    super();
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.a = this.B(new $De());
    this.onDidOpenWindow = this.a.event;
    this.b = this.B(new $De());
    this.onDidSignalReadyWindow = this.b.event;
    this.c = this.B(new $De());
    this.onDidDestroyWindow = this.c.event;
    this.f = this.B(new $De());
    this.onDidChangeWindowsCount = this.f.event;
    this.g = this.B(new $De());
    this.onDidMaximizeWindow = this.g.event;
    this.h = this.B(new $De());
    this.onDidUnmaximizeWindow = this.h.event;
    this.j = this.B(new $De());
    this.onDidChangeFullScreen = this.j.event;
    this.m = this.B(new $De());
    this.onDidTriggerSystemContextMenu = this.m.event;
    this.n = /* @__PURE__ */ new Map();
    this.r = this.B(new $elc(this, this.D, this.I, this.z, this.L));
    this.X();
  }
  X() {
    this.B(this.N.onDidEnterWorkspace((event) => this.b.fire(event.window)));
    this.B(this.onDidSignalReadyWindow((window2) => {
      if (window2.config?.extensionDevelopmentPath || window2.config?.extensionTestsPath) {
        const disposables = new $9c();
        disposables.add(Event.any(window2.onDidClose, window2.onDidDestroy)(() => disposables.dispose()));
        if (window2.config.extensionDevelopmentPath) {
          for (const extensionDevelopmentPath of window2.config.extensionDevelopmentPath) {
            disposables.add(this.R.addValidFileRoot(extensionDevelopmentPath));
          }
        }
        if (window2.config.extensionTestsPath) {
          disposables.add(this.R.addValidFileRoot(window2.config.extensionTestsPath));
        }
      }
    }));
  }
  openEmptyWindow(openConfig, options) {
    const cli = this.G.args;
    const remoteAuthority = options?.remoteAuthority || void 0;
    const forceEmpty = true;
    const forceReuseWindow = options?.forceReuseWindow;
    const forceNewWindow = !forceReuseWindow;
    return this.open({ ...openConfig, cli, forceEmpty, forceNewWindow, forceReuseWindow, remoteAuthority, forceTempProfile: options?.forceTempProfile, forceProfile: options?.forceProfile });
  }
  openExistingWindow(window2, openConfig) {
    window2.focus();
    this.Y(openConfig, [window2]);
  }
  async open(openConfig) {
    this.z.trace("windowsManager#open");
    if (openConfig.addMode && (openConfig.initialStartup || !this.getLastActiveWindow())) {
      openConfig.addMode = false;
    }
    const foldersToAdd = [];
    const foldersToOpen = [];
    const workspacesToOpen = [];
    const untitledWorkspacesToRestore = [];
    const emptyWindowsWithBackupsToRestore = [];
    let filesToOpen;
    let openOneEmptyWindow = false;
    const pathsToOpen = await this.eb(openConfig);
    this.z.trace("windowsManager#open pathsToOpen", pathsToOpen);
    for (const path3 of pathsToOpen) {
      if (isSingleFolderWorkspacePathToOpen(path3)) {
        if (openConfig.addMode) {
          foldersToAdd.push(path3);
        } else {
          foldersToOpen.push(path3);
        }
      } else if (isWorkspacePathToOpen(path3)) {
        workspacesToOpen.push(path3);
      } else if (path3.fileUri) {
        if (!filesToOpen) {
          filesToOpen = { filesToOpenOrCreate: [], filesToDiff: [], filesToMerge: [], remoteAuthority: path3.remoteAuthority };
        }
        filesToOpen.filesToOpenOrCreate.push(path3);
      } else if (path3.backupPath) {
        emptyWindowsWithBackupsToRestore.push({ backupFolder: $zc(path3.backupPath), remoteAuthority: path3.remoteAuthority });
      } else {
        openOneEmptyWindow = true;
      }
    }
    if (openConfig.diffMode && filesToOpen && filesToOpen.filesToOpenOrCreate.length >= 2) {
      filesToOpen.filesToDiff = filesToOpen.filesToOpenOrCreate.slice(0, 2);
      filesToOpen.filesToOpenOrCreate = [];
    }
    if (openConfig.mergeMode && filesToOpen && filesToOpen.filesToOpenOrCreate.length === 4) {
      filesToOpen.filesToMerge = filesToOpen.filesToOpenOrCreate.slice(0, 4);
      filesToOpen.filesToOpenOrCreate = [];
      filesToOpen.filesToDiff = [];
    }
    if (filesToOpen && openConfig.waitMarkerFileURI) {
      filesToOpen.filesToWait = { paths: $Ub([...filesToOpen.filesToDiff, filesToOpen.filesToMerge[3], ...filesToOpen.filesToOpenOrCreate]), waitMarkerFileUri: openConfig.waitMarkerFileURI };
    }
    if (openConfig.initialStartup) {
      untitledWorkspacesToRestore.push(...this.N.getUntitledWorkspaces());
      workspacesToOpen.push(...untitledWorkspacesToRestore);
      emptyWindowsWithBackupsToRestore.push(...this.J.getEmptyWindowBackups());
    } else {
      emptyWindowsWithBackupsToRestore.length = 0;
    }
    const { windows: usedWindows, filesOpenedInWindow } = await this.Z(openConfig, workspacesToOpen, foldersToOpen, emptyWindowsWithBackupsToRestore, openOneEmptyWindow, filesToOpen, foldersToAdd);
    this.z.trace(`windowsManager#open used window count ${usedWindows.length} (workspacesToOpen: ${workspacesToOpen.length}, foldersToOpen: ${foldersToOpen.length}, emptyToRestore: ${emptyWindowsWithBackupsToRestore.length}, openOneEmptyWindow: ${openOneEmptyWindow})`);
    if (usedWindows.length > 1) {
      if (filesOpenedInWindow) {
        filesOpenedInWindow.focus();
      } else {
        const focusLastActive = this.r.state.lastActiveWindow && !openConfig.forceEmpty && !openConfig.cli._.length && !openConfig.cli["file-uri"] && !openConfig.cli["folder-uri"] && !(openConfig.urisToOpen && openConfig.urisToOpen.length);
        let focusLastOpened = true;
        let focusLastWindow = true;
        if (focusLastActive) {
          const lastActiveWindow = usedWindows.filter((window2) => this.r.state.lastActiveWindow && window2.backupPath === this.r.state.lastActiveWindow.backupPath);
          if (lastActiveWindow.length) {
            lastActiveWindow[0].focus();
            focusLastOpened = false;
            focusLastWindow = false;
          }
        }
        if (focusLastOpened) {
          for (let i = usedWindows.length - 1; i >= 0; i--) {
            const usedWindow = usedWindows[i];
            if (usedWindow.openedWorkspace && untitledWorkspacesToRestore.some((workspace) => usedWindow.openedWorkspace && workspace.workspace.id === usedWindow.openedWorkspace.id) || // skip over restored workspace
            usedWindow.backupPath && emptyWindowsWithBackupsToRestore.some((empty) => usedWindow.backupPath && empty.backupFolder === $zc(usedWindow.backupPath))) {
              continue;
            }
            usedWindow.focus();
            focusLastWindow = false;
            break;
          }
        }
        if (focusLastWindow) {
          usedWindows[usedWindows.length - 1].focus();
        }
      }
    }
    const isDiff = filesToOpen && filesToOpen.filesToDiff.length > 0;
    const isMerge = filesToOpen && filesToOpen.filesToMerge.length > 0;
    if (!usedWindows.some((window2) => window2.isExtensionDevelopmentHost) && !isDiff && !isMerge && !openConfig.noRecentEntry) {
      const recents = [];
      for (const pathToOpen of pathsToOpen) {
        if (isWorkspacePathToOpen(pathToOpen) && !pathToOpen.transient) {
          recents.push({ label: pathToOpen.label, workspace: pathToOpen.workspace, remoteAuthority: pathToOpen.remoteAuthority });
        } else if (isSingleFolderWorkspacePathToOpen(pathToOpen)) {
          recents.push({ label: pathToOpen.label, folderUri: pathToOpen.workspace.uri, remoteAuthority: pathToOpen.remoteAuthority });
        } else if (pathToOpen.fileUri) {
          recents.push({ label: pathToOpen.label, fileUri: pathToOpen.fileUri, remoteAuthority: pathToOpen.remoteAuthority });
        }
      }
      this.M.addRecentlyOpened(recents);
    }
    this.Y(openConfig, usedWindows);
    return usedWindows;
  }
  Y(openConfig, usedWindows) {
    const waitMarkerFileURI = openConfig.waitMarkerFileURI;
    if (openConfig.context === 0 && waitMarkerFileURI && usedWindows.length === 1 && usedWindows[0]) {
      (async () => {
        await usedWindows[0].whenClosedOrLoaded;
        try {
          await this.Q.del(waitMarkerFileURI);
        } catch (error) {
        }
      })();
    }
  }
  async Z(openConfig, workspacesToOpen, foldersToOpen, emptyToRestore, openOneEmptyWindow, filesToOpen, foldersToAdd) {
    const usedWindows = [];
    let filesOpenedInWindow = void 0;
    function addUsedWindow(window2, openedFiles) {
      usedWindows.push(window2);
      if (openedFiles) {
        filesOpenedInWindow = window2;
        filesToOpen = void 0;
      }
    }
    let { openFolderInNewWindow, openFilesInNewWindow } = this.qb(openConfig);
    if (!openConfig.initialStartup && foldersToAdd.length > 0) {
      const authority = foldersToAdd[0].remoteAuthority;
      const lastActiveWindow = this.wb(authority);
      if (lastActiveWindow) {
        addUsedWindow(this.bb(lastActiveWindow, foldersToAdd.map((folderToAdd) => folderToAdd.workspace.uri)));
      }
    }
    const potentialNewWindowsCount = foldersToOpen.length + workspacesToOpen.length + emptyToRestore.length;
    if (filesToOpen && potentialNewWindowsCount === 0) {
      const fileToCheck = filesToOpen.filesToOpenOrCreate[0] || filesToOpen.filesToDiff[0] || filesToOpen.filesToMerge[3];
      const windows = this.getWindows().filter((window2) => filesToOpen && $Fh(window2.remoteAuthority, filesToOpen.remoteAuthority));
      let windowToUseForFiles = void 0;
      if (fileToCheck?.fileUri && !openFilesInNewWindow) {
        if (openConfig.context === 4 || openConfig.context === 0 || openConfig.context === 1 || openConfig.context === 6) {
          windowToUseForFiles = await $Ujc(windows, fileToCheck.fileUri, async (workspace) => workspace.configPath.scheme === Schemas.file ? this.N.resolveLocalWorkspace(workspace.configPath) : void 0);
        }
        if (!windowToUseForFiles) {
          windowToUseForFiles = this.xb(windows);
        }
      }
      if (windowToUseForFiles) {
        if ($cj(windowToUseForFiles.openedWorkspace)) {
          workspacesToOpen.push({ workspace: windowToUseForFiles.openedWorkspace, remoteAuthority: windowToUseForFiles.remoteAuthority });
        } else if ($0i(windowToUseForFiles.openedWorkspace)) {
          foldersToOpen.push({ workspace: windowToUseForFiles.openedWorkspace, remoteAuthority: windowToUseForFiles.remoteAuthority });
        } else {
          addUsedWindow(this.$(openConfig, windowToUseForFiles, filesToOpen), true);
        }
      } else {
        addUsedWindow(await this.rb({
          userEnv: openConfig.userEnv,
          cli: openConfig.cli,
          initialStartup: openConfig.initialStartup,
          filesToOpen,
          forceNewWindow: true,
          remoteAuthority: filesToOpen.remoteAuthority,
          forceNewTabbedWindow: openConfig.forceNewTabbedWindow,
          forceProfile: openConfig.forceProfile,
          forceTempProfile: openConfig.forceTempProfile
        }), true);
      }
    }
    const allWorkspacesToOpen = $Zb(workspacesToOpen, (workspace) => workspace.workspace.id);
    if (allWorkspacesToOpen.length > 0) {
      const windowsOnWorkspace = $Ub(allWorkspacesToOpen.map((workspaceToOpen) => $Vjc(this.getWindows(), workspaceToOpen.workspace.configPath)));
      if (windowsOnWorkspace.length > 0) {
        const windowOnWorkspace = windowsOnWorkspace[0];
        const filesToOpenInWindow = $Fh(filesToOpen?.remoteAuthority, windowOnWorkspace.remoteAuthority) ? filesToOpen : void 0;
        addUsedWindow(this.$(openConfig, windowOnWorkspace, filesToOpenInWindow), !!filesToOpenInWindow);
        openFolderInNewWindow = true;
      }
      for (const workspaceToOpen of allWorkspacesToOpen) {
        if (windowsOnWorkspace.some((window2) => window2.openedWorkspace && window2.openedWorkspace.id === workspaceToOpen.workspace.id)) {
          continue;
        }
        const remoteAuthority = workspaceToOpen.remoteAuthority;
        const filesToOpenInWindow = $Fh(filesToOpen?.remoteAuthority, remoteAuthority) ? filesToOpen : void 0;
        addUsedWindow(await this.db(openConfig, workspaceToOpen, openFolderInNewWindow, filesToOpenInWindow), !!filesToOpenInWindow);
        openFolderInNewWindow = true;
      }
    }
    const allFoldersToOpen = $Zb(foldersToOpen, (folder) => $rh.getComparisonKey(folder.workspace.uri));
    if (allFoldersToOpen.length > 0) {
      const windowsOnFolderPath = $Ub(allFoldersToOpen.map((folderToOpen) => $Vjc(this.getWindows(), folderToOpen.workspace.uri)));
      if (windowsOnFolderPath.length > 0) {
        const windowOnFolderPath = windowsOnFolderPath[0];
        const filesToOpenInWindow = $Fh(filesToOpen?.remoteAuthority, windowOnFolderPath.remoteAuthority) ? filesToOpen : void 0;
        addUsedWindow(this.$(openConfig, windowOnFolderPath, filesToOpenInWindow), !!filesToOpenInWindow);
        openFolderInNewWindow = true;
      }
      for (const folderToOpen of allFoldersToOpen) {
        if (windowsOnFolderPath.some((window2) => $0i(window2.openedWorkspace) && $rh.isEqual(window2.openedWorkspace.uri, folderToOpen.workspace.uri))) {
          continue;
        }
        const remoteAuthority = folderToOpen.remoteAuthority;
        const filesToOpenInWindow = $Fh(filesToOpen?.remoteAuthority, remoteAuthority) ? filesToOpen : void 0;
        addUsedWindow(await this.db(openConfig, folderToOpen, openFolderInNewWindow, filesToOpenInWindow), !!filesToOpenInWindow);
        openFolderInNewWindow = true;
      }
    }
    const allEmptyToRestore = $Zb(emptyToRestore, (info) => info.backupFolder);
    if (allEmptyToRestore.length > 0) {
      for (const emptyWindowBackupInfo of allEmptyToRestore) {
        const remoteAuthority = emptyWindowBackupInfo.remoteAuthority;
        const filesToOpenInWindow = $Fh(filesToOpen?.remoteAuthority, remoteAuthority) ? filesToOpen : void 0;
        addUsedWindow(await this.cb(openConfig, true, remoteAuthority, filesToOpenInWindow, emptyWindowBackupInfo), !!filesToOpenInWindow);
        openFolderInNewWindow = true;
      }
    }
    if (filesToOpen || openOneEmptyWindow) {
      const remoteAuthority = filesToOpen ? filesToOpen.remoteAuthority : openConfig.remoteAuthority;
      addUsedWindow(await this.cb(openConfig, openFolderInNewWindow, remoteAuthority, filesToOpen), !!filesToOpen);
    }
    return { windows: $Zb(usedWindows), filesOpenedInWindow };
  }
  $(configuration, window2, filesToOpen) {
    this.z.trace("windowsManager#doOpenFilesInExistingWindow", { filesToOpen });
    this.ab(window2);
    const params = {
      filesToOpenOrCreate: filesToOpen?.filesToOpenOrCreate,
      filesToDiff: filesToOpen?.filesToDiff,
      filesToMerge: filesToOpen?.filesToMerge,
      filesToWait: filesToOpen?.filesToWait,
      termProgram: configuration?.userEnv?.["TERM_PROGRAM"]
    };
    window2.sendWhenReady("vscode:openFiles", CancellationToken.None, params);
    return window2;
  }
  ab(mainWindow) {
    let windowToFocus = mainWindow;
    const focusedWindow = BrowserWindow5.getFocusedWindow();
    if (focusedWindow && focusedWindow.id !== mainWindow.id) {
      const auxiliaryWindowCandidate = this.U.getWindowByWebContents(focusedWindow.webContents);
      if (auxiliaryWindowCandidate && auxiliaryWindowCandidate.parentId === mainWindow.id) {
        windowToFocus = auxiliaryWindowCandidate;
      }
    }
    windowToFocus.focus();
  }
  bb(window2, foldersToAdd) {
    this.z.trace("windowsManager#doAddFoldersToExistingWindow", { foldersToAdd });
    window2.focus();
    const request = { foldersToAdd };
    window2.sendWhenReady("vscode:addFolders", CancellationToken.None, request);
    return window2;
  }
  cb(openConfig, forceNewWindow, remoteAuthority, filesToOpen, emptyWindowBackupInfo) {
    this.z.trace("windowsManager#doOpenEmpty", { restore: !!emptyWindowBackupInfo, remoteAuthority, filesToOpen, forceNewWindow });
    let windowToUse;
    if (!forceNewWindow && typeof openConfig.contextWindowId === "number") {
      windowToUse = this.getWindowById(openConfig.contextWindowId);
    }
    return this.rb({
      userEnv: openConfig.userEnv,
      cli: openConfig.cli,
      initialStartup: openConfig.initialStartup,
      remoteAuthority,
      forceNewWindow,
      forceNewTabbedWindow: openConfig.forceNewTabbedWindow,
      filesToOpen,
      windowToUse,
      emptyWindowBackupInfo,
      forceProfile: openConfig.forceProfile,
      forceTempProfile: openConfig.forceTempProfile
    });
  }
  db(openConfig, folderOrWorkspace, forceNewWindow, filesToOpen, windowToUse) {
    this.z.trace("windowsManager#doOpenFolderOrWorkspace", { folderOrWorkspace, filesToOpen });
    if (!forceNewWindow && !windowToUse && typeof openConfig.contextWindowId === "number") {
      windowToUse = this.getWindowById(openConfig.contextWindowId);
    }
    return this.rb({
      workspace: folderOrWorkspace.workspace,
      userEnv: openConfig.userEnv,
      cli: openConfig.cli,
      initialStartup: openConfig.initialStartup,
      remoteAuthority: folderOrWorkspace.remoteAuthority,
      forceNewWindow,
      forceNewTabbedWindow: openConfig.forceNewTabbedWindow,
      filesToOpen,
      windowToUse,
      forceProfile: openConfig.forceProfile,
      forceTempProfile: openConfig.forceTempProfile
    });
  }
  async eb(openConfig) {
    let pathsToOpen;
    let isCommandLineOrAPICall = false;
    let restoredWindows = false;
    if (openConfig.urisToOpen && openConfig.urisToOpen.length > 0) {
      pathsToOpen = await this.fb(openConfig);
      isCommandLineOrAPICall = true;
    } else if (openConfig.forceEmpty) {
      pathsToOpen = [/* @__PURE__ */ Object.create(null)];
    } else if (openConfig.cli._.length || openConfig.cli["folder-uri"] || openConfig.cli["file-uri"]) {
      pathsToOpen = await this.gb(openConfig.cli);
      if (pathsToOpen.length === 0) {
        pathsToOpen.push(/* @__PURE__ */ Object.create(null));
      }
      isCommandLineOrAPICall = true;
    } else {
      pathsToOpen = await this.ib();
      if (pathsToOpen.length === 0) {
        pathsToOpen.push(/* @__PURE__ */ Object.create(null));
      }
      restoredWindows = true;
    }
    if (!openConfig.addMode && isCommandLineOrAPICall) {
      const foldersToOpen = pathsToOpen.filter((path3) => isSingleFolderWorkspacePathToOpen(path3));
      if (foldersToOpen.length > 1) {
        const remoteAuthority = foldersToOpen[0].remoteAuthority;
        if (foldersToOpen.every((folderToOpen) => $Fh(folderToOpen.remoteAuthority, remoteAuthority))) {
          const workspace = await this.N.createUntitledWorkspace(foldersToOpen.map((folder) => ({ uri: folder.workspace.uri })));
          pathsToOpen.push({ workspace, remoteAuthority });
          pathsToOpen = pathsToOpen.filter((path3) => !isSingleFolderWorkspacePathToOpen(path3));
        }
      }
    }
    if (openConfig.initialStartup && !restoredWindows && this.L.getValue("window")?.restoreWindows === "preserve") {
      const lastSessionPaths = await this.ib();
      pathsToOpen.unshift(...lastSessionPaths.filter((path3) => isWorkspacePathToOpen(path3) || isSingleFolderWorkspacePathToOpen(path3) || path3.backupPath));
    }
    return pathsToOpen;
  }
  async fb(openConfig) {
    const pathResolveOptions = {
      gotoLineMode: openConfig.gotoLineMode,
      remoteAuthority: openConfig.remoteAuthority
    };
    const pathsToOpen = await Promise.all($Ub(openConfig.urisToOpen || []).map(async (pathToOpen) => {
      const path3 = await this.kb(pathToOpen, pathResolveOptions);
      if (path3) {
        path3.label = pathToOpen.label;
        return path3;
      }
      const uri = this.mb(pathToOpen);
      this.P.showMessageBox({
        type: "info",
        buttons: [localize(2492, null)],
        message: uri.scheme === Schemas.file ? localize(2493, null) : localize(2494, null),
        detail: uri.scheme === Schemas.file ? localize(2495, null, $rx(uri, { os: OS, tildify: this.G })) : localize(2496, null, uri.toString(true))
      }, BrowserWindow5.getFocusedWindow() ?? void 0);
      return void 0;
    }));
    return $Ub(pathsToOpen);
  }
  async gb(cli) {
    const pathsToOpen = [];
    const pathResolveOptions = {
      ignoreFileNotFound: true,
      gotoLineMode: cli.goto,
      remoteAuthority: cli.remote || void 0,
      forceOpenWorkspaceAsFile: (
        // special case diff / merge mode to force open
        // workspace as file
        // https://github.com/microsoft/vscode/issues/149731
        cli.diff && cli._.length === 2 || cli.merge && cli._.length === 4
      )
    };
    const folderUris = cli["folder-uri"];
    if (folderUris) {
      const resolvedFolderUris = await Promise.all(folderUris.map((rawFolderUri) => {
        const folderUri = this.hb(rawFolderUri);
        if (!folderUri) {
          return void 0;
        }
        return this.kb({ folderUri }, pathResolveOptions);
      }));
      pathsToOpen.push(...$Ub(resolvedFolderUris));
    }
    const fileUris = cli["file-uri"];
    if (fileUris) {
      const resolvedFileUris = await Promise.all(fileUris.map((rawFileUri) => {
        const fileUri = this.hb(rawFileUri);
        if (!fileUri) {
          return void 0;
        }
        return this.kb($sj(rawFileUri) ? { workspaceUri: fileUri } : { fileUri }, pathResolveOptions);
      }));
      pathsToOpen.push(...$Ub(resolvedFileUris));
    }
    const resolvedCliPaths = await Promise.all(cli._.map((cliPath) => {
      return pathResolveOptions.remoteAuthority ? this.pb(cliPath, pathResolveOptions) : this.nb(cliPath, pathResolveOptions);
    }));
    pathsToOpen.push(...$Ub(resolvedCliPaths));
    return pathsToOpen;
  }
  hb(arg) {
    try {
      const uri = URI.parse(arg);
      if (!uri.scheme) {
        this.z.error(`Invalid URI input string, scheme missing: ${arg}`);
        return void 0;
      }
      if (!uri.path) {
        return uri.with({ path: "/" });
      }
      return uri;
    } catch (e) {
      this.z.error(`Invalid URI input string: ${arg}, ${e.message}`);
    }
    return void 0;
  }
  async ib() {
    const restoreWindowsSetting = this.jb();
    switch (restoreWindowsSetting) {
      case "none":
        return [];
      case "one":
      case "all":
      case "preserve":
      case "folders": {
        const lastSessionWindows = [];
        if (restoreWindowsSetting !== "one") {
          lastSessionWindows.push(...this.r.state.openedWindows);
        }
        if (this.r.state.lastActiveWindow) {
          lastSessionWindows.push(this.r.state.lastActiveWindow);
        }
        const pathsToOpen = await Promise.all(lastSessionWindows.map(async (lastSessionWindow) => {
          if (lastSessionWindow.workspace) {
            const pathToOpen = await this.kb({ workspaceUri: lastSessionWindow.workspace.configPath }, {
              remoteAuthority: lastSessionWindow.remoteAuthority,
              rejectTransientWorkspaces: true
              /* https://github.com/microsoft/vscode/issues/119695 */
            });
            if (isWorkspacePathToOpen(pathToOpen)) {
              return pathToOpen;
            }
          } else if (lastSessionWindow.folderUri) {
            const pathToOpen = await this.kb({ folderUri: lastSessionWindow.folderUri }, { remoteAuthority: lastSessionWindow.remoteAuthority });
            if (isSingleFolderWorkspacePathToOpen(pathToOpen)) {
              return pathToOpen;
            }
          } else if (restoreWindowsSetting !== "folders" && lastSessionWindow.backupPath) {
            return { backupPath: lastSessionWindow.backupPath, remoteAuthority: lastSessionWindow.remoteAuthority };
          }
          return void 0;
        }));
        return $Ub(pathsToOpen);
      }
    }
  }
  jb() {
    let restoreWindows;
    if (this.I.wasRestarted) {
      restoreWindows = "all";
    } else {
      const windowConfig = this.L.getValue("window");
      restoreWindows = windowConfig?.restoreWindows || "all";
      if (!["preserve", "all", "folders", "one", "none"].includes(restoreWindows)) {
        restoreWindows = "all";
      }
    }
    return restoreWindows;
  }
  async kb(openable, options = /* @__PURE__ */ Object.create(null)) {
    const uri = this.mb(openable);
    if (uri.scheme === Schemas.file) {
      if ($NE(openable)) {
        options = { ...options, forceOpenWorkspaceAsFile: true };
      }
      return this.nb(uri.fsPath, options);
    }
    return this.lb(openable, options);
  }
  lb(openable, options) {
    let uri = this.mb(openable);
    const remoteAuthority = $Cn(uri) || options.remoteAuthority;
    uri = $Hh($Bh(uri));
    if ($NE(openable)) {
      if (options.gotoLineMode) {
        const { path: path3, line, column } = $7g(uri.path);
        return {
          fileUri: uri.with({ path: path3 }),
          options: {
            selection: line ? { startLineNumber: line, startColumn: column || 1 } : void 0
          },
          remoteAuthority
        };
      }
      return { fileUri: uri, remoteAuthority };
    } else if ($LE(openable)) {
      return { workspace: $Yjc(uri), remoteAuthority };
    }
    return { workspace: $Zjc(uri), remoteAuthority };
  }
  mb(openable) {
    if ($LE(openable)) {
      return openable.workspaceUri;
    }
    if ($ME(openable)) {
      return openable.folderUri;
    }
    return openable.fileUri;
  }
  async nb(path3, options, skipHandleUNCError) {
    let lineNumber;
    let columnNumber;
    if (options.gotoLineMode) {
      ({ path: path3, line: lineNumber, column: columnNumber } = $7g(path3));
    }
    path3 = $1g($tc(path3), cwd());
    try {
      const pathStat = await fs10.promises.stat(path3);
      if (pathStat.isFile()) {
        if (!options.forceOpenWorkspaceAsFile) {
          const workspace = await this.N.resolveLocalWorkspace(URI.file(path3));
          if (workspace) {
            if (workspace.transient && options.rejectTransientWorkspaces) {
              return void 0;
            }
            return {
              workspace: { id: workspace.id, configPath: workspace.configPath },
              type: FileType.File,
              exists: true,
              remoteAuthority: workspace.remoteAuthority,
              transient: workspace.transient
            };
          }
        }
        return {
          fileUri: URI.file(path3),
          type: FileType.File,
          exists: true,
          options: {
            selection: lineNumber ? { startLineNumber: lineNumber, startColumn: columnNumber || 1 } : void 0
          }
        };
      } else if (pathStat.isDirectory()) {
        return {
          workspace: $Zjc(URI.file(path3), pathStat),
          type: FileType.Directory,
          exists: true
        };
      } else if (!$l && path3 === "/dev/null") {
        return {
          fileUri: URI.file(path3),
          type: FileType.File,
          exists: true
        };
      }
    } catch (error) {
      if (error.code === "ERR_UNC_HOST_NOT_ALLOWED" && !skipHandleUNCError) {
        return this.ob(path3, options);
      }
      const fileUri = URI.file(path3);
      this.M.removeRecentlyOpened([fileUri]);
      if (options.ignoreFileNotFound) {
        return {
          fileUri,
          type: FileType.File,
          exists: false
        };
      }
    }
    return void 0;
  }
  async ob(path3, options) {
    const uri = URI.file(path3);
    const { response, checkboxChecked } = await this.P.showMessageBox({
      type: "warning",
      buttons: [
        localize(2497, null),
        localize(2498, null),
        localize(2499, null)
      ],
      message: localize(2500, null, uri.authority),
      detail: localize(2501, null, $rx(uri, { os: OS, tildify: this.G })),
      checkboxLabel: localize(2502, null, uri.authority),
      cancelId: 1
    });
    if (response === 0) {
      addUNCHostToAllowlist(uri.authority);
      if (checkboxChecked) {
        const request = { channel: "vscode:configureAllowedUNCHost", args: uri.authority };
        this.sendToFocused(request.channel, request.args);
        this.sendToOpeningWindow(request.channel, request.args);
      }
      return this.nb(
        path3,
        options,
        true
        /* do not handle UNC error again */
      );
    }
    if (response === 2) {
      shell3.openExternal("https://aka.ms/vscode-windows-unc");
      return this.ob(path3, options);
    }
    return void 0;
  }
  pb(path3, options) {
    const first = path3.charCodeAt(0);
    const remoteAuthority = options.remoteAuthority;
    let lineNumber;
    let columnNumber;
    if (options.gotoLineMode) {
      ({ path: path3, line: lineNumber, column: columnNumber } = $7g(path3));
    }
    if (first !== 47) {
      if ($Zg(first) && path3.charCodeAt(path3.charCodeAt(1)) === 58) {
        path3 = $Sg(path3);
      }
      path3 = `/${path3}`;
    }
    const uri = URI.from({ scheme: Schemas.vscodeRemote, authority: remoteAuthority, path: path3 });
    if (path3.charCodeAt(path3.length - 1) !== 47) {
      if ($sj(path3)) {
        if (options.forceOpenWorkspaceAsFile) {
          return {
            fileUri: uri,
            options: {
              selection: lineNumber ? { startLineNumber: lineNumber, startColumn: columnNumber || 1 } : void 0
            },
            remoteAuthority: options.remoteAuthority
          };
        }
        return { workspace: $Yjc(uri), remoteAuthority };
      } else if (options.gotoLineMode || $sc.basename(path3).indexOf(".") !== -1) {
        return {
          fileUri: uri,
          options: {
            selection: lineNumber ? { startLineNumber: lineNumber, startColumn: columnNumber || 1 } : void 0
          },
          remoteAuthority
        };
      }
    }
    return { workspace: $Zjc(uri), remoteAuthority };
  }
  qb(openConfig) {
    const windowConfig = this.L.getValue("window");
    const openFolderInNewWindowConfig = windowConfig?.openFoldersInNewWindow || "default";
    const openFilesInNewWindowConfig = windowConfig?.openFilesInNewWindow || "off";
    let openFolderInNewWindow = (openConfig.preferNewWindow || openConfig.forceNewWindow) && !openConfig.forceReuseWindow;
    if (!openConfig.forceNewWindow && !openConfig.forceReuseWindow && (openFolderInNewWindowConfig === "on" || openFolderInNewWindowConfig === "off")) {
      openFolderInNewWindow = openFolderInNewWindowConfig === "on";
    }
    let openFilesInNewWindow = false;
    if (openConfig.forceNewWindow || openConfig.forceReuseWindow) {
      openFilesInNewWindow = !!openConfig.forceNewWindow && !openConfig.forceReuseWindow;
    } else {
      if ($m) {
        if (openConfig.context === 1) {
          openFilesInNewWindow = true;
        }
      } else {
        if (openConfig.context !== 3 && openConfig.context !== 2 && !(openConfig.userEnv && openConfig.userEnv["TERM_PROGRAM"] === "vscode")) {
          openFilesInNewWindow = true;
        }
      }
      if (!openConfig.cli.extensionDevelopmentPath && (openFilesInNewWindowConfig === "on" || openFilesInNewWindowConfig === "off")) {
        openFilesInNewWindow = openFilesInNewWindowConfig === "on";
      }
    }
    return { openFolderInNewWindow: !!openFolderInNewWindow, openFilesInNewWindow };
  }
  async openExtensionDevelopmentHostWindow(extensionDevelopmentPaths, openConfig) {
    const existingWindow = $Wjc(this.getWindows(), extensionDevelopmentPaths);
    if (existingWindow) {
      this.I.reload(existingWindow, openConfig.cli);
      existingWindow.focus();
      return [existingWindow];
    }
    let folderUris = openConfig.cli["folder-uri"] || [];
    let fileUris = openConfig.cli["file-uri"] || [];
    let cliArgs = openConfig.cli._;
    if (!cliArgs.length && !folderUris.length && !fileUris.length && !openConfig.cli.extensionTestsPath) {
      const extensionDevelopmentWindowState = this.r.state.lastPluginDevelopmentHostWindow;
      const workspaceToOpen = extensionDevelopmentWindowState?.workspace ?? extensionDevelopmentWindowState?.folderUri;
      if (workspaceToOpen) {
        if (URI.isUri(workspaceToOpen)) {
          if (workspaceToOpen.scheme === Schemas.file) {
            cliArgs = [workspaceToOpen.fsPath];
          } else {
            folderUris = [workspaceToOpen.toString()];
          }
        } else {
          if (workspaceToOpen.configPath.scheme === Schemas.file) {
            cliArgs = [$oh(workspaceToOpen.configPath)];
          } else {
            fileUris = [workspaceToOpen.configPath.toString()];
          }
        }
      }
    }
    let remoteAuthority = openConfig.remoteAuthority;
    for (const extensionDevelopmentPath of extensionDevelopmentPaths) {
      if (extensionDevelopmentPath.match(/^[a-zA-Z][a-zA-Z0-9\+\-\.]+:/)) {
        const url = URI.parse(extensionDevelopmentPath);
        const extensionDevelopmentPathRemoteAuthority = $Cn(url);
        if (extensionDevelopmentPathRemoteAuthority) {
          if (remoteAuthority) {
            if (!$Fh(extensionDevelopmentPathRemoteAuthority, remoteAuthority)) {
              this.z.error("more than one extension development path authority");
            }
          } else {
            remoteAuthority = extensionDevelopmentPathRemoteAuthority;
          }
        }
      }
    }
    cliArgs = cliArgs.filter((path3) => {
      const uri = URI.file(path3);
      if (!!$Vjc(this.getWindows(), uri)) {
        return false;
      }
      return $Fh($Cn(uri), remoteAuthority);
    });
    folderUris = folderUris.filter((folderUriStr) => {
      const folderUri = this.hb(folderUriStr);
      if (folderUri && !!$Vjc(this.getWindows(), folderUri)) {
        return false;
      }
      return folderUri ? $Fh($Cn(folderUri), remoteAuthority) : false;
    });
    fileUris = fileUris.filter((fileUriStr) => {
      const fileUri = this.hb(fileUriStr);
      if (fileUri && !!$Vjc(this.getWindows(), fileUri)) {
        return false;
      }
      return fileUri ? $Fh($Cn(fileUri), remoteAuthority) : false;
    });
    openConfig.cli._ = cliArgs;
    openConfig.cli["folder-uri"] = folderUris;
    openConfig.cli["file-uri"] = fileUris;
    const openArgs = {
      context: openConfig.context,
      cli: openConfig.cli,
      forceNewWindow: true,
      forceEmpty: !cliArgs.length && !folderUris.length && !fileUris.length,
      userEnv: openConfig.userEnv,
      noRecentEntry: true,
      waitMarkerFileURI: openConfig.waitMarkerFileURI,
      remoteAuthority,
      forceProfile: openConfig.forceProfile,
      forceTempProfile: openConfig.forceTempProfile
    };
    return this.open(openArgs);
  }
  async rb(options) {
    const windowConfig = this.L.getValue("window");
    const lastActiveWindow = this.getLastActiveWindow();
    const newWindowProfile = windowConfig?.newWindowProfile ? this.H.profiles.find((profile) => profile.name === windowConfig.newWindowProfile) : void 0;
    const defaultProfile = newWindowProfile ?? lastActiveWindow?.profile ?? this.H.defaultProfile;
    let window2;
    if (!options.forceNewWindow && !options.forceNewTabbedWindow) {
      window2 = options.windowToUse || lastActiveWindow;
      if (window2) {
        window2.focus();
      }
    }
    const configuration = {
      // Inherit CLI arguments from environment and/or
      // the specific properties from this launch if provided
      ...this.G.args,
      ...options.cli,
      machineId: this.s,
      sqmId: this.t,
      devDeviceId: this.u,
      windowId: -1,
      // Will be filled in by the window once loaded later
      mainPid: process.pid,
      appRoot: this.G.appRoot,
      execPath: process.execPath,
      codeCachePath: this.G.codeCachePath,
      // If we know the backup folder upfront (for empty windows to restore), we can set it
      // directly here which helps for restoring UI state associated with that window.
      // For all other cases we first call into registerEmptyWindowBackup() to set it before
      // loading the window.
      backupPath: options.emptyWindowBackupInfo ? $vc(this.G.backupHome, options.emptyWindowBackupInfo.backupFolder) : void 0,
      profiles: {
        home: this.H.profilesHome,
        all: this.H.profiles,
        // Set to default profile first and resolve and update the profile
        // only after the workspace-backup is registered.
        // Because, workspace identifier of an empty window is known only then.
        profile: defaultProfile
      },
      homeDir: this.G.userHome.with({ scheme: Schemas.file }).fsPath,
      tmpDir: this.G.tmpDir.with({ scheme: Schemas.file }).fsPath,
      userDataDir: this.G.userDataPath,
      remoteAuthority: options.remoteAuthority,
      workspace: options.workspace,
      userEnv: { ...this.w, ...options.userEnv },
      nls: {
        messages: $f(),
        language: $g()
      },
      filesToOpenOrCreate: options.filesToOpen?.filesToOpenOrCreate,
      filesToDiff: options.filesToOpen?.filesToDiff,
      filesToMerge: options.filesToOpen?.filesToMerge,
      filesToWait: options.filesToOpen?.filesToWait,
      logLevel: this.C.getLogLevel(),
      loggers: {
        window: [],
        global: this.C.getRegisteredLoggers()
      },
      logsPath: this.G.logsHome.with({ scheme: Schemas.file }).fsPath,
      product: product_default,
      isInitialStartup: options.initialStartup,
      perfMarks: getMarks(),
      os: { release: release5(), hostname: hostname(), arch: arch3() },
      autoDetectHighContrast: windowConfig?.autoDetectHighContrast ?? true,
      autoDetectColorScheme: windowConfig?.autoDetectColorScheme ?? false,
      accessibilitySupport: app10.accessibilitySupportEnabled,
      colorScheme: this.S.getColorScheme(),
      policiesData: this.F.serialize(),
      continueOn: this.G.continueOn,
      cssModules: this.W.isEnabled ? await this.W.getCssModules() : void 0
    };
    if (!window2) {
      const state = this.r.getNewWindowState(configuration);
      mark("code/willCreateCodeWindow");
      const createdWindow = window2 = this.O.createInstance($7jc, {
        state,
        extensionDevelopmentPath: configuration.extensionDevelopmentPath,
        isExtensionTestHost: !!configuration.extensionTestsPath
      });
      mark("code/didCreateCodeWindow");
      if (options.forceNewTabbedWindow) {
        const activeWindow = this.getLastActiveWindow();
        activeWindow?.addTabbedWindow(createdWindow);
      }
      this.n.set(createdWindow.id, createdWindow);
      this.a.fire(createdWindow);
      this.f.fire({ oldCount: this.getWindowCount() - 1, newCount: this.getWindowCount() });
      const disposables = new $9c();
      disposables.add(createdWindow.onDidSignalReady(() => this.b.fire(createdWindow)));
      disposables.add(Event.once(createdWindow.onDidClose)(() => this.ub(createdWindow, disposables)));
      disposables.add(Event.once(createdWindow.onDidDestroy)(() => this.vb(createdWindow)));
      disposables.add(createdWindow.onDidMaximize(() => this.g.fire(createdWindow)));
      disposables.add(createdWindow.onDidUnmaximize(() => this.h.fire(createdWindow)));
      disposables.add(createdWindow.onDidEnterFullScreen(() => this.j.fire({ window: createdWindow, fullscreen: true })));
      disposables.add(createdWindow.onDidLeaveFullScreen(() => this.j.fire({ window: createdWindow, fullscreen: false })));
      disposables.add(createdWindow.onDidTriggerSystemContextMenu(({ x, y }) => this.m.fire({ window: createdWindow, x, y })));
      const webContents3 = $Jg(createdWindow.win?.webContents);
      webContents3.removeAllListeners("devtools-reload-page");
      disposables.add(Event.fromNodeEventEmitter(webContents3, "devtools-reload-page")(() => this.I.reload(createdWindow)));
      this.I.registerWindow(createdWindow);
    } else {
      const currentWindowConfig = window2.config;
      if (!configuration.extensionDevelopmentPath && currentWindowConfig?.extensionDevelopmentPath) {
        configuration.extensionDevelopmentPath = currentWindowConfig.extensionDevelopmentPath;
        configuration.extensionDevelopmentKind = currentWindowConfig.extensionDevelopmentKind;
        configuration["enable-proposed-api"] = currentWindowConfig["enable-proposed-api"];
        configuration.verbose = currentWindowConfig.verbose;
        configuration["inspect-extensions"] = currentWindowConfig["inspect-extensions"];
        configuration["inspect-brk-extensions"] = currentWindowConfig["inspect-brk-extensions"];
        configuration.debugId = currentWindowConfig.debugId;
        configuration.extensionEnvironment = currentWindowConfig.extensionEnvironment;
        configuration["extensions-dir"] = currentWindowConfig["extensions-dir"];
        configuration["disable-extensions"] = currentWindowConfig["disable-extensions"];
      }
      configuration.loggers = {
        global: configuration.loggers.global,
        window: currentWindowConfig?.loggers.window ?? configuration.loggers.window
      };
    }
    configuration.windowId = window2.id;
    if (window2.isReady) {
      this.I.unload(
        window2,
        4
        /* UnloadReason.LOAD */
      ).then(async (veto) => {
        if (!veto) {
          await this.sb(window2, configuration, options, defaultProfile);
        }
      });
    } else {
      await this.sb(window2, configuration, options, defaultProfile);
    }
    return window2;
  }
  async sb(window2, configuration, options, defaultProfile) {
    if (!configuration.extensionDevelopmentPath) {
      if ($cj(configuration.workspace)) {
        configuration.backupPath = this.J.registerWorkspaceBackup({
          workspace: configuration.workspace,
          remoteAuthority: configuration.remoteAuthority
        });
      } else if ($0i(configuration.workspace)) {
        configuration.backupPath = this.J.registerFolderBackup({
          folderUri: configuration.workspace.uri,
          remoteAuthority: configuration.remoteAuthority
        });
      } else {
        configuration.backupPath = this.J.registerEmptyWindowBackup({
          backupFolder: options.emptyWindowBackupInfo?.backupFolder ?? $1jc().id,
          remoteAuthority: configuration.remoteAuthority
        });
      }
    }
    if (this.H.isEnabled()) {
      const workspace = configuration.workspace ?? $bj(configuration.backupPath, false);
      const profilePromise = this.tb(options, workspace, defaultProfile);
      const profile = profilePromise instanceof Promise ? await profilePromise : profilePromise;
      configuration.profiles.profile = profile;
      if (!configuration.extensionDevelopmentPath) {
        await this.H.setProfileForWorkspace(workspace, profile);
      }
    }
    window2.load(configuration);
  }
  tb(options, workspace, defaultProfile) {
    if (options.forceProfile) {
      return this.H.profiles.find((p) => p.name === options.forceProfile) ?? this.H.createNamedProfile(options.forceProfile);
    }
    if (options.forceTempProfile) {
      return this.H.createTransientProfile();
    }
    return this.H.getProfileForWorkspace(workspace) ?? defaultProfile;
  }
  ub(window2, disposables) {
    this.n.delete(window2.id);
    this.f.fire({ oldCount: this.getWindowCount() + 1, newCount: this.getWindowCount() });
    disposables.dispose();
  }
  vb(window2) {
    this.n.delete(window2.id);
    this.c.fire(window2);
  }
  getFocusedWindow() {
    const window2 = BrowserWindow5.getFocusedWindow();
    if (window2) {
      return this.getWindowById(window2.id);
    }
    return void 0;
  }
  getLastActiveWindow() {
    return this.xb(this.getWindows());
  }
  wb(remoteAuthority) {
    return this.xb(this.getWindows().filter((window2) => $Fh(window2.remoteAuthority, remoteAuthority)));
  }
  xb(windows) {
    return $Rjc(windows);
  }
  sendToFocused(channel, ...args) {
    const focusedWindow = this.getFocusedWindow() || this.getLastActiveWindow();
    focusedWindow?.sendWhenReady(channel, CancellationToken.None, ...args);
  }
  sendToOpeningWindow(channel, ...args) {
    this.B(Event.once(this.onDidSignalReadyWindow)((window2) => {
      window2.sendWhenReady(channel, CancellationToken.None, ...args);
    }));
  }
  sendToAll(channel, payload, windowIdsToIgnore) {
    for (const window2 of this.getWindows()) {
      if (windowIdsToIgnore && windowIdsToIgnore.indexOf(window2.id) >= 0) {
        continue;
      }
      window2.sendWhenReady(channel, CancellationToken.None, payload);
    }
  }
  getWindows() {
    return Array.from(this.n.values());
  }
  getWindowCount() {
    return this.n.size;
  }
  getWindowById(windowId) {
    return this.n.get(windowId);
  }
  getWindowByWebContents(webContents3) {
    const browserWindow = BrowserWindow5.fromWebContents(webContents3);
    if (!browserWindow) {
      return void 0;
    }
    const window2 = this.getWindowById(browserWindow.id);
    return window2?.matches(webContents3) ? window2 : void 0;
  }
};
$hlc = __decorate([
  __param(4, $uk),
  __param(5, $4jc),
  __param(6, $BS),
  __param(7, $Oo),
  __param(8, $Cjc),
  __param(9, $Sjc),
  __param(10, $9jc),
  __param(11, $Jjc),
  __param(12, $tj),
  __param(13, $Pkc),
  __param(14, $2jc),
  __param(15, $Yi),
  __param(16, $Kjc),
  __param(17, $ul),
  __param(18, $Mjc),
  __param(19, $Njc),
  __param(20, $Bkc),
  __param(21, $SS)
], $hlc);

// out-build/vs/platform/windows/node/windowTracker.js
var $ilc = class extends $0c {
  constructor({ onDidOpenMainWindow, onDidFocusMainWindow, getActiveWindowId }) {
    super();
    this.a = this.B(new $9c());
    const onActiveWindowChange = Event.latch(Event.any(onDidOpenMainWindow, onDidFocusMainWindow));
    onActiveWindowChange(this.f, this, this.a);
    this.b = $Mh(() => getActiveWindowId());
    (async () => {
      try {
        const windowId = await this.b;
        this.c = typeof this.c === "number" ? this.c : windowId;
      } catch (error) {
      } finally {
        this.b = void 0;
      }
    })();
  }
  f(windowId) {
    if (this.b) {
      this.b.cancel();
      this.b = void 0;
    }
    this.c = windowId;
  }
  async getActiveClientId() {
    const id2 = this.b ? await this.b : this.c;
    return `window:${id2}`;
  }
};

// out-build/vs/platform/workspaces/electron-main/workspacesMainService.js
var $jlc = class $jlc2 {
  constructor(a, b, c, d) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.onDidChangeRecentlyOpened = this.c.onDidChangeRecentlyOpened;
  }
  //#region Workspace Management
  async enterWorkspace(windowId, path3) {
    const window2 = this.b.getWindowById(windowId);
    if (window2) {
      return this.a.enterWorkspace(window2, this.b.getWindows(), path3);
    }
    return void 0;
  }
  createUntitledWorkspace(windowId, folders, remoteAuthority) {
    return this.a.createUntitledWorkspace(folders, remoteAuthority);
  }
  deleteUntitledWorkspace(windowId, workspace) {
    return this.a.deleteUntitledWorkspace(workspace);
  }
  getWorkspaceIdentifier(windowId, workspacePath) {
    return this.a.getWorkspaceIdentifier(workspacePath);
  }
  getRecentlyOpened(windowId) {
    return this.c.getRecentlyOpened();
  }
  addRecentlyOpened(windowId, recents) {
    return this.c.addRecentlyOpened(recents);
  }
  removeRecentlyOpened(windowId, paths) {
    return this.c.removeRecentlyOpened(paths);
  }
  clearRecentlyOpened(windowId) {
    return this.c.clearRecentlyOpened();
  }
  //#endregion
  //#region Dirty Workspaces
  async getDirtyWorkspaces() {
    return this.d.getDirtyWorkspaces();
  }
};
$jlc = __decorate([
  __param(0, $2jc),
  __param(1, $Pjc),
  __param(2, $Pkc),
  __param(3, $Jjc)
], $jlc);

// out-build/vs/platform/policy/common/policyIpc.js
var $klc = class {
  constructor(b) {
    this.b = b;
    this.a = new $9c();
  }
  listen(_, event) {
    switch (event) {
      case "onDidChange":
        return Event.map(this.b.onDidChange, (names) => names.reduce((r, name) => ({ ...r, [name]: this.b.getPolicyValue(name) ?? null }), {}), this.a);
    }
    throw new Error(`Event not found: ${event}`);
  }
  call(_, command, arg) {
    switch (command) {
      case "updatePolicyDefinitions":
        return this.b.updatePolicyDefinitions(arg);
    }
    throw new Error(`Call not found: ${command}`);
  }
  dispose() {
    this.a.dispose();
  }
};

// out-build/vs/platform/extensionManagement/common/extensionManagement.js
var $tp = "^([a-z0-9A-Z][a-z0-9-A-Z]*)\\.([a-z0-9A-Z][a-z0-9-A-Z]*)$";
var $up = new RegExp($tp);
var ExtensionInstallSource;
(function(ExtensionInstallSource2) {
  ExtensionInstallSource2["COMMAND"] = "command";
  ExtensionInstallSource2["SETTINGS_SYNC"] = "settingsSync";
})(ExtensionInstallSource || (ExtensionInstallSource = {}));
function $Cp(platform2, arch5) {
  switch (platform2) {
    case 3:
      if (arch5 === "x64") {
        return "win32-x64";
      }
      if (arch5 === "arm64") {
        return "win32-arm64";
      }
      return "unknown";
    case 2:
      if (arch5 === "x64") {
        return "linux-x64";
      }
      if (arch5 === "arm64") {
        return "linux-arm64";
      }
      if (arch5 === "arm") {
        return "linux-armhf";
      }
      return "unknown";
    case "alpine":
      if (arch5 === "x64") {
        return "alpine-x64";
      }
      if (arch5 === "arm64") {
        return "alpine-arm64";
      }
      return "unknown";
    case 1:
      if (arch5 === "x64") {
        return "darwin-x64";
      }
      if (arch5 === "arm64") {
        return "darwin-arm64";
      }
      return "unknown";
    case 0:
      return "web";
  }
}
function $Fp(thing) {
  return thing && typeof thing === "object" && typeof thing.id === "string" && (!thing.uuid || typeof thing.uuid === "string");
}
var SortBy;
(function(SortBy2) {
  SortBy2[SortBy2["NoneOrRelevance"] = 0] = "NoneOrRelevance";
  SortBy2[SortBy2["LastUpdatedDate"] = 1] = "LastUpdatedDate";
  SortBy2[SortBy2["Title"] = 2] = "Title";
  SortBy2[SortBy2["PublisherName"] = 3] = "PublisherName";
  SortBy2[SortBy2["InstallCount"] = 4] = "InstallCount";
  SortBy2[SortBy2["PublishedDate"] = 10] = "PublishedDate";
  SortBy2[SortBy2["AverageRating"] = 6] = "AverageRating";
  SortBy2[SortBy2["WeightedRating"] = 12] = "WeightedRating";
})(SortBy || (SortBy = {}));
var SortOrder;
(function(SortOrder2) {
  SortOrder2[SortOrder2["Default"] = 0] = "Default";
  SortOrder2[SortOrder2["Ascending"] = 1] = "Ascending";
  SortOrder2[SortOrder2["Descending"] = 2] = "Descending";
})(SortOrder || (SortOrder = {}));
var StatisticType;
(function(StatisticType2) {
  StatisticType2["Install"] = "install";
  StatisticType2["Uninstall"] = "uninstall";
})(StatisticType || (StatisticType = {}));
var InstallOperation;
(function(InstallOperation2) {
  InstallOperation2[InstallOperation2["None"] = 1] = "None";
  InstallOperation2[InstallOperation2["Install"] = 2] = "Install";
  InstallOperation2[InstallOperation2["Update"] = 3] = "Update";
  InstallOperation2[InstallOperation2["Migrate"] = 4] = "Migrate";
})(InstallOperation || (InstallOperation = {}));
var $Gp = $Zi("extensionGalleryService");
var ExtensionGalleryErrorCode;
(function(ExtensionGalleryErrorCode2) {
  ExtensionGalleryErrorCode2["Timeout"] = "Timeout";
  ExtensionGalleryErrorCode2["Cancelled"] = "Cancelled";
  ExtensionGalleryErrorCode2["Failed"] = "Failed";
  ExtensionGalleryErrorCode2["DownloadFailedWriting"] = "DownloadFailedWriting";
  ExtensionGalleryErrorCode2["Offline"] = "Offline";
})(ExtensionGalleryErrorCode || (ExtensionGalleryErrorCode = {}));
var ExtensionManagementErrorCode;
(function(ExtensionManagementErrorCode2) {
  ExtensionManagementErrorCode2["Unsupported"] = "Unsupported";
  ExtensionManagementErrorCode2["Deprecated"] = "Deprecated";
  ExtensionManagementErrorCode2["Malicious"] = "Malicious";
  ExtensionManagementErrorCode2["Incompatible"] = "Incompatible";
  ExtensionManagementErrorCode2["IncompatibleApi"] = "IncompatibleApi";
  ExtensionManagementErrorCode2["IncompatibleTargetPlatform"] = "IncompatibleTargetPlatform";
  ExtensionManagementErrorCode2["ReleaseVersionNotFound"] = "ReleaseVersionNotFound";
  ExtensionManagementErrorCode2["Invalid"] = "Invalid";
  ExtensionManagementErrorCode2["Download"] = "Download";
  ExtensionManagementErrorCode2["DownloadSignature"] = "DownloadSignature";
  ExtensionManagementErrorCode2["DownloadFailedWriting"] = "DownloadFailedWriting";
  ExtensionManagementErrorCode2["UpdateMetadata"] = "UpdateMetadata";
  ExtensionManagementErrorCode2["Extract"] = "Extract";
  ExtensionManagementErrorCode2["Scanning"] = "Scanning";
  ExtensionManagementErrorCode2["ScanningExtension"] = "ScanningExtension";
  ExtensionManagementErrorCode2["ReadUninstalled"] = "ReadUninstalled";
  ExtensionManagementErrorCode2["UnsetUninstalled"] = "UnsetUninstalled";
  ExtensionManagementErrorCode2["Delete"] = "Delete";
  ExtensionManagementErrorCode2["Rename"] = "Rename";
  ExtensionManagementErrorCode2["IntializeDefaultProfile"] = "IntializeDefaultProfile";
  ExtensionManagementErrorCode2["AddToProfile"] = "AddToProfile";
  ExtensionManagementErrorCode2["InstalledExtensionNotFound"] = "InstalledExtensionNotFound";
  ExtensionManagementErrorCode2["PostInstall"] = "PostInstall";
  ExtensionManagementErrorCode2["CorruptZip"] = "CorruptZip";
  ExtensionManagementErrorCode2["IncompleteZip"] = "IncompleteZip";
  ExtensionManagementErrorCode2["PackageNotSigned"] = "PackageNotSigned";
  ExtensionManagementErrorCode2["SignatureVerificationInternal"] = "SignatureVerificationInternal";
  ExtensionManagementErrorCode2["SignatureVerificationFailed"] = "SignatureVerificationFailed";
  ExtensionManagementErrorCode2["NotAllowed"] = "NotAllowed";
  ExtensionManagementErrorCode2["Gallery"] = "Gallery";
  ExtensionManagementErrorCode2["Cancelled"] = "Cancelled";
  ExtensionManagementErrorCode2["Unknown"] = "Unknown";
  ExtensionManagementErrorCode2["Internal"] = "Internal";
})(ExtensionManagementErrorCode || (ExtensionManagementErrorCode = {}));
var ExtensionSignatureVerificationCode;
(function(ExtensionSignatureVerificationCode2) {
  ExtensionSignatureVerificationCode2["Success"] = "Success";
  ExtensionSignatureVerificationCode2["RequiredArgumentMissing"] = "RequiredArgumentMissing";
  ExtensionSignatureVerificationCode2["InvalidArgument"] = "InvalidArgument";
  ExtensionSignatureVerificationCode2["PackageIsUnreadable"] = "PackageIsUnreadable";
  ExtensionSignatureVerificationCode2["UnhandledException"] = "UnhandledException";
  ExtensionSignatureVerificationCode2["SignatureManifestIsMissing"] = "SignatureManifestIsMissing";
  ExtensionSignatureVerificationCode2["SignatureManifestIsUnreadable"] = "SignatureManifestIsUnreadable";
  ExtensionSignatureVerificationCode2["SignatureIsMissing"] = "SignatureIsMissing";
  ExtensionSignatureVerificationCode2["SignatureIsUnreadable"] = "SignatureIsUnreadable";
  ExtensionSignatureVerificationCode2["CertificateIsUnreadable"] = "CertificateIsUnreadable";
  ExtensionSignatureVerificationCode2["SignatureArchiveIsUnreadable"] = "SignatureArchiveIsUnreadable";
  ExtensionSignatureVerificationCode2["FileAlreadyExists"] = "FileAlreadyExists";
  ExtensionSignatureVerificationCode2["SignatureArchiveIsInvalidZip"] = "SignatureArchiveIsInvalidZip";
  ExtensionSignatureVerificationCode2["SignatureArchiveHasSameSignatureFile"] = "SignatureArchiveHasSameSignatureFile";
  ExtensionSignatureVerificationCode2["PackageIntegrityCheckFailed"] = "PackageIntegrityCheckFailed";
  ExtensionSignatureVerificationCode2["SignatureIsInvalid"] = "SignatureIsInvalid";
  ExtensionSignatureVerificationCode2["SignatureManifestIsInvalid"] = "SignatureManifestIsInvalid";
  ExtensionSignatureVerificationCode2["SignatureIntegrityCheckFailed"] = "SignatureIntegrityCheckFailed";
  ExtensionSignatureVerificationCode2["EntryIsMissing"] = "EntryIsMissing";
  ExtensionSignatureVerificationCode2["EntryIsTampered"] = "EntryIsTampered";
  ExtensionSignatureVerificationCode2["Untrusted"] = "Untrusted";
  ExtensionSignatureVerificationCode2["CertificateRevoked"] = "CertificateRevoked";
  ExtensionSignatureVerificationCode2["SignatureIsNotValid"] = "SignatureIsNotValid";
  ExtensionSignatureVerificationCode2["UnknownError"] = "UnknownError";
  ExtensionSignatureVerificationCode2["PackageIsInvalidZip"] = "PackageIsInvalidZip";
  ExtensionSignatureVerificationCode2["SignatureArchiveHasTooManyEntries"] = "SignatureArchiveHasTooManyEntries";
})(ExtensionSignatureVerificationCode || (ExtensionSignatureVerificationCode = {}));
var $Jp = $Zi("extensionManagementService");
var $Mp = $Zi("IGlobalExtensionEnablementService");
var $Np = $Zi("IExtensionTipsService");
var $Op = localize2(1790, "Extensions");
var $Pp = localize2(1791, "Preferences");

// out-build/vs/platform/extensions/common/extensions.js
var $Gn = "extensions.user.cache";
var $Hn = "extensions.builtin.cache";
var $In = "undefined_publisher";
var ExtensionType;
(function(ExtensionType2) {
  ExtensionType2[ExtensionType2["System"] = 0] = "System";
  ExtensionType2[ExtensionType2["User"] = 1] = "User";
})(ExtensionType || (ExtensionType = {}));
var TargetPlatform;
(function(TargetPlatform2) {
  TargetPlatform2["WIN32_X64"] = "win32-x64";
  TargetPlatform2["WIN32_ARM64"] = "win32-arm64";
  TargetPlatform2["LINUX_X64"] = "linux-x64";
  TargetPlatform2["LINUX_ARM64"] = "linux-arm64";
  TargetPlatform2["LINUX_ARMHF"] = "linux-armhf";
  TargetPlatform2["ALPINE_X64"] = "alpine-x64";
  TargetPlatform2["ALPINE_ARM64"] = "alpine-arm64";
  TargetPlatform2["DARWIN_X64"] = "darwin-x64";
  TargetPlatform2["DARWIN_ARM64"] = "darwin-arm64";
  TargetPlatform2["WEB"] = "web";
  TargetPlatform2["UNIVERSAL"] = "universal";
  TargetPlatform2["UNKNOWN"] = "unknown";
  TargetPlatform2["UNDEFINED"] = "undefined";
})(TargetPlatform || (TargetPlatform = {}));
var $Mn = class {
  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") {
      const aValue = typeof a === "string" ? a : a.value;
      const bValue = typeof b === "string" ? b : b.value;
      return $Zf(aValue, bValue);
    }
    return a._lower === b._lower;
  }
  /**
   * Gives the value by which to index (for equality).
   */
  static toKey(id2) {
    if (typeof id2 === "string") {
      return id2.toLowerCase();
    }
    return id2._lower;
  }
};
var $On = class {
  constructor() {
    this.c = /* @__PURE__ */ new Map();
  }
  clear() {
    this.c.clear();
  }
  delete(id2) {
    this.c.delete($Mn.toKey(id2));
  }
  get(id2) {
    return this.c.get($Mn.toKey(id2));
  }
  has(id2) {
    return this.c.has($Mn.toKey(id2));
  }
  set(id2, value) {
    this.c.set($Mn.toKey(id2), value);
  }
  values() {
    return this.c.values();
  }
  forEach(callbackfn) {
    this.c.forEach(callbackfn);
  }
  [Symbol.iterator]() {
    return this.c[Symbol.iterator]();
  }
};
function $Tn(enabledApiProposals) {
  return enabledApiProposals.map((proposal) => {
    const [proposalName, version] = proposal.split("@");
    return { proposalName, version: version ? parseInt(version) : void 0 };
  });
}
function $Un(enabledApiProposals) {
  return enabledApiProposals.map((proposal) => proposal.split("@")[0]);
}
var $Vn = $Zi("IBuiltinExtensionsScannerService");

// out-build/vs/platform/extensionManagement/common/extensionManagementUtil.js
function $8p(a, b) {
  if (a.uuid && b.uuid) {
    return a.uuid === b.uuid;
  }
  if (a.id === b.id) {
    return true;
  }
  return $Uf(a.id, b.id) === 0;
}
var ExtensionKeyRegex = /^([^.]+\..+)-(\d+\.\d+\.\d+)(-(.+))?$/;
var $9p = class _$9p {
  static create(extension) {
    const version = extension.manifest ? extension.manifest.version : extension.version;
    const targetPlatform = extension.manifest ? extension.targetPlatform : extension.properties.targetPlatform;
    return new _$9p(extension.identifier, version, targetPlatform);
  }
  static parse(key) {
    const matches = ExtensionKeyRegex.exec(key);
    return matches && matches[1] && matches[2] ? new _$9p({ id: matches[1] }, matches[2], matches[4] || void 0) : null;
  }
  constructor(identifier, version, targetPlatform = "undefined") {
    this.identifier = identifier;
    this.version = version;
    this.targetPlatform = targetPlatform;
    this.id = identifier.id;
  }
  toString() {
    return `${this.id}-${this.version}${this.targetPlatform !== "undefined" ? `-${this.targetPlatform}` : ""}`;
  }
  equals(o) {
    if (!(o instanceof _$9p)) {
      return false;
    }
    return $8p(this, o) && this.version === o.version && this.targetPlatform === o.targetPlatform;
  }
};
function $$p(publisher, name) {
  return `${publisher}.${name}`;
}
function $_p(id2) {
  return id2.toLowerCase();
}
function $aq(publisher, name) {
  return $_p($$p(publisher ?? $In, name));
}
var $eq = new $Mn("pprice.better-merge");
async function isAlpineLinux(fileService, logService) {
  if (!$n) {
    return false;
  }
  let content;
  try {
    const fileContent = await fileService.readFile(URI.file("/etc/os-release"));
    content = fileContent.value.toString();
  } catch (error) {
    try {
      const fileContent = await fileService.readFile(URI.file("/usr/lib/os-release"));
      content = fileContent.value.toString();
    } catch (error2) {
      logService.debug(`Error while getting the os-release file.`, $kb(error2));
    }
  }
  return !!content && (content.match(/^ID=([^\u001b\r\n]*)/m) || [])[1] === "alpine";
}
async function $gq(fileService, logService) {
  const alpineLinux = await isAlpineLinux(fileService, logService);
  const targetPlatform = $Cp(alpineLinux ? "alpine" : $x, $qc);
  logService.debug("ComputeTargetPlatform:", targetPlatform);
  return targetPlatform;
}

// out-build/vs/platform/extensionManagement/common/extensionsProfileScannerService.js
var ExtensionsProfileScanningErrorCode;
(function(ExtensionsProfileScanningErrorCode2) {
  ExtensionsProfileScanningErrorCode2["ERROR_PROFILE_NOT_FOUND"] = "ERROR_PROFILE_NOT_FOUND";
  ExtensionsProfileScanningErrorCode2["ERROR_INVALID_CONTENT"] = "ERROR_INVALID_CONTENT";
})(ExtensionsProfileScanningErrorCode || (ExtensionsProfileScanningErrorCode = {}));
var $5q = class extends Error {
  constructor(message, code2) {
    super(message);
    this.code = code2;
  }
};
var $6q = $Zi("IExtensionsProfileScannerService");
var $7q = class $7q2 extends $0c {
  constructor(j, m, n, r, s, t) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r;
    this.s = s;
    this.t = t;
    this.b = this.B(new $De());
    this.onAddExtensions = this.b.event;
    this.c = this.B(new $De());
    this.onDidAddExtensions = this.c.event;
    this.f = this.B(new $De());
    this.onRemoveExtensions = this.f.event;
    this.g = this.B(new $De());
    this.onDidRemoveExtensions = this.g.event;
    this.h = new $Mc();
  }
  scanProfileExtensions(profileLocation, options) {
    return this.u(profileLocation, void 0, options);
  }
  async addExtensionsToProfile(extensions, profileLocation, keepExistingVersions) {
    const extensionsToRemove = [];
    const extensionsToAdd = [];
    try {
      await this.u(profileLocation, (existingExtensions) => {
        const result = [];
        if (keepExistingVersions) {
          result.push(...existingExtensions);
        } else {
          for (const existing of existingExtensions) {
            if (extensions.some(([e]) => $8p(e.identifier, existing.identifier) && e.manifest.version !== existing.version)) {
              extensionsToRemove.push(existing);
            } else {
              result.push(existing);
            }
          }
        }
        for (const [extension, metadata] of extensions) {
          const index = result.findIndex((e) => $8p(e.identifier, extension.identifier) && e.version === extension.manifest.version);
          const extensionToAdd = { identifier: extension.identifier, version: extension.manifest.version, location: extension.location, metadata };
          if (index === -1) {
            extensionsToAdd.push(extensionToAdd);
            result.push(extensionToAdd);
          } else {
            result.splice(index, 1, extensionToAdd);
          }
        }
        if (extensionsToAdd.length) {
          this.b.fire({ extensions: extensionsToAdd, profileLocation });
        }
        if (extensionsToRemove.length) {
          this.f.fire({ extensions: extensionsToRemove, profileLocation });
        }
        return result;
      });
      if (extensionsToAdd.length) {
        this.c.fire({ extensions: extensionsToAdd, profileLocation });
      }
      if (extensionsToRemove.length) {
        this.g.fire({ extensions: extensionsToRemove, profileLocation });
      }
      return extensionsToAdd;
    } catch (error) {
      if (extensionsToAdd.length) {
        this.c.fire({ extensions: extensionsToAdd, error, profileLocation });
      }
      if (extensionsToRemove.length) {
        this.g.fire({ extensions: extensionsToRemove, error, profileLocation });
      }
      throw error;
    }
  }
  async updateMetadata(extensions, profileLocation) {
    const updatedExtensions = [];
    await this.u(profileLocation, (profileExtensions) => {
      const result = [];
      for (const profileExtension of profileExtensions) {
        const extension = extensions.find(([e]) => $8p(e.identifier, profileExtension.identifier) && e.manifest.version === profileExtension.version);
        if (extension) {
          profileExtension.metadata = { ...profileExtension.metadata, ...extension[1] };
          updatedExtensions.push(profileExtension);
          result.push(profileExtension);
        } else {
          result.push(profileExtension);
        }
      }
      return result;
    });
    return updatedExtensions;
  }
  async removeExtensionFromProfile(extension, profileLocation) {
    const extensionsToRemove = [];
    try {
      await this.u(profileLocation, (profileExtensions) => {
        const result = [];
        for (const e of profileExtensions) {
          if ($8p(e.identifier, extension.identifier)) {
            extensionsToRemove.push(e);
          } else {
            result.push(e);
          }
        }
        if (extensionsToRemove.length) {
          this.f.fire({ extensions: extensionsToRemove, profileLocation });
        }
        return result;
      });
      if (extensionsToRemove.length) {
        this.g.fire({ extensions: extensionsToRemove, profileLocation });
      }
    } catch (error) {
      if (extensionsToRemove.length) {
        this.g.fire({ extensions: extensionsToRemove, error, profileLocation });
      }
      throw error;
    }
  }
  async u(file, updateFn, options) {
    return this.F(file).queue(async () => {
      let extensions = [];
      let storedProfileExtensions;
      try {
        const content = await this.m.readFile(file);
        storedProfileExtensions = JSON.parse(content.value.toString().trim() || "[]");
      } catch (error) {
        if ($Ll(error) !== 1) {
          throw error;
        }
        if (this.r.extUri.isEqual(file, this.n.defaultProfile.extensionsResource)) {
          storedProfileExtensions = await this.D();
        }
        if (!storedProfileExtensions && options?.bailOutWhenFileNotFound) {
          throw new $5q(
            $kb(error),
            "ERROR_PROFILE_NOT_FOUND"
            /* ExtensionsProfileScanningErrorCode.ERROR_PROFILE_NOT_FOUND */
          );
        }
      }
      if (storedProfileExtensions) {
        if (!Array.isArray(storedProfileExtensions)) {
          this.w(file);
        }
        let migrate = false;
        for (const e of storedProfileExtensions) {
          if (!isStoredProfileExtension(e)) {
            this.w(file);
          }
          let location;
          if ($yg(e.relativeLocation) && e.relativeLocation) {
            location = this.z(e.relativeLocation);
          } else if ($yg(e.location)) {
            this.t.warn(`Extensions profile: Ignoring extension with invalid location: ${e.location}`);
            continue;
          } else {
            location = URI.revive(e.location);
            const relativePath = this.y(location);
            if (relativePath) {
              migrate = true;
              e.relativeLocation = relativePath;
            }
          }
          if ($Fg(e.metadata?.hasPreReleaseVersion) && e.metadata?.preRelease) {
            migrate = true;
            e.metadata.hasPreReleaseVersion = true;
          }
          extensions.push({
            identifier: e.identifier,
            location,
            version: e.version,
            metadata: e.metadata
          });
        }
        if (migrate) {
          await this.m.writeFile(file, $7e.fromString(JSON.stringify(storedProfileExtensions)));
        }
      }
      if (updateFn) {
        extensions = updateFn(extensions);
        const storedProfileExtensions2 = extensions.map((e) => ({
          identifier: e.identifier,
          version: e.version,
          // retain old format so that old clients can read it
          location: e.location.toJSON(),
          relativeLocation: this.y(e.location),
          metadata: e.metadata
        }));
        await this.m.writeFile(file, $7e.fromString(JSON.stringify(storedProfileExtensions2)));
      }
      return extensions;
    });
  }
  w(file) {
    const error = new $5q(
      `Invalid extensions content in ${file.toString()}`,
      "ERROR_INVALID_CONTENT"
      /* ExtensionsProfileScanningErrorCode.ERROR_INVALID_CONTENT */
    );
    this.s.publicLogError2("extensionsProfileScanningError", { code: error.code });
    throw error;
  }
  y(extensionLocation) {
    return this.r.extUri.isEqual(this.r.extUri.dirname(extensionLocation), this.j) ? this.r.extUri.basename(extensionLocation) : void 0;
  }
  z(path3) {
    return this.r.extUri.joinPath(this.j, path3);
  }
  async D() {
    if (!this.C) {
      this.C = (async () => {
        const oldDefaultProfileExtensionsLocation = this.r.extUri.joinPath(this.n.defaultProfile.location, "extensions.json");
        const oldDefaultProfileExtensionsInitLocation = this.r.extUri.joinPath(this.j, ".init-default-profile-extensions");
        let content;
        try {
          content = (await this.m.readFile(oldDefaultProfileExtensionsLocation)).value.toString();
        } catch (error) {
          if ($Ll(error) === 1) {
            return void 0;
          }
          throw error;
        }
        this.t.info("Migrating extensions from old default profile location", oldDefaultProfileExtensionsLocation.toString());
        let storedProfileExtensions;
        try {
          const parsedData = JSON.parse(content);
          if (Array.isArray(parsedData) && parsedData.every((candidate) => isStoredProfileExtension(candidate))) {
            storedProfileExtensions = parsedData;
          } else {
            this.t.warn("Skipping migrating from old default profile locaiton: Found invalid data", parsedData);
          }
        } catch (error) {
          this.t.error(error);
        }
        if (storedProfileExtensions) {
          try {
            await this.m.createFile(this.n.defaultProfile.extensionsResource, $7e.fromString(JSON.stringify(storedProfileExtensions)), { overwrite: false });
            this.t.info("Migrated extensions from old default profile location to new location", oldDefaultProfileExtensionsLocation.toString(), this.n.defaultProfile.extensionsResource.toString());
          } catch (error) {
            if ($Ll(error) === 3) {
              this.t.info("Migration from old default profile location to new location is done by another window", oldDefaultProfileExtensionsLocation.toString(), this.n.defaultProfile.extensionsResource.toString());
            } else {
              throw error;
            }
          }
        }
        try {
          await this.m.del(oldDefaultProfileExtensionsLocation);
        } catch (error) {
          if ($Ll(error) !== 1) {
            this.t.error(error);
          }
        }
        try {
          await this.m.del(oldDefaultProfileExtensionsInitLocation);
        } catch (error) {
          if ($Ll(error) !== 1) {
            this.t.error(error);
          }
        }
        return storedProfileExtensions;
      })();
    }
    return this.C;
  }
  F(file) {
    let resourceQueue = this.h.get(file);
    if (!resourceQueue) {
      resourceQueue = new $7h();
      this.h.set(file, resourceQueue);
    }
    return resourceQueue;
  }
};
$7q = __decorate([
  __param(1, $ul),
  __param(2, $7l),
  __param(3, $5l),
  __param(4, $tm),
  __param(5, $uk)
], $7q);
function isStoredProfileExtension(candidate) {
  return $Ag(candidate) && $Fp(candidate.identifier) && (isUriComponents(candidate.location) || $yg(candidate.location) && candidate.location) && ($Fg(candidate.relativeLocation) || $yg(candidate.relativeLocation)) && candidate.version && $yg(candidate.version);
}
function isUriComponents(thing) {
  if (!thing) {
    return false;
  }
  return $yg(thing.path) && $yg(thing.scheme);
}

// out-build/vs/base/common/jsonErrorMessages.js
function $8q(errorCode) {
  switch (errorCode) {
    case 1:
      return localize(114, null);
    case 2:
      return localize(115, null);
    case 3:
      return localize(116, null);
    case 4:
      return localize(117, null);
    case 5:
      return localize(118, null);
    case 6:
      return localize(119, null);
    case 7:
      return localize(120, null);
    case 8:
      return localize(121, null);
    case 9:
      return localize(122, null);
    default:
      return "";
  }
}

// out-build/vs/base/common/semver/semver.js
var exports = {};
var module5 = { exports };
!function(e, r) {
  if ("object" == typeof exports && "object" == typeof module5) module5.exports = r();
  else if ("function" == typeof define && define.amd) define([], r);
  else {
    var t = r();
    for (var n in t) ("object" == typeof exports ? exports : e)[n] = t[n];
  }
}("undefined" != typeof self ? self : void 0, function() {
  return function(e) {
    var r = {};
    function t(n) {
      if (r[n]) return r[n].exports;
      var o = r[n] = { i: n, l: false, exports: {} };
      return e[n].call(o.exports, o, o.exports, t), o.l = true, o.exports;
    }
    return t.m = e, t.c = r, t.d = function(e2, r2, n) {
      t.o(e2, r2) || Object.defineProperty(e2, r2, { enumerable: true, get: n });
    }, t.r = function(e2) {
      "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e2, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(e2, "__esModule", { value: true });
    }, t.t = function(e2, r2) {
      if (1 & r2 && (e2 = t(e2)), 8 & r2) return e2;
      if (4 & r2 && "object" == typeof e2 && e2 && e2.__esModule) return e2;
      var n = /* @__PURE__ */ Object.create(null);
      if (t.r(n), Object.defineProperty(n, "default", { enumerable: true, value: e2 }), 2 & r2 && "string" != typeof e2) for (var o in e2) t.d(n, o, function(r3) {
        return e2[r3];
      }.bind(null, o));
      return n;
    }, t.n = function(e2) {
      var r2 = e2 && e2.__esModule ? function() {
        return e2.default;
      } : function() {
        return e2;
      };
      return t.d(r2, "a", r2), r2;
    }, t.o = function(e2, r2) {
      return Object.prototype.hasOwnProperty.call(e2, r2);
    }, t.p = "", t(t.s = 0);
  }([function(e, r, t) {
    (function(t2) {
      var n;
      r = e.exports = H, n = "object" == typeof t2 && t2.env && t2.env.NODE_DEBUG && /\bsemver\b/i.test(t2.env.NODE_DEBUG) ? function() {
        var e2 = Array.prototype.slice.call(arguments, 0);
        e2.unshift("SEMVER"), console.log.apply(console, e2);
      } : function() {
      }, r.SEMVER_SPEC_VERSION = "2.0.0";
      var o = 256, i = Number.MAX_SAFE_INTEGER || 9007199254740991, s = r.re = [], a = r.src = [], u = 0, c = u++;
      a[c] = "0|[1-9]\\d*";
      var p = u++;
      a[p] = "[0-9]+";
      var f = u++;
      a[f] = "\\d*[a-zA-Z-][a-zA-Z0-9-]*";
      var l = u++;
      a[l] = "(" + a[c] + ")\\.(" + a[c] + ")\\.(" + a[c] + ")";
      var h = u++;
      a[h] = "(" + a[p] + ")\\.(" + a[p] + ")\\.(" + a[p] + ")";
      var v = u++;
      a[v] = "(?:" + a[c] + "|" + a[f] + ")";
      var m = u++;
      a[m] = "(?:" + a[p] + "|" + a[f] + ")";
      var w = u++;
      a[w] = "(?:-(" + a[v] + "(?:\\." + a[v] + ")*))";
      var g = u++;
      a[g] = "(?:-?(" + a[m] + "(?:\\." + a[m] + ")*))";
      var y = u++;
      a[y] = "[0-9A-Za-z-]+";
      var d = u++;
      a[d] = "(?:\\+(" + a[y] + "(?:\\." + a[y] + ")*))";
      var b = u++, j = "v?" + a[l] + a[w] + "?" + a[d] + "?";
      a[b] = "^" + j + "$";
      var E = "[v=\\s]*" + a[h] + a[g] + "?" + a[d] + "?", T = u++;
      a[T] = "^" + E + "$";
      var x = u++;
      a[x] = "((?:<|>)?=?)";
      var $ = u++;
      a[$] = a[p] + "|x|X|\\*";
      var k = u++;
      a[k] = a[c] + "|x|X|\\*";
      var S = u++;
      a[S] = "[v=\\s]*(" + a[k] + ")(?:\\.(" + a[k] + ")(?:\\.(" + a[k] + ")(?:" + a[w] + ")?" + a[d] + "?)?)?";
      var R = u++;
      a[R] = "[v=\\s]*(" + a[$] + ")(?:\\.(" + a[$] + ")(?:\\.(" + a[$] + ")(?:" + a[g] + ")?" + a[d] + "?)?)?";
      var I = u++;
      a[I] = "^" + a[x] + "\\s*" + a[S] + "$";
      var _ = u++;
      a[_] = "^" + a[x] + "\\s*" + a[R] + "$";
      var O = u++;
      a[O] = "(?:^|[^\\d])(\\d{1,16})(?:\\.(\\d{1,16}))?(?:\\.(\\d{1,16}))?(?:$|[^\\d])";
      var A = u++;
      a[A] = "(?:~>?)";
      var M = u++;
      a[M] = "(\\s*)" + a[A] + "\\s+", s[M] = new RegExp(a[M], "g");
      var V = u++;
      a[V] = "^" + a[A] + a[S] + "$";
      var P = u++;
      a[P] = "^" + a[A] + a[R] + "$";
      var C = u++;
      a[C] = "(?:\\^)";
      var L = u++;
      a[L] = "(\\s*)" + a[C] + "\\s+", s[L] = new RegExp(a[L], "g");
      var N = u++;
      a[N] = "^" + a[C] + a[S] + "$";
      var q = u++;
      a[q] = "^" + a[C] + a[R] + "$";
      var D = u++;
      a[D] = "^" + a[x] + "\\s*(" + E + ")$|^$";
      var X = u++;
      a[X] = "^" + a[x] + "\\s*(" + j + ")$|^$";
      var z = u++;
      a[z] = "(\\s*)" + a[x] + "\\s*(" + E + "|" + a[S] + ")", s[z] = new RegExp(a[z], "g");
      var G = u++;
      a[G] = "^\\s*(" + a[S] + ")\\s+-\\s+(" + a[S] + ")\\s*$";
      var Z = u++;
      a[Z] = "^\\s*(" + a[R] + ")\\s+-\\s+(" + a[R] + ")\\s*$";
      var B = u++;
      a[B] = "(<|>)?=?\\s*\\*";
      for (var U = 0; U < 35; U++) n(U, a[U]), s[U] || (s[U] = new RegExp(a[U]));
      function F(e2, r2) {
        if (e2 instanceof H) return e2;
        if ("string" != typeof e2) return null;
        if (e2.length > o) return null;
        if (!(r2 ? s[T] : s[b]).test(e2)) return null;
        try {
          return new H(e2, r2);
        } catch (e3) {
          return null;
        }
      }
      function H(e2, r2) {
        if (e2 instanceof H) {
          if (e2.loose === r2) return e2;
          e2 = e2.version;
        } else if ("string" != typeof e2) throw new TypeError("Invalid Version: " + e2);
        if (e2.length > o) throw new TypeError("version is longer than " + o + " characters");
        if (!(this instanceof H)) return new H(e2, r2);
        n("SemVer", e2, r2), this.loose = r2;
        var t3 = e2.trim().match(r2 ? s[T] : s[b]);
        if (!t3) throw new TypeError("Invalid Version: " + e2);
        if (this.raw = e2, this.major = +t3[1], this.minor = +t3[2], this.patch = +t3[3], this.major > i || this.major < 0) throw new TypeError("Invalid major version");
        if (this.minor > i || this.minor < 0) throw new TypeError("Invalid minor version");
        if (this.patch > i || this.patch < 0) throw new TypeError("Invalid patch version");
        t3[4] ? this.prerelease = t3[4].split(".").map(function(e3) {
          if (/^[0-9]+$/.test(e3)) {
            var r3 = +e3;
            if (r3 >= 0 && r3 < i) return r3;
          }
          return e3;
        }) : this.prerelease = [], this.build = t3[5] ? t3[5].split(".") : [], this.format();
      }
      r.parse = F, r.valid = function(e2, r2) {
        var t3 = F(e2, r2);
        return t3 ? t3.version : null;
      }, r.clean = function(e2, r2) {
        var t3 = F(e2.trim().replace(/^[=v]+/, ""), r2);
        return t3 ? t3.version : null;
      }, r.SemVer = H, H.prototype.format = function() {
        return this.version = this.major + "." + this.minor + "." + this.patch, this.prerelease.length && (this.version += "-" + this.prerelease.join(".")), this.version;
      }, H.prototype.toString = function() {
        return this.version;
      }, H.prototype.compare = function(e2) {
        return n("SemVer.compare", this.version, this.loose, e2), e2 instanceof H || (e2 = new H(e2, this.loose)), this.compareMain(e2) || this.comparePre(e2);
      }, H.prototype.compareMain = function(e2) {
        return e2 instanceof H || (e2 = new H(e2, this.loose)), K(this.major, e2.major) || K(this.minor, e2.minor) || K(this.patch, e2.patch);
      }, H.prototype.comparePre = function(e2) {
        if (e2 instanceof H || (e2 = new H(e2, this.loose)), this.prerelease.length && !e2.prerelease.length) return -1;
        if (!this.prerelease.length && e2.prerelease.length) return 1;
        if (!this.prerelease.length && !e2.prerelease.length) return 0;
        var r2 = 0;
        do {
          var t3 = this.prerelease[r2], o2 = e2.prerelease[r2];
          if (n("prerelease compare", r2, t3, o2), void 0 === t3 && void 0 === o2) return 0;
          if (void 0 === o2) return 1;
          if (void 0 === t3) return -1;
          if (t3 !== o2) return K(t3, o2);
        } while (++r2);
      }, H.prototype.inc = function(e2, r2) {
        switch (e2) {
          case "premajor":
            this.prerelease.length = 0, this.patch = 0, this.minor = 0, this.major++, this.inc("pre", r2);
            break;
          case "preminor":
            this.prerelease.length = 0, this.patch = 0, this.minor++, this.inc("pre", r2);
            break;
          case "prepatch":
            this.prerelease.length = 0, this.inc("patch", r2), this.inc("pre", r2);
            break;
          case "prerelease":
            0 === this.prerelease.length && this.inc("patch", r2), this.inc("pre", r2);
            break;
          case "major":
            0 === this.minor && 0 === this.patch && 0 !== this.prerelease.length || this.major++, this.minor = 0, this.patch = 0, this.prerelease = [];
            break;
          case "minor":
            0 === this.patch && 0 !== this.prerelease.length || this.minor++, this.patch = 0, this.prerelease = [];
            break;
          case "patch":
            0 === this.prerelease.length && this.patch++, this.prerelease = [];
            break;
          case "pre":
            if (0 === this.prerelease.length) this.prerelease = [0];
            else {
              for (var t3 = this.prerelease.length; --t3 >= 0; ) "number" == typeof this.prerelease[t3] && (this.prerelease[t3]++, t3 = -2);
              -1 === t3 && this.prerelease.push(0);
            }
            r2 && (this.prerelease[0] === r2 ? isNaN(this.prerelease[1]) && (this.prerelease = [r2, 0]) : this.prerelease = [r2, 0]);
            break;
          default:
            throw new Error("invalid increment argument: " + e2);
        }
        return this.format(), this.raw = this.version, this;
      }, r.inc = function(e2, r2, t3, n2) {
        "string" == typeof t3 && (n2 = t3, t3 = void 0);
        try {
          return new H(e2, t3).inc(r2, n2).version;
        } catch (e3) {
          return null;
        }
      }, r.diff = function(e2, r2) {
        if (ee(e2, r2)) return null;
        var t3 = F(e2), n2 = F(r2);
        if (t3.prerelease.length || n2.prerelease.length) {
          for (var o2 in t3) if (("major" === o2 || "minor" === o2 || "patch" === o2) && t3[o2] !== n2[o2]) return "pre" + o2;
          return "prerelease";
        }
        for (var o2 in t3) if (("major" === o2 || "minor" === o2 || "patch" === o2) && t3[o2] !== n2[o2]) return o2;
      }, r.compareIdentifiers = K;
      var J = /^[0-9]+$/;
      function K(e2, r2) {
        var t3 = J.test(e2), n2 = J.test(r2);
        return t3 && n2 && (e2 = +e2, r2 = +r2), t3 && !n2 ? -1 : n2 && !t3 ? 1 : e2 < r2 ? -1 : e2 > r2 ? 1 : 0;
      }
      function Q(e2, r2, t3) {
        return new H(e2, t3).compare(new H(r2, t3));
      }
      function W(e2, r2, t3) {
        return Q(e2, r2, t3) > 0;
      }
      function Y(e2, r2, t3) {
        return Q(e2, r2, t3) < 0;
      }
      function ee(e2, r2, t3) {
        return 0 === Q(e2, r2, t3);
      }
      function re(e2, r2, t3) {
        return 0 !== Q(e2, r2, t3);
      }
      function te(e2, r2, t3) {
        return Q(e2, r2, t3) >= 0;
      }
      function ne(e2, r2, t3) {
        return Q(e2, r2, t3) <= 0;
      }
      function oe(e2, r2, t3, n2) {
        var o2;
        switch (r2) {
          case "===":
            "object" == typeof e2 && (e2 = e2.version), "object" == typeof t3 && (t3 = t3.version), o2 = e2 === t3;
            break;
          case "!==":
            "object" == typeof e2 && (e2 = e2.version), "object" == typeof t3 && (t3 = t3.version), o2 = e2 !== t3;
            break;
          case "":
          case "=":
          case "==":
            o2 = ee(e2, t3, n2);
            break;
          case "!=":
            o2 = re(e2, t3, n2);
            break;
          case ">":
            o2 = W(e2, t3, n2);
            break;
          case ">=":
            o2 = te(e2, t3, n2);
            break;
          case "<":
            o2 = Y(e2, t3, n2);
            break;
          case "<=":
            o2 = ne(e2, t3, n2);
            break;
          default:
            throw new TypeError("Invalid operator: " + r2);
        }
        return o2;
      }
      function ie(e2, r2) {
        if (e2 instanceof ie) {
          if (e2.loose === r2) return e2;
          e2 = e2.value;
        }
        if (!(this instanceof ie)) return new ie(e2, r2);
        n("comparator", e2, r2), this.loose = r2, this.parse(e2), this.semver === se ? this.value = "" : this.value = this.operator + this.semver.version, n("comp", this);
      }
      r.rcompareIdentifiers = function(e2, r2) {
        return K(r2, e2);
      }, r.major = function(e2, r2) {
        return new H(e2, r2).major;
      }, r.minor = function(e2, r2) {
        return new H(e2, r2).minor;
      }, r.patch = function(e2, r2) {
        return new H(e2, r2).patch;
      }, r.compare = Q, r.compareLoose = function(e2, r2) {
        return Q(e2, r2, true);
      }, r.rcompare = function(e2, r2, t3) {
        return Q(r2, e2, t3);
      }, r.sort = function(e2, t3) {
        return e2.sort(function(e3, n2) {
          return r.compare(e3, n2, t3);
        });
      }, r.rsort = function(e2, t3) {
        return e2.sort(function(e3, n2) {
          return r.rcompare(e3, n2, t3);
        });
      }, r.gt = W, r.lt = Y, r.eq = ee, r.neq = re, r.gte = te, r.lte = ne, r.cmp = oe, r.Comparator = ie;
      var se = {};
      function ae(e2, r2) {
        if (e2 instanceof ae) return e2.loose === r2 ? e2 : new ae(e2.raw, r2);
        if (e2 instanceof ie) return new ae(e2.value, r2);
        if (!(this instanceof ae)) return new ae(e2, r2);
        if (this.loose = r2, this.raw = e2, this.set = e2.split(/\s*\|\|\s*/).map(function(e3) {
          return this.parseRange(e3.trim());
        }, this).filter(function(e3) {
          return e3.length;
        }), !this.set.length) throw new TypeError("Invalid SemVer Range: " + e2);
        this.format();
      }
      function ue(e2) {
        return !e2 || "x" === e2.toLowerCase() || "*" === e2;
      }
      function ce(e2, r2, t3, n2, o2, i2, s2, a2, u2, c2, p2, f2, l2) {
        return ((r2 = ue(t3) ? "" : ue(n2) ? ">=" + t3 + ".0.0" : ue(o2) ? ">=" + t3 + "." + n2 + ".0" : ">=" + r2) + " " + (a2 = ue(u2) ? "" : ue(c2) ? "<" + (+u2 + 1) + ".0.0" : ue(p2) ? "<" + u2 + "." + (+c2 + 1) + ".0" : f2 ? "<=" + u2 + "." + c2 + "." + p2 + "-" + f2 : "<=" + a2)).trim();
      }
      function pe(e2, r2) {
        for (var t3 = 0; t3 < e2.length; t3++) if (!e2[t3].test(r2)) return false;
        if (r2.prerelease.length) {
          for (t3 = 0; t3 < e2.length; t3++) if (n(e2[t3].semver), e2[t3].semver !== se && e2[t3].semver.prerelease.length > 0) {
            var o2 = e2[t3].semver;
            if (o2.major === r2.major && o2.minor === r2.minor && o2.patch === r2.patch) return true;
          }
          return false;
        }
        return true;
      }
      function fe(e2, r2, t3) {
        try {
          r2 = new ae(r2, t3);
        } catch (e3) {
          return false;
        }
        return r2.test(e2);
      }
      function le(e2, r2, t3, n2) {
        var o2, i2, s2, a2, u2;
        switch (e2 = new H(e2, n2), r2 = new ae(r2, n2), t3) {
          case ">":
            o2 = W, i2 = ne, s2 = Y, a2 = ">", u2 = ">=";
            break;
          case "<":
            o2 = Y, i2 = te, s2 = W, a2 = "<", u2 = "<=";
            break;
          default:
            throw new TypeError('Must provide a hilo val of "<" or ">"');
        }
        if (fe(e2, r2, n2)) return false;
        for (var c2 = 0; c2 < r2.set.length; ++c2) {
          var p2 = r2.set[c2], f2 = null, l2 = null;
          if (p2.forEach(function(e3) {
            e3.semver === se && (e3 = new ie(">=0.0.0")), f2 = f2 || e3, l2 = l2 || e3, o2(e3.semver, f2.semver, n2) ? f2 = e3 : s2(e3.semver, l2.semver, n2) && (l2 = e3);
          }), f2.operator === a2 || f2.operator === u2) return false;
          if ((!l2.operator || l2.operator === a2) && i2(e2, l2.semver)) return false;
          if (l2.operator === u2 && s2(e2, l2.semver)) return false;
        }
        return true;
      }
      ie.prototype.parse = function(e2) {
        var r2 = this.loose ? s[D] : s[X], t3 = e2.match(r2);
        if (!t3) throw new TypeError("Invalid comparator: " + e2);
        this.operator = t3[1], "=" === this.operator && (this.operator = ""), t3[2] ? this.semver = new H(t3[2], this.loose) : this.semver = se;
      }, ie.prototype.toString = function() {
        return this.value;
      }, ie.prototype.test = function(e2) {
        return n("Comparator.test", e2, this.loose), this.semver === se || ("string" == typeof e2 && (e2 = new H(e2, this.loose)), oe(e2, this.operator, this.semver, this.loose));
      }, ie.prototype.intersects = function(e2, r2) {
        if (!(e2 instanceof ie)) throw new TypeError("a Comparator is required");
        var t3;
        if ("" === this.operator) return t3 = new ae(e2.value, r2), fe(this.value, t3, r2);
        if ("" === e2.operator) return t3 = new ae(this.value, r2), fe(e2.semver, t3, r2);
        var n2 = !(">=" !== this.operator && ">" !== this.operator || ">=" !== e2.operator && ">" !== e2.operator), o2 = !("<=" !== this.operator && "<" !== this.operator || "<=" !== e2.operator && "<" !== e2.operator), i2 = this.semver.version === e2.semver.version, s2 = !(">=" !== this.operator && "<=" !== this.operator || ">=" !== e2.operator && "<=" !== e2.operator), a2 = oe(this.semver, "<", e2.semver, r2) && (">=" === this.operator || ">" === this.operator) && ("<=" === e2.operator || "<" === e2.operator), u2 = oe(this.semver, ">", e2.semver, r2) && ("<=" === this.operator || "<" === this.operator) && (">=" === e2.operator || ">" === e2.operator);
        return n2 || o2 || i2 && s2 || a2 || u2;
      }, r.Range = ae, ae.prototype.format = function() {
        return this.range = this.set.map(function(e2) {
          return e2.join(" ").trim();
        }).join("||").trim(), this.range;
      }, ae.prototype.toString = function() {
        return this.range;
      }, ae.prototype.parseRange = function(e2) {
        var r2 = this.loose;
        e2 = e2.trim(), n("range", e2, r2);
        var t3 = r2 ? s[Z] : s[G];
        e2 = e2.replace(t3, ce), n("hyphen replace", e2), e2 = e2.replace(s[z], "$1$2$3"), n("comparator trim", e2, s[z]), e2 = (e2 = (e2 = e2.replace(s[M], "$1~")).replace(s[L], "$1^")).split(/\s+/).join(" ");
        var o2 = r2 ? s[D] : s[X], i2 = e2.split(" ").map(function(e3) {
          return function(e4, r3) {
            return n("comp", e4), e4 = function(e5, r4) {
              return e5.trim().split(/\s+/).map(function(e6) {
                return function(e7, r5) {
                  n("caret", e7, r5);
                  var t4 = r5 ? s[q] : s[N];
                  return e7.replace(t4, function(r6, t5, o3, i3, s2) {
                    var a2;
                    return n("caret", e7, r6, t5, o3, i3, s2), ue(t5) ? a2 = "" : ue(o3) ? a2 = ">=" + t5 + ".0.0 <" + (+t5 + 1) + ".0.0" : ue(i3) ? a2 = "0" === t5 ? ">=" + t5 + "." + o3 + ".0 <" + t5 + "." + (+o3 + 1) + ".0" : ">=" + t5 + "." + o3 + ".0 <" + (+t5 + 1) + ".0.0" : s2 ? (n("replaceCaret pr", s2), "-" !== s2.charAt(0) && (s2 = "-" + s2), a2 = "0" === t5 ? "0" === o3 ? ">=" + t5 + "." + o3 + "." + i3 + s2 + " <" + t5 + "." + o3 + "." + (+i3 + 1) : ">=" + t5 + "." + o3 + "." + i3 + s2 + " <" + t5 + "." + (+o3 + 1) + ".0" : ">=" + t5 + "." + o3 + "." + i3 + s2 + " <" + (+t5 + 1) + ".0.0") : (n("no pr"), a2 = "0" === t5 ? "0" === o3 ? ">=" + t5 + "." + o3 + "." + i3 + " <" + t5 + "." + o3 + "." + (+i3 + 1) : ">=" + t5 + "." + o3 + "." + i3 + " <" + t5 + "." + (+o3 + 1) + ".0" : ">=" + t5 + "." + o3 + "." + i3 + " <" + (+t5 + 1) + ".0.0"), n("caret return", a2), a2;
                  });
                }(e6, r4);
              }).join(" ");
            }(e4, r3), n("caret", e4), e4 = function(e5, r4) {
              return e5.trim().split(/\s+/).map(function(e6) {
                return function(e7, r5) {
                  var t4 = r5 ? s[P] : s[V];
                  return e7.replace(t4, function(r6, t5, o3, i3, s2) {
                    var a2;
                    return n("tilde", e7, r6, t5, o3, i3, s2), ue(t5) ? a2 = "" : ue(o3) ? a2 = ">=" + t5 + ".0.0 <" + (+t5 + 1) + ".0.0" : ue(i3) ? a2 = ">=" + t5 + "." + o3 + ".0 <" + t5 + "." + (+o3 + 1) + ".0" : s2 ? (n("replaceTilde pr", s2), "-" !== s2.charAt(0) && (s2 = "-" + s2), a2 = ">=" + t5 + "." + o3 + "." + i3 + s2 + " <" + t5 + "." + (+o3 + 1) + ".0") : a2 = ">=" + t5 + "." + o3 + "." + i3 + " <" + t5 + "." + (+o3 + 1) + ".0", n("tilde return", a2), a2;
                  });
                }(e6, r4);
              }).join(" ");
            }(e4, r3), n("tildes", e4), e4 = function(e5, r4) {
              return n("replaceXRanges", e5, r4), e5.split(/\s+/).map(function(e6) {
                return function(e7, r5) {
                  e7 = e7.trim();
                  var t4 = r5 ? s[_] : s[I];
                  return e7.replace(t4, function(r6, t5, o3, i3, s2, a2) {
                    n("xRange", e7, r6, t5, o3, i3, s2, a2);
                    var u2 = ue(o3), c2 = u2 || ue(i3), p2 = c2 || ue(s2);
                    return "=" === t5 && p2 && (t5 = ""), u2 ? r6 = ">" === t5 || "<" === t5 ? "<0.0.0" : "*" : t5 && p2 ? (c2 && (i3 = 0), p2 && (s2 = 0), ">" === t5 ? (t5 = ">=", c2 ? (o3 = +o3 + 1, i3 = 0, s2 = 0) : p2 && (i3 = +i3 + 1, s2 = 0)) : "<=" === t5 && (t5 = "<", c2 ? o3 = +o3 + 1 : i3 = +i3 + 1), r6 = t5 + o3 + "." + i3 + "." + s2) : c2 ? r6 = ">=" + o3 + ".0.0 <" + (+o3 + 1) + ".0.0" : p2 && (r6 = ">=" + o3 + "." + i3 + ".0 <" + o3 + "." + (+i3 + 1) + ".0"), n("xRange return", r6), r6;
                  });
                }(e6, r4);
              }).join(" ");
            }(e4, r3), n("xrange", e4), e4 = function(e5, r4) {
              return n("replaceStars", e5, r4), e5.trim().replace(s[B], "");
            }(e4, r3), n("stars", e4), e4;
          }(e3, r2);
        }).join(" ").split(/\s+/);
        return this.loose && (i2 = i2.filter(function(e3) {
          return !!e3.match(o2);
        })), i2 = i2.map(function(e3) {
          return new ie(e3, r2);
        });
      }, ae.prototype.intersects = function(e2, r2) {
        if (!(e2 instanceof ae)) throw new TypeError("a Range is required");
        return this.set.some(function(t3) {
          return t3.every(function(t4) {
            return e2.set.some(function(e3) {
              return e3.every(function(e4) {
                return t4.intersects(e4, r2);
              });
            });
          });
        });
      }, r.toComparators = function(e2, r2) {
        return new ae(e2, r2).set.map(function(e3) {
          return e3.map(function(e4) {
            return e4.value;
          }).join(" ").trim().split(" ");
        });
      }, ae.prototype.test = function(e2) {
        if (!e2) return false;
        "string" == typeof e2 && (e2 = new H(e2, this.loose));
        for (var r2 = 0; r2 < this.set.length; r2++) if (pe(this.set[r2], e2)) return true;
        return false;
      }, r.satisfies = fe, r.maxSatisfying = function(e2, r2, t3) {
        var n2 = null, o2 = null;
        try {
          var i2 = new ae(r2, t3);
        } catch (e3) {
          return null;
        }
        return e2.forEach(function(e3) {
          i2.test(e3) && (n2 && -1 !== o2.compare(e3) || (o2 = new H(n2 = e3, t3)));
        }), n2;
      }, r.minSatisfying = function(e2, r2, t3) {
        var n2 = null, o2 = null;
        try {
          var i2 = new ae(r2, t3);
        } catch (e3) {
          return null;
        }
        return e2.forEach(function(e3) {
          i2.test(e3) && (n2 && 1 !== o2.compare(e3) || (o2 = new H(n2 = e3, t3)));
        }), n2;
      }, r.validRange = function(e2, r2) {
        try {
          return new ae(e2, r2).range || "*";
        } catch (e3) {
          return null;
        }
      }, r.ltr = function(e2, r2, t3) {
        return le(e2, r2, "<", t3);
      }, r.gtr = function(e2, r2, t3) {
        return le(e2, r2, ">", t3);
      }, r.outside = le, r.prerelease = function(e2, r2) {
        var t3 = F(e2, r2);
        return t3 && t3.prerelease.length ? t3.prerelease : null;
      }, r.intersects = function(e2, r2, t3) {
        return e2 = new ae(e2, t3), r2 = new ae(r2, t3), e2.intersects(r2);
      }, r.coerce = function(e2) {
        if (e2 instanceof H) return e2;
        if ("string" != typeof e2) return null;
        var r2 = e2.match(s[O]);
        return null == r2 ? null : F((r2[1] || "0") + "." + (r2[2] || "0") + "." + (r2[3] || "0"));
      };
    }).call(this, t(1));
  }, function(e, r) {
    var t, n, o = e.exports = {};
    function i() {
      throw new Error("setTimeout has not been defined");
    }
    function s() {
      throw new Error("clearTimeout has not been defined");
    }
    function a(e2) {
      if (t === setTimeout) return setTimeout(e2, 0);
      if ((t === i || !t) && setTimeout) return t = setTimeout, setTimeout(e2, 0);
      try {
        return t(e2, 0);
      } catch (r2) {
        try {
          return t.call(null, e2, 0);
        } catch (r3) {
          return t.call(this, e2, 0);
        }
      }
    }
    !function() {
      try {
        t = "function" == typeof setTimeout ? setTimeout : i;
      } catch (e2) {
        t = i;
      }
      try {
        n = "function" == typeof clearTimeout ? clearTimeout : s;
      } catch (e2) {
        n = s;
      }
    }();
    var u, c = [], p = false, f = -1;
    function l() {
      p && u && (p = false, u.length ? c = u.concat(c) : f = -1, c.length && h());
    }
    function h() {
      if (!p) {
        var e2 = a(l);
        p = true;
        for (var r2 = c.length; r2; ) {
          for (u = c, c = []; ++f < r2; ) u && u[f].run();
          f = -1, r2 = c.length;
        }
        u = null, p = false, function(e3) {
          if (n === clearTimeout) return clearTimeout(e3);
          if ((n === s || !n) && clearTimeout) return n = clearTimeout, clearTimeout(e3);
          try {
            n(e3);
          } catch (r3) {
            try {
              return n.call(null, e3);
            } catch (r4) {
              return n.call(this, e3);
            }
          }
        }(e2);
      }
    }
    function v(e2, r2) {
      this.fun = e2, this.array = r2;
    }
    function m() {
    }
    o.nextTick = function(e2) {
      var r2 = new Array(arguments.length - 1);
      if (arguments.length > 1) for (var t2 = 1; t2 < arguments.length; t2++) r2[t2 - 1] = arguments[t2];
      c.push(new v(e2, r2)), 1 !== c.length || p || a(h);
    }, v.prototype.run = function() {
      this.fun.apply(null, this.array);
    }, o.title = "browser", o.browser = true, o.env = {}, o.argv = [], o.version = "", o.versions = {}, o.on = m, o.addListener = m, o.once = m, o.off = m, o.removeListener = m, o.removeAllListeners = m, o.emit = m, o.prependListener = m, o.prependOnceListener = m, o.listeners = function(e2) {
      return [];
    }, o.binding = function(e2) {
      throw new Error("process.binding is not supported");
    }, o.cwd = function() {
      return "/";
    }, o.chdir = function(e2) {
      throw new Error("process.chdir is not supported");
    }, o.umask = function() {
      return 0;
    };
  }]);
});
var SEMVER_SPEC_VERSION = module5.exports.SEMVER_SPEC_VERSION;
var parse2 = module5.exports.parse;
var valid = module5.exports.valid;
var coerce = module5.exports.coerce;
var clean = module5.exports.clean;
var inc = module5.exports.inc;
var major = module5.exports.major;
var minor = module5.exports.minor;
var patch = module5.exports.patch;
var prerelease = module5.exports.prerelease;
var gt = module5.exports.gt;
var gte = module5.exports.gte;
var lt = module5.exports.lt;
var lte = module5.exports.lte;
var eq = module5.exports.eq;
var neq = module5.exports.neq;
var cmp3 = module5.exports.cmp;
var compare = module5.exports.compare;
var rcompare = module5.exports.rcompare;
var compareIdentifiers = module5.exports.compareIdentifiers;
var rcompareIdentifiers = module5.exports.rcompareIdentifiers;
var compareBuild = module5.exports.compareBuild;
var sort = module5.exports.sort;
var rsort = module5.exports.rsort;
var diff = module5.exports.diff;
var validRange = module5.exports.validRange;
var satisfies = module5.exports.satisfies;
var maxSatisfying = module5.exports.maxSatisfying;
var minSatisfying = module5.exports.minSatisfying;
var minVersion = module5.exports.minVersion;
var gtr = module5.exports.gtr;
var ltr = module5.exports.ltr;
var outside = module5.exports.outside;
var intersects = module5.exports.intersects;
var SemVer = module5.exports.SemVer;
var Comparator = module5.exports.Comparator;
var Range = module5.exports.Range;

// out-build/vs/platform/extensions/common/extensionsApiProposals.js
var _allApiProposals = {
  activeComment: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.activeComment.d.ts"
  },
  aiRelatedInformation: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.aiRelatedInformation.d.ts"
  },
  aiTextSearchProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.aiTextSearchProvider.d.ts"
  },
  aiTextSearchProviderNew: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.aiTextSearchProviderNew.d.ts"
  },
  attributableCoverage: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.attributableCoverage.d.ts"
  },
  authLearnMore: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.authLearnMore.d.ts"
  },
  authSession: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.authSession.d.ts"
  },
  canonicalUriProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.canonicalUriProvider.d.ts"
  },
  chatParticipantAdditions: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatParticipantAdditions.d.ts"
  },
  chatParticipantPrivate: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatParticipantPrivate.d.ts",
    version: 2
  },
  chatProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatProvider.d.ts"
  },
  chatTab: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatTab.d.ts"
  },
  chatVariableResolver: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatVariableResolver.d.ts"
  },
  codeActionAI: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.codeActionAI.d.ts"
  },
  codeActionRanges: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.codeActionRanges.d.ts"
  },
  codiconDecoration: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.codiconDecoration.d.ts"
  },
  commentReactor: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.commentReactor.d.ts"
  },
  commentReveal: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.commentReveal.d.ts"
  },
  commentThreadApplicability: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.commentThreadApplicability.d.ts"
  },
  commentingRangeHint: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.commentingRangeHint.d.ts"
  },
  commentsDraftState: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.commentsDraftState.d.ts"
  },
  contribAccessibilityHelpContent: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribAccessibilityHelpContent.d.ts"
  },
  contribChatParticipantDetection: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribChatParticipantDetection.d.ts"
  },
  contribCommentEditorActionsMenu: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribCommentEditorActionsMenu.d.ts"
  },
  contribCommentPeekContext: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribCommentPeekContext.d.ts"
  },
  contribCommentThreadAdditionalMenu: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribCommentThreadAdditionalMenu.d.ts"
  },
  contribCommentsViewThreadMenus: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribCommentsViewThreadMenus.d.ts"
  },
  contribDebugCreateConfiguration: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribDebugCreateConfiguration.d.ts"
  },
  contribDiffEditorGutterToolBarMenus: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribDiffEditorGutterToolBarMenus.d.ts"
  },
  contribEditSessions: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribEditSessions.d.ts"
  },
  contribEditorContentMenu: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribEditorContentMenu.d.ts"
  },
  contribIssueReporter: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribIssueReporter.d.ts"
  },
  contribLabelFormatterWorkspaceTooltip: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribLabelFormatterWorkspaceTooltip.d.ts"
  },
  contribMenuBarHome: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribMenuBarHome.d.ts"
  },
  contribMergeEditorMenus: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribMergeEditorMenus.d.ts"
  },
  contribMultiDiffEditorMenus: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribMultiDiffEditorMenus.d.ts"
  },
  contribNotebookStaticPreloads: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribNotebookStaticPreloads.d.ts"
  },
  contribRemoteHelp: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribRemoteHelp.d.ts"
  },
  contribShareMenu: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribShareMenu.d.ts"
  },
  contribSourceControlHistoryItemMenu: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribSourceControlHistoryItemMenu.d.ts"
  },
  contribSourceControlHistoryTitleMenu: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribSourceControlHistoryTitleMenu.d.ts"
  },
  contribSourceControlInputBoxMenu: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribSourceControlInputBoxMenu.d.ts"
  },
  contribSourceControlTitleMenu: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribSourceControlTitleMenu.d.ts"
  },
  contribStatusBarItems: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribStatusBarItems.d.ts"
  },
  contribViewContainerTitle: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribViewContainerTitle.d.ts"
  },
  contribViewsRemote: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribViewsRemote.d.ts"
  },
  contribViewsWelcome: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribViewsWelcome.d.ts"
  },
  createFileSystemWatcher: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.createFileSystemWatcher.d.ts"
  },
  customEditorMove: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.customEditorMove.d.ts"
  },
  debugVisualization: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.debugVisualization.d.ts"
  },
  defaultChatParticipant: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.defaultChatParticipant.d.ts",
    version: 2
  },
  diffCommand: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.diffCommand.d.ts"
  },
  diffContentOptions: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.diffContentOptions.d.ts"
  },
  documentFiltersExclusive: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.documentFiltersExclusive.d.ts"
  },
  documentPaste: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.documentPaste.d.ts"
  },
  editSessionIdentityProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.editSessionIdentityProvider.d.ts"
  },
  editorHoverVerbosityLevel: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.editorHoverVerbosityLevel.d.ts"
  },
  editorInsets: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.editorInsets.d.ts"
  },
  embeddings: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.embeddings.d.ts"
  },
  extensionRuntime: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.extensionRuntime.d.ts"
  },
  extensionsAny: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.extensionsAny.d.ts"
  },
  externalUriOpener: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.externalUriOpener.d.ts"
  },
  fileComments: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.fileComments.d.ts"
  },
  fileSearchProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.fileSearchProvider.d.ts"
  },
  fileSearchProviderNew: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.fileSearchProviderNew.d.ts"
  },
  findFiles2: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.findFiles2.d.ts"
  },
  findFiles2New: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.findFiles2New.d.ts"
  },
  findTextInFiles: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.findTextInFiles.d.ts"
  },
  findTextInFilesNew: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.findTextInFilesNew.d.ts"
  },
  fsChunks: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.fsChunks.d.ts"
  },
  idToken: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.idToken.d.ts"
  },
  inlineCompletionsAdditions: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.inlineCompletionsAdditions.d.ts"
  },
  inlineEdit: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.inlineEdit.d.ts"
  },
  interactive: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.interactive.d.ts"
  },
  interactiveWindow: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.interactiveWindow.d.ts"
  },
  ipc: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.ipc.d.ts"
  },
  languageModelSystem: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.languageModelSystem.d.ts"
  },
  languageStatusText: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.languageStatusText.d.ts"
  },
  lmTools: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.lmTools.d.ts",
    version: 7
  },
  mappedEditsProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.mappedEditsProvider.d.ts"
  },
  multiDocumentHighlightProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.multiDocumentHighlightProvider.d.ts"
  },
  newSymbolNamesProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.newSymbolNamesProvider.d.ts"
  },
  notebookCellExecution: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookCellExecution.d.ts"
  },
  notebookCellExecutionState: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookCellExecutionState.d.ts"
  },
  notebookControllerAffinityHidden: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookControllerAffinityHidden.d.ts"
  },
  notebookDeprecated: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookDeprecated.d.ts"
  },
  notebookExecution: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookExecution.d.ts"
  },
  notebookKernelSource: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookKernelSource.d.ts"
  },
  notebookLiveShare: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookLiveShare.d.ts"
  },
  notebookMessaging: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookMessaging.d.ts"
  },
  notebookMime: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookMime.d.ts"
  },
  notebookReplDocument: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookReplDocument.d.ts"
  },
  notebookVariableProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookVariableProvider.d.ts"
  },
  portsAttributes: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.portsAttributes.d.ts"
  },
  profileContentHandlers: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.profileContentHandlers.d.ts"
  },
  quickDiffProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.quickDiffProvider.d.ts"
  },
  quickInputButtonLocation: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.quickInputButtonLocation.d.ts"
  },
  quickPickItemTooltip: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.quickPickItemTooltip.d.ts"
  },
  quickPickSortByLabel: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.quickPickSortByLabel.d.ts"
  },
  resolvers: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.resolvers.d.ts"
  },
  scmActionButton: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.scmActionButton.d.ts"
  },
  scmHistoryProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.scmHistoryProvider.d.ts"
  },
  scmMultiDiffEditor: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.scmMultiDiffEditor.d.ts"
  },
  scmSelectedProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.scmSelectedProvider.d.ts"
  },
  scmTextDocument: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.scmTextDocument.d.ts"
  },
  scmValidation: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.scmValidation.d.ts"
  },
  shareProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.shareProvider.d.ts"
  },
  showLocal: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.showLocal.d.ts"
  },
  speech: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.speech.d.ts"
  },
  tabInputMultiDiff: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.tabInputMultiDiff.d.ts"
  },
  tabInputTextMerge: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.tabInputTextMerge.d.ts"
  },
  taskPresentationGroup: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.taskPresentationGroup.d.ts"
  },
  telemetry: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.telemetry.d.ts"
  },
  terminalDataWriteEvent: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.terminalDataWriteEvent.d.ts"
  },
  terminalDimensions: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.terminalDimensions.d.ts"
  },
  terminalExecuteCommandEvent: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.terminalExecuteCommandEvent.d.ts"
  },
  terminalQuickFixProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.terminalQuickFixProvider.d.ts"
  },
  terminalSelection: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.terminalSelection.d.ts"
  },
  testObserver: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.testObserver.d.ts"
  },
  testRelatedCode: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.testRelatedCode.d.ts"
  },
  textSearchCompleteNew: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.textSearchCompleteNew.d.ts"
  },
  textSearchProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.textSearchProvider.d.ts"
  },
  textSearchProviderNew: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.textSearchProviderNew.d.ts"
  },
  timeline: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.timeline.d.ts"
  },
  tokenInformation: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.tokenInformation.d.ts"
  },
  treeViewActiveItem: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.treeViewActiveItem.d.ts"
  },
  treeViewMarkdownMessage: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.treeViewMarkdownMessage.d.ts"
  },
  treeViewReveal: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.treeViewReveal.d.ts"
  },
  tunnelFactory: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.tunnelFactory.d.ts"
  },
  tunnels: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.tunnels.d.ts"
  },
  workspaceTrust: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.workspaceTrust.d.ts"
  }
};
var allApiProposals = Object.freeze(_allApiProposals);

// out-build/vs/platform/extensions/common/extensionValidator.js
var VERSION_REGEXP = /^(\^|>=)?((\d+)|x)\.((\d+)|x)\.((\d+)|x)(\-.*)?$/;
var NOT_BEFORE_REGEXP = /^-(\d{4})(\d{2})(\d{2})$/;
function $iq(version) {
  version = version.trim();
  return version === "*" || VERSION_REGEXP.test(version);
}
function $jq(version) {
  if (!$iq(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
    };
  }
  const 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
  };
}
function $kq(version) {
  if (!version) {
    return null;
  }
  const majorBase = version.majorBase;
  const majorMustEqual = version.majorMustEqual;
  const minorBase = version.minorBase;
  let minorMustEqual = version.minorMustEqual;
  const patchBase = version.patchBase;
  let patchMustEqual = version.patchMustEqual;
  if (version.hasCaret) {
    if (majorBase === 0) {
      patchMustEqual = false;
    } else {
      minorMustEqual = false;
      patchMustEqual = false;
    }
  }
  let notBefore = 0;
  if (version.preRelease) {
    const match = NOT_BEFORE_REGEXP.exec(version.preRelease);
    if (match) {
      const [, year2, month2, day2] = match;
      notBefore = Date.UTC(Number(year2), Number(month2) - 1, Number(day2));
    }
  }
  return {
    majorBase,
    majorMustEqual,
    minorBase,
    minorMustEqual,
    patchBase,
    patchMustEqual,
    isMinimum: version.hasGreaterEquals,
    notBefore
  };
}
function $lq(_inputVersion, _inputDate, _desiredVersion) {
  let version;
  if (typeof _inputVersion === "string") {
    version = $kq($jq(_inputVersion));
  } else {
    version = _inputVersion;
  }
  let productTs;
  if (_inputDate instanceof Date) {
    productTs = _inputDate.getTime();
  } else if (typeof _inputDate === "string") {
    productTs = new Date(_inputDate).getTime();
  }
  let desiredVersion;
  if (typeof _desiredVersion === "string") {
    desiredVersion = $kq($jq(_desiredVersion));
  } else {
    desiredVersion = _desiredVersion;
  }
  if (!version || !desiredVersion) {
    return false;
  }
  const majorBase = version.majorBase;
  const minorBase = version.minorBase;
  const patchBase = version.patchBase;
  let desiredMajorBase = desiredVersion.majorBase;
  let desiredMinorBase = desiredVersion.minorBase;
  let desiredPatchBase = desiredVersion.patchBase;
  const desiredNotBefore = desiredVersion.notBefore;
  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;
    }
    if (productTs && productTs < desiredNotBefore) {
      return false;
    }
    return patchBase >= desiredPatchBase;
  }
  if (majorBase === 1 && desiredMajorBase === 0 && (!majorMustEqual || !minorMustEqual || !patchMustEqual)) {
    desiredMajorBase = 1;
    desiredMinorBase = 0;
    desiredPatchBase = 0;
    majorMustEqual = true;
    minorMustEqual = false;
    patchMustEqual = false;
  }
  if (majorBase < desiredMajorBase) {
    return false;
  }
  if (majorBase > desiredMajorBase) {
    return !majorMustEqual;
  }
  if (minorBase < desiredMinorBase) {
    return false;
  }
  if (minorBase > desiredMinorBase) {
    return !minorMustEqual;
  }
  if (patchBase < desiredPatchBase) {
    return false;
  }
  if (patchBase > desiredPatchBase) {
    return !patchMustEqual;
  }
  if (productTs && productTs < desiredNotBefore) {
    return false;
  }
  return true;
}
function $mq(productVersion, productDate, extensionLocation, extensionManifest, extensionIsBuiltin, validateApiVersion) {
  const validations = [];
  if (typeof extensionManifest.publisher !== "undefined" && typeof extensionManifest.publisher !== "string") {
    validations.push([severity_default.Error, localize(1846, null)]);
    return validations;
  }
  if (typeof extensionManifest.name !== "string") {
    validations.push([severity_default.Error, localize(1847, null, "name")]);
    return validations;
  }
  if (typeof extensionManifest.version !== "string") {
    validations.push([severity_default.Error, localize(1848, null, "version")]);
    return validations;
  }
  if (!extensionManifest.engines) {
    validations.push([severity_default.Error, localize(1849, null, "engines")]);
    return validations;
  }
  if (typeof extensionManifest.engines.vscode !== "string") {
    validations.push([severity_default.Error, localize(1850, null, "engines.vscode")]);
    return validations;
  }
  if (typeof extensionManifest.extensionDependencies !== "undefined") {
    if (!isStringArray(extensionManifest.extensionDependencies)) {
      validations.push([severity_default.Error, localize(1851, null, "extensionDependencies")]);
      return validations;
    }
  }
  if (typeof extensionManifest.activationEvents !== "undefined") {
    if (!isStringArray(extensionManifest.activationEvents)) {
      validations.push([severity_default.Error, localize(1852, null, "activationEvents")]);
      return validations;
    }
    if (typeof extensionManifest.main === "undefined" && typeof extensionManifest.browser === "undefined") {
      validations.push([severity_default.Error, localize(1853, null, "activationEvents", "main", "browser")]);
      return validations;
    }
  }
  if (typeof extensionManifest.extensionKind !== "undefined") {
    if (typeof extensionManifest.main === "undefined") {
      validations.push([severity_default.Warning, localize(1854, null, "extensionKind")]);
    }
  }
  if (typeof extensionManifest.main !== "undefined") {
    if (typeof extensionManifest.main !== "string") {
      validations.push([severity_default.Error, localize(1855, null, "main")]);
      return validations;
    } else {
      const mainLocation = $Ah(extensionLocation, extensionManifest.main);
      if (!$uh(mainLocation, extensionLocation)) {
        validations.push([severity_default.Warning, localize(1856, null, mainLocation.path, extensionLocation.path)]);
      }
    }
  }
  if (typeof extensionManifest.browser !== "undefined") {
    if (typeof extensionManifest.browser !== "string") {
      validations.push([severity_default.Error, localize(1857, null, "browser")]);
      return validations;
    } else {
      const browserLocation = $Ah(extensionLocation, extensionManifest.browser);
      if (!$uh(browserLocation, extensionLocation)) {
        validations.push([severity_default.Warning, localize(1858, null, browserLocation.path, extensionLocation.path)]);
      }
    }
  }
  if (!valid(extensionManifest.version)) {
    validations.push([severity_default.Error, localize(1859, null)]);
    return validations;
  }
  const notices = [];
  const validExtensionVersion = $nq(productVersion, productDate, extensionManifest, extensionIsBuiltin, notices);
  if (!validExtensionVersion) {
    for (const notice of notices) {
      validations.push([severity_default.Error, notice]);
    }
  }
  if (validateApiVersion && extensionManifest.enabledApiProposals?.length) {
    const incompatibleNotices = [];
    if (!$pq([...extensionManifest.enabledApiProposals], incompatibleNotices)) {
      for (const notice of incompatibleNotices) {
        validations.push([severity_default.Error, notice]);
      }
    }
  }
  return validations;
}
function $nq(productVersion, productDate, extensionManifest, extensionIsBuiltin, notices) {
  if (extensionIsBuiltin || typeof extensionManifest.main === "undefined" && typeof extensionManifest.browser === "undefined") {
    return true;
  }
  return isVersionValid(productVersion, productDate, extensionManifest.engines.vscode, notices);
}
function $pq(apiProposals, arg1) {
  if (apiProposals.length === 0) {
    return true;
  }
  const notices = Array.isArray(arg1) ? arg1 : void 0;
  const productApiProposals = (notices ? void 0 : arg1) ?? allApiProposals;
  const incompatibleNotices = [];
  const parsedProposals = $Tn(apiProposals);
  for (const { proposalName, version } of parsedProposals) {
    const existingProposal = productApiProposals[proposalName];
    if (!existingProposal) {
      continue;
    }
    if (!version) {
      continue;
    }
    if (existingProposal.version !== version) {
      incompatibleNotices.push(localize(1860, null, proposalName));
    }
  }
  notices?.push(...incompatibleNotices);
  return incompatibleNotices.length === 0;
}
function isVersionValid(currentVersion, date, requestedVersion, notices = []) {
  const desiredVersion = $kq($jq(requestedVersion));
  if (!desiredVersion) {
    notices.push(localize(1861, null, requestedVersion));
    return false;
  }
  if (desiredVersion.majorBase === 0) {
    if (!desiredVersion.majorMustEqual || !desiredVersion.minorMustEqual) {
      notices.push(localize(1862, null, requestedVersion));
      return false;
    }
  } else {
    if (!desiredVersion.majorMustEqual) {
      notices.push(localize(1863, null, requestedVersion));
      return false;
    }
  }
  if (!$lq(currentVersion, date, desiredVersion)) {
    notices.push(localize(1864, null, currentVersion, requestedVersion));
    return false;
  }
  return true;
}
function isStringArray(arr) {
  if (!Array.isArray(arr)) {
    return false;
  }
  for (let i = 0, len = arr.length; i < len; i++) {
    if (typeof arr[i] !== "string") {
      return false;
    }
  }
  return true;
}

// out-build/vs/platform/extensionManagement/common/extensionNls.js
function $9q(logger, extensionManifest, translations, fallbackTranslations) {
  try {
    replaceNLStrings(logger, extensionManifest, translations, fallbackTranslations);
  } catch (error) {
    logger.error(error?.message ?? error);
  }
  return extensionManifest;
}
function replaceNLStrings(logger, extensionManifest, messages, originalMessages) {
  const processEntry = (obj, key, command) => {
    const value = obj[key];
    if ($yg(value)) {
      const str = value;
      const length = str.length;
      if (length > 1 && str[0] === "%" && str[length - 1] === "%") {
        const messageKey = str.substr(1, length - 2);
        let translated = messages[messageKey];
        if (translated === void 0 && originalMessages) {
          translated = originalMessages[messageKey];
        }
        const message = typeof translated === "string" ? translated : translated?.message;
        const original = originalMessages?.[messageKey];
        const originalMessage = typeof original === "string" ? original : original?.message;
        if (!message) {
          if (!originalMessage) {
            logger.warn(`[${extensionManifest.name}]: ${localize(1824, null, messageKey)}`);
          }
          return;
        }
        if (
          // if we are translating the title or category of a command
          command && (key === "title" || key === "category") && // and the original value is not the same as the translated value
          originalMessage && originalMessage !== message
        ) {
          const localizedString = {
            value: message,
            original: originalMessage
          };
          obj[key] = localizedString;
        } else {
          obj[key] = message;
        }
      }
    } else if ($Ag(value)) {
      for (const k in value) {
        if (value.hasOwnProperty(k)) {
          k === "commands" ? processEntry(value, k, true) : processEntry(value, k, command);
        }
      }
    } else if (Array.isArray(value)) {
      for (let i = 0; i < value.length; i++) {
        processEntry(value, i, command);
      }
    }
  };
  for (const key in extensionManifest) {
    if (extensionManifest.hasOwnProperty(key)) {
      processEntry(extensionManifest, key);
    }
  }
}

// out-build/vs/platform/extensionManagement/common/extensionsScannerService.js
var Translations;
(function(Translations2) {
  function equals(a, b) {
    if (a === b) {
      return true;
    }
    const aKeys = Object.keys(a);
    const bKeys = /* @__PURE__ */ new Set();
    for (const key of Object.keys(b)) {
      bKeys.add(key);
    }
    if (aKeys.length !== bKeys.size) {
      return false;
    }
    for (const key of aKeys) {
      if (a[key] !== b[key]) {
        return false;
      }
      bKeys.delete(key);
    }
    return bKeys.size === 0;
  }
  Translations2.equals = equals;
})(Translations || (Translations = {}));
var $0q = $Zi("IExtensionsScannerService");
var $$q = class $$q2 extends $0c {
  constructor(systemExtensionsLocation, userExtensionsLocation, r, s, t, u, w, y, z, C, D, F) {
    super();
    this.systemExtensionsLocation = systemExtensionsLocation;
    this.userExtensionsLocation = userExtensionsLocation;
    this.r = r;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.g = this.B(new $De());
    this.onDidChangeCache = this.g.event;
    this.h = $Ah(this.userExtensionsLocation, ".obsolete");
    this.j = this.B(this.F.createInstance(CachedExtensionsScanner, this.s, this.h));
    this.m = this.B(this.F.createInstance(CachedExtensionsScanner, this.s, this.h));
    this.n = this.B(this.F.createInstance(ExtensionsScanner, this.h));
    this.H = void 0;
    this.B(this.j.onDidChangeCache(() => this.g.fire(
      0
      /* ExtensionType.System */
    )));
    this.B(this.m.onDidChangeCache(() => this.g.fire(
      1
      /* ExtensionType.User */
    )));
  }
  getTargetPlatform() {
    if (!this.G) {
      this.G = $gq(this.w, this.y);
    }
    return this.G;
  }
  async scanAllExtensions(systemScanOptions, userScanOptions, includeExtensionsUnderDev) {
    const [system, user] = await Promise.all([
      this.scanSystemExtensions(systemScanOptions),
      this.scanUserExtensions(userScanOptions)
    ]);
    const development = includeExtensionsUnderDev ? await this.scanExtensionsUnderDevelopment(systemScanOptions, [...system, ...user]) : [];
    return this.L(system, user, development, await this.getTargetPlatform(), true);
  }
  async scanSystemExtensions(scanOptions) {
    const promises16 = [];
    promises16.push(this.M(!!scanOptions.useCache, scanOptions.language));
    promises16.push(this.N(scanOptions.language, !!scanOptions.checkControlFile));
    const [defaultSystemExtensions, devSystemExtensions] = await Promise.all(promises16);
    return this.J([...defaultSystemExtensions, ...devSystemExtensions], 0, scanOptions, false);
  }
  async scanUserExtensions(scanOptions) {
    const location = scanOptions.profileLocation ?? this.userExtensionsLocation;
    this.y.trace("Started scanning user extensions", location);
    const profileScanOptions = this.D.extUri.isEqual(scanOptions.profileLocation, this.t.defaultProfile.extensionsResource) ? { bailOutWhenFileNotFound: true } : void 0;
    const extensionsScannerInput = await this.P(location, !!scanOptions.profileLocation, 1, !scanOptions.includeUninstalled, scanOptions.language, true, profileScanOptions, scanOptions.productVersion ?? this.R());
    const extensionsScanner = scanOptions.useCache && !extensionsScannerInput.devMode && extensionsScannerInput.excludeObsolete ? this.m : this.n;
    let extensions;
    try {
      extensions = await extensionsScanner.scanExtensions(extensionsScannerInput);
    } catch (error) {
      if (error instanceof $5q && error.code === "ERROR_PROFILE_NOT_FOUND") {
        await this.I();
        extensions = await extensionsScanner.scanExtensions(extensionsScannerInput);
      } else {
        throw error;
      }
    }
    extensions = await this.J(extensions, 1, scanOptions, true);
    this.y.trace("Scanned user extensions:", extensions.length);
    return extensions;
  }
  async scanExtensionsUnderDevelopment(scanOptions, existingExtensions) {
    if (this.z.isExtensionDevelopment && this.z.extensionDevelopmentLocationURI) {
      const extensions = (await Promise.all(this.z.extensionDevelopmentLocationURI.filter((extLoc) => extLoc.scheme === Schemas.file).map(async (extensionDevelopmentLocationURI) => {
        const input = await this.P(extensionDevelopmentLocationURI, false, 1, true, scanOptions.language, false, void 0, scanOptions.productVersion ?? this.R());
        const extensions2 = await this.n.scanOneOrMultipleExtensions(input);
        return extensions2.map((extension) => {
          extension.type = existingExtensions.find((e) => $8p(e.identifier, extension.identifier))?.type ?? extension.type;
          return this.n.validate(extension, input);
        });
      }))).flat();
      return this.J(extensions, "development", scanOptions, true);
    }
    return [];
  }
  async scanExistingExtension(extensionLocation, extensionType, scanOptions) {
    const extensionsScannerInput = await this.P(extensionLocation, false, extensionType, true, scanOptions.language, true, void 0, scanOptions.productVersion ?? this.R());
    const extension = await this.n.scanExtension(extensionsScannerInput);
    if (!extension) {
      return null;
    }
    if (!scanOptions.includeInvalid && !extension.isValid) {
      return null;
    }
    return extension;
  }
  async scanOneOrMultipleExtensions(extensionLocation, extensionType, scanOptions) {
    const extensionsScannerInput = await this.P(extensionLocation, false, extensionType, true, scanOptions.language, true, void 0, scanOptions.productVersion ?? this.R());
    const extensions = await this.n.scanOneOrMultipleExtensions(extensionsScannerInput);
    return this.J(extensions, extensionType, scanOptions, true);
  }
  async scanMultipleExtensions(extensionLocations, extensionType, scanOptions) {
    const extensions = [];
    await Promise.all(extensionLocations.map(async (extensionLocation) => {
      const scannedExtensions = await this.scanOneOrMultipleExtensions(extensionLocation, extensionType, scanOptions);
      extensions.push(...scannedExtensions);
    }));
    return this.J(extensions, extensionType, scanOptions, true);
  }
  async scanMetadata(extensionLocation) {
    const manifestLocation = $Ah(extensionLocation, "package.json");
    const content = (await this.w.readFile(manifestLocation)).value.toString();
    const manifest = JSON.parse(content);
    return manifest.__metadata;
  }
  async updateMetadata(extensionLocation, metaData) {
    const manifestLocation = $Ah(extensionLocation, "package.json");
    const content = (await this.w.readFile(manifestLocation)).value.toString();
    const manifest = JSON.parse(content);
    if (metaData.isMachineScoped === false) {
      delete metaData.isMachineScoped;
    }
    if (metaData.isBuiltin === false) {
      delete metaData.isBuiltin;
    }
    manifest.__metadata = { ...manifest.__metadata, ...metaData };
    await this.w.writeFile($Ah(extensionLocation, "package.json"), $7e.fromString(JSON.stringify(manifest, null, "	")));
  }
  async initializeDefaultProfileExtensions() {
    try {
      await this.u.scanProfileExtensions(this.t.defaultProfile.extensionsResource, { bailOutWhenFileNotFound: true });
    } catch (error) {
      if (error instanceof $5q && error.code === "ERROR_PROFILE_NOT_FOUND") {
        await this.I();
      } else {
        throw error;
      }
    }
  }
  async I() {
    if (!this.H) {
      this.H = (async () => {
        try {
          this.y.info("Started initializing default profile extensions in extensions installation folder.", this.userExtensionsLocation.toString());
          const userExtensions = await this.scanUserExtensions({ includeInvalid: true });
          if (userExtensions.length) {
            await this.u.addExtensionsToProfile(userExtensions.map((e) => [e, e.metadata]), this.t.defaultProfile.extensionsResource);
          } else {
            try {
              await this.w.createFile(this.t.defaultProfile.extensionsResource, $7e.fromString(JSON.stringify([])));
            } catch (error) {
              if ($Ll(error) !== 1) {
                this.y.warn("Failed to create default profile extensions manifest in extensions installation folder.", this.userExtensionsLocation.toString(), $kb(error));
              }
            }
          }
          this.y.info("Completed initializing default profile extensions in extensions installation folder.", this.userExtensionsLocation.toString());
        } catch (error) {
          this.y.error(error);
        } finally {
          this.H = void 0;
        }
      })();
    }
    return this.H;
  }
  async J(extensions, type4, scanOptions, pickLatest) {
    if (!scanOptions.includeAllVersions) {
      extensions = this.L(type4 === 0 ? extensions : void 0, type4 === 1 ? extensions : void 0, type4 === "development" ? extensions : void 0, await this.getTargetPlatform(), pickLatest);
    }
    if (!scanOptions.includeInvalid) {
      extensions = extensions.filter((extension) => extension.isValid);
    }
    return extensions.sort((a, b) => {
      const aLastSegment = $zc(a.location.fsPath);
      const bLastSegment = $zc(b.location.fsPath);
      if (aLastSegment < bLastSegment) {
        return -1;
      }
      if (aLastSegment > bLastSegment) {
        return 1;
      }
      return 0;
    });
  }
  L(system, user, development, targetPlatform, pickLatest) {
    const pick = (existing, extension, isDevelopment) => {
      if (existing.isValid && !extension.isValid) {
        return false;
      }
      if (existing.isValid === extension.isValid) {
        if (pickLatest && gt(existing.manifest.version, extension.manifest.version)) {
          this.y.debug(`Skipping extension ${extension.location.path} with lower version ${extension.manifest.version} in favour of ${existing.location.path} with version ${existing.manifest.version}`);
          return false;
        }
        if (eq(existing.manifest.version, extension.manifest.version)) {
          if (existing.type === 0) {
            this.y.debug(`Skipping extension ${extension.location.path} in favour of system extension ${existing.location.path} with same version`);
            return false;
          }
          if (existing.targetPlatform === targetPlatform) {
            this.y.debug(`Skipping extension ${extension.location.path} from different target platform ${extension.targetPlatform}`);
            return false;
          }
        }
      }
      if (isDevelopment) {
        this.y.warn(`Overwriting user extension ${existing.location.path} with ${extension.location.path}.`);
      } else {
        this.y.debug(`Overwriting user extension ${existing.location.path} with ${extension.location.path}.`);
      }
      return true;
    };
    const result = new $On();
    system?.forEach((extension) => {
      const existing = result.get(extension.identifier.id);
      if (!existing || pick(existing, extension, false)) {
        result.set(extension.identifier.id, extension);
      }
    });
    user?.forEach((extension) => {
      const existing = result.get(extension.identifier.id);
      if (!existing && system && extension.type === 0) {
        this.y.debug(`Skipping obsolete system extension ${extension.location.path}.`);
        return;
      }
      if (!existing || pick(existing, extension, false)) {
        result.set(extension.identifier.id, extension);
      }
    });
    development?.forEach((extension) => {
      const existing = result.get(extension.identifier.id);
      if (!existing || pick(existing, extension, true)) {
        result.set(extension.identifier.id, extension);
      }
      result.set(extension.identifier.id, extension);
    });
    return [...result.values()];
  }
  async M(useCache, language) {
    this.y.trace("Started scanning system extensions");
    const extensionsScannerInput = await this.P(this.systemExtensionsLocation, false, 0, true, language, true, void 0, this.R());
    const extensionsScanner = useCache && !extensionsScannerInput.devMode ? this.j : this.n;
    const result = await extensionsScanner.scanExtensions(extensionsScannerInput);
    this.y.trace("Scanned system extensions:", result.length);
    return result;
  }
  async N(language, checkControlFile) {
    const devSystemExtensionsList = this.z.isBuilt ? [] : this.C.builtInExtensions;
    if (!devSystemExtensionsList?.length) {
      return [];
    }
    this.y.trace("Started scanning dev system extensions");
    const builtinExtensionControl = checkControlFile ? await this.O() : {};
    const devSystemExtensionsLocations = [];
    const devSystemExtensionsLocation = URI.file($tc($vc($hh.asFileUri("").fsPath, "..", ".build", "builtInExtensions")));
    for (const extension of devSystemExtensionsList) {
      const controlState = builtinExtensionControl[extension.name] || "marketplace";
      switch (controlState) {
        case "disabled":
          break;
        case "marketplace":
          devSystemExtensionsLocations.push($Ah(devSystemExtensionsLocation, extension.name));
          break;
        default:
          devSystemExtensionsLocations.push(URI.file(controlState));
          break;
      }
    }
    const result = await Promise.all(devSystemExtensionsLocations.map(async (location) => this.n.scanExtension(await this.P(location, false, 0, true, language, true, void 0, this.R()))));
    this.y.trace("Scanned dev system extensions:", result.length);
    return $Ub(result);
  }
  async O() {
    try {
      const content = await this.w.readFile(this.r);
      return JSON.parse(content.value.toString());
    } catch (error) {
      return {};
    }
  }
  async P(location, profile, type4, excludeObsolete, language, validate, profileScanOptions, productVersion) {
    const translations = await this.f(language ?? $z);
    const mtime = await this.Q(location);
    const applicationExtensionsLocation = profile && !this.D.extUri.isEqual(location, this.t.defaultProfile.extensionsResource) ? this.t.defaultProfile.extensionsResource : void 0;
    const applicationExtensionsLocationMtime = applicationExtensionsLocation ? await this.Q(applicationExtensionsLocation) : void 0;
    return new $_q(location, mtime, applicationExtensionsLocation, applicationExtensionsLocationMtime, profile, profileScanOptions, type4, excludeObsolete, validate, productVersion.version, productVersion.date, this.C.commit, !this.z.isBuilt, language, translations);
  }
  async Q(location) {
    try {
      const stat = await this.w.stat(location);
      if (typeof stat.mtime === "number") {
        return stat.mtime;
      }
    } catch (err) {
    }
    return void 0;
  }
  R() {
    return {
      version: this.C.version,
      date: this.C.date
    };
  }
};
$$q = __decorate([
  __param(4, $7l),
  __param(5, $6q),
  __param(6, $ul),
  __param(7, $uk),
  __param(8, $7i),
  __param(9, $Nk),
  __param(10, $5l),
  __param(11, $Yi)
], $$q);
var $_q = class {
  constructor(location, mtime, applicationExtensionslocation, applicationExtensionslocationMtime, profile, profileScanOptions, type4, excludeObsolete, validate, productVersion, productDate, productCommit, devMode, language, translations) {
    this.location = location;
    this.mtime = mtime;
    this.applicationExtensionslocation = applicationExtensionslocation;
    this.applicationExtensionslocationMtime = applicationExtensionslocationMtime;
    this.profile = profile;
    this.profileScanOptions = profileScanOptions;
    this.type = type4;
    this.excludeObsolete = excludeObsolete;
    this.validate = validate;
    this.productVersion = productVersion;
    this.productDate = productDate;
    this.productCommit = productCommit;
    this.devMode = devMode;
    this.language = language;
    this.translations = translations;
  }
  static createNlsConfiguration(input) {
    return {
      language: input.language,
      pseudo: input.language === "pseudo",
      devMode: input.devMode,
      translations: input.translations
    };
  }
  static equals(a, b) {
    return $th(a.location, b.location) && a.mtime === b.mtime && $th(a.applicationExtensionslocation, b.applicationExtensionslocation) && a.applicationExtensionslocationMtime === b.applicationExtensionslocationMtime && a.profile === b.profile && $Do(a.profileScanOptions, b.profileScanOptions) && a.type === b.type && a.excludeObsolete === b.excludeObsolete && a.validate === b.validate && a.productVersion === b.productVersion && a.productDate === b.productDate && a.productCommit === b.productCommit && a.devMode === b.devMode && a.language === b.language && Translations.equals(a.translations, b.translations);
  }
};
var ExtensionsScanner = class ExtensionsScanner2 extends $0c {
  constructor(g, h, j, m, productService, n, r) {
    super();
    this.g = g;
    this.h = h;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r;
    this.f = productService.extensionsEnabledWithApiProposalVersion?.map((id2) => id2.toLowerCase()) ?? [];
  }
  async scanExtensions(input) {
    const extensions = input.profile ? await this.t(input) : await this.s(input);
    let obsolete = {};
    if (input.excludeObsolete && input.type === 1) {
      try {
        const raw = (await this.m.readFile(this.g)).value.toString();
        obsolete = JSON.parse(raw);
      } catch (error) {
      }
    }
    return $Lg(obsolete) ? extensions : extensions.filter((e) => !obsolete[$9p.create(e).toString()]);
  }
  async s(input) {
    const stat = await this.m.resolve(input.location);
    if (!stat.children?.length) {
      return [];
    }
    const extensions = await Promise.all(stat.children.map(async (c) => {
      if (!c.isDirectory) {
        return null;
      }
      if (input.type === 1 && $xh(c.resource).indexOf(".") === 0) {
        return null;
      }
      const extensionScannerInput = new $_q(c.resource, input.mtime, input.applicationExtensionslocation, input.applicationExtensionslocationMtime, input.profile, input.profileScanOptions, input.type, input.excludeObsolete, input.validate, input.productVersion, input.productDate, input.productCommit, input.devMode, input.language, input.translations);
      return this.scanExtension(extensionScannerInput);
    }));
    return $Ub(extensions).sort((a, b) => a.location.path < b.location.path ? -1 : 1);
  }
  async t(input) {
    let profileExtensions = await this.u(input.location, () => true, input);
    if (input.applicationExtensionslocation && !this.j.extUri.isEqual(input.location, input.applicationExtensionslocation)) {
      profileExtensions = profileExtensions.filter((e) => !e.metadata?.isApplicationScoped);
      const applicationExtensions = await this.u(input.applicationExtensionslocation, (e) => !!e.metadata?.isBuiltin || !!e.metadata?.isApplicationScoped, input);
      profileExtensions.push(...applicationExtensions);
    }
    return profileExtensions;
  }
  async u(profileResource, filter, input) {
    const scannedProfileExtensions = await this.h.scanProfileExtensions(profileResource, input.profileScanOptions);
    if (!scannedProfileExtensions.length) {
      return [];
    }
    const extensions = await Promise.all(scannedProfileExtensions.map(async (extensionInfo) => {
      if (filter(extensionInfo)) {
        const extensionScannerInput = new $_q(extensionInfo.location, input.mtime, input.applicationExtensionslocation, input.applicationExtensionslocationMtime, input.profile, input.profileScanOptions, input.type, input.excludeObsolete, input.validate, input.productVersion, input.productDate, input.productCommit, input.devMode, input.language, input.translations);
        return this.scanExtension(extensionScannerInput, extensionInfo.metadata);
      }
      return null;
    }));
    return $Ub(extensions);
  }
  async scanOneOrMultipleExtensions(input) {
    try {
      if (await this.m.exists($Ah(input.location, "package.json"))) {
        const extension = await this.scanExtension(input);
        return extension ? [extension] : [];
      } else {
        return await this.scanExtensions(input);
      }
    } catch (error) {
      this.r.error(`Error scanning extensions at ${input.location.path}:`, $kb(error));
      return [];
    }
  }
  async scanExtension(input, metadata) {
    try {
      let manifest = await this.w(input.location);
      if (manifest) {
        if (!manifest.publisher) {
          manifest.publisher = $In;
        }
        metadata = metadata ?? manifest.__metadata;
        delete manifest.__metadata;
        const id2 = $aq(manifest.publisher, manifest.name);
        const identifier = metadata?.id ? { id: id2, uuid: metadata.id } : { id: id2 };
        const type4 = metadata?.isSystem ? 0 : input.type;
        const isBuiltin = type4 === 0 || !!metadata?.isBuiltin;
        manifest = await this.y(input.location, manifest, $_q.createNlsConfiguration(input));
        let extension = {
          type: type4,
          identifier,
          manifest,
          location: input.location,
          isBuiltin,
          targetPlatform: metadata?.targetPlatform ?? "undefined",
          publisherDisplayName: metadata?.publisherDisplayName,
          metadata,
          isValid: true,
          validations: []
        };
        if (input.validate) {
          extension = this.validate(extension, input);
        }
        if (manifest.enabledApiProposals && (!this.n.isBuilt || this.f.includes(id2.toLowerCase()))) {
          manifest.originalEnabledApiProposals = manifest.enabledApiProposals;
          manifest.enabledApiProposals = $Un([...manifest.enabledApiProposals]);
        }
        return extension;
      }
    } catch (e) {
      if (input.type !== 0) {
        this.r.error(e);
      }
    }
    return null;
  }
  validate(extension, input) {
    let isValid = true;
    const validateApiVersion = this.n.isBuilt && this.f.includes(extension.identifier.id.toLowerCase());
    const validations = $mq(input.productVersion, input.productDate, input.location, extension.manifest, extension.isBuiltin, validateApiVersion);
    for (const [severity, message] of validations) {
      if (severity === severity_default.Error) {
        isValid = false;
        this.r.error(this.F(input.location, message));
      }
    }
    extension.isValid = isValid;
    extension.validations = validations;
    return extension;
  }
  async w(extensionLocation) {
    const manifestLocation = $Ah(extensionLocation, "package.json");
    let content;
    try {
      content = (await this.m.readFile(manifestLocation)).value.toString();
    } catch (error) {
      if ($Ll(error) !== 1) {
        this.r.error(this.F(extensionLocation, localize(1825, null, manifestLocation.path, error.message)));
      }
      return null;
    }
    let manifest;
    try {
      manifest = JSON.parse(content);
    } catch (err) {
      const errors = [];
      $ho(content, errors);
      for (const e of errors) {
        this.r.error(this.F(extensionLocation, localize(1826, null, manifestLocation.path, e.offset, e.length, $8q(e.error))));
      }
      return null;
    }
    if ($po(manifest) !== "object") {
      this.r.error(this.F(extensionLocation, localize(1827, null, manifestLocation.path)));
      return null;
    }
    return manifest;
  }
  async y(extensionLocation, extensionManifest, nlsConfiguration) {
    const localizedMessages = await this.z(extensionLocation, extensionManifest, nlsConfiguration);
    if (localizedMessages) {
      try {
        const errors = [];
        const defaults = await this.C(localizedMessages.default, errors);
        if (errors.length > 0) {
          errors.forEach((error) => {
            this.r.error(this.F(extensionLocation, localize(1828, null, localizedMessages.default?.path, $8q(error.error))));
          });
          return extensionManifest;
        } else if ($po(localizedMessages) !== "object") {
          this.r.error(this.F(extensionLocation, localize(1829, null, localizedMessages.default?.path)));
          return extensionManifest;
        }
        const localized = localizedMessages.values || /* @__PURE__ */ Object.create(null);
        return $9q(this.r, extensionManifest, localized, defaults);
      } catch (error) {
      }
    }
    return extensionManifest;
  }
  async z(extensionLocation, extensionManifest, nlsConfiguration) {
    const defaultPackageNLS = $Ah(extensionLocation, "package.nls.json");
    const reportErrors = (localized, errors) => {
      errors.forEach((error) => {
        this.r.error(this.F(extensionLocation, localize(1830, null, localized?.path, $8q(error.error))));
      });
    };
    const reportInvalidFormat = (localized) => {
      this.r.error(this.F(extensionLocation, localize(1831, null, localized?.path)));
    };
    const translationId = `${extensionManifest.publisher}.${extensionManifest.name}`;
    const translationPath = nlsConfiguration.translations[translationId];
    if (translationPath) {
      try {
        const translationResource = URI.file(translationPath);
        const content = (await this.m.readFile(translationResource)).value.toString();
        const errors = [];
        const translationBundle = $ho(content, errors);
        if (errors.length > 0) {
          reportErrors(translationResource, errors);
          return { values: void 0, default: defaultPackageNLS };
        } else if ($po(translationBundle) !== "object") {
          reportInvalidFormat(translationResource);
          return { values: void 0, default: defaultPackageNLS };
        } else {
          const values = translationBundle.contents ? translationBundle.contents.package : void 0;
          return { values, default: defaultPackageNLS };
        }
      } catch (error) {
        return { values: void 0, default: defaultPackageNLS };
      }
    } else {
      const exists = await this.m.exists(defaultPackageNLS);
      if (!exists) {
        return void 0;
      }
      let messageBundle;
      try {
        messageBundle = await this.D(extensionLocation, nlsConfiguration);
      } catch (error) {
        return void 0;
      }
      if (!messageBundle.localized) {
        return { values: void 0, default: messageBundle.original };
      }
      try {
        const messageBundleContent = (await this.m.readFile(messageBundle.localized)).value.toString();
        const errors = [];
        const messages = $ho(messageBundleContent, errors);
        if (errors.length > 0) {
          reportErrors(messageBundle.localized, errors);
          return { values: void 0, default: messageBundle.original };
        } else if ($po(messages) !== "object") {
          reportInvalidFormat(messageBundle.localized);
          return { values: void 0, default: messageBundle.original };
        }
        return { values: messages, default: messageBundle.original };
      } catch (error) {
        return { values: void 0, default: messageBundle.original };
      }
    }
  }
  /**
   * Parses original message bundle, returns null if the original message bundle is null.
   */
  async C(originalMessageBundle, errors) {
    if (originalMessageBundle) {
      try {
        const originalBundleContent = (await this.m.readFile(originalMessageBundle)).value.toString();
        return $ho(originalBundleContent, errors);
      } catch (error) {
      }
    }
    return;
  }
  /**
   * Finds localized message bundle and the original (unlocalized) one.
   * If the localized file is not present, returns null for the original and marks original as localized.
   */
  D(extensionLocation, nlsConfiguration) {
    return new Promise((c, e) => {
      const loop = (locale) => {
        const toCheck = $Ah(extensionLocation, `package.nls.${locale}.json`);
        this.m.exists(toCheck).then((exists) => {
          if (exists) {
            c({ localized: toCheck, original: $Ah(extensionLocation, "package.nls.json") });
          }
          const index = locale.lastIndexOf("-");
          if (index === -1) {
            c({ localized: $Ah(extensionLocation, "package.nls.json"), original: null });
          } else {
            locale = locale.substring(0, index);
            loop(locale);
          }
        });
      };
      if (nlsConfiguration.devMode || nlsConfiguration.pseudo || !nlsConfiguration.language) {
        return c({ localized: $Ah(extensionLocation, "package.nls.json"), original: null });
      }
      loop(nlsConfiguration.language);
    });
  }
  F(extensionLocation, message) {
    return `[${extensionLocation.path}]: ${message}`;
  }
};
ExtensionsScanner = __decorate([
  __param(1, $6q),
  __param(2, $5l),
  __param(3, $ul),
  __param(4, $Nk),
  __param(5, $7i),
  __param(6, $uk)
], ExtensionsScanner);
var CachedExtensionsScanner = class CachedExtensionsScanner2 extends ExtensionsScanner {
  constructor(J, obsoleteFile, L, extensionsProfileScannerService, uriIdentityService, fileService, productService, environmentService, logService) {
    super(obsoleteFile, extensionsProfileScannerService, uriIdentityService, fileService, productService, environmentService, logService);
    this.J = J;
    this.L = L;
    this.H = this.B(new $Xh(3e3));
    this.I = this.B(new $De());
    this.onDidChangeCache = this.I.event;
  }
  async scanExtensions(input) {
    const cacheFile = this.P(input);
    const cacheContents = await this.M(cacheFile);
    this.G = input;
    if (cacheContents && cacheContents.input && $_q.equals(cacheContents.input, this.G)) {
      this.r.debug("Using cached extensions scan result", input.type === 0 ? "system" : "user", input.location.toString());
      this.H.trigger(() => this.O());
      return cacheContents.result.map((extension) => {
        extension.location = URI.revive(extension.location);
        return extension;
      });
    }
    const result = await super.scanExtensions(input);
    await this.N(cacheFile, { input, result });
    return result;
  }
  async M(cacheFile) {
    try {
      const cacheRawContents = await this.m.readFile(cacheFile);
      const extensionCacheData = JSON.parse(cacheRawContents.value.toString());
      return { result: extensionCacheData.result, input: $wi(extensionCacheData.input) };
    } catch (error) {
      this.r.debug("Error while reading the extension cache file:", cacheFile.path, $kb(error));
    }
    return null;
  }
  async N(cacheFile, cacheContents) {
    try {
      await this.m.writeFile(cacheFile, $7e.fromString(JSON.stringify(cacheContents)));
    } catch (error) {
      this.r.debug("Error while writing the extension cache file:", cacheFile.path, $kb(error));
    }
  }
  async O() {
    if (!this.G) {
      return;
    }
    const cacheFile = this.P(this.G);
    const cacheContents = await this.M(cacheFile);
    if (!cacheContents) {
      return;
    }
    const actual = cacheContents.result;
    const expected = JSON.parse(JSON.stringify(await super.scanExtensions(this.G)));
    if ($Do(expected, actual)) {
      return;
    }
    try {
      this.r.info("Invalidating Cache", actual, expected);
      await this.m.del(cacheFile);
      this.I.fire();
    } catch (error) {
      this.r.error(error);
    }
  }
  P(input) {
    const profile = this.Q(input);
    return this.j.extUri.joinPath(profile.cacheHome, input.type === 0 ? $Hn : $Gn);
  }
  Q(input) {
    if (input.type === 0) {
      return this.L.defaultProfile;
    }
    if (!input.profile) {
      return this.L.defaultProfile;
    }
    if (this.j.extUri.isEqual(input.location, this.J.extensionsResource)) {
      return this.J;
    }
    return this.L.profiles.find((p) => this.j.extUri.isEqual(input.location, p.extensionsResource)) ?? this.J;
  }
};
CachedExtensionsScanner = __decorate([
  __param(2, $7l),
  __param(3, $6q),
  __param(4, $5l),
  __param(5, $ul),
  __param(6, $Nk),
  __param(7, $7i),
  __param(8, $uk)
], CachedExtensionsScanner);
var $br = class extends $$q {
  constructor(systemExtensionsLocation, userExtensionsLocation, userHome, currentProfile, userDataProfilesService, extensionsProfileScannerService, fileService, logService, environmentService, productService, uriIdentityService, instantiationService) {
    super(systemExtensionsLocation, userExtensionsLocation, $Ah(userHome, ".vscode-oss-dev", "extensions", "control.json"), currentProfile, userDataProfilesService, extensionsProfileScannerService, fileService, logService, environmentService, productService, uriIdentityService, instantiationService);
    this.S = (async () => {
      if ($C) {
        try {
          const content = await this.w.readFile(URI.file($C));
          return JSON.parse(content.value.toString());
        } catch (err) {
        }
      }
      return /* @__PURE__ */ Object.create(null);
    })();
  }
  f(language) {
    return this.S;
  }
};

// out-build/vs/platform/extensionManagement/node/extensionsScannerService.js
var $mlc = class $mlc2 extends $br {
  constructor(userDataProfilesService, extensionsProfileScannerService, fileService, logService, environmentService, productService, uriIdentityService, instantiationService) {
    super(URI.file(environmentService.builtinExtensionsPath), URI.file(environmentService.extensionsPath), environmentService.userHome, userDataProfilesService.defaultProfile, userDataProfilesService, extensionsProfileScannerService, fileService, logService, environmentService, productService, uriIdentityService, instantiationService);
  }
};
$mlc = __decorate([
  __param(0, $7l),
  __param(1, $6q),
  __param(2, $ul),
  __param(3, $uk),
  __param(4, $8i),
  __param(5, $Nk),
  __param(6, $5l),
  __param(7, $Yi)
], $mlc);

// out-build/vs/platform/userDataProfile/electron-main/userDataProfilesHandler.js
var $nlc = class $nlc2 extends $0c {
  constructor(lifecycleMainService, a, b) {
    super();
    this.a = a;
    this.b = b;
    this.B(lifecycleMainService.onWillLoadWindow((e) => {
      if (e.reason === 2) {
        this.c(e.window);
      }
    }));
    this.B(lifecycleMainService.onBeforeCloseWindow((window2) => this.c(window2)));
    this.B(new $_h(
      () => this.g(),
      30 * 1e3
      /* after 30s */
    )).schedule();
  }
  async c(window2) {
    const workspace = this.f(window2);
    const profile = this.a.getProfileForWorkspace(workspace);
    if (profile?.isTransient) {
      this.a.unsetWorkspace(workspace, profile.isTransient);
      if (profile.isTransient) {
        await this.a.cleanUpTransientProfiles();
      }
    }
  }
  f(window2) {
    return window2.openedWorkspace ?? $bj(window2.backupPath, window2.isExtensionDevelopmentHost);
  }
  g() {
    const associatedEmptyWindows = this.a.getAssociatedEmptyWindows();
    if (associatedEmptyWindows.length === 0) {
      return;
    }
    const openedWorkspaces = this.b.getWindows().map((window2) => this.f(window2));
    for (const associatedEmptyWindow of associatedEmptyWindows) {
      if (openedWorkspaces.some((openedWorkspace) => openedWorkspace.id === associatedEmptyWindow.id)) {
        continue;
      }
      this.a.unsetWorkspace(associatedEmptyWindow, false);
    }
  }
};
$nlc = __decorate([
  __param(0, $9jc),
  __param(1, $Sjc),
  __param(2, $Pjc)
], $nlc);

// out-build/vs/platform/userDataProfile/electron-main/userDataProfileStorageIpc.js
var $olc = class extends $0c {
  constructor(b, c, f) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    const disposable = this.B(new $$c());
    this.a = this.B(new $De({
      // Start listening to profile storage changes only when someone is listening
      onWillAddFirstListener: () => disposable.value = this.g(),
      // Stop listening to profile storage changes when no one is listening
      onDidRemoveLastListener: () => disposable.value = void 0
    }));
  }
  g() {
    this.f.debug("ProfileStorageChangesListenerChannel#registerStorageChangeListeners");
    const disposables = new $9c();
    disposables.add(Event.debounce(this.b.applicationStorage.onDidChangeStorage, (keys, e) => {
      if (keys) {
        keys.push(e.key);
      } else {
        keys = [e.key];
      }
      return keys;
    }, 100)((keys) => this.h(keys)));
    disposables.add(Event.debounce(this.b.onDidChangeProfileStorage, (changes, e) => {
      if (!changes) {
        changes = /* @__PURE__ */ new Map();
      }
      let profileChanges = changes.get(e.profile.id);
      if (!profileChanges) {
        changes.set(e.profile.id, profileChanges = { profile: e.profile, keys: [], storage: e.storage });
      }
      profileChanges.keys.push(e.key);
      return changes;
    }, 100)((keys) => this.j(keys)));
    return disposables;
  }
  h(keys) {
    const targetChangedProfiles = keys.includes($Cq) ? [this.c.defaultProfile] : [];
    const profileStorageValueChanges = [];
    keys = keys.filter((key) => key !== $Cq);
    if (keys.length) {
      const keyTargets = $Eq(this.b.applicationStorage.storage);
      profileStorageValueChanges.push({ profile: this.c.defaultProfile, changes: keys.map((key) => ({ key, scope: 0, target: keyTargets[key] })) });
    }
    this.m(targetChangedProfiles, profileStorageValueChanges);
  }
  j(changes) {
    const targetChangedProfiles = [];
    const profileStorageValueChanges = /* @__PURE__ */ new Map();
    for (const [profileId, profileChanges] of changes.entries()) {
      if (profileChanges.keys.includes($Cq)) {
        targetChangedProfiles.push(profileChanges.profile);
      }
      const keys = profileChanges.keys.filter((key) => key !== $Cq);
      if (keys.length) {
        const keyTargets = $Eq(profileChanges.storage.storage);
        profileStorageValueChanges.set(profileId, { profile: profileChanges.profile, changes: keys.map((key) => ({ key, scope: 0, target: keyTargets[key] })) });
      }
    }
    this.m(targetChangedProfiles, [...profileStorageValueChanges.values()]);
  }
  m(targetChanges, valueChanges) {
    if (targetChanges.length || valueChanges.length) {
      this.a.fire({ valueChanges, targetChanges });
    }
  }
  listen(_, event, arg) {
    switch (event) {
      case "onDidChange":
        return this.a.event;
    }
    throw new Error(`[ProfileStorageChangesListenerChannel] Event not found: ${event}`);
  }
  async call(_, command) {
    throw new Error(`Call not found: ${command}`);
  }
};

// out-build/vs/platform/telemetry/node/telemetryUtils.js
async function $plc(stateService, logService) {
  let machineId2 = stateService.getItem($ym);
  if (typeof machineId2 !== "string" || $m && machineId2 === "6c9d2bc8f91b89624add29c0abeae7fb42bf539fa1cdb2e3e57cd668fa9bcead") {
    machineId2 = await $co(logService.error.bind(logService));
  }
  return machineId2;
}
async function $qlc(stateService, logService) {
  let sqmId = stateService.getItem($zm);
  if (typeof sqmId !== "string") {
    sqmId = await $do(logService.error.bind(logService));
  }
  return sqmId;
}
async function $rlc(stateService, logService) {
  let devDeviceId = stateService.getItem($Am);
  if (typeof devDeviceId !== "string") {
    devDeviceId = await $eo(logService.error.bind(logService));
  }
  return devDeviceId;
}

// out-build/vs/platform/telemetry/electron-main/telemetryUtils.js
async function $slc(stateService, logService) {
  const machineId2 = await $plc(stateService, logService);
  stateService.setItem($ym, machineId2);
  return machineId2;
}
async function $tlc(stateService, logService) {
  const sqmId = await $qlc(stateService, logService);
  stateService.setItem($zm, sqmId);
  return sqmId;
}
async function $ulc(stateService, logService) {
  const devDeviceId = await $rlc(stateService, logService);
  stateService.setItem($Am, devDeviceId);
  return devDeviceId;
}

// out-build/vs/platform/extensionManagement/node/extensionsProfileScannerService.js
var $IS = class $IS2 extends $7q {
  constructor(environmentService, fileService, userDataProfilesService, uriIdentityService, telemetryService, logService) {
    super(URI.file(environmentService.extensionsPath), fileService, userDataProfilesService, uriIdentityService, telemetryService, logService);
  }
};
$IS = __decorate([
  __param(0, $8i),
  __param(1, $ul),
  __param(2, $7l),
  __param(3, $5l),
  __param(4, $tm),
  __param(5, $uk)
], $IS);

// out-build/vs/platform/log/electron-main/logIpc.js
var $vlc = class {
  constructor(b) {
    this.b = b;
    this.a = new $Mc();
  }
  listen(_, event, windowId) {
    switch (event) {
      case "onDidChangeLoggers":
        return windowId ? this.b.getOnDidChangeLoggersEvent(windowId) : this.b.onDidChangeLoggers;
      case "onDidChangeLogLevel":
        return windowId ? this.b.getOnDidChangeLogLevelEvent(windowId) : this.b.onDidChangeLogLevel;
      case "onDidChangeVisibility":
        return windowId ? this.b.getOnDidChangeVisibilityEvent(windowId) : this.b.onDidChangeVisibility;
    }
    throw new Error(`Event not found: ${event}`);
  }
  async call(_, command, arg) {
    switch (command) {
      case "createLogger":
        this.c(URI.revive(arg[0]), arg[1], arg[2]);
        return;
      case "log":
        return this.e(URI.revive(arg[0]), arg[1]);
      case "consoleLog":
        return this.d(arg[0], arg[1]);
      case "setLogLevel":
        return $wk(arg[0]) ? this.b.setLogLevel(arg[0]) : this.b.setLogLevel(URI.revive(arg[0]), arg[1]);
      case "setVisibility":
        return this.b.setVisibility(URI.revive(arg[0]), arg[1]);
      case "registerLogger":
        return this.b.registerLogger({ ...arg[0], resource: URI.revive(arg[0].resource) }, arg[1]);
      case "deregisterLogger":
        return this.b.deregisterLogger(URI.revive(arg[0]));
    }
    throw new Error(`Call not found: ${command}`);
  }
  c(file, options, windowId) {
    this.a.set(file, this.b.createLogger(file, options, windowId));
  }
  d(level, args) {
    let consoleFn = console.log;
    switch (level) {
      case LogLevel.Error:
        consoleFn = console.error;
        break;
      case LogLevel.Warning:
        consoleFn = console.warn;
        break;
      case LogLevel.Info:
        consoleFn = console.info;
        break;
    }
    consoleFn.call(console, ...args);
  }
  e(file, messages) {
    const logger = this.a.get(file);
    if (!logger) {
      throw new Error("Create the logger before logging");
    }
    for (const [level, message] of messages) {
      log(logger, level, message);
    }
  }
};

// out-build/vs/platform/utilityProcess/electron-main/utilityProcessWorkerMainService.js
var $xlc = $Zi("utilityProcessWorker");
var $ylc = class $ylc2 extends $0c {
  constructor(b, c, f, g) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = /* @__PURE__ */ new Map();
  }
  async createWorker(configuration) {
    const workerLogId = `window: ${configuration.reply.windowId}, moduleId: ${configuration.process.moduleId}`;
    this.b.trace(`[UtilityProcessWorker]: createWorker(${workerLogId})`);
    const workerId = this.h(configuration);
    if (this.a.has(workerId)) {
      this.b.warn(`[UtilityProcessWorker]: createWorker() found an existing worker that will be terminated (${workerLogId})`);
      this.disposeWorker(configuration);
    }
    const worker = new UtilityProcessWorker(this.b, this.c, this.f, this.g, configuration);
    if (!worker.spawn()) {
      return { reason: { code: 1, signal: "EINVALID" } };
    }
    this.a.set(workerId, worker);
    const onDidTerminate = new $ki();
    Event.once(worker.onDidTerminate)((reason) => {
      if (reason.code === 0) {
        this.b.trace(`[UtilityProcessWorker]: terminated normally with code ${reason.code}, signal: ${reason.signal}`);
      } else {
        this.b.error(`[UtilityProcessWorker]: terminated unexpectedly with code ${reason.code}, signal: ${reason.signal}`);
      }
      this.a.delete(workerId);
      onDidTerminate.complete({ reason });
    });
    return onDidTerminate.p;
  }
  h(configuration) {
    return $Nj({
      moduleId: configuration.process.moduleId,
      windowId: configuration.reply.windowId
    });
  }
  async disposeWorker(configuration) {
    const workerId = this.h(configuration);
    const worker = this.a.get(workerId);
    if (!worker) {
      return;
    }
    this.b.trace(`[UtilityProcessWorker]: disposeWorker(window: ${configuration.reply.windowId}, moduleId: ${configuration.process.moduleId})`);
    worker.kill();
    worker.dispose();
    this.a.delete(workerId);
  }
};
$ylc = __decorate([
  __param(0, $uk),
  __param(1, $Pjc),
  __param(2, $tm),
  __param(3, $9jc)
], $ylc);
var UtilityProcessWorker = class UtilityProcessWorker2 extends $0c {
  constructor(c, f, g, h, j) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h;
    this.j = j;
    this.a = this.B(new $De());
    this.onDidTerminate = this.a.event;
    this.b = this.B(new $lkc(this.c, this.f, this.g, this.h));
    this.m();
  }
  m() {
    this.B(this.b.onExit((e) => this.a.fire({ code: e.code, signal: e.signal })));
    this.B(this.b.onCrash((e) => this.a.fire({ code: e.code, signal: "ECRASH" })));
  }
  spawn() {
    const window2 = this.f.getWindowById(this.j.reply.windowId);
    const windowPid = window2?.win?.webContents.getOSProcessId();
    return this.b.start({
      type: this.j.process.type,
      entryPoint: this.j.process.moduleId,
      parentLifecycleBound: windowPid,
      windowLifecycleBound: true,
      correlationId: `${this.j.reply.windowId}`,
      responseWindowId: this.j.reply.windowId,
      responseChannel: this.j.reply.channel,
      responseNonce: this.j.reply.nonce
    });
  }
  kill() {
    this.b.kill();
  }
};
UtilityProcessWorker = __decorate([
  __param(0, $uk),
  __param(1, $Pjc),
  __param(2, $tm),
  __param(3, $9jc)
], UtilityProcessWorker);

// out-build/vs/platform/utilityProcess/common/utilityProcessWorkerService.js
var $wlc = "utilityProcessWorker";

// out-build/vs/platform/terminal/common/terminal.js
var $Ks = new $ek("terminalTabFocusMode", false, true);
var TerminalSettingPrefix;
(function(TerminalSettingPrefix2) {
  TerminalSettingPrefix2["AutomationProfile"] = "terminal.integrated.automationProfile.";
  TerminalSettingPrefix2["DefaultProfile"] = "terminal.integrated.defaultProfile.";
  TerminalSettingPrefix2["Profiles"] = "terminal.integrated.profiles.";
})(TerminalSettingPrefix || (TerminalSettingPrefix = {}));
var TerminalSettingId;
(function(TerminalSettingId2) {
  TerminalSettingId2["SendKeybindingsToShell"] = "terminal.integrated.sendKeybindingsToShell";
  TerminalSettingId2["AutomationProfileLinux"] = "terminal.integrated.automationProfile.linux";
  TerminalSettingId2["AutomationProfileMacOs"] = "terminal.integrated.automationProfile.osx";
  TerminalSettingId2["AutomationProfileWindows"] = "terminal.integrated.automationProfile.windows";
  TerminalSettingId2["ProfilesWindows"] = "terminal.integrated.profiles.windows";
  TerminalSettingId2["ProfilesMacOs"] = "terminal.integrated.profiles.osx";
  TerminalSettingId2["ProfilesLinux"] = "terminal.integrated.profiles.linux";
  TerminalSettingId2["DefaultProfileLinux"] = "terminal.integrated.defaultProfile.linux";
  TerminalSettingId2["DefaultProfileMacOs"] = "terminal.integrated.defaultProfile.osx";
  TerminalSettingId2["DefaultProfileWindows"] = "terminal.integrated.defaultProfile.windows";
  TerminalSettingId2["UseWslProfiles"] = "terminal.integrated.useWslProfiles";
  TerminalSettingId2["TabsDefaultColor"] = "terminal.integrated.tabs.defaultColor";
  TerminalSettingId2["TabsDefaultIcon"] = "terminal.integrated.tabs.defaultIcon";
  TerminalSettingId2["TabsEnabled"] = "terminal.integrated.tabs.enabled";
  TerminalSettingId2["TabsEnableAnimation"] = "terminal.integrated.tabs.enableAnimation";
  TerminalSettingId2["TabsHideCondition"] = "terminal.integrated.tabs.hideCondition";
  TerminalSettingId2["TabsShowActiveTerminal"] = "terminal.integrated.tabs.showActiveTerminal";
  TerminalSettingId2["TabsShowActions"] = "terminal.integrated.tabs.showActions";
  TerminalSettingId2["TabsLocation"] = "terminal.integrated.tabs.location";
  TerminalSettingId2["TabsFocusMode"] = "terminal.integrated.tabs.focusMode";
  TerminalSettingId2["MacOptionIsMeta"] = "terminal.integrated.macOptionIsMeta";
  TerminalSettingId2["MacOptionClickForcesSelection"] = "terminal.integrated.macOptionClickForcesSelection";
  TerminalSettingId2["AltClickMovesCursor"] = "terminal.integrated.altClickMovesCursor";
  TerminalSettingId2["CopyOnSelection"] = "terminal.integrated.copyOnSelection";
  TerminalSettingId2["EnableMultiLinePasteWarning"] = "terminal.integrated.enableMultiLinePasteWarning";
  TerminalSettingId2["DrawBoldTextInBrightColors"] = "terminal.integrated.drawBoldTextInBrightColors";
  TerminalSettingId2["FontFamily"] = "terminal.integrated.fontFamily";
  TerminalSettingId2["FontSize"] = "terminal.integrated.fontSize";
  TerminalSettingId2["LetterSpacing"] = "terminal.integrated.letterSpacing";
  TerminalSettingId2["LineHeight"] = "terminal.integrated.lineHeight";
  TerminalSettingId2["MinimumContrastRatio"] = "terminal.integrated.minimumContrastRatio";
  TerminalSettingId2["TabStopWidth"] = "terminal.integrated.tabStopWidth";
  TerminalSettingId2["FastScrollSensitivity"] = "terminal.integrated.fastScrollSensitivity";
  TerminalSettingId2["MouseWheelScrollSensitivity"] = "terminal.integrated.mouseWheelScrollSensitivity";
  TerminalSettingId2["BellDuration"] = "terminal.integrated.bellDuration";
  TerminalSettingId2["FontWeight"] = "terminal.integrated.fontWeight";
  TerminalSettingId2["FontWeightBold"] = "terminal.integrated.fontWeightBold";
  TerminalSettingId2["CursorBlinking"] = "terminal.integrated.cursorBlinking";
  TerminalSettingId2["CursorStyle"] = "terminal.integrated.cursorStyle";
  TerminalSettingId2["CursorStyleInactive"] = "terminal.integrated.cursorStyleInactive";
  TerminalSettingId2["CursorWidth"] = "terminal.integrated.cursorWidth";
  TerminalSettingId2["Scrollback"] = "terminal.integrated.scrollback";
  TerminalSettingId2["DetectLocale"] = "terminal.integrated.detectLocale";
  TerminalSettingId2["DefaultLocation"] = "terminal.integrated.defaultLocation";
  TerminalSettingId2["GpuAcceleration"] = "terminal.integrated.gpuAcceleration";
  TerminalSettingId2["TerminalTitleSeparator"] = "terminal.integrated.tabs.separator";
  TerminalSettingId2["TerminalTitle"] = "terminal.integrated.tabs.title";
  TerminalSettingId2["TerminalDescription"] = "terminal.integrated.tabs.description";
  TerminalSettingId2["RightClickBehavior"] = "terminal.integrated.rightClickBehavior";
  TerminalSettingId2["MiddleClickBehavior"] = "terminal.integrated.middleClickBehavior";
  TerminalSettingId2["Cwd"] = "terminal.integrated.cwd";
  TerminalSettingId2["ConfirmOnExit"] = "terminal.integrated.confirmOnExit";
  TerminalSettingId2["ConfirmOnKill"] = "terminal.integrated.confirmOnKill";
  TerminalSettingId2["EnableBell"] = "terminal.integrated.enableBell";
  TerminalSettingId2["EnableVisualBell"] = "terminal.integrated.enableVisualBell";
  TerminalSettingId2["CommandsToSkipShell"] = "terminal.integrated.commandsToSkipShell";
  TerminalSettingId2["AllowChords"] = "terminal.integrated.allowChords";
  TerminalSettingId2["AllowMnemonics"] = "terminal.integrated.allowMnemonics";
  TerminalSettingId2["TabFocusMode"] = "terminal.integrated.tabFocusMode";
  TerminalSettingId2["EnvMacOs"] = "terminal.integrated.env.osx";
  TerminalSettingId2["EnvLinux"] = "terminal.integrated.env.linux";
  TerminalSettingId2["EnvWindows"] = "terminal.integrated.env.windows";
  TerminalSettingId2["EnvironmentChangesIndicator"] = "terminal.integrated.environmentChangesIndicator";
  TerminalSettingId2["EnvironmentChangesRelaunch"] = "terminal.integrated.environmentChangesRelaunch";
  TerminalSettingId2["ExperimentalWindowsUseConptyDll"] = "terminal.integrated.experimental.windowsUseConptyDll";
  TerminalSettingId2["ShowExitAlert"] = "terminal.integrated.showExitAlert";
  TerminalSettingId2["SplitCwd"] = "terminal.integrated.splitCwd";
  TerminalSettingId2["WindowsEnableConpty"] = "terminal.integrated.windowsEnableConpty";
  TerminalSettingId2["WordSeparators"] = "terminal.integrated.wordSeparators";
  TerminalSettingId2["EnableFileLinks"] = "terminal.integrated.enableFileLinks";
  TerminalSettingId2["AllowedLinkSchemes"] = "terminal.integrated.allowedLinkSchemes";
  TerminalSettingId2["UnicodeVersion"] = "terminal.integrated.unicodeVersion";
  TerminalSettingId2["EnablePersistentSessions"] = "terminal.integrated.enablePersistentSessions";
  TerminalSettingId2["PersistentSessionReviveProcess"] = "terminal.integrated.persistentSessionReviveProcess";
  TerminalSettingId2["HideOnStartup"] = "terminal.integrated.hideOnStartup";
  TerminalSettingId2["CustomGlyphs"] = "terminal.integrated.customGlyphs";
  TerminalSettingId2["RescaleOverlappingGlyphs"] = "terminal.integrated.rescaleOverlappingGlyphs";
  TerminalSettingId2["PersistentSessionScrollback"] = "terminal.integrated.persistentSessionScrollback";
  TerminalSettingId2["InheritEnv"] = "terminal.integrated.inheritEnv";
  TerminalSettingId2["ShowLinkHover"] = "terminal.integrated.showLinkHover";
  TerminalSettingId2["IgnoreProcessNames"] = "terminal.integrated.ignoreProcessNames";
  TerminalSettingId2["AutoReplies"] = "terminal.integrated.autoReplies";
  TerminalSettingId2["ShellIntegrationEnabled"] = "terminal.integrated.shellIntegration.enabled";
  TerminalSettingId2["ShellIntegrationShowWelcome"] = "terminal.integrated.shellIntegration.showWelcome";
  TerminalSettingId2["ShellIntegrationDecorationsEnabled"] = "terminal.integrated.shellIntegration.decorationsEnabled";
  TerminalSettingId2["ShellIntegrationCommandHistory"] = "terminal.integrated.shellIntegration.history";
  TerminalSettingId2["EnableImages"] = "terminal.integrated.enableImages";
  TerminalSettingId2["SmoothScrolling"] = "terminal.integrated.smoothScrolling";
  TerminalSettingId2["IgnoreBracketedPasteMode"] = "terminal.integrated.ignoreBracketedPasteMode";
  TerminalSettingId2["FocusAfterRun"] = "terminal.integrated.focusAfterRun";
  TerminalSettingId2["DeveloperPtyHostLatency"] = "terminal.integrated.developer.ptyHost.latency";
  TerminalSettingId2["DeveloperPtyHostStartupDelay"] = "terminal.integrated.developer.ptyHost.startupDelay";
  TerminalSettingId2["DevMode"] = "terminal.integrated.developer.devMode";
})(TerminalSettingId || (TerminalSettingId = {}));
var PosixShellType;
(function(PosixShellType2) {
  PosixShellType2["Bash"] = "bash";
  PosixShellType2["Fish"] = "fish";
  PosixShellType2["Sh"] = "sh";
  PosixShellType2["Csh"] = "csh";
  PosixShellType2["Ksh"] = "ksh";
  PosixShellType2["Zsh"] = "zsh";
})(PosixShellType || (PosixShellType = {}));
var WindowsShellType;
(function(WindowsShellType2) {
  WindowsShellType2["CommandPrompt"] = "cmd";
  WindowsShellType2["Wsl"] = "wsl";
  WindowsShellType2["GitBash"] = "gitbash";
})(WindowsShellType || (WindowsShellType = {}));
var GeneralShellType;
(function(GeneralShellType2) {
  GeneralShellType2["PowerShell"] = "pwsh";
  GeneralShellType2["Python"] = "python";
  GeneralShellType2["Julia"] = "julia";
  GeneralShellType2["NuShell"] = "nu";
})(GeneralShellType || (GeneralShellType = {}));
var TitleEventSource;
(function(TitleEventSource2) {
  TitleEventSource2[TitleEventSource2["Api"] = 0] = "Api";
  TitleEventSource2[TitleEventSource2["Process"] = 1] = "Process";
  TitleEventSource2[TitleEventSource2["Sequence"] = 2] = "Sequence";
  TitleEventSource2[TitleEventSource2["Config"] = 3] = "Config";
})(TitleEventSource || (TitleEventSource = {}));
var TerminalIpcChannels;
(function(TerminalIpcChannels2) {
  TerminalIpcChannels2["LocalPty"] = "localPty";
  TerminalIpcChannels2["PtyHost"] = "ptyHost";
  TerminalIpcChannels2["PtyHostWindow"] = "ptyHostWindow";
  TerminalIpcChannels2["Logger"] = "logger";
  TerminalIpcChannels2["Heartbeat"] = "heartbeat";
})(TerminalIpcChannels || (TerminalIpcChannels = {}));
var ProcessPropertyType;
(function(ProcessPropertyType2) {
  ProcessPropertyType2["Cwd"] = "cwd";
  ProcessPropertyType2["InitialCwd"] = "initialCwd";
  ProcessPropertyType2["FixedDimensions"] = "fixedDimensions";
  ProcessPropertyType2["Title"] = "title";
  ProcessPropertyType2["ShellType"] = "shellType";
  ProcessPropertyType2["HasChildProcesses"] = "hasChildProcesses";
  ProcessPropertyType2["ResolvedShellLaunchConfig"] = "resolvedShellLaunchConfig";
  ProcessPropertyType2["OverrideDimensions"] = "overrideDimensions";
  ProcessPropertyType2["FailedShellIntegrationActivation"] = "failedShellIntegrationActivation";
  ProcessPropertyType2["UsedShellIntegrationInjection"] = "usedShellIntegrationInjection";
})(ProcessPropertyType || (ProcessPropertyType = {}));
var $Ls = $Zi("ptyService");
var HeartbeatConstants;
(function(HeartbeatConstants2) {
  HeartbeatConstants2[HeartbeatConstants2["BeatInterval"] = 5e3] = "BeatInterval";
  HeartbeatConstants2[HeartbeatConstants2["ConnectingBeatInterval"] = 2e4] = "ConnectingBeatInterval";
  HeartbeatConstants2[HeartbeatConstants2["FirstWaitMultiplier"] = 1.2] = "FirstWaitMultiplier";
  HeartbeatConstants2[HeartbeatConstants2["SecondWaitMultiplier"] = 1] = "SecondWaitMultiplier";
  HeartbeatConstants2[HeartbeatConstants2["CreateProcessTimeout"] = 5e3] = "CreateProcessTimeout";
})(HeartbeatConstants || (HeartbeatConstants = {}));
var TerminalLocation;
(function(TerminalLocation2) {
  TerminalLocation2[TerminalLocation2["Panel"] = 1] = "Panel";
  TerminalLocation2[TerminalLocation2["Editor"] = 2] = "Editor";
})(TerminalLocation || (TerminalLocation = {}));
var TerminalLocationString;
(function(TerminalLocationString2) {
  TerminalLocationString2["TerminalView"] = "view";
  TerminalLocationString2["Editor"] = "editor";
})(TerminalLocationString || (TerminalLocationString = {}));
var LocalReconnectConstants;
(function(LocalReconnectConstants2) {
  LocalReconnectConstants2[LocalReconnectConstants2["GraceTime"] = 6e4] = "GraceTime";
  LocalReconnectConstants2[LocalReconnectConstants2["ShortGraceTime"] = 6e3] = "ShortGraceTime";
})(LocalReconnectConstants || (LocalReconnectConstants = {}));
var FlowControlConstants;
(function(FlowControlConstants2) {
  FlowControlConstants2[FlowControlConstants2["HighWatermarkChars"] = 1e5] = "HighWatermarkChars";
  FlowControlConstants2[FlowControlConstants2["LowWatermarkChars"] = 5e3] = "LowWatermarkChars";
  FlowControlConstants2[FlowControlConstants2["CharCountAckSize"] = 5e3] = "CharCountAckSize";
})(FlowControlConstants || (FlowControlConstants = {}));
var ProfileSource;
(function(ProfileSource2) {
  ProfileSource2["GitBash"] = "Git Bash";
  ProfileSource2["Pwsh"] = "PowerShell";
})(ProfileSource || (ProfileSource = {}));
var ShellIntegrationStatus;
(function(ShellIntegrationStatus2) {
  ShellIntegrationStatus2[ShellIntegrationStatus2["Off"] = 0] = "Off";
  ShellIntegrationStatus2[ShellIntegrationStatus2["FinalTerm"] = 1] = "FinalTerm";
  ShellIntegrationStatus2[ShellIntegrationStatus2["VSCode"] = 2] = "VSCode";
})(ShellIntegrationStatus || (ShellIntegrationStatus = {}));
var TerminalExitReason;
(function(TerminalExitReason2) {
  TerminalExitReason2[TerminalExitReason2["Unknown"] = 0] = "Unknown";
  TerminalExitReason2[TerminalExitReason2["Shutdown"] = 1] = "Shutdown";
  TerminalExitReason2[TerminalExitReason2["Process"] = 2] = "Process";
  TerminalExitReason2[TerminalExitReason2["User"] = 3] = "User";
  TerminalExitReason2[TerminalExitReason2["Extension"] = 4] = "Extension";
})(TerminalExitReason || (TerminalExitReason = {}));
var $Ms = {
  Backend: "workbench.contributions.terminal.processBackend"
};
var TerminalBackendRegistry = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  get backends() {
    return this.a;
  }
  registerTerminalBackend(backend) {
    const key = this.b(backend.remoteAuthority);
    if (this.a.has(key)) {
      throw new Error(`A terminal backend with remote authority '${key}' was already registered.`);
    }
    this.a.set(key, backend);
  }
  getTerminalBackend(remoteAuthority) {
    return this.a.get(this.b(remoteAuthority));
  }
  b(remoteAuthority) {
    return remoteAuthority?.toLowerCase() ?? "";
  }
};
$Mo.add($Ms.Backend, new TerminalBackendRegistry());
var $Ns = $Zi("localPtyService");
var $Os = $Zi("terminalLogService");

// out-build/vs/platform/terminal/electron-main/electronPtyHostStarter.js
var $zlc = class $zlc2 extends $0c {
  constructor(f, g, h, j, m) {
    super();
    this.f = f;
    this.g = g;
    this.h = h;
    this.j = j;
    this.m = m;
    this.a = void 0;
    this.b = new $De();
    this.onRequestConnection = this.b.event;
    this.c = new $De();
    this.onWillShutdown = this.c.event;
    this.B(this.j.onWillShutdown(() => this.c.fire()));
    $ZY.on("vscode:createPtyHostMessageChannel", (e, nonce) => this.r(e, nonce));
    this.B($8c(() => {
      $ZY.removeHandler("vscode:createPtyHostMessageChannel");
    }));
  }
  start() {
    this.a = new $kkc(this.m, $Up, this.j);
    const inspectParams = $sn(this.h.args, this.h.isBuilt);
    const execArgv = inspectParams.port ? [
      "--nolazy",
      `--inspect${inspectParams.break ? "-brk" : ""}=${inspectParams.port}`
    ] : void 0;
    this.a.start({
      type: "ptyHost",
      entryPoint: "vs/platform/terminal/node/ptyHostMain",
      execArgv,
      args: ["--logsPath", this.h.logsHome.with({ scheme: Schemas.file }).fsPath],
      env: this.n()
    });
    const port = this.a.connect();
    const client = new $8Y(port, "ptyHost");
    const store = new $9c();
    store.add(client);
    store.add($8c(() => {
      this.a?.kill();
      this.a?.dispose();
      this.a = void 0;
    }));
    return {
      client,
      store,
      onDidProcessExit: this.a.onExit
    };
  }
  n() {
    this.h.unsetSnapExportedVariables();
    const config = {
      ...$zo(process.env),
      VSCODE_AMD_ENTRYPOINT: "vs/platform/terminal/node/ptyHostMain",
      VSCODE_PIPE_LOGGING: "true",
      VSCODE_VERBOSE_LOGGING: "true",
      // transmit console logs from server to client,
      VSCODE_RECONNECT_GRACE_TIME: String(this.f.graceTime),
      VSCODE_RECONNECT_SHORT_GRACE_TIME: String(this.f.shortGraceTime),
      VSCODE_RECONNECT_SCROLLBACK: String(this.f.scrollback)
    };
    const simulatedLatency = this.g.getValue(
      "terminal.integrated.developer.ptyHost.latency"
      /* TerminalSettingId.DeveloperPtyHostLatency */
    );
    if (simulatedLatency && typeof simulatedLatency === "number") {
      config.VSCODE_LATENCY = String(simulatedLatency);
    }
    const startupDelay = this.g.getValue(
      "terminal.integrated.developer.ptyHost.startupDelay"
      /* TerminalSettingId.DeveloperPtyHostStartupDelay */
    );
    if (startupDelay && typeof startupDelay === "number") {
      config.VSCODE_STARTUP_DELAY = String(startupDelay);
    }
    this.h.restoreSnapExportedVariables();
    return config;
  }
  r(e, nonce) {
    this.b.fire();
    const port = this.a.connect();
    if (e.sender.isDestroyed()) {
      port.close();
      return;
    }
    e.sender.postMessage("vscode:createPtyHostMessageChannelResult", nonce, [port]);
  }
};
$zlc = __decorate([
  __param(1, $tj),
  __param(2, $Cjc),
  __param(3, $9jc),
  __param(4, $uk)
], $zlc);

// out-build/vs/platform/log/common/logIpc.js
var $Rs = class extends $0c {
  constructor(loggerService, channel) {
    super();
    channel.call("setLogLevel", [loggerService.getLogLevel()]);
    this.B(loggerService.onDidChangeLogLevel((arg) => channel.call("setLogLevel", [arg])));
    channel.call("getRegisteredLoggers").then((loggers) => {
      for (const loggerResource of loggers) {
        loggerService.registerLogger({ ...loggerResource, resource: URI.revive(loggerResource.resource) });
      }
    });
    this.B(channel.listen("onDidChangeVisibility")(([resource, visibility]) => loggerService.setVisibility(URI.revive(resource), visibility)));
    this.B(channel.listen("onDidChangeLoggers")(({ added, removed }) => {
      for (const loggerResource of added) {
        loggerService.registerLogger({ ...loggerResource, resource: URI.revive(loggerResource.resource) });
      }
      for (const loggerResource of removed) {
        loggerService.deregisterLogger(loggerResource.resource);
      }
    }));
  }
};

// out-build/vs/platform/terminal/common/requestStore.js
var $Ss = class $Ss2 extends $0c {
  /**
   * @param timeout How long in ms to allow requests to go unanswered for, undefined will use the
   * default (15 seconds).
   */
  constructor(timeout, h) {
    super();
    this.h = h;
    this.a = 0;
    this.c = /* @__PURE__ */ new Map();
    this.f = /* @__PURE__ */ new Map();
    this.g = this.B(new $De());
    this.onCreateRequest = this.g.event;
    this.b = timeout === void 0 ? 15e3 : timeout;
    this.B($8c(() => {
      for (const d of this.f.values()) {
        $5c(d);
      }
    }));
  }
  /**
   * Creates a request.
   * @param args The arguments to pass to the onCreateRequest event.
   */
  createRequest(args) {
    return new Promise((resolve2, reject) => {
      const requestId = ++this.a;
      this.c.set(requestId, resolve2);
      this.g.fire({ requestId, ...args });
      const tokenSource = new $Pe();
      $1h(this.b, tokenSource.token).then(() => reject(`Request ${requestId} timed out (${this.b}ms)`));
      this.f.set(requestId, [$8c(() => tokenSource.cancel())]);
    });
  }
  /**
   * Accept a reply to a request.
   * @param requestId The request ID originating from the onCreateRequest event.
   * @param data The reply data.
   */
  acceptReply(requestId, data) {
    const resolveRequest = this.c.get(requestId);
    if (resolveRequest) {
      this.c.delete(requestId);
      $5c(this.f.get(requestId) || []);
      this.f.delete(requestId);
      resolveRequest(data);
    } else {
      this.h.warn(`RequestStore#acceptReply was called without receiving a matching request ${requestId}`);
    }
  }
};
$Ss = __decorate([
  __param(1, $uk)
], $Ss);

// out-build/vs/platform/terminal/common/terminalProfiles.js
function $Ts(detectedProfiles, extensionProfiles) {
  const result = [{
    name: null,
    description: localize(2132, null)
  }];
  result.push(...detectedProfiles.map((e) => {
    return {
      name: e.profileName,
      description: createProfileDescription(e)
    };
  }));
  if (extensionProfiles) {
    result.push(...extensionProfiles.map((extensionProfile) => {
      return {
        name: extensionProfile.title,
        description: createExtensionProfileDescription(extensionProfile)
      };
    }));
  }
  return {
    values: result.map((e) => e.name),
    markdownDescriptions: result.map((e) => e.description)
  };
}
function createProfileDescription(profile) {
  let description = `$(${ThemeIcon.isThemeIcon(profile.icon) ? profile.icon.id : profile.icon ? profile.icon : $mk.terminal.id}) ${profile.profileName}
- path: ${profile.path}`;
  if (profile.args) {
    if (typeof profile.args === "string") {
      description += `
- args: "${profile.args}"`;
    } else {
      description += `
- args: [${profile.args.length === 0 ? "" : `'${profile.args.join(`','`)}'`}]`;
    }
  }
  if (profile.overrideName !== void 0) {
    description += `
- overrideName: ${profile.overrideName}`;
  }
  if (profile.color) {
    description += `
- color: ${profile.color}`;
  }
  if (profile.env) {
    description += `
- env: ${JSON.stringify(profile.env)}`;
  }
  return description;
}
function createExtensionProfileDescription(profile) {
  const description = `$(${ThemeIcon.isThemeIcon(profile.icon) ? profile.icon.id : profile.icon ? profile.icon : $mk.terminal.id}) ${profile.title}
- extensionIdentifier: ${profile.extensionIdentifier}`;
  return description;
}

// out-build/vs/platform/terminal/common/terminalPlatformConfiguration.js
var $Xs = {
  type: ["string", "null"],
  enum: [
    "terminal.ansiBlack",
    "terminal.ansiRed",
    "terminal.ansiGreen",
    "terminal.ansiYellow",
    "terminal.ansiBlue",
    "terminal.ansiMagenta",
    "terminal.ansiCyan",
    "terminal.ansiWhite"
  ],
  default: null
};
var $Ys = {
  type: "string",
  enum: Array.from($kk(), (icon) => icon.id),
  markdownEnumDescriptions: Array.from($kk(), (icon) => `$(${icon.id})`)
};
var terminalProfileBaseProperties = {
  args: {
    description: localize(2101, null),
    type: "array",
    items: {
      type: "string"
    }
  },
  overrideName: {
    description: localize(2102, null),
    type: "boolean"
  },
  icon: {
    description: localize(2103, null),
    ...$Ys
  },
  color: {
    description: localize(2104, null),
    ...$Xs
  },
  env: {
    markdownDescription: localize(2105, null),
    type: "object",
    additionalProperties: {
      type: ["string", "null"]
    },
    default: {}
  }
};
var terminalProfileSchema = {
  type: "object",
  required: ["path"],
  properties: {
    path: {
      description: localize(2106, null),
      type: ["string", "array"],
      items: {
        type: "string"
      }
    },
    ...terminalProfileBaseProperties
  }
};
var terminalAutomationProfileSchema = {
  type: "object",
  required: ["path"],
  properties: {
    path: {
      description: localize(2107, null),
      type: ["string"],
      items: {
        type: "string"
      }
    },
    ...terminalProfileBaseProperties
  }
};
function createTerminalProfileMarkdownDescription(platform2) {
  const key = platform2 === 2 ? "linux" : platform2 === 1 ? "osx" : "windows";
  return localize(2108, null, $k(platform2), '```json\n"terminal.integrated.profile.' + key + '": {\n  "bash": null\n}\n```', "[", "](https://code.visualstudio.com/docs/terminal/profiles)");
}
var terminalPlatformConfiguration = {
  id: "terminal",
  order: 100,
  title: localize(2109, null),
  type: "object",
  properties: {
    [
      "terminal.integrated.automationProfile.linux"
      /* TerminalSettingId.AutomationProfileLinux */
    ]: {
      restricted: true,
      markdownDescription: localize(2110, null),
      type: ["object", "null"],
      default: null,
      "anyOf": [
        { type: "null" },
        terminalAutomationProfileSchema
      ],
      defaultSnippets: [
        {
          body: {
            path: "${1}",
            icon: "${2}"
          }
        }
      ]
    },
    [
      "terminal.integrated.automationProfile.osx"
      /* TerminalSettingId.AutomationProfileMacOs */
    ]: {
      restricted: true,
      markdownDescription: localize(2111, null),
      type: ["object", "null"],
      default: null,
      "anyOf": [
        { type: "null" },
        terminalAutomationProfileSchema
      ],
      defaultSnippets: [
        {
          body: {
            path: "${1}",
            icon: "${2}"
          }
        }
      ]
    },
    [
      "terminal.integrated.automationProfile.windows"
      /* TerminalSettingId.AutomationProfileWindows */
    ]: {
      restricted: true,
      markdownDescription: localize(2112, null, "`terminal.integrated.automationShell.windows`"),
      type: ["object", "null"],
      default: null,
      "anyOf": [
        { type: "null" },
        terminalAutomationProfileSchema
      ],
      defaultSnippets: [
        {
          body: {
            path: "${1}",
            icon: "${2}"
          }
        }
      ]
    },
    [
      "terminal.integrated.profiles.windows"
      /* TerminalSettingId.ProfilesWindows */
    ]: {
      restricted: true,
      markdownDescription: createTerminalProfileMarkdownDescription(
        3
        /* Platform.Windows */
      ),
      type: "object",
      default: {
        "PowerShell": {
          source: "PowerShell",
          icon: "terminal-powershell"
        },
        "Command Prompt": {
          path: [
            "${env:windir}\\Sysnative\\cmd.exe",
            "${env:windir}\\System32\\cmd.exe"
          ],
          args: [],
          icon: "terminal-cmd"
        },
        "Git Bash": {
          source: "Git Bash"
        }
      },
      additionalProperties: {
        "anyOf": [
          {
            type: "object",
            required: ["source"],
            properties: {
              source: {
                description: localize(2113, null),
                enum: ["PowerShell", "Git Bash"]
              },
              ...terminalProfileBaseProperties
            }
          },
          {
            type: "object",
            required: ["extensionIdentifier", "id", "title"],
            properties: {
              extensionIdentifier: {
                description: localize(2114, null),
                type: "string"
              },
              id: {
                description: localize(2115, null),
                type: "string"
              },
              title: {
                description: localize(2116, null),
                type: "string"
              },
              ...terminalProfileBaseProperties
            }
          },
          { type: "null" },
          terminalProfileSchema
        ]
      }
    },
    [
      "terminal.integrated.profiles.osx"
      /* TerminalSettingId.ProfilesMacOs */
    ]: {
      restricted: true,
      markdownDescription: createTerminalProfileMarkdownDescription(
        1
        /* Platform.Mac */
      ),
      type: "object",
      default: {
        "bash": {
          path: "bash",
          args: ["-l"],
          icon: "terminal-bash"
        },
        "zsh": {
          path: "zsh",
          args: ["-l"]
        },
        "fish": {
          path: "fish",
          args: ["-l"]
        },
        "tmux": {
          path: "tmux",
          icon: "terminal-tmux"
        },
        "pwsh": {
          path: "pwsh",
          icon: "terminal-powershell"
        }
      },
      additionalProperties: {
        "anyOf": [
          {
            type: "object",
            required: ["extensionIdentifier", "id", "title"],
            properties: {
              extensionIdentifier: {
                description: localize(2117, null),
                type: "string"
              },
              id: {
                description: localize(2118, null),
                type: "string"
              },
              title: {
                description: localize(2119, null),
                type: "string"
              },
              ...terminalProfileBaseProperties
            }
          },
          { type: "null" },
          terminalProfileSchema
        ]
      }
    },
    [
      "terminal.integrated.profiles.linux"
      /* TerminalSettingId.ProfilesLinux */
    ]: {
      restricted: true,
      markdownDescription: createTerminalProfileMarkdownDescription(
        2
        /* Platform.Linux */
      ),
      type: "object",
      default: {
        "bash": {
          path: "bash",
          icon: "terminal-bash"
        },
        "zsh": {
          path: "zsh"
        },
        "fish": {
          path: "fish"
        },
        "tmux": {
          path: "tmux",
          icon: "terminal-tmux"
        },
        "pwsh": {
          path: "pwsh",
          icon: "terminal-powershell"
        }
      },
      additionalProperties: {
        "anyOf": [
          {
            type: "object",
            required: ["extensionIdentifier", "id", "title"],
            properties: {
              extensionIdentifier: {
                description: localize(2120, null),
                type: "string"
              },
              id: {
                description: localize(2121, null),
                type: "string"
              },
              title: {
                description: localize(2122, null),
                type: "string"
              },
              ...terminalProfileBaseProperties
            }
          },
          { type: "null" },
          terminalProfileSchema
        ]
      }
    },
    [
      "terminal.integrated.useWslProfiles"
      /* TerminalSettingId.UseWslProfiles */
    ]: {
      description: localize(2123, null),
      type: "boolean",
      default: true
    },
    [
      "terminal.integrated.inheritEnv"
      /* TerminalSettingId.InheritEnv */
    ]: {
      scope: 1,
      description: localize(2124, null),
      type: "boolean",
      default: true
    },
    [
      "terminal.integrated.persistentSessionScrollback"
      /* TerminalSettingId.PersistentSessionScrollback */
    ]: {
      scope: 1,
      markdownDescription: localize(2125, null),
      type: "number",
      default: 100
    },
    [
      "terminal.integrated.showLinkHover"
      /* TerminalSettingId.ShowLinkHover */
    ]: {
      scope: 1,
      description: localize(2126, null),
      type: "boolean",
      default: true
    },
    [
      "terminal.integrated.ignoreProcessNames"
      /* TerminalSettingId.IgnoreProcessNames */
    ]: {
      markdownDescription: localize(2127, null, "`#terminal.integrated.confirmOnKill#`"),
      type: "array",
      items: {
        type: "string",
        uniqueItems: true
      },
      default: [
        // Popular prompt programs, these should not count as child processes
        "starship",
        "oh-my-posh",
        // Git bash may runs a subprocess of itself (bin\bash.exe -> usr\bin\bash.exe)
        "bash",
        "zsh"
      ]
    }
  }
};
function $Zs() {
  $Mo.as($Ro.Configuration).registerConfiguration(terminalPlatformConfiguration);
  $1s();
}
var defaultProfilesConfiguration;
function $1s(detectedProfiles, extensionContributedProfiles) {
  const registry = $Mo.as($Ro.Configuration);
  let profileEnum;
  if (detectedProfiles) {
    profileEnum = $Ts(detectedProfiles?.profiles, extensionContributedProfiles);
  }
  const oldDefaultProfilesConfiguration = defaultProfilesConfiguration;
  defaultProfilesConfiguration = {
    id: "terminal",
    order: 100,
    title: localize(2128, null),
    type: "object",
    properties: {
      [
        "terminal.integrated.defaultProfile.linux"
        /* TerminalSettingId.DefaultProfileLinux */
      ]: {
        restricted: true,
        markdownDescription: localize(2129, null),
        type: ["string", "null"],
        default: null,
        enum: detectedProfiles?.os === 3 ? profileEnum?.values : void 0,
        markdownEnumDescriptions: detectedProfiles?.os === 3 ? profileEnum?.markdownDescriptions : void 0
      },
      [
        "terminal.integrated.defaultProfile.osx"
        /* TerminalSettingId.DefaultProfileMacOs */
      ]: {
        restricted: true,
        markdownDescription: localize(2130, null),
        type: ["string", "null"],
        default: null,
        enum: detectedProfiles?.os === 2 ? profileEnum?.values : void 0,
        markdownEnumDescriptions: detectedProfiles?.os === 2 ? profileEnum?.markdownDescriptions : void 0
      },
      [
        "terminal.integrated.defaultProfile.windows"
        /* TerminalSettingId.DefaultProfileWindows */
      ]: {
        restricted: true,
        markdownDescription: localize(2131, null),
        type: ["string", "null"],
        default: null,
        enum: detectedProfiles?.os === 1 ? profileEnum?.values : void 0,
        markdownEnumDescriptions: detectedProfiles?.os === 1 ? profileEnum?.markdownDescriptions : void 0
      }
    }
  };
  registry.updateConfigurations({ add: [defaultProfilesConfiguration], remove: oldDefaultProfilesConfiguration ? [oldDefaultProfilesConfiguration] : [] });
}

// out-build/vs/platform/terminal/node/terminalProfiles.js
import * as fs11 from "fs";
import * as cp3 from "child_process";

// out-build/vs/platform/terminal/node/terminalEnvironment.js
import * as os4 from "os";

// out-build/vs/platform/terminal/common/environmentVariable.js
var EnvironmentVariableMutatorType;
(function(EnvironmentVariableMutatorType2) {
  EnvironmentVariableMutatorType2[EnvironmentVariableMutatorType2["Replace"] = 1] = "Replace";
  EnvironmentVariableMutatorType2[EnvironmentVariableMutatorType2["Append"] = 2] = "Append";
  EnvironmentVariableMutatorType2[EnvironmentVariableMutatorType2["Prepend"] = 3] = "Prepend";
})(EnvironmentVariableMutatorType || (EnvironmentVariableMutatorType = {}));

// out-build/vs/platform/terminal/common/environmentVariableCollection.js
var mutatorTypeToLabelMap = /* @__PURE__ */ new Map([
  [EnvironmentVariableMutatorType.Append, "APPEND"],
  [EnvironmentVariableMutatorType.Prepend, "PREPEND"],
  [EnvironmentVariableMutatorType.Replace, "REPLACE"]
]);

// out-build/vs/platform/terminal/node/terminalEnvironment.js
function $9s() {
  const osVersion = /(\d+)\.(\d+)\.(\d+)/g.exec(os4.release());
  let buildNumber = 0;
  if (osVersion && osVersion.length === 4) {
    buildNumber = parseInt(osVersion[3]);
  }
  return buildNumber;
}
async function $0s(command, cwd2, paths, env2 = env, exists = Promises2.exists) {
  if ($uc(command)) {
    return await exists(command) ? command : void 0;
  }
  if (cwd2 === void 0) {
    cwd2 = cwd();
  }
  const dir = $yc(command);
  if (dir !== ".") {
    const fullPath2 = $vc(cwd2, command);
    return await exists(fullPath2) ? fullPath2 : void 0;
  }
  const envPath = $Go(env2, "PATH");
  if (paths === void 0 && $yg(envPath)) {
    paths = envPath.split($Fc);
  }
  if (paths === void 0 || paths.length === 0) {
    const fullPath2 = $vc(cwd2, command);
    return await exists(fullPath2) ? fullPath2 : void 0;
  }
  for (const pathEntry of paths) {
    let fullPath2;
    if ($uc(pathEntry)) {
      fullPath2 = $vc(pathEntry, command);
    } else {
      fullPath2 = $vc(cwd2, pathEntry, command);
    }
    if (await exists(fullPath2)) {
      return fullPath2;
    }
    if ($l) {
      let withExtension = fullPath2 + ".com";
      if (await exists(withExtension)) {
        return withExtension;
      }
      withExtension = fullPath2 + ".exe";
      if (await exists(withExtension)) {
        return withExtension;
      }
    }
  }
  const fullPath = $vc(cwd2, command);
  return await exists(fullPath) ? fullPath : void 0;
}
var ShellIntegrationExecutable;
(function(ShellIntegrationExecutable2) {
  ShellIntegrationExecutable2["WindowsPwsh"] = "windows-pwsh";
  ShellIntegrationExecutable2["WindowsPwshLogin"] = "windows-pwsh-login";
  ShellIntegrationExecutable2["Pwsh"] = "pwsh";
  ShellIntegrationExecutable2["PwshLogin"] = "pwsh-login";
  ShellIntegrationExecutable2["Zsh"] = "zsh";
  ShellIntegrationExecutable2["ZshLogin"] = "zsh-login";
  ShellIntegrationExecutable2["Bash"] = "bash";
})(ShellIntegrationExecutable || (ShellIntegrationExecutable = {}));
var shellIntegrationArgs = /* @__PURE__ */ new Map();
shellIntegrationArgs.set(ShellIntegrationExecutable.WindowsPwsh, ["-noexit", "-command", 'try { . "{0}\\out\\vs\\workbench\\contrib\\terminal\\common\\scripts\\shellIntegration.ps1" } catch {}{1}']);
shellIntegrationArgs.set(ShellIntegrationExecutable.WindowsPwshLogin, ["-l", "-noexit", "-command", 'try { . "{0}\\out\\vs\\workbench\\contrib\\terminal\\common\\scripts\\shellIntegration.ps1" } catch {}{1}']);
shellIntegrationArgs.set(ShellIntegrationExecutable.Pwsh, ["-noexit", "-command", '. "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.ps1"{1}']);
shellIntegrationArgs.set(ShellIntegrationExecutable.PwshLogin, ["-l", "-noexit", "-command", '. "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.ps1"']);
shellIntegrationArgs.set(ShellIntegrationExecutable.Zsh, ["-i"]);
shellIntegrationArgs.set(ShellIntegrationExecutable.ZshLogin, ["-il"]);
shellIntegrationArgs.set(ShellIntegrationExecutable.Bash, ["--init-file", "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-bash.sh"]);

// out-build/vs/platform/terminal/node/terminalProfiles.js
import { dirname, resolve } from "path";
var Constants2;
(function(Constants4) {
  Constants4["UnixShellsPath"] = "/etc/shells";
})(Constants2 || (Constants2 = {}));
var profileSources;
var logIfWslNotInstalled = true;
function $_s(profiles, defaultProfile, includeDetectedProfiles, configurationService, shellEnv = process.env, fsProvider, logService, variableResolver, testPwshSourcePaths) {
  fsProvider = fsProvider || {
    existsFile: SymlinkSupport.existsFile,
    readFile: fs11.promises.readFile
  };
  if ($l) {
    return detectAvailableWindowsProfiles(includeDetectedProfiles, fsProvider, shellEnv, logService, configurationService.getValue(
      "terminal.integrated.useWslProfiles"
      /* TerminalSettingId.UseWslProfiles */
    ) !== false, profiles && typeof profiles === "object" ? { ...profiles } : configurationService.getValue(
      "terminal.integrated.profiles.windows"
      /* TerminalSettingId.ProfilesWindows */
    ), typeof defaultProfile === "string" ? defaultProfile : configurationService.getValue(
      "terminal.integrated.defaultProfile.windows"
      /* TerminalSettingId.DefaultProfileWindows */
    ), testPwshSourcePaths, variableResolver);
  }
  return detectAvailableUnixProfiles(fsProvider, logService, includeDetectedProfiles, profiles && typeof profiles === "object" ? { ...profiles } : configurationService.getValue(
    $n ? "terminal.integrated.profiles.linux" : "terminal.integrated.profiles.osx"
    /* TerminalSettingId.ProfilesMacOs */
  ), typeof defaultProfile === "string" ? defaultProfile : configurationService.getValue(
    $n ? "terminal.integrated.defaultProfile.linux" : "terminal.integrated.defaultProfile.osx"
    /* TerminalSettingId.DefaultProfileMacOs */
  ), testPwshSourcePaths, variableResolver, shellEnv);
}
async function detectAvailableWindowsProfiles(includeDetectedProfiles, fsProvider, shellEnv, logService, useWslProfiles, configProfiles, defaultProfileName, testPwshSourcePaths, variableResolver) {
  const is32ProcessOn64Windows = process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432");
  const system32Path = `${process.env["windir"]}\\${is32ProcessOn64Windows ? "Sysnative" : "System32"}`;
  let useWSLexe = false;
  if ($9s() >= 16299) {
    useWSLexe = true;
  }
  await initializeWindowsProfiles(testPwshSourcePaths);
  const detectedProfiles = /* @__PURE__ */ new Map();
  if (includeDetectedProfiles) {
    detectedProfiles.set("PowerShell", {
      source: "PowerShell",
      icon: $mk.terminalPowershell,
      isAutoDetected: true
    });
    detectedProfiles.set("Windows PowerShell", {
      path: `${system32Path}\\WindowsPowerShell\\v1.0\\powershell.exe`,
      icon: $mk.terminalPowershell,
      isAutoDetected: true
    });
    detectedProfiles.set("Git Bash", {
      source: "Git Bash",
      isAutoDetected: true
    });
    detectedProfiles.set("Command Prompt", {
      path: `${system32Path}\\cmd.exe`,
      icon: $mk.terminalCmd,
      isAutoDetected: true
    });
    detectedProfiles.set("Cygwin", {
      path: [
        { path: `${process.env["HOMEDRIVE"]}\\cygwin64\\bin\\bash.exe`, isUnsafe: true },
        { path: `${process.env["HOMEDRIVE"]}\\cygwin\\bin\\bash.exe`, isUnsafe: true }
      ],
      args: ["--login"],
      isAutoDetected: true
    });
    detectedProfiles.set("bash (MSYS2)", {
      path: [
        { path: `${process.env["HOMEDRIVE"]}\\msys64\\usr\\bin\\bash.exe`, isUnsafe: true }
      ],
      args: ["--login", "-i"],
      // CHERE_INVOKING retains current working directory
      env: { CHERE_INVOKING: "1" },
      icon: $mk.terminalBash,
      isAutoDetected: true
    });
    const cmderPath = `${process.env["CMDER_ROOT"] || `${process.env["HOMEDRIVE"]}\\cmder`}\\vendor\\bin\\vscode_init.cmd`;
    detectedProfiles.set("Cmder", {
      path: `${system32Path}\\cmd.exe`,
      args: ["/K", cmderPath],
      // The path is safe if it was derived from CMDER_ROOT
      requiresPath: process.env["CMDER_ROOT"] ? cmderPath : { path: cmderPath, isUnsafe: true },
      isAutoDetected: true
    });
  }
  applyConfigProfilesToMap(configProfiles, detectedProfiles);
  const resultProfiles = await transformToTerminalProfiles(detectedProfiles.entries(), defaultProfileName, fsProvider, shellEnv, logService, variableResolver);
  if (includeDetectedProfiles && useWslProfiles) {
    try {
      const result = await getWslProfiles(`${system32Path}\\${useWSLexe ? "wsl" : "bash"}.exe`, defaultProfileName);
      for (const wslProfile of result) {
        if (!configProfiles || !(wslProfile.profileName in configProfiles)) {
          resultProfiles.push(wslProfile);
        }
      }
    } catch (e) {
      if (logIfWslNotInstalled) {
        logService?.trace("WSL is not installed, so could not detect WSL profiles");
        logIfWslNotInstalled = false;
      }
    }
  }
  return resultProfiles;
}
async function transformToTerminalProfiles(entries, defaultProfileName, fsProvider, shellEnv = process.env, logService, variableResolver) {
  const promises16 = [];
  for (const [profileName, profile] of entries) {
    promises16.push(getValidatedProfile(profileName, profile, defaultProfileName, fsProvider, shellEnv, logService, variableResolver));
  }
  return (await Promise.all(promises16)).filter((e) => !!e);
}
async function getValidatedProfile(profileName, profile, defaultProfileName, fsProvider, shellEnv = process.env, logService, variableResolver) {
  if (profile === null) {
    return void 0;
  }
  let originalPaths;
  let args;
  let icon = void 0;
  if ("source" in profile && !("path" in profile)) {
    const source = profileSources?.get(profile.source);
    if (!source) {
      return void 0;
    }
    originalPaths = source.paths;
    args = profile.args || source.args;
    if (profile.icon) {
      icon = validateIcon(profile.icon);
    } else if (source.icon) {
      icon = source.icon;
    }
  } else {
    originalPaths = Array.isArray(profile.path) ? profile.path : [profile.path];
    args = $l ? profile.args : Array.isArray(profile.args) ? profile.args : void 0;
    icon = validateIcon(profile.icon);
  }
  let paths;
  if (variableResolver) {
    const mapped = originalPaths.map((e) => typeof e === "string" ? e : e.path);
    const resolved = await variableResolver(mapped);
    paths = new Array(originalPaths.length);
    for (let i = 0; i < originalPaths.length; i++) {
      if (typeof originalPaths[i] === "string") {
        paths[i] = resolved[i];
      } else {
        paths[i] = {
          path: resolved[i],
          isUnsafe: true
        };
      }
    }
  } else {
    paths = originalPaths.slice();
  }
  let requiresUnsafePath;
  if (profile.requiresPath) {
    let actualRequiredPath;
    if ($yg(profile.requiresPath)) {
      actualRequiredPath = profile.requiresPath;
    } else {
      actualRequiredPath = profile.requiresPath.path;
      if (profile.requiresPath.isUnsafe) {
        requiresUnsafePath = actualRequiredPath;
      }
    }
    const result = await fsProvider.existsFile(actualRequiredPath);
    if (!result) {
      return;
    }
  }
  const validatedProfile = await validateProfilePaths(profileName, defaultProfileName, paths, fsProvider, shellEnv, args, profile.env, profile.overrideName, profile.isAutoDetected, requiresUnsafePath);
  if (!validatedProfile) {
    logService?.debug("Terminal profile not validated", profileName, originalPaths);
    return void 0;
  }
  validatedProfile.isAutoDetected = profile.isAutoDetected;
  validatedProfile.icon = icon;
  validatedProfile.color = profile.color;
  return validatedProfile;
}
function validateIcon(icon) {
  if (typeof icon === "string") {
    return { id: icon };
  }
  return icon;
}
async function initializeWindowsProfiles(testPwshSourcePaths) {
  if (profileSources && !testPwshSourcePaths) {
    return;
  }
  const [gitBashPaths, pwshPaths] = await Promise.all([getGitBashPaths(), testPwshSourcePaths || getPowershellPaths()]);
  profileSources = /* @__PURE__ */ new Map();
  profileSources.set("Git Bash", {
    profileName: "Git Bash",
    paths: gitBashPaths,
    args: ["--login", "-i"]
  });
  profileSources.set("PowerShell", {
    profileName: "PowerShell",
    paths: pwshPaths,
    icon: $mk.terminalPowershell
  });
}
async function getGitBashPaths() {
  const gitDirs = /* @__PURE__ */ new Set();
  const gitExePath = await $0s("git.exe");
  if (gitExePath) {
    const gitExeDir = dirname(gitExePath);
    gitDirs.add(resolve(gitExeDir, "../.."));
  }
  function addTruthy(set, value) {
    if (value) {
      set.add(value);
    }
  }
  addTruthy(gitDirs, process.env["ProgramW6432"]);
  addTruthy(gitDirs, process.env["ProgramFiles"]);
  addTruthy(gitDirs, process.env["ProgramFiles(X86)"]);
  addTruthy(gitDirs, `${process.env["LocalAppData"]}\\Program`);
  const gitBashPaths = [];
  for (const gitDir of gitDirs) {
    gitBashPaths.push(
      `${gitDir}\\Git\\bin\\bash.exe`,
      `${gitDir}\\Git\\usr\\bin\\bash.exe`,
      `${gitDir}\\usr\\bin\\bash.exe`
      // using Git for Windows SDK
    );
  }
  gitBashPaths.push(`${process.env["UserProfile"]}\\scoop\\apps\\git\\current\\bin\\bash.exe`);
  gitBashPaths.push(`${process.env["UserProfile"]}\\scoop\\apps\\git-with-openssh\\current\\bin\\bash.exe`);
  return gitBashPaths;
}
async function getPowershellPaths() {
  const paths = [];
  for await (const pwshExe of $Qm()) {
    paths.push(pwshExe.exePath);
  }
  return paths;
}
async function getWslProfiles(wslPath, defaultProfileName) {
  const profiles = [];
  const distroOutput = await new Promise((resolve2, reject) => {
    cp3.exec("wsl.exe -l -q", { encoding: "utf16le", timeout: 1e3 }, (err, stdout) => {
      if (err) {
        return reject("Problem occurred when getting wsl distros");
      }
      resolve2(stdout);
    });
  });
  if (!distroOutput) {
    return [];
  }
  const regex = new RegExp(/[\r?\n]/);
  const distroNames = distroOutput.split(regex).filter((t) => t.trim().length > 0 && t !== "");
  for (const distroName of distroNames) {
    if (distroName === "") {
      continue;
    }
    if (distroName.startsWith("docker-desktop")) {
      continue;
    }
    const profileName = `${distroName} (WSL)`;
    const profile = {
      profileName,
      path: wslPath,
      args: [`-d`, `${distroName}`],
      isDefault: profileName === defaultProfileName,
      icon: getWslIcon(distroName),
      isAutoDetected: false
    };
    profiles.push(profile);
  }
  return profiles;
}
function getWslIcon(distroName) {
  if (distroName.includes("Ubuntu")) {
    return $mk.terminalUbuntu;
  } else if (distroName.includes("Debian")) {
    return $mk.terminalDebian;
  } else {
    return $mk.terminalLinux;
  }
}
async function detectAvailableUnixProfiles(fsProvider, logService, includeDetectedProfiles, configProfiles, defaultProfileName, testPaths, variableResolver, shellEnv) {
  const detectedProfiles = /* @__PURE__ */ new Map();
  if (includeDetectedProfiles && await fsProvider.existsFile(
    "/etc/shells"
    /* Constants.UnixShellsPath */
  )) {
    const contents = (await fsProvider.readFile(
      "/etc/shells"
      /* Constants.UnixShellsPath */
    )).toString();
    const profiles = (testPaths || contents.split("\n")).map((e) => {
      const index = e.indexOf("#");
      return index === -1 ? e : e.substring(0, index);
    }).filter((e) => e.trim().length > 0);
    const counts = /* @__PURE__ */ new Map();
    for (const profile of profiles) {
      let profileName = $zc(profile);
      let count = counts.get(profileName) || 0;
      count++;
      if (count > 1) {
        profileName = `${profileName} (${count})`;
      }
      counts.set(profileName, count);
      detectedProfiles.set(profileName, { path: profile, isAutoDetected: true });
    }
  }
  applyConfigProfilesToMap(configProfiles, detectedProfiles);
  return await transformToTerminalProfiles(detectedProfiles.entries(), defaultProfileName, fsProvider, shellEnv, logService, variableResolver);
}
function applyConfigProfilesToMap(configProfiles, profilesMap) {
  if (!configProfiles) {
    return;
  }
  for (const [profileName, value] of Object.entries(configProfiles)) {
    if (value === null || typeof value !== "object" || !("path" in value) && !("source" in value)) {
      profilesMap.delete(profileName);
    } else {
      value.icon = value.icon || profilesMap.get(profileName)?.icon;
      profilesMap.set(profileName, value);
    }
  }
}
async function validateProfilePaths(profileName, defaultProfileName, potentialPaths, fsProvider, shellEnv, args, env2, overrideName, isAutoDetected, requiresUnsafePath) {
  if (potentialPaths.length === 0) {
    return Promise.resolve(void 0);
  }
  const path3 = potentialPaths.shift();
  if (path3 === "") {
    return validateProfilePaths(profileName, defaultProfileName, potentialPaths, fsProvider, shellEnv, args, env2, overrideName, isAutoDetected);
  }
  const isUnsafePath = typeof path3 !== "string" && path3.isUnsafe;
  const actualPath = typeof path3 === "string" ? path3 : path3.path;
  const profile = {
    profileName,
    path: actualPath,
    args,
    env: env2,
    overrideName,
    isAutoDetected,
    isDefault: profileName === defaultProfileName,
    isUnsafePath,
    requiresUnsafePath
  };
  if ($zc(actualPath) === actualPath) {
    const envPaths = shellEnv.PATH ? shellEnv.PATH.split($Fc) : void 0;
    const executable = await $0s(actualPath, void 0, envPaths, void 0, fsProvider.existsFile);
    if (!executable) {
      return validateProfilePaths(profileName, defaultProfileName, potentialPaths, fsProvider, shellEnv, args);
    }
    profile.path = executable;
    profile.isFromPath = true;
    return profile;
  }
  const result = await fsProvider.existsFile($tc(actualPath));
  if (result) {
    return profile;
  }
  return validateProfilePaths(profileName, defaultProfileName, potentialPaths, fsProvider, shellEnv, args, env2, overrideName, isAutoDetected);
}

// out-build/vs/platform/terminal/node/ptyHostService.js
var Constants3;
(function(Constants4) {
  Constants4[Constants4["MaxRestarts"] = 5] = "MaxRestarts";
})(Constants3 || (Constants3 = {}));
var $at = class $at2 extends $0c {
  get c() {
    this.h();
    return this.a;
  }
  get f() {
    this.h();
    return this.b;
  }
  /**
   * Get the proxy if it exists, otherwise undefined. This is used when calls are not needed to be
   * passed through to the pty host if it has not yet been spawned.
   */
  get g() {
    return this.b;
  }
  h() {
    if (!this.a) {
      this.U();
    }
  }
  constructor(M, N, O, P) {
    super();
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.m = false;
    this.n = 0;
    this.r = true;
    this.u = this.B(new $De());
    this.onPtyHostExit = this.u.event;
    this.w = this.B(new $De());
    this.onPtyHostStart = this.w.event;
    this.y = this.B(new $De());
    this.onPtyHostUnresponsive = this.y.event;
    this.z = this.B(new $De());
    this.onPtyHostResponsive = this.z.event;
    this.C = this.B(new $De());
    this.onPtyHostRequestResolveVariables = this.C.event;
    this.D = this.B(new $De());
    this.onProcessData = this.D.event;
    this.F = this.B(new $De());
    this.onProcessReady = this.F.event;
    this.G = this.B(new $De());
    this.onProcessReplay = this.G.event;
    this.H = this.B(new $De());
    this.onProcessOrphanQuestion = this.H.event;
    this.I = this.B(new $De());
    this.onDidRequestDetach = this.I.event;
    this.J = this.B(new $De());
    this.onDidChangeProperty = this.J.event;
    this.L = this.B(new $De());
    this.onProcessExit = this.L.event;
    $Zs();
    this.B(this.M);
    this.B($8c(() => this.W()));
    this.j = this.B(new $Ss(void 0, this.O));
    this.B(this.j.onCreateRequest(this.C.fire, this.C));
    if (this.M.onRequestConnection) {
      this.B(Event.once(this.M.onRequestConnection)(() => this.h()));
    }
    if (this.M.onWillShutdown) {
      this.B(this.M.onWillShutdown(() => this.m = true));
    }
  }
  get Q() {
    return this.N.getValue(
      "terminal.integrated.ignoreProcessNames"
      /* TerminalSettingId.IgnoreProcessNames */
    );
  }
  async R() {
    return this.g?.refreshIgnoreProcessNames?.(this.Q);
  }
  async S() {
    if ($l) {
      return process.env;
    }
    try {
      return await $_m(this.N, this.O, { _: [] }, process.env);
    } catch (error) {
      this.O.error("ptyHost was unable to resolve shell environment", error);
      return {};
    }
  }
  U() {
    const connection = this.M.start();
    const client = connection.client;
    if (this.O.getLevel() === LogLevel.Trace) {
      this.O.trace("PtyHostService#_startPtyHost", new Error().stack?.replace(/^Error/, ""));
    }
    const heartbeatService = ProxyChannel.toService(client.getChannel(TerminalIpcChannels.Heartbeat));
    heartbeatService.onBeat(() => this.X());
    this.X(true);
    this.B(connection.onDidProcessExit((e) => {
      this.u.fire(e.code);
      if (!this.m && !this.q.isDisposed) {
        if (this.n <= Constants3.MaxRestarts) {
          this.O.error(`ptyHost terminated unexpectedly with code ${e.code}`);
          this.n++;
          this.restartPtyHost();
        } else {
          this.O.error(`ptyHost terminated unexpectedly with code ${e.code}, giving up`);
        }
      }
    }));
    const proxy = ProxyChannel.toService(client.getChannel(TerminalIpcChannels.PtyHost));
    this.B(proxy.onProcessData((e) => this.D.fire(e)));
    this.B(proxy.onProcessReady((e) => this.F.fire(e)));
    this.B(proxy.onProcessExit((e) => this.L.fire(e)));
    this.B(proxy.onDidChangeProperty((e) => this.J.fire(e)));
    this.B(proxy.onProcessReplay((e) => this.G.fire(e)));
    this.B(proxy.onProcessOrphanQuestion((e) => this.H.fire(e)));
    this.B(proxy.onDidRequestDetach((e) => this.I.fire(e)));
    this.B(new $Rs(this.P, client.getChannel(TerminalIpcChannels.Logger)));
    this.a = connection;
    this.b = proxy;
    this.w.fire();
    this.B(this.N.onDidChangeConfiguration(async (e) => {
      if (e.affectsConfiguration(
        "terminal.integrated.ignoreProcessNames"
        /* TerminalSettingId.IgnoreProcessNames */
      )) {
        await this.R();
      }
    }));
    this.R();
    return [connection, proxy];
  }
  async createProcess(shellLaunchConfig, cwd2, cols, rows, unicodeVersion, env2, executableEnv, options, shouldPersist, workspaceId, workspaceName) {
    const timeout = setTimeout(() => this.$(), HeartbeatConstants.CreateProcessTimeout);
    const id2 = await this.f.createProcess(shellLaunchConfig, cwd2, cols, rows, unicodeVersion, env2, executableEnv, options, shouldPersist, workspaceId, workspaceName);
    clearTimeout(timeout);
    return id2;
  }
  updateTitle(id2, title, titleSource) {
    return this.f.updateTitle(id2, title, titleSource);
  }
  updateIcon(id2, userInitiated, icon, color2) {
    return this.f.updateIcon(id2, userInitiated, icon, color2);
  }
  attachToProcess(id2) {
    return this.f.attachToProcess(id2);
  }
  detachFromProcess(id2, forcePersist) {
    return this.f.detachFromProcess(id2, forcePersist);
  }
  shutdownAll() {
    return this.f.shutdownAll();
  }
  listProcesses() {
    return this.f.listProcesses();
  }
  async getPerformanceMarks() {
    return this.g?.getPerformanceMarks() ?? [];
  }
  async reduceConnectionGraceTime() {
    return this.g?.reduceConnectionGraceTime();
  }
  start(id2) {
    return this.f.start(id2);
  }
  shutdown(id2, immediate) {
    return this.f.shutdown(id2, immediate);
  }
  input(id2, data) {
    return this.f.input(id2, data);
  }
  processBinary(id2, data) {
    return this.f.processBinary(id2, data);
  }
  resize(id2, cols, rows) {
    return this.f.resize(id2, cols, rows);
  }
  clearBuffer(id2) {
    return this.f.clearBuffer(id2);
  }
  acknowledgeDataEvent(id2, charCount) {
    return this.f.acknowledgeDataEvent(id2, charCount);
  }
  setUnicodeVersion(id2, version) {
    return this.f.setUnicodeVersion(id2, version);
  }
  getInitialCwd(id2) {
    return this.f.getInitialCwd(id2);
  }
  getCwd(id2) {
    return this.f.getCwd(id2);
  }
  async getLatency() {
    const sw = new $xe();
    const results = await this.f.getLatency();
    sw.stop();
    return [
      {
        label: "ptyhostservice<->ptyhost",
        latency: sw.elapsed()
      },
      ...results
    ];
  }
  orphanQuestionReply(id2) {
    return this.f.orphanQuestionReply(id2);
  }
  installAutoReply(match, reply) {
    return this.f.installAutoReply(match, reply);
  }
  uninstallAllAutoReplies() {
    return this.f.uninstallAllAutoReplies();
  }
  uninstallAutoReply(match) {
    return this.f.uninstallAutoReply(match);
  }
  getDefaultSystemShell(osOverride) {
    return this.g?.getDefaultSystemShell(osOverride) ?? $Um(osOverride ?? OS, process.env);
  }
  async getProfiles(workspaceId, profiles, defaultProfile, includeDetectedProfiles = false) {
    const shellEnv = await this.S();
    return $_s(profiles, defaultProfile, includeDetectedProfiles, this.N, shellEnv, void 0, this.O, this.bb.bind(this, workspaceId));
  }
  async getEnvironment() {
    if (!this.b) {
      return { ...process.env };
    }
    return this.f.getEnvironment();
  }
  getWslPath(original, direction) {
    return this.f.getWslPath(original, direction);
  }
  getRevivedPtyNewId(workspaceId, id2) {
    return this.f.getRevivedPtyNewId(workspaceId, id2);
  }
  setTerminalLayoutInfo(args) {
    return this.f.setTerminalLayoutInfo(args);
  }
  async getTerminalLayoutInfo(args) {
    return this.g?.getTerminalLayoutInfo(args);
  }
  async requestDetachInstance(workspaceId, instanceId) {
    return this.f.requestDetachInstance(workspaceId, instanceId);
  }
  async acceptDetachInstanceReply(requestId, persistentProcessId) {
    return this.f.acceptDetachInstanceReply(requestId, persistentProcessId);
  }
  async freePortKillProcess(port) {
    if (!this.f.freePortKillProcess) {
      throw new Error("freePortKillProcess does not exist on the pty proxy");
    }
    return this.f.freePortKillProcess(port);
  }
  async serializeTerminalState(ids) {
    return this.f.serializeTerminalState(ids);
  }
  async reviveTerminalProcesses(workspaceId, state, dateTimeFormatLocate) {
    return this.f.reviveTerminalProcesses(workspaceId, state, dateTimeFormatLocate);
  }
  async refreshProperty(id2, property) {
    return this.f.refreshProperty(id2, property);
  }
  async updateProperty(id2, property, value) {
    return this.f.updateProperty(id2, property, value);
  }
  async restartPtyHost() {
    this.W();
    this.r = true;
    this.U();
  }
  W() {
    this.f.shutdownAll();
    this.c.store.dispose();
  }
  X(isConnecting) {
    this.ab();
    this.s = setTimeout(() => this.Y(), isConnecting ? HeartbeatConstants.ConnectingBeatInterval : HeartbeatConstants.BeatInterval * HeartbeatConstants.FirstWaitMultiplier);
    if (!this.r) {
      this.r = true;
      this.z.fire();
    }
  }
  Y() {
    this.O.warn(`No ptyHost heartbeat after ${HeartbeatConstants.BeatInterval * HeartbeatConstants.FirstWaitMultiplier / 1e3} seconds`);
    this.s = void 0;
    this.t = setTimeout(() => this.Z(), HeartbeatConstants.BeatInterval * HeartbeatConstants.SecondWaitMultiplier);
  }
  Z() {
    this.O.error(`No ptyHost heartbeat after ${(HeartbeatConstants.BeatInterval * HeartbeatConstants.FirstWaitMultiplier + HeartbeatConstants.BeatInterval * HeartbeatConstants.FirstWaitMultiplier) / 1e3} seconds`);
    this.t = void 0;
    if (this.r) {
      this.r = false;
      this.y.fire();
    }
  }
  $() {
    this.ab();
    this.O.error(`No ptyHost response to createProcess after ${HeartbeatConstants.CreateProcessTimeout / 1e3} seconds`);
    if (this.r) {
      this.r = false;
      this.y.fire();
    }
  }
  ab() {
    if (this.s) {
      clearTimeout(this.s);
      this.s = void 0;
    }
    if (this.t) {
      clearTimeout(this.t);
      this.t = void 0;
    }
  }
  bb(workspaceId, text) {
    return this.j.createRequest({ workspaceId, originalText: text });
  }
  async acceptPtyHostResolvedVariables(requestId, resolved) {
    this.j.acceptReply(requestId, resolved);
  }
};
$at = __decorate([
  __param(1, $tj),
  __param(2, $uk),
  __param(3, $vk)
], $at);

// out-build/vs/platform/remote/common/electronRemoteResources.js
var $Alc = "request";
var $Blc = "remoteResourceHandler";
var $Clc = class {
  async routeCall(hub, command, arg) {
    if (command !== $Alc) {
      throw new Error(`Call not found: ${command}`);
    }
    const uri = arg[0];
    if (uri?.authority) {
      const connection = hub.connections.find((c) => c.ctx === uri.authority);
      if (connection) {
        return connection;
      }
    }
    throw new Error(`Caller not found`);
  }
  routeEvent(_, event) {
    throw new Error(`Event not found: ${event}`);
  }
};

// out-build/vs/platform/auxiliaryWindow/electron-main/auxiliaryWindowsMainService.js
import { BrowserWindow as BrowserWindow7, app as app11 } from "electron";

// out-build/vs/platform/auxiliaryWindow/electron-main/auxiliaryWindow.js
import { BrowserWindow as BrowserWindow6 } from "electron";
var $8jc = class $8jc2 extends $6jc {
  get win() {
    if (!super.win) {
      this.tryClaimWindow();
    }
    return super.win;
  }
  constructor(O, environmentMainService, logService, configurationService, stateService, P) {
    super(configurationService, stateService, environmentMainService, logService);
    this.O = O;
    this.P = P;
    this.id = this.O.id;
    this.parentId = -1;
    this.N = false;
    this.tryClaimWindow();
  }
  tryClaimWindow(options) {
    if (this.q.isDisposed || this.O.isDestroyed()) {
      return;
    }
    this.Q(options);
    if (options && !this.N) {
      this.N = true;
      this.w({
        x: options.x,
        y: options.y,
        width: options.width,
        height: options.height,
        // TODO@bpasero We currently do not support restoring fullscreen state for
        // auxiliary windows because we do not get hold of the original `features`
        // string that contains that info in `window-fullscreen`. However, we can
        // probe the `options.show` value for whether the window should be maximized
        // or not because we never show maximized windows initially to reduce flicker.
        mode: options.show === false ? 0 : 1
        /* WindowMode.Normal */
      });
    }
  }
  Q(options) {
    if (this.m) {
      return;
    }
    const window2 = BrowserWindow6.fromWebContents(this.O);
    if (window2) {
      this.u.trace("[aux window] Claimed browser window instance");
      this.n(window2, options);
      window2.setMenu(null);
      if (($l || $n) && $QE(
        this.r,
        options?.titleBarStyle === "hidden" ? "custom" : void 0
        /* unknown */
      )) {
        window2.setAutoHideMenuBar(true);
      }
      this.P.registerAuxWindow(this);
    }
  }
  matches(webContents3) {
    return this.O.id === webContents3.id;
  }
};
$8jc = __decorate([
  __param(1, $Cjc),
  __param(2, $uk),
  __param(3, $tj),
  __param(4, $BS),
  __param(5, $9jc)
], $8jc);

// out-build/vs/platform/auxiliaryWindow/electron-main/auxiliaryWindowsMainService.js
var $Dlc = class $Dlc2 extends $0c {
  constructor(h, j) {
    super();
    this.h = h;
    this.j = j;
    this.a = this.B(new $De());
    this.onDidMaximizeWindow = this.a.event;
    this.b = this.B(new $De());
    this.onDidUnmaximizeWindow = this.b.event;
    this.c = this.B(new $De());
    this.onDidChangeFullScreen = this.c.event;
    this.f = this.B(new $De());
    this.onDidTriggerSystemContextMenu = this.f.event;
    this.g = /* @__PURE__ */ new Map();
    this.m();
  }
  m() {
    app11.on("browser-window-created", (_event, browserWindow) => {
      const auxiliaryWindow = this.getWindowByWebContents(browserWindow.webContents);
      if (auxiliaryWindow) {
        this.j.trace('[aux window] app.on("browser-window-created"): Trying to claim auxiliary window');
        auxiliaryWindow.tryClaimWindow();
      } else {
        const disposables = new $9c();
        disposables.add(Event.fromNodeEventEmitter(browserWindow.webContents, "did-create-window", (browserWindow2, details) => ({ browserWindow: browserWindow2, details }))(({ browserWindow: browserWindow2, details }) => {
          const auxiliaryWindow2 = this.getWindowByWebContents(browserWindow2.webContents);
          if (auxiliaryWindow2) {
            this.j.trace('[aux window] window.on("did-create-window"): Trying to claim auxiliary window');
            auxiliaryWindow2.tryClaimWindow(details.options);
          }
        }));
        disposables.add(Event.fromNodeEventEmitter(browserWindow, "closed")(() => disposables.dispose()));
      }
    });
    $ZY.handle("vscode:registerAuxiliaryWindow", async (event, mainWindowId) => {
      const auxiliaryWindow = this.getWindowByWebContents(event.sender);
      if (auxiliaryWindow) {
        this.j.trace("[aux window] vscode:registerAuxiliaryWindow: Registering auxiliary window to main window");
        auxiliaryWindow.parentId = mainWindowId;
      }
      return event.sender.id;
    });
  }
  createWindow(details) {
    const { state, overrides } = this.n(details);
    return this.h.invokeFunction($Qjc, state, overrides, {
      preload: $hh.asFileUri("vs/base/parts/sandbox/electron-sandbox/preload-aux.js").fsPath
    });
  }
  n(details) {
    const windowState = {};
    const overrides = {};
    const features = details.features.split(",");
    for (const feature of features) {
      const [key, value] = feature.split("=");
      switch (key) {
        case "width":
          windowState.width = parseInt(value, 10);
          break;
        case "height":
          windowState.height = parseInt(value, 10);
          break;
        case "left":
          windowState.x = parseInt(value, 10);
          break;
        case "top":
          windowState.y = parseInt(value, 10);
          break;
        case "window-maximized":
          windowState.mode = 0;
          break;
        case "window-fullscreen":
          windowState.mode = 3;
          break;
        case "window-disable-fullscreen":
          overrides.disableFullscreen = true;
          break;
        case "window-native-titlebar":
          overrides.forceNativeTitlebar = true;
          break;
      }
    }
    const state = WindowStateValidator.validateWindowState(this.j, windowState) ?? $Fjc();
    this.j.trace("[aux window] using window state", state);
    return { state, overrides };
  }
  registerWindow(webContents3) {
    const disposables = new $9c();
    const auxiliaryWindow = this.h.createInstance($8jc, webContents3);
    this.g.set(auxiliaryWindow.id, auxiliaryWindow);
    disposables.add($8c(() => this.g.delete(auxiliaryWindow.id)));
    disposables.add(auxiliaryWindow.onDidMaximize(() => this.a.fire(auxiliaryWindow)));
    disposables.add(auxiliaryWindow.onDidUnmaximize(() => this.b.fire(auxiliaryWindow)));
    disposables.add(auxiliaryWindow.onDidEnterFullScreen(() => this.c.fire({ window: auxiliaryWindow, fullscreen: true })));
    disposables.add(auxiliaryWindow.onDidLeaveFullScreen(() => this.c.fire({ window: auxiliaryWindow, fullscreen: false })));
    disposables.add(auxiliaryWindow.onDidTriggerSystemContextMenu(({ x, y }) => this.f.fire({ window: auxiliaryWindow, x, y })));
    Event.once(auxiliaryWindow.onDidClose)(() => disposables.dispose());
  }
  getWindowByWebContents(webContents3) {
    const window2 = this.g.get(webContents3.id);
    return window2?.matches(webContents3) ? window2 : void 0;
  }
  getFocusedWindow() {
    const window2 = BrowserWindow7.getFocusedWindow();
    if (window2) {
      return this.getWindowByWebContents(window2.webContents);
    }
    return void 0;
  }
  getLastActiveWindow() {
    return $Rjc(Array.from(this.g.values()));
  }
  getWindows() {
    return Array.from(this.g.values());
  }
};
$Dlc = __decorate([
  __param(0, $Yi),
  __param(1, $uk)
], $Dlc);

// out-build/vs/amdX.js
var DefineCall = class {
  constructor(id2, dependencies, callback) {
    this.id = id2;
    this.dependencies = dependencies;
    this.callback = callback;
  }
};
var AMDModuleImporterState;
(function(AMDModuleImporterState2) {
  AMDModuleImporterState2[AMDModuleImporterState2["Uninitialized"] = 1] = "Uninitialized";
  AMDModuleImporterState2[AMDModuleImporterState2["InitializedInternal"] = 2] = "InitializedInternal";
  AMDModuleImporterState2[AMDModuleImporterState2["InitializedExternal"] = 3] = "InitializedExternal";
})(AMDModuleImporterState || (AMDModuleImporterState = {}));
var AMDModuleImporter = class _AMDModuleImporter {
  static {
    this.INSTANCE = new _AMDModuleImporter();
  }
  constructor() {
    this.a = typeof self === "object" && self.constructor && self.constructor.name === "DedicatedWorkerGlobalScope";
    this.b = typeof document === "object";
    this.c = [];
    this.d = AMDModuleImporterState.Uninitialized;
  }
  g() {
    if (this.d === AMDModuleImporterState.Uninitialized) {
      if (globalThis.define) {
        console.log("[amdX] AMD loader already present externally");
        this.d = AMDModuleImporterState.InitializedExternal;
        return;
      }
    } else {
      return;
    }
    this.d = AMDModuleImporterState.InitializedInternal;
    globalThis.define = (id2, dependencies, callback) => {
      if (typeof id2 !== "string") {
        callback = dependencies;
        dependencies = id2;
        id2 = null;
      }
      if (typeof dependencies !== "object" || !Array.isArray(dependencies)) {
        callback = dependencies;
        dependencies = null;
      }
      this.c.push(new DefineCall(id2, dependencies, callback));
    };
    globalThis.define.amd = true;
    if (this.b) {
      this.f = globalThis._VSCODE_WEB_PACKAGE_TTP ?? window.trustedTypes?.createPolicy("amdLoader", {
        createScriptURL(value) {
          if (value.startsWith(window.location.origin)) {
            return value;
          }
          if (value.startsWith(`${Schemas.vscodeFileResource}://${$gh}`)) {
            return value;
          }
          throw new Error(`[trusted_script_src] Invalid script url: ${value}`);
        }
      });
    } else if (this.a) {
      this.f = globalThis._VSCODE_WEB_PACKAGE_TTP ?? globalThis.trustedTypes?.createPolicy("amdLoader", {
        createScriptURL(value) {
          return value;
        }
      });
    }
  }
  async load(scriptSrc) {
    this.g();
    if (this.d === AMDModuleImporterState.InitializedExternal) {
      return new Promise((resolve2) => {
        const tmpModuleId = $jh();
        console.log(`[amdX] Using external define("${tmpModuleId}", ["${scriptSrc}"])`);
        globalThis.define(tmpModuleId, [scriptSrc], function(moduleResult) {
          console.log(`[amdX] Got a result for ${tmpModuleId}: ${!!moduleResult}`);
          resolve2(moduleResult);
        });
      });
    }
    const defineCall = await (this.a ? this.i(scriptSrc) : this.b ? this.h(scriptSrc) : this.j(scriptSrc));
    if (!defineCall) {
      console.warn(`Did not receive a define call from script ${scriptSrc}`);
      return void 0;
    }
    const exports2 = {};
    const dependencyObjs = [];
    const dependencyModules = [];
    if (Array.isArray(defineCall.dependencies)) {
      for (const mod of defineCall.dependencies) {
        if (mod === "exports") {
          dependencyObjs.push(exports2);
        } else {
          dependencyModules.push(mod);
        }
      }
    }
    if (dependencyModules.length > 0) {
      throw new Error(`Cannot resolve dependencies for script ${scriptSrc}. The dependencies are: ${dependencyModules.join(", ")}`);
    }
    if (typeof defineCall.callback === "function") {
      return defineCall.callback(...dependencyObjs) ?? exports2;
    } else {
      return defineCall.callback;
    }
  }
  h(scriptSrc) {
    return new Promise((resolve2, reject) => {
      const scriptElement = document.createElement("script");
      scriptElement.setAttribute("async", "async");
      scriptElement.setAttribute("type", "text/javascript");
      const unbind = () => {
        scriptElement.removeEventListener("load", loadEventListener);
        scriptElement.removeEventListener("error", errorEventListener);
      };
      const loadEventListener = (e) => {
        unbind();
        resolve2(this.c.pop());
      };
      const errorEventListener = (e) => {
        unbind();
        reject(e);
      };
      scriptElement.addEventListener("load", loadEventListener);
      scriptElement.addEventListener("error", errorEventListener);
      if (this.f) {
        scriptSrc = this.f.createScriptURL(scriptSrc);
      }
      scriptElement.setAttribute("src", scriptSrc);
      window.document.getElementsByTagName("head")[0].appendChild(scriptElement);
    });
  }
  async i(scriptSrc) {
    if (this.f) {
      scriptSrc = this.f.createScriptURL(scriptSrc);
    }
    if ($4) {
      await import(scriptSrc);
    } else {
      importScripts(scriptSrc);
    }
    return this.c.pop();
  }
  async j(scriptSrc) {
    try {
      const fs13 = (await import(`${"fs"}`)).default;
      const vm = (await import(`${"vm"}`)).default;
      const module6 = (await import(`${"module"}`)).default;
      const filePath = URI.parse(scriptSrc).fsPath;
      const content = fs13.readFileSync(filePath).toString();
      const scriptSource = module6.wrap(content.replace(/^#!.*/, ""));
      const script = new vm.Script(scriptSource);
      const compileWrapper = script.runInThisContext();
      compileWrapper.apply();
      return this.c.pop();
    } catch (error) {
      throw error;
    }
  }
};
var cache = /* @__PURE__ */ new Map();
async function $Oq(nodeModuleName, pathInsideNodeModule, isBuilt) {
  if ($4) {
    if (isBuilt === void 0) {
      const product2 = globalThis._VSCODE_PRODUCT_JSON;
      isBuilt = Boolean((product2 ?? globalThis.vscode?.context?.configuration()?.product)?.commit);
    }
    const nodeModulePath = pathInsideNodeModule ? `${nodeModuleName}/${pathInsideNodeModule}` : nodeModuleName;
    if (cache.has(nodeModulePath)) {
      return cache.get(nodeModulePath);
    }
    let scriptSrc;
    if (/^\w[\w\d+.-]*:\/\//.test(nodeModulePath)) {
      scriptSrc = nodeModulePath;
    } else {
      const useASAR = $5 && isBuilt && !$r;
      const actualNodeModulesPath = useASAR ? $eh : $dh;
      const resourcePath = `${actualNodeModulesPath}/${nodeModulePath}`;
      scriptSrc = $hh.asBrowserUri(resourcePath).toString(true);
    }
    const result = AMDModuleImporter.INSTANCE.load(scriptSrc);
    cache.set(nodeModulePath, result);
    return result;
  } else {
    return await import(nodeModuleName);
  }
}

// out-build/vs/platform/extensionManagement/node/extensionSignatureVerificationService.js
var $Qq = $Zi("IExtensionSignatureVerificationService");
var $Rq = class $Rq2 {
  constructor(b, c) {
    this.b = b;
    this.c = c;
  }
  d() {
    if (!this.a) {
      this.a = this.f();
    }
    return this.a;
  }
  async f() {
    if (typeof $Oq === "function") {
    }
    const mod = "@vscode/vsce-sign";
    return import(mod);
  }
  async verify(extensionId, version, vsixFilePath, signatureArchiveFilePath, clientTargetPlatform) {
    let module6;
    try {
      module6 = await this.d();
    } catch (error) {
      this.b.error("Could not load vsce-sign module", $kb(error));
      this.b.info(`Extension signature verification is not done: ${extensionId}`);
      return void 0;
    }
    const startTime = (/* @__PURE__ */ new Date()).getTime();
    let result;
    try {
      this.b.trace(`Verifying extension signature for ${extensionId}...`);
      result = await module6.verify(vsixFilePath, signatureArchiveFilePath, this.b.getLevel() === LogLevel.Trace);
    } catch (e) {
      result = {
        code: ExtensionSignatureVerificationCode.UnknownError,
        didExecute: false,
        output: $kb(e)
      };
    }
    const duration = (/* @__PURE__ */ new Date()).getTime() - startTime;
    this.b.info(`Extension signature verification result for ${extensionId}: ${result.code}. Executed: ${result.didExecute}. Duration: ${duration}ms.`);
    this.b.trace(`Extension signature verification output for ${extensionId}:
${result.output}`);
    this.c.publicLog2("extensionsignature:verification", {
      extensionId,
      extensionVersion: version,
      code: result.code,
      internalCode: result.internalCode,
      duration,
      didExecute: result.didExecute,
      clientTargetPlatform
    });
    return { code: result.code };
  }
};
$Rq = __decorate([
  __param(0, $uk),
  __param(1, $tm)
], $Rq);

// out-build/vs/platform/void/electron-main/llmMessage/anthropic.js
import Anthropic from "@anthropic-ai/sdk";

// out-build/vs/platform/void/common/voidSettingsTypes.js
var $mOb = (modelNames, options) => {
  const { isAutodetected, existingModels } = options ?? {};
  const isDefault = true;
  const isHidden = modelNames.length >= 10;
  if (!existingModels) {
    return modelNames.map((modelName, i) => ({ modelName, isDefault, isAutodetected, isHidden }));
  } else {
    const existingModelsMap = {};
    for (const em of existingModels) {
      existingModelsMap[em.modelName] = em;
    }
    return modelNames.map((modelName, i) => ({ modelName, isDefault, isAutodetected, isHidden: !!existingModelsMap[modelName]?.isHidden }));
  }
};
var $nOb = $mOb([
  "claude-3-5-sonnet-20241022",
  "claude-3-5-haiku-20241022",
  "claude-3-opus-20240229",
  "claude-3-sonnet-20240229"
  // 'claude-3-haiku-20240307',
]);
var $oOb = $mOb([
  "o1-preview",
  "o1-mini",
  "gpt-4o",
  "gpt-4o-mini"
  // 'gpt-4o-2024-05-13',
  // 'gpt-4o-2024-08-06',
  // 'gpt-4o-mini-2024-07-18',
  // 'gpt-4-turbo',
  // 'gpt-4-turbo-2024-04-09',
  // 'gpt-4-turbo-preview',
  // 'gpt-4-0125-preview',
  // 'gpt-4-1106-preview',
  // 'gpt-4',
  // 'gpt-4-0613',
  // 'gpt-3.5-turbo-0125',
  // 'gpt-3.5-turbo',
  // 'gpt-3.5-turbo-1106',
]);
var $pOb = $mOb([
  "mixtral-8x7b-32768",
  "llama2-70b-4096",
  "gemma-7b-it"
]);
var $qOb = $mOb([
  "gemini-1.5-flash",
  "gemini-1.5-pro",
  "gemini-1.5-flash-8b",
  "gemini-1.0-pro"
]);
var $rOb = (modelName) => {
  if (modelName === "claude-3-5-sonnet-20241022" || modelName === "claude-3-5-haiku-20241022")
    return 8192;
  if (modelName === "claude-3-opus-20240229" || modelName === "claude-3-sonnet-20240229" || modelName === "claude-3-haiku-20240307")
    return 4096;
  return 1024;
};
var $sOb = {
  anthropic: {
    apiKey: ""
  },
  openAI: {
    apiKey: ""
  },
  ollama: {
    endpoint: "http://127.0.0.1:11434"
  },
  openRouter: {
    apiKey: ""
  },
  openAICompatible: {
    endpoint: "",
    apiKey: ""
  },
  gemini: {
    apiKey: ""
  },
  groq: {
    apiKey: ""
  }
};
var $tOb = Object.keys($sOb);
var $uOb = ["ollama", "openAICompatible"];
var $vOb = $tOb.filter((name) => !$uOb.includes(name));
var defaultCustomSettings = {
  apiKey: void 0,
  endpoint: void 0
};
var $zOb = {
  anthropic: {
    models: $nOb
  },
  openAI: {
    models: $oOb
  },
  ollama: {
    models: []
  },
  openRouter: {
    models: []
    // any string
  },
  openAICompatible: {
    models: []
  },
  gemini: {
    models: $qOb
  },
  groq: {
    models: $pOb
  }
};
var $AOb = {
  anthropic: {
    _enabled: void 0,
    ...defaultCustomSettings,
    ...$sOb.anthropic,
    ...$zOb.anthropic
  },
  openAI: {
    _enabled: void 0,
    ...defaultCustomSettings,
    ...$sOb.openAI,
    ...$zOb.openAI
  },
  gemini: {
    ...defaultCustomSettings,
    ...$sOb.gemini,
    ...$zOb.gemini,
    _enabled: void 0
  },
  groq: {
    ...defaultCustomSettings,
    ...$sOb.groq,
    ...$zOb.groq,
    _enabled: void 0
  },
  ollama: {
    ...defaultCustomSettings,
    ...$sOb.ollama,
    ...$zOb.ollama,
    _enabled: void 0
  },
  openRouter: {
    ...defaultCustomSettings,
    ...$sOb.openRouter,
    ...$zOb.openRouter,
    _enabled: void 0
  },
  openAICompatible: {
    ...defaultCustomSettings,
    ...$sOb.openAICompatible,
    ...$zOb.openAICompatible,
    _enabled: void 0
  }
};
var $EOb = {
  autoRefreshModels: true
};
var $FOb = Object.keys($EOb);

// out-build/vs/platform/void/electron-main/llmMessage/anthropic.js
var $Elc = ({ messages, onText, onFinalMessage, onError, settingsOfProvider, modelName, _setAborter }) => {
  const thisConfig = settingsOfProvider.anthropic;
  const maxTokens = $rOb(modelName);
  if (maxTokens === void 0) {
    onError({ message: `Please set a value for Max Tokens.`, fullError: null });
    return;
  }
  const anthropic = new Anthropic({ apiKey: thisConfig.apiKey, dangerouslyAllowBrowser: true });
  const systemMessage = messages.filter((msg) => msg.role === "system").map((msg) => msg.content).join("\n");
  const anthropicMessages = messages.filter((msg) => msg.role !== "system");
  const stream = anthropic.messages.stream({
    system: systemMessage,
    messages: anthropicMessages,
    model: modelName,
    max_tokens: maxTokens
  });
  stream.on("text", (newText, fullText) => {
    onText({ newText, fullText });
  });
  stream.on("finalMessage", (claude_response) => {
    const content = claude_response.content.map((c) => c.type === "text" ? c.text : c.type).join("\n");
    onFinalMessage({ fullText: content });
  });
  stream.on("error", (error) => {
    if (error instanceof Anthropic.APIError && error.status === 401) {
      onError({ message: "Invalid API key.", fullError: error });
    } else {
      onError({ message: error + "", fullError: error });
    }
  });
  _setAborter(() => stream.controller.abort());
};

// out-build/vs/platform/void/electron-main/llmMessage/ollama.js
import { Ollama } from "ollama";
var $Flc = async ({ onSuccess: onSuccess_, onError: onError_, settingsOfProvider }) => {
  const onSuccess = ({ models }) => {
    onSuccess_({ models });
  };
  const onError = ({ error }) => {
    onError_({ error });
  };
  try {
    const thisConfig = settingsOfProvider.ollama;
    if (!thisConfig.endpoint)
      throw new Error(`Ollama Endpoint was empty (please enter ${$sOb.ollama.endpoint} in Void if you want the default url).`);
    const ollama = new Ollama({ host: thisConfig.endpoint });
    ollama.list().then((response) => {
      const { models } = response;
      onSuccess({ models });
    }).catch((error) => {
      onError({ error: error + "" });
    });
  } catch (error) {
    onError({ error: error + "" });
  }
};
var $Glc = ({ messages, onText, onFinalMessage, onError, settingsOfProvider, modelName, _setAborter }) => {
  const thisConfig = settingsOfProvider.ollama;
  if (!thisConfig.endpoint)
    throw new Error(`Ollama Endpoint was empty (please enter ${$sOb.ollama.endpoint} if you want the default).`);
  let fullText = "";
  const ollama = new Ollama({ host: thisConfig.endpoint });
  ollama.chat({
    model: modelName,
    messages,
    stream: true
    // options: { num_predict: parseMaxTokensStr(thisConfig.maxTokens) } // this is max_tokens
  }).then(async (stream) => {
    _setAborter(() => stream.abort());
    for await (const chunk of stream) {
      const newText = chunk.message.content;
      fullText += newText;
      onText({ newText, fullText });
    }
    onFinalMessage({ fullText });
  }).catch((error) => {
    onError({ message: error + "", fullError: error });
  });
};

// out-build/vs/platform/void/electron-main/llmMessage/openai.js
import OpenAI from "openai";
var $Hlc = async ({ onSuccess: onSuccess_, onError: onError_, settingsOfProvider }) => {
  const onSuccess = ({ models }) => {
    onSuccess_({ models });
  };
  const onError = ({ error }) => {
    onError_({ error });
  };
  try {
    const thisConfig = settingsOfProvider.openAICompatible;
    const openai = new OpenAI({ baseURL: thisConfig.endpoint, apiKey: thisConfig.apiKey, dangerouslyAllowBrowser: true });
    openai.models.list().then(async (response) => {
      const models = [];
      models.push(...response.data);
      while (response.hasNextPage()) {
        models.push(...(await response.getNextPage()).data);
      }
      onSuccess({ models });
    }).catch((error) => {
      onError({ error: error + "" });
    });
  } catch (error) {
    onError({ error: error + "" });
  }
};
var $Ilc = ({ messages, onText, onFinalMessage, onError, settingsOfProvider, modelName, _setAborter, providerName }) => {
  let fullText = "";
  let openai;
  let options;
  if (providerName === "openAI") {
    const thisConfig = settingsOfProvider.openAI;
    openai = new OpenAI({ apiKey: thisConfig.apiKey, dangerouslyAllowBrowser: true });
    options = {
      model: modelName,
      messages,
      stream: true
      /*max_completion_tokens: parseMaxTokensStr(thisConfig.maxTokens)*/
    };
  } else if (providerName === "openRouter") {
    const thisConfig = settingsOfProvider.openRouter;
    openai = new OpenAI({
      baseURL: "https://openrouter.ai/api/v1",
      apiKey: thisConfig.apiKey,
      dangerouslyAllowBrowser: true,
      defaultHeaders: {
        "HTTP-Referer": "https://voideditor.com",
        // Optional, for including your app on openrouter.ai rankings.
        "X-Title": "Void Editor"
        // Optional. Shows in rankings on openrouter.ai.
      }
    });
    options = {
      model: modelName,
      messages,
      stream: true
      /*max_completion_tokens: parseMaxTokensStr(thisConfig.maxTokens)*/
    };
  } else if (providerName === "openAICompatible") {
    const thisConfig = settingsOfProvider.openAICompatible;
    openai = new OpenAI({ baseURL: thisConfig.endpoint, apiKey: thisConfig.apiKey, dangerouslyAllowBrowser: true });
    options = {
      model: modelName,
      messages,
      stream: true
      /*max_completion_tokens: parseMaxTokensStr(thisConfig.maxTokens)*/
    };
  } else {
    console.error(`sendOpenAIMsg: invalid providerName: ${providerName}`);
    throw new Error(`providerName was invalid: ${providerName}`);
  }
  openai.models.list();
  openai.chat.completions.create(options).then(async (response) => {
    _setAborter(() => response.controller.abort());
    for await (const chunk of response) {
      const newText = chunk.choices[0]?.delta?.content || "";
      fullText += newText;
      onText({ newText, fullText });
    }
    onFinalMessage({ fullText });
  }).catch((error) => {
    if (error instanceof OpenAI.APIError && error.status === 401) {
      onError({ message: "Invalid API key.", fullError: error });
    } else {
      onError({ message: error, fullError: error });
    }
  });
};

// out-build/vs/platform/void/electron-main/llmMessage/gemini.js
import { GoogleGenerativeAI, GoogleGenerativeAIFetchError } from "@google/generative-ai";
var $Jlc = async ({ messages, onText, onFinalMessage, onError, settingsOfProvider, modelName, _setAborter }) => {
  let fullText = "";
  const thisConfig = settingsOfProvider.gemini;
  const genAI = new GoogleGenerativeAI(thisConfig.apiKey);
  const model = genAI.getGenerativeModel({ model: modelName });
  const systemMessage = messages.filter((msg) => msg.role === "system").map((msg) => msg.content).join("\n");
  const geminiMessages = messages.filter((msg) => msg.role !== "system").map((msg, i) => ({
    parts: [{ text: msg.content }],
    role: msg.role === "assistant" ? "model" : "user"
  }));
  model.generateContentStream({ contents: geminiMessages, systemInstruction: systemMessage }).then(async (response) => {
    _setAborter(() => response.stream.return(fullText));
    for await (const chunk of response.stream) {
      const newText = chunk.text();
      fullText += newText;
      onText({ newText, fullText });
    }
    onFinalMessage({ fullText });
  }).catch((error) => {
    if (error instanceof GoogleGenerativeAIFetchError && error.status === 400) {
      onError({ message: "Invalid API key.", fullError: null });
    } else {
      onError({ message: error + "", fullError: error });
    }
  });
};

// out-build/vs/platform/void/electron-main/llmMessage/groq.js
import Groq from "groq-sdk";
var $Klc = async ({ messages, onText, onFinalMessage, onError, settingsOfProvider, modelName, _setAborter }) => {
  let fullText = "";
  const thisConfig = settingsOfProvider.groq;
  const groq = new Groq({
    apiKey: thisConfig.apiKey,
    dangerouslyAllowBrowser: true
  });
  await groq.chat.completions.create({
    messages,
    model: modelName,
    stream: true,
    temperature: 0.7
    // max_tokens: parseMaxTokensStr(thisConfig.maxTokens),
  }).then(async (response) => {
    _setAborter(() => response.controller.abort());
    for await (const chunk of response) {
      const newText = chunk.choices[0]?.delta?.content || "";
      if (newText) {
        fullText += newText;
        onText({ newText, fullText });
      }
    }
    onFinalMessage({ fullText });
  }).catch((error) => {
    onError({ message: error + "", fullError: error });
  });
};

// out-build/vs/platform/void/electron-main/llmMessage/sendLLMMessage.js
var $Llc = ({ messages, onText: onText_, onFinalMessage: onFinalMessage_, onError: onError_, abortRef: abortRef_, logging: { loggingName }, settingsOfProvider, providerName, modelName }, metricsService) => {
  messages = messages.map((m) => ({ ...m, content: m.content.trim() }));
  const captureChatEvent = (eventId, extras) => {
    metricsService.capture(eventId, {
      providerName,
      numMessages: messages?.length,
      messagesShape: messages?.map((msg) => ({ role: msg.role, length: msg.content.length })),
      version: "2024-11-14",
      ...extras
    });
  };
  const submit_time = /* @__PURE__ */ new Date();
  let _fullTextSoFar = "";
  let _aborter = null;
  let _setAborter = (fn) => {
    _aborter = fn;
  };
  let _didAbort = false;
  const onText = ({ newText, fullText }) => {
    if (_didAbort)
      return;
    onText_({ newText, fullText });
    _fullTextSoFar = fullText;
  };
  const onFinalMessage = ({ fullText }) => {
    if (_didAbort)
      return;
    captureChatEvent(`${loggingName} - Received Full Message`, { messageLength: fullText.length, duration: (/* @__PURE__ */ new Date()).getMilliseconds() - submit_time.getMilliseconds() });
    onFinalMessage_({ fullText });
  };
  const onError = ({ message: error, fullError }) => {
    if (_didAbort)
      return;
    console.log("ERROR!!!!!", error);
    console.error("sendLLMMessage onError:", error);
    captureChatEvent(`${loggingName} - Error`, { error });
    onError_({ message: error, fullError });
  };
  const onAbort = () => {
    captureChatEvent(`${loggingName} - Abort`, { messageLengthSoFar: _fullTextSoFar.length });
    try {
      _aborter?.();
    } catch (e) {
    }
    _didAbort = true;
  };
  abortRef_.current = onAbort;
  captureChatEvent(`${loggingName} - Sending Message`, { messageLength: messages[messages.length - 1]?.content.length });
  try {
    switch (providerName) {
      case "anthropic":
        $Elc({ messages, onText, onFinalMessage, onError, settingsOfProvider, modelName, _setAborter, providerName });
        break;
      case "openAI":
      case "openRouter":
      case "openAICompatible":
        $Ilc({ messages, onText, onFinalMessage, onError, settingsOfProvider, modelName, _setAborter, providerName });
        break;
      case "gemini":
        $Jlc({ messages, onText, onFinalMessage, onError, settingsOfProvider, modelName, _setAborter, providerName });
        break;
      case "ollama":
        $Glc({ messages, onText, onFinalMessage, onError, settingsOfProvider, modelName, _setAborter, providerName });
        break;
      case "groq":
        $Klc({ messages, onText, onFinalMessage, onError, settingsOfProvider, modelName, _setAborter, providerName });
        break;
      default:
        onError({ message: `Error: Void provider was "${providerName}", which is not recognized.`, fullError: null });
        break;
    }
  } catch (error) {
    if (error instanceof Error) {
      onError({ message: error + "", fullError: error });
    } else {
      onError({ message: `Unexpected Error in sendLLMMessage: ${error}`, fullError: error });
    }
  }
};

// out-build/vs/platform/void/electron-main/llmMessageChannel.js
var $Mlc = class {
  // stupidly, channels can't take in @IService
  constructor(j) {
    this.j = j;
    this.a = new $De();
    this.b = new $De();
    this.c = new $De();
    this.d = {};
    this.f = new $De();
    this.g = new $De();
    this.h = new $De();
    this.i = new $De();
  }
  // browser uses this to listen for changes
  listen(_, event) {
    if (event === "onText_llm") {
      return this.a.event;
    } else if (event === "onFinalMessage_llm") {
      return this.b.event;
    } else if (event === "onError_llm") {
      return this.c.event;
    } else if (event === "onSuccess_ollama") {
      return this.f.event;
    } else if (event === "onError_ollama") {
      return this.g.event;
    } else if (event === "onSuccess_openAICompatible") {
      return this.h.event;
    } else if (event === "onError_openAICompatible") {
      return this.i.event;
    } else {
      throw new Error(`Event not found: ${event}`);
    }
  }
  // browser uses this to call
  async call(_, command, params) {
    try {
      if (command === "sendLLMMessage") {
        this.k(params);
      } else if (command === "abort") {
        this.l(params);
      } else if (command === "ollamaList") {
        this.m(params);
      } else if (command === "openAICompatibleList") {
        this.n(params);
      } else {
        throw new Error(`Void sendLLM: command "${command}" not recognized.`);
      }
    } catch (e) {
      console.log("llmMessageChannel: Call Error:", e);
    }
  }
  // the only place sendLLMMessage is actually called
  async k(params) {
    const { requestId } = params;
    if (!(requestId in this.d))
      this.d[requestId] = { current: null };
    const mainThreadParams = {
      ...params,
      onText: ({ newText, fullText }) => {
        this.a.fire({ requestId, newText, fullText });
      },
      onFinalMessage: ({ fullText }) => {
        this.b.fire({ requestId, fullText });
      },
      onError: ({ message: error, fullError }) => {
        console.log("sendLLM: firing err");
        this.c.fire({ requestId, message: error, fullError });
      },
      abortRef: this.d[requestId]
    };
    $Llc(mainThreadParams, this.j);
  }
  l(params) {
    const { requestId } = params;
    if (!(requestId in this.d))
      return;
    this.d[requestId].current?.();
    delete this.d[requestId];
  }
  m(params) {
    const { requestId } = params;
    const mainThreadParams = {
      ...params,
      onSuccess: ({ models }) => {
        this.f.fire({ requestId, models });
      },
      onError: ({ error }) => {
        this.g.fire({ requestId, error });
      }
    };
    $Flc(mainThreadParams);
  }
  n(params) {
    const { requestId } = params;
    const mainThreadParams = {
      ...params,
      onSuccess: ({ models }) => {
        this.h.fire({ requestId, models });
      },
      onError: ({ error }) => {
        this.i.fire({ requestId, error });
      }
    };
    $Hlc(mainThreadParams);
  }
};

// out-build/vs/platform/ipc/common/mainProcessService.js
var $HOb = $Zi("mainProcessService");

// out-build/vs/platform/instantiation/common/extensions.js
var _registry = [];
var InstantiationType;
(function(InstantiationType2) {
  InstantiationType2[InstantiationType2["Eager"] = 0] = "Eager";
  InstantiationType2[InstantiationType2["Delayed"] = 1] = "Delayed";
})(InstantiationType || (InstantiationType = {}));
function $bt(id2, ctorOrDescriptor, supportsDelayedInstantiation) {
  if (!(ctorOrDescriptor instanceof $Wi)) {
    ctorOrDescriptor = new $Wi(ctorOrDescriptor, [], Boolean(supportsDelayedInstantiation));
  }
  _registry.push([id2, ctorOrDescriptor]);
}

// out-build/vs/platform/void/common/metricsService.js
var $ZOb = $Zi("metricsService");
var $1Ob = class $1Ob2 {
  constructor(mainProcessService) {
    this.a = ProxyChannel.toService(mainProcessService.getChannel("void-channel-metrics"));
  }
  // call capture on the channel
  capture(...params) {
    this.a.capture(...params);
  }
};
$1Ob = __decorate([
  __param(0, $HOb)
], $1Ob);
$bt(
  $ZOb,
  $1Ob,
  0
  /* InstantiationType.Eager */
);

// out-build/vs/platform/void/electron-main/metricsMainService.js
import { PostHog } from "posthog-node";
var $Nlc = class $Nlc2 extends $0c {
  constructor(a) {
    super();
    this.a = a;
    this.capture = (event, params) => {
      const capture = { distinctId: this._distinctId, event, properties: params };
      this.client.capture(capture);
    };
    this.client = new PostHog("phc_UanIdujHiLp55BkUTjB1AuBXcasVkdqRwgnwRlWESH2", { host: "https://us.i.posthog.com" });
    const { devDeviceId, firstSessionDate, machineId: machineId2 } = this.a;
    this._distinctId = devDeviceId;
    this.client.identify({ distinctId: devDeviceId, properties: { firstSessionDate, machineId: machineId2 } });
    console.log("Void posthog metrics info:", JSON.stringify({ devDeviceId, firstSessionDate, machineId: machineId2 }));
  }
};
$Nlc = __decorate([
  __param(0, $tm)
], $Nlc);

// out-build/vs/code/electron-main/app.js
var $Olc_1;
var $Olc = class $Olc2 extends $0c {
  static {
    $Olc_1 = this;
  }
  static {
    this.a = {
      [Schemas.file]: "security.promptForLocalFileProtocolHandling",
      [Schemas.vscodeRemote]: "security.promptForRemoteFileProtocolHandling"
    };
  }
  constructor(g, h, j, m, n, s, t, u, w, y, z, C) {
    super();
    this.g = g;
    this.h = h;
    this.j = j;
    this.m = m;
    this.n = n;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D();
    this.F();
  }
  D() {
    const isUrlFromWebview = (requestingUrl) => requestingUrl?.startsWith(`${Schemas.vscodeWebview}://`);
    const allowedPermissionsInWebview = /* @__PURE__ */ new Set([
      "clipboard-read",
      "clipboard-sanitized-write"
    ]);
    session.defaultSession.setPermissionRequestHandler((_webContents, permission, callback, details) => {
      if (isUrlFromWebview(details.requestingUrl)) {
        return callback(allowedPermissionsInWebview.has(permission));
      }
      return callback(false);
    });
    session.defaultSession.setPermissionCheckHandler((_webContents, permission, _origin, details) => {
      if (isUrlFromWebview(details.requestingUrl)) {
        return allowedPermissionsInWebview.has(permission);
      }
      return false;
    });
    const supportedSvgSchemes = /* @__PURE__ */ new Set([Schemas.file, Schemas.vscodeFileResource, Schemas.vscodeRemoteResource, Schemas.vscodeManagedRemoteResource, "devtools"]);
    const isSafeFrame = (requestFrame) => {
      for (let frame = requestFrame; frame; frame = frame.parent) {
        if (frame.url.startsWith(`${Schemas.vscodeWebview}://`)) {
          return true;
        }
      }
      return false;
    };
    const isSvgRequestFromSafeContext = (details) => {
      return details.resourceType === "xhr" || isSafeFrame(details.frame);
    };
    const isAllowedVsCodeFileRequest = (details) => {
      const frame = details.frame;
      if (!frame || !this.b) {
        return false;
      }
      const windows = BrowserWindow8.getAllWindows();
      for (const window2 of windows) {
        if (frame.processId === window2.webContents.mainFrame.processId) {
          return true;
        }
      }
      return false;
    };
    const isAllowedWebviewRequest = (uri, details) => {
      if (uri.path !== "/index.html") {
        return true;
      }
      const frame = details.frame;
      if (!frame || !this.b) {
        return false;
      }
      for (const window2 of this.b.getWindows()) {
        if (window2.win) {
          if (frame.processId === window2.win.webContents.mainFrame.processId) {
            return true;
          }
        }
      }
      return false;
    };
    session.defaultSession.webRequest.onBeforeRequest((details, callback) => {
      const uri = URI.parse(details.url);
      if (uri.scheme === Schemas.vscodeWebview) {
        if (!isAllowedWebviewRequest(uri, details)) {
          this.m.error("Blocked vscode-webview request", details.url);
          return callback({ cancel: true });
        }
      }
      if (uri.scheme === Schemas.vscodeFileResource) {
        if (!isAllowedVsCodeFileRequest(details)) {
          this.m.error("Blocked vscode-file request", details.url);
          return callback({ cancel: true });
        }
      }
      if (uri.path.endsWith(".svg")) {
        const isSafeResourceUrl = supportedSvgSchemes.has(uri.scheme);
        if (!isSafeResourceUrl) {
          return callback({ cancel: !isSvgRequestFromSafeContext(details) });
        }
      }
      return callback({ cancel: false });
    });
    session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
      const responseHeaders = details.responseHeaders;
      const contentTypes = responseHeaders["content-type"] || responseHeaders["Content-Type"];
      if (contentTypes && Array.isArray(contentTypes)) {
        const uri = URI.parse(details.url);
        if (uri.path.endsWith(".svg")) {
          if (supportedSvgSchemes.has(uri.scheme)) {
            responseHeaders["Content-Type"] = ["image/svg+xml"];
            return callback({ cancel: false, responseHeaders });
          }
        }
        if (!uri.path.endsWith(Schemas.vscodeRemoteResource) && contentTypes.some((contentType) => contentType.toLowerCase().includes("image/svg"))) {
          return callback({ cancel: !isSvgRequestFromSafeContext(details) });
        }
      }
      return callback({ cancel: false });
    });
    session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
      if (details.url.startsWith("https://vscode.download.prss.microsoft.com/")) {
        const responseHeaders = details.responseHeaders ?? /* @__PURE__ */ Object.create(null);
        if (responseHeaders["Access-Control-Allow-Origin"] === void 0) {
          responseHeaders["Access-Control-Allow-Origin"] = ["*"];
          return callback({ cancel: false, responseHeaders });
        }
      }
      return callback({ cancel: false });
    });
    const defaultSession = session.defaultSession;
    if (typeof defaultSession.setCodeCachePath === "function" && this.s.codeCachePath) {
      defaultSession.setCodeCachePath($vc(this.s.codeCachePath, "chrome"));
    }
    if ($l) {
      if (this.u.getValue("security.restrictUNCAccess") === false) {
        disableUNCAccessRestrictions();
      } else {
        addUNCHostToAllowlist(this.u.getValue("security.allowedUNCHosts"));
      }
    }
  }
  F() {
    setUnexpectedErrorHandler((error) => this.G(error));
    process.on("uncaughtException", (error) => {
      if (!$$(error)) {
        $ab(error);
      }
    });
    process.on("unhandledRejection", (reason) => $ab(reason));
    Event.once(this.t.onWillShutdown)(() => this.dispose());
    $1Y();
    app12.on("accessibility-support-changed", (event, accessibilitySupportEnabled) => {
      this.b?.sendToAll("vscode:accessibilitySupportChanged", accessibilitySupportEnabled);
    });
    app12.on("activate", async (event, hasVisibleWindows) => {
      this.m.trace("app#activate");
      if (!hasVisibleWindows) {
        await this.b?.openEmptyWindow({
          context: 1
          /* OpenContext.DOCK */
        });
      }
    });
    app12.on("web-contents-created", (event, contents) => {
      if (contents?.opener?.url.startsWith(`${Schemas.vscodeFileResource}://${$gh}/`)) {
        this.m.trace('[aux window]  app.on("web-contents-created"): Registering auxiliary window');
        this.c?.registerWindow(contents);
      }
      contents.on("will-navigate", (event2) => {
        this.m.error("webContents#will-navigate: Prevented webcontent navigation");
        event2.preventDefault();
      });
      contents.setWindowOpenHandler((details) => {
        if (details.url === "about:blank") {
          this.m.trace("[aux window] webContents#setWindowOpenHandler: Allowing auxiliary window to open on about:blank");
          return {
            action: "allow",
            overrideBrowserWindowOptions: this.c?.createWindow(details)
          };
        } else {
          this.m.trace(`webContents#setWindowOpenHandler: Prevented opening window with URL ${details.url}}`);
          this.f?.openExternal(void 0, details.url);
          return { action: "deny" };
        }
      });
    });
    let macOpenFileURIs = [];
    let runningTimeout = void 0;
    app12.on("open-file", (event, path3) => {
      path3 = $Hm(path3);
      this.m.trace("app#open-file: ", path3);
      event.preventDefault();
      macOpenFileURIs.push($sj(path3) ? { workspaceUri: URI.file(path3) } : { fileUri: URI.file(path3) });
      if (runningTimeout !== void 0) {
        clearTimeout(runningTimeout);
        runningTimeout = void 0;
      }
      runningTimeout = setTimeout(async () => {
        await this.b?.open({
          context: 1,
          cli: this.s.args,
          urisToOpen: macOpenFileURIs,
          gotoLineMode: false,
          preferNewWindow: true
          /* dropping on the dock or opening from finder prefers to open in a new window */
        });
        macOpenFileURIs = [];
        runningTimeout = void 0;
      }, 100);
    });
    app12.on("new-window-for-tab", async () => {
      await this.b?.openEmptyWindow({
        context: 4
        /* OpenContext.DESKTOP */
      });
    });
    $ZY.handle("vscode:fetchShellEnv", (event) => {
      const window2 = this.b?.getWindowByWebContents(event.sender);
      let args;
      let env2;
      if (window2?.config) {
        args = window2.config;
        env2 = { ...process.env, ...window2.config.userEnv };
      } else {
        args = this.s.args;
        env2 = process.env;
      }
      return this.W(args, env2, false);
    });
    $ZY.on("vscode:toggleDevTools", (event) => event.sender.toggleDevTools());
    $ZY.on("vscode:openDevTools", (event) => event.sender.openDevTools());
    $ZY.on("vscode:reloadWindow", (event) => event.sender.reload());
    $ZY.handle("vscode:notifyZoomLevel", async (event, zoomLevel) => {
      const window2 = this.b?.getWindowByWebContents(event.sender);
      if (window2) {
        window2.notifyZoomLevel(zoomLevel);
      }
    });
  }
  G(error) {
    if (error) {
      const friendlyError = {
        message: `[uncaught exception in main]: ${error.message}`,
        stack: error.stack
      };
      this.b?.sendToFocused("vscode:reportError", JSON.stringify(friendlyError));
    }
    this.m.error(`[uncaught exception in main]: ${error}`);
    if (error.stack) {
      this.m.error(error.stack);
    }
  }
  async startup() {
    this.m.debug("Starting VS Code");
    this.m.debug(`from: ${this.s.appRoot}`);
    this.m.debug("args:", this.s.args);
    const win32AppUserModelId = this.z.win32AppUserModelId;
    if ($l && win32AppUserModelId) {
      app12.setAppUserModelId(win32AppUserModelId);
    }
    try {
      if ($m && this.u.getValue("window.nativeTabs") === true && !systemPreferences.getUserDefault("NSUseImprovedLayoutPass", "boolean")) {
        systemPreferences.setUserDefault("NSUseImprovedLayoutPass", "boolean", true);
      }
    } catch (error) {
      this.m.error(error);
    }
    const mainProcessElectronServer = new $7Y();
    Event.once(this.t.onWillShutdown)((e) => {
      if (e.reason === 2) {
        mainProcessElectronServer.dispose();
      }
    });
    this.m.trace("Resolving machine identifier...");
    const [machineId2, sqmId, devDeviceId] = await Promise.all([
      $slc(this.w, this.m),
      $tlc(this.w, this.m),
      $ulc(this.w, this.m)
    ]);
    this.m.trace(`Resolved machine identifier: ${machineId2}`);
    const { sharedProcessReady, sharedProcessClient } = this.O(machineId2, sqmId, devDeviceId);
    const appInstantiationService = await this.P(machineId2, sqmId, devDeviceId, sharedProcessReady);
    appInstantiationService.invokeFunction((accessor) => accessor.get($gkc));
    this.B(appInstantiationService.createInstance($nlc));
    appInstantiationService.invokeFunction((accessor) => this.Q(accessor, mainProcessElectronServer, sharedProcessClient));
    const initialProtocolUrls = await appInstantiationService.invokeFunction((accessor) => this.H(accessor, mainProcessElectronServer));
    this.I(mainProcessElectronServer);
    this.t.phase = 2;
    await appInstantiationService.invokeFunction((accessor) => this.R(accessor, initialProtocolUrls));
    this.t.phase = 3;
    this.S();
    const eventuallyPhaseScheduler = this.B(new $_h(() => {
      this.B($di(() => this.t.phase = 4, 2500));
    }, 2500));
    eventuallyPhaseScheduler.schedule();
  }
  async H(accessor, mainProcessElectronServer) {
    const windowsMainService = this.b = accessor.get($Pjc);
    const urlService = accessor.get($OZ);
    const nativeHostMainService = this.f = accessor.get($Ckc);
    const dialogMainService = accessor.get($Kjc);
    const app14 = this;
    urlService.registerHandler({
      async handleURL(uri, options) {
        return app14.N(windowsMainService, dialogMainService, urlService, uri, options);
      }
    });
    const activeWindowManager = this.B(new $ilc({
      onDidOpenMainWindow: nativeHostMainService.onDidOpenMainWindow,
      onDidFocusMainWindow: nativeHostMainService.onDidFocusMainWindow,
      getActiveWindowId: () => nativeHostMainService.getActiveWindowId(-1)
    }));
    const activeWindowRouter = new $Hi((ctx) => activeWindowManager.getActiveClientId().then((id2) => ctx === id2));
    const urlHandlerRouter = new $_kc(activeWindowRouter, this.m);
    const urlHandlerChannel = mainProcessElectronServer.getChannel("urlHandler", urlHandlerRouter);
    urlService.registerHandler(new $$kc(urlHandlerChannel));
    const initialProtocolUrls = await this.J(windowsMainService, dialogMainService);
    this.B(new $alc(initialProtocolUrls?.urls, urlService, windowsMainService, this.s, this.z, this.m));
    return initialProtocolUrls;
  }
  I(mainProcessElectronServer) {
    const notFound = () => ({ statusCode: 404, data: "Not found" });
    const remoteResourceChannel = new $7(() => mainProcessElectronServer.getChannel($Blc, new $Clc()));
    protocol2.registerBufferProtocol(Schemas.vscodeManagedRemoteResource, (request, callback) => {
      const url = URI.parse(request.url);
      if (!url.authority.startsWith("window:")) {
        return callback(notFound());
      }
      remoteResourceChannel.value.call($Alc, [url]).then((r) => callback({ ...r, data: Buffer.from(r.body, "base64") }), (err) => {
        this.m.warn("error dispatching remote resource call", err);
        callback({ statusCode: 500, data: String(err) });
      });
    });
  }
  async J(windowsMainService, dialogMainService) {
    const protocolUrlsFromCommandLine = this.s.args["open-url"] ? this.s.args._urls || [] : [];
    if (protocolUrlsFromCommandLine.length > 0) {
      this.m.trace("app#resolveInitialProtocolUrls() protocol urls from command line:", protocolUrlsFromCommandLine);
    }
    const protocolUrlsFromEvent = global.getOpenUrls() || [];
    if (protocolUrlsFromEvent.length > 0) {
      this.m.trace(`app#resolveInitialProtocolUrls() protocol urls from macOS 'open-url' event:`, protocolUrlsFromEvent);
    }
    if (protocolUrlsFromCommandLine.length + protocolUrlsFromEvent.length === 0) {
      return void 0;
    }
    const protocolUrls = [
      ...protocolUrlsFromCommandLine,
      ...protocolUrlsFromEvent
    ].map((url) => {
      try {
        return { uri: URI.parse(url), originalUrl: url };
      } catch {
        this.m.trace("app#resolveInitialProtocolUrls() protocol url failed to parse:", url);
        return void 0;
      }
    });
    const openables = [];
    const urls = [];
    for (const protocolUrl of protocolUrls) {
      if (!protocolUrl) {
        continue;
      }
      const windowOpenable = this.M(protocolUrl.uri);
      if (windowOpenable) {
        if (await this.L(windowOpenable, windowsMainService, dialogMainService)) {
          this.m.trace("app#resolveInitialProtocolUrls() protocol url was blocked:", protocolUrl.uri.toString(true));
          continue;
        } else {
          this.m.trace("app#resolveInitialProtocolUrls() protocol url will be handled as window to open:", protocolUrl.uri.toString(true), windowOpenable);
          openables.push(windowOpenable);
        }
      } else {
        this.m.trace("app#resolveInitialProtocolUrls() protocol url will be passed to active window for handling:", protocolUrl.uri.toString(true));
        urls.push(protocolUrl);
      }
    }
    return { urls, openables };
  }
  async L(openable, windowsMainService, dialogMainService) {
    let openableUri;
    let message;
    if ($LE(openable)) {
      openableUri = openable.workspaceUri;
      message = localize(146, null, openableUri.scheme === Schemas.file ? $rx(openableUri, { os: OS, tildify: this.s }) : openableUri.toString(true), this.z.nameShort);
    } else if ($ME(openable)) {
      openableUri = openable.folderUri;
      message = localize(147, null, openableUri.scheme === Schemas.file ? $rx(openableUri, { os: OS, tildify: this.s }) : openableUri.toString(true), this.z.nameShort);
    } else {
      openableUri = openable.fileUri;
      message = localize(148, null, openableUri.scheme === Schemas.file ? $rx(openableUri, { os: OS, tildify: this.s }) : openableUri.toString(true), this.z.nameShort);
    }
    if (openableUri.scheme !== Schemas.file && openableUri.scheme !== Schemas.vscodeRemote) {
      return false;
    }
    const askForConfirmation = this.u.getValue($Olc_1.a[openableUri.scheme]);
    if (askForConfirmation === false) {
      return false;
    }
    const { response, checkboxChecked } = await dialogMainService.showMessageBox({
      type: "warning",
      buttons: [
        localize(149, null),
        localize(150, null)
      ],
      message,
      detail: localize(151, null),
      checkboxLabel: openableUri.scheme === Schemas.file ? localize(152, null) : localize(153, null),
      cancelId: 1
    });
    if (response !== 0) {
      return true;
    }
    if (checkboxChecked) {
      const request = { channel: "vscode:disablePromptForProtocolHandling", args: openableUri.scheme === Schemas.file ? "local" : "remote" };
      windowsMainService.sendToFocused(request.channel, request.args);
      windowsMainService.sendToOpeningWindow(request.channel, request.args);
    }
    return false;
  }
  M(uri) {
    if (!uri.path) {
      return void 0;
    }
    if (uri.authority === Schemas.file) {
      const fileUri = URI.file(uri.fsPath);
      if ($sj(fileUri)) {
        return { workspaceUri: fileUri };
      }
      return { fileUri };
    } else if (uri.authority === Schemas.vscodeRemote) {
      const secondSlash = uri.path.indexOf(
        $sc.sep,
        1
        /* skip over the leading slash */
      );
      let authority;
      let path3;
      if (secondSlash !== -1) {
        authority = uri.path.substring(1, secondSlash);
        path3 = uri.path.substring(secondSlash);
      } else {
        authority = uri.path.substring(1);
        path3 = "/";
      }
      let query = uri.query;
      const params = new URLSearchParams(uri.query);
      if (params.get("windowId") === "_blank") {
        params.delete("windowId");
        query = params.toString();
      }
      const remoteUri = URI.from({ scheme: Schemas.vscodeRemote, authority, path: path3, query, fragment: uri.fragment });
      if ($sj(path3)) {
        return { workspaceUri: remoteUri };
      }
      if (/:[\d]+$/.test(path3)) {
        return { fileUri: remoteUri };
      }
      return { folderUri: remoteUri };
    }
    return void 0;
  }
  async N(windowsMainService, dialogMainService, urlService, uri, options) {
    this.m.trace("app#handleProtocolUrl():", uri.toString(true), options);
    if (uri.scheme === this.z.urlProtocol && uri.path === "workspace") {
      uri = uri.with({
        authority: "file",
        path: URI.parse(uri.query).path,
        query: ""
      });
    }
    let shouldOpenInNewWindow = false;
    const params = new URLSearchParams(uri.query);
    if (params.get("windowId") === "_blank") {
      this.m.trace(`app#handleProtocolUrl() found 'windowId=_blank' as parameter, setting shouldOpenInNewWindow=true:`, uri.toString(true));
      params.delete("windowId");
      uri = uri.with({ query: params.toString() });
      shouldOpenInNewWindow = true;
    } else if ($m && windowsMainService.getWindowCount() === 0) {
      this.m.trace(`app#handleProtocolUrl() running on macOS with no window open, setting shouldOpenInNewWindow=true:`, uri.toString(true));
      shouldOpenInNewWindow = true;
    }
    const continueOn = params.get("continueOn");
    if (continueOn !== null) {
      this.m.trace(`app#handleProtocolUrl() found 'continueOn' as parameter:`, uri.toString(true));
      params.delete("continueOn");
      uri = uri.with({ query: params.toString() });
      this.s.continueOn = continueOn ?? void 0;
    }
    const windowOpenableFromProtocolUrl = this.M(uri);
    if (windowOpenableFromProtocolUrl) {
      if (await this.L(windowOpenableFromProtocolUrl, windowsMainService, dialogMainService)) {
        this.m.trace("app#handleProtocolUrl() protocol url was blocked:", uri.toString(true));
        return true;
      } else {
        this.m.trace("app#handleProtocolUrl() opening protocol url as window:", windowOpenableFromProtocolUrl, uri.toString(true));
        const window2 = (await windowsMainService.open({
          context: 6,
          cli: { ...this.s.args },
          urisToOpen: [windowOpenableFromProtocolUrl],
          forceNewWindow: shouldOpenInNewWindow,
          gotoLineMode: true
          // remoteAuthority: will be determined based on windowOpenableFromProtocolUrl
        })).at(0);
        window2?.focus();
        return true;
      }
    }
    if (shouldOpenInNewWindow) {
      this.m.trace("app#handleProtocolUrl() opening empty window and passing in protocol url:", uri.toString(true));
      const window2 = (await windowsMainService.open({
        context: 6,
        cli: { ...this.s.args },
        forceNewWindow: true,
        forceEmpty: true,
        gotoLineMode: true,
        remoteAuthority: $Cn(uri)
      })).at(0);
      await window2?.ready();
      return urlService.open(uri, options);
    }
    this.m.trace("app#handleProtocolUrl(): not handled", uri.toString(true), options);
    return false;
  }
  O(machineId2, sqmId, devDeviceId) {
    const sharedProcess = this.B(this.j.createInstance($Xkc, machineId2, sqmId, devDeviceId));
    this.B(sharedProcess.onDidCrash(() => this.b?.sendToFocused("vscode:reportSharedProcessCrash")));
    const sharedProcessClient = (async () => {
      this.m.trace("Main->SharedProcess#connect");
      const port = await sharedProcess.connect();
      this.m.trace("Main->SharedProcess#connect: connection established");
      return new $8Y(port, "main");
    })();
    const sharedProcessReady = (async () => {
      await sharedProcess.whenReady();
      return sharedProcessClient;
    })();
    return { sharedProcessReady, sharedProcessClient };
  }
  async P(machineId2, sqmId, devDeviceId, sharedProcessReady) {
    const services = new $Xi();
    switch (process.platform) {
      case "win32":
        services.set($YZ, new $Wi($9kc));
        break;
      case "linux":
        if ($o) {
          services.set($YZ, new $Wi($8kc, [process.env["SNAP"], process.env["SNAP_REVISION"]]));
        } else {
          services.set($YZ, new $Wi($7kc));
        }
        break;
      case "darwin":
        services.set($YZ, new $Wi($6kc));
        break;
    }
    services.set($Pjc, new $Wi($hlc, [machineId2, sqmId, devDeviceId, this.h], false));
    services.set($Bkc, new $Wi($Dlc, void 0, false));
    const dialogMainService = new $Ljc(this.m, this.z);
    services.set($Kjc, dialogMainService);
    services.set($Jkc, new $Wi(
      $Kkc,
      void 0,
      false
      /* proxied to other processes */
    ));
    services.set($nkc, new $Wi(
      $okc,
      void 0,
      false
      /* proxied to other processes */
    ));
    services.set($bn, ProxyChannel.toService($Fi(sharedProcessReady.then((client) => client.getChannel("diagnostics")))));
    services.set($Eqb, new $Wi($Ekc, [this.h]));
    services.set($Fqb, new $Wi($Fkc, [this.h]));
    services.set($IZ, new $Wi($pkc));
    services.set($Gkc, new $Wi($Hkc));
    services.set($Ckc, new $Wi(
      $Dkc,
      void 0,
      false
      /* proxied to other processes */
    ));
    services.set($blc, new $Wi($dlc));
    services.set($Skc, new $Wi($Tkc));
    services.set($qkc, new $Wi($skc));
    services.set($ckc, new $Wi($dkc));
    services.set($ekc, new $Wi($fkc));
    const ptyHostStarter = new $zlc({
      graceTime: 6e4,
      shortGraceTime: 6e3,
      scrollback: this.u.getValue(
        "terminal.integrated.persistentSessionScrollback"
        /* TerminalSettingId.PersistentSessionScrollback */
      ) ?? 100
    }, this.u, this.s, this.t, this.m);
    const ptyHostService = new $at(ptyHostStarter, this.u, this.m, this.n);
    services.set($Ns, ptyHostService);
    if ($l) {
      services.set($tkc, new $Wi($ukc));
    } else if ($m) {
      services.set($tkc, new $Wi($vkc));
    } else if ($n) {
      services.set($tkc, new $Wi($wkc));
    }
    const backupMainService = new $ikc(this.s, this.u, this.m, this.w);
    services.set($Jjc, backupMainService);
    const workspacesManagementMainService = new $3jc(this.s, this.m, this.C, backupMainService, dialogMainService);
    services.set($2jc, workspacesManagementMainService);
    services.set($8jb, new $Wi(
      $jlc,
      void 0,
      false
      /* proxied to other processes */
    ));
    services.set($Pkc, new $Wi($Qkc, void 0, false));
    services.set($OZ, new $Wi(
      $QZ,
      void 0,
      false
      /* proxied to other processes */
    ));
    if ($Zp(this.z, this.s)) {
      const isInternal = $5p(this.z, this.u);
      const channel = $Fi(sharedProcessReady.then((client) => client.getChannel("telemetryAppender")));
      const appender = new $1kc(channel);
      const commonProperties = $Qp(release7(), hostname2(), process.arch, this.z.commit, this.z.version, machineId2, sqmId, devDeviceId, isInternal);
      const piiPaths = $6p(this.s);
      const config = { appenders: [appender], commonProperties, piiPaths, sendErrorTelemetry: true };
      services.set($tm, new $Wi($Ds, [config], false));
    } else {
      services.set($tm, $Up);
    }
    services.set($ZOb, new $Wi($Nlc, void 0, false));
    services.set($6q, new $Wi($IS, void 0, true));
    services.set($0q, new $Wi($mlc, void 0, true));
    services.set($xlc, new $Wi($ylc, void 0, true));
    services.set($gkc, new $Wi($hkc));
    services.set($SS, new $Wi($TS, void 0, true));
    if (this.z.quality !== "stable") {
      services.set($Qq, new $Wi($Rq, void 0, true));
    }
    await Promises.settled([
      backupMainService.initialize(),
      workspacesManagementMainService.initialize()
    ]);
    return this.j.createChild(services);
  }
  Q(accessor, mainProcessElectronServer, sharedProcessClient) {
    const disposables = this.B(new $9c());
    const launchChannel = ProxyChannel.fromService(accessor.get($Jkc), disposables, { disableMarshalling: true });
    this.g.registerChannel("launch", launchChannel);
    const diagnosticsChannel = ProxyChannel.fromService(accessor.get($nkc), disposables, { disableMarshalling: true });
    this.g.registerChannel("diagnostics", diagnosticsChannel);
    const policyChannel = disposables.add(new $klc(accessor.get($Oo)));
    mainProcessElectronServer.registerChannel("policy", policyChannel);
    sharedProcessClient.then((client) => client.registerChannel("policy", policyChannel));
    const diskFileSystemProvider = this.y.getProvider(Schemas.file);
    $Ig(diskFileSystemProvider instanceof $Pr);
    const fileSystemProviderChannel = disposables.add(new $xkc(diskFileSystemProvider, this.m, this.s));
    mainProcessElectronServer.registerChannel($rS, fileSystemProviderChannel);
    sharedProcessClient.then((client) => client.registerChannel($rS, fileSystemProviderChannel));
    const userDataProfilesService = ProxyChannel.fromService(accessor.get($Sjc), disposables);
    mainProcessElectronServer.registerChannel("userDataProfiles", userDataProfilesService);
    sharedProcessClient.then((client) => client.registerChannel("userDataProfiles", userDataProfilesService));
    if (this.z.quality !== "stable") {
      const extensionSignatureVerificationService = accessor.get($Qq);
      sharedProcessClient.then((client) => client.registerChannel("signatureVerificationService", ProxyChannel.fromService(extensionSignatureVerificationService, disposables)));
    }
    const updateChannel = new $2kc(accessor.get($YZ));
    mainProcessElectronServer.registerChannel("update", updateChannel);
    const issueChannel = ProxyChannel.fromService(accessor.get($Eqb), disposables);
    mainProcessElectronServer.registerChannel("issue", issueChannel);
    const processChannel = ProxyChannel.fromService(accessor.get($Fqb), disposables);
    mainProcessElectronServer.registerChannel("process", processChannel);
    const encryptionChannel = ProxyChannel.fromService(accessor.get($IZ), disposables);
    mainProcessElectronServer.registerChannel("encryption", encryptionChannel);
    const signChannel = ProxyChannel.fromService(accessor.get($hm), disposables);
    mainProcessElectronServer.registerChannel("sign", signChannel);
    const keyboardLayoutChannel = ProxyChannel.fromService(accessor.get($Gkc), disposables);
    mainProcessElectronServer.registerChannel("keyboardLayout", keyboardLayoutChannel);
    this.f = accessor.get($Ckc);
    const nativeHostChannel = ProxyChannel.fromService(this.f, disposables);
    mainProcessElectronServer.registerChannel("nativeHost", nativeHostChannel);
    sharedProcessClient.then((client) => client.registerChannel("nativeHost", nativeHostChannel));
    const workspacesChannel = ProxyChannel.fromService(accessor.get($8jb), disposables);
    mainProcessElectronServer.registerChannel("workspaces", workspacesChannel);
    const menubarChannel = ProxyChannel.fromService(accessor.get($Skc), disposables);
    mainProcessElectronServer.registerChannel("menubar", menubarChannel);
    const urlChannel = ProxyChannel.fromService(accessor.get($OZ), disposables);
    mainProcessElectronServer.registerChannel("url", urlChannel);
    const webviewChannel = ProxyChannel.fromService(accessor.get($blc), disposables);
    mainProcessElectronServer.registerChannel("webview", webviewChannel);
    const storageChannel = disposables.add(new $Ykc(this.m, accessor.get($ckc)));
    mainProcessElectronServer.registerChannel("storage", storageChannel);
    sharedProcessClient.then((client) => client.registerChannel("storage", storageChannel));
    const profileStorageListener = disposables.add(new $olc(accessor.get($ckc), accessor.get($Sjc), this.m));
    sharedProcessClient.then((client) => client.registerChannel("profileStorageListener", profileStorageListener));
    const ptyHostChannel = ProxyChannel.fromService(accessor.get($Ns), disposables);
    mainProcessElectronServer.registerChannel(TerminalIpcChannels.LocalPty, ptyHostChannel);
    const externalTerminalChannel = ProxyChannel.fromService(accessor.get($tkc), disposables);
    mainProcessElectronServer.registerChannel("externalTerminal", externalTerminalChannel);
    const loggerChannel = new $vlc(accessor.get($4jc));
    mainProcessElectronServer.registerChannel("logger", loggerChannel);
    sharedProcessClient.then((client) => client.registerChannel("logger", loggerChannel));
    const metricsChannel = ProxyChannel.fromService(accessor.get($ZOb), disposables);
    mainProcessElectronServer.registerChannel("void-channel-metrics", metricsChannel);
    const llmMessageChannel = new $Mlc(accessor.get($ZOb));
    mainProcessElectronServer.registerChannel("void-channel-llmMessageService", llmMessageChannel);
    const electronExtensionHostDebugBroadcastChannel = new $jkc(accessor.get($Pjc));
    mainProcessElectronServer.registerChannel("extensionhostdebugservice", electronExtensionHostDebugBroadcastChannel);
    const extensionHostStarterChannel = ProxyChannel.fromService(accessor.get($qkc), disposables);
    mainProcessElectronServer.registerChannel($rkc, extensionHostStarterChannel);
    const utilityProcessWorkerChannel = ProxyChannel.fromService(accessor.get($xlc), disposables);
    mainProcessElectronServer.registerChannel($wlc, utilityProcessWorkerChannel);
  }
  async R(accessor, initialProtocolUrls) {
    const windowsMainService = this.b = accessor.get($Pjc);
    this.c = accessor.get($Bkc);
    const context = $5m(process.env) ? 0 : 4;
    const args = this.s.args;
    if (initialProtocolUrls) {
      if (initialProtocolUrls.openables.length > 0) {
        return windowsMainService.open({
          context,
          cli: args,
          urisToOpen: initialProtocolUrls.openables,
          gotoLineMode: true,
          initialStartup: true
          // remoteAuthority: will be determined based on openables
        });
      }
      if (initialProtocolUrls.urls.length > 0) {
        for (const protocolUrl of initialProtocolUrls.urls) {
          const params = new URLSearchParams(protocolUrl.uri.query);
          if (params.get("windowId") === "_blank") {
            params.delete("windowId");
            protocolUrl.originalUrl = protocolUrl.uri.toString(true);
            protocolUrl.uri = protocolUrl.uri.with({ query: params.toString() });
            return windowsMainService.open({
              context,
              cli: args,
              forceNewWindow: true,
              forceEmpty: true,
              gotoLineMode: true,
              initialStartup: true
              // remoteAuthority: will be determined based on openables
            });
          }
        }
      }
    }
    const macOpenFiles = global.macOpenFiles;
    const hasCliArgs = args._.length;
    const hasFolderURIs = !!args["folder-uri"];
    const hasFileURIs = !!args["file-uri"];
    const noRecentEntry = args["skip-add-to-recently-opened"] === true;
    const waitMarkerFileURI = args.wait && args.waitMarkerFilePath ? URI.file(args.waitMarkerFilePath) : void 0;
    const remoteAuthority = args.remote || void 0;
    const forceProfile = args.profile;
    const forceTempProfile = args["profile-temp"];
    if (!hasCliArgs && !hasFolderURIs && !hasFileURIs) {
      if (args["new-window"] || forceProfile || forceTempProfile) {
        return windowsMainService.open({
          context,
          cli: args,
          forceNewWindow: true,
          forceEmpty: true,
          noRecentEntry,
          waitMarkerFileURI,
          initialStartup: true,
          remoteAuthority,
          forceProfile,
          forceTempProfile
        });
      }
      if (macOpenFiles.length) {
        return windowsMainService.open({
          context: 1,
          cli: args,
          urisToOpen: macOpenFiles.map((path3) => {
            path3 = $Hm(path3);
            return $sj(path3) ? { workspaceUri: URI.file(path3) } : { fileUri: URI.file(path3) };
          }),
          noRecentEntry,
          waitMarkerFileURI,
          initialStartup: true
          // remoteAuthority: will be determined based on macOpenFiles
        });
      }
    }
    return windowsMainService.open({
      context,
      cli: args,
      forceNewWindow: args["new-window"],
      diffMode: args.diff,
      mergeMode: args.merge,
      noRecentEntry,
      waitMarkerFileURI,
      gotoLineMode: args.goto,
      initialStartup: true,
      remoteAuthority,
      forceProfile,
      forceTempProfile
    });
  }
  S() {
    this.U();
    protocol2.registerHttpProtocol(Schemas.vscodeRemoteResource, (request, callback) => {
      callback({
        url: request.url.replace(/^vscode-remote-resource:/, "http:"),
        method: request.method
      });
    });
    this.W(this.s.args, process.env, true);
    this.X();
    if ($m && app12.runningUnderARM64Translation) {
      this.b?.sendToFocused("vscode:showTranslatedBuildWarning");
    }
  }
  async U() {
    const win32MutexName = this.z.win32MutexName;
    if ($l && win32MutexName) {
      try {
        const WindowsMutex = await import("@vscode/windows-mutex");
        const mutex = new WindowsMutex.Mutex(win32MutexName);
        Event.once(this.t.onWillShutdown)(() => mutex.release());
      } catch (error) {
        this.m.error(error);
      }
    }
  }
  async W(args, env2, notifyOnError) {
    try {
      return await $_m(this.u, this.m, args, env2);
    } catch (error) {
      const errorMessage = $Kj(error);
      if (notifyOnError) {
        this.b?.sendToFocused("vscode:showResolveShellEnvError", errorMessage);
      } else {
        this.m.error(errorMessage);
      }
    }
    return {};
  }
  async X() {
    try {
      const argvContent = await this.y.readFile(this.s.argvResource);
      const argvString = argvContent.value.toString();
      const argvJSON = parse(argvString);
      const telemetryLevel = $2p(this.u);
      const enableCrashReporter = telemetryLevel >= 1;
      if (argvJSON["enable-crash-reporter"] === void 0) {
        const additionalArgvContent = [
          "",
          "	// Allows to disable crash reporting.",
          "	// Should restart the app if the value is changed.",
          `	"enable-crash-reporter": ${enableCrashReporter},`,
          "",
          "	// Unique id used for correlating crash reports sent from this instance.",
          "	// Do not edit this value.",
          `	"crash-reporter-id": "${$jh()}"`,
          "}"
        ];
        const newArgvString = argvString.substring(0, argvString.length - 2).concat(",\n", additionalArgvContent.join("\n"));
        await this.y.writeFile(this.s.argvResource, $7e.fromString(newArgvString));
      } else {
        const newArgvString = argvString.replace(/"enable-crash-reporter": .*,/, `"enable-crash-reporter": ${enableCrashReporter},`);
        if (newArgvString !== argvString) {
          await this.y.writeFile(this.s.argvResource, $7e.fromString(newArgvString));
        }
      }
    } catch (error) {
      this.m.error(error);
      this.b?.sendToFocused("vscode:showArgvParseWarning");
    }
  }
};
$Olc = $Olc_1 = __decorate([
  __param(2, $Yi),
  __param(3, $uk),
  __param(4, $vk),
  __param(5, $Cjc),
  __param(6, $9jc),
  __param(7, $tj),
  __param(8, $BS),
  __param(9, $ul),
  __param(10, $Nk),
  __param(11, $Sjc)
], $Olc);

// out-build/vs/platform/configuration/common/configurationModels.js
function freeze(data) {
  return Object.isFrozen(data) ? data : $Ao(data);
}
var $0o = class _$0o {
  static createEmptyModel(logService) {
    return new _$0o({}, [], [], void 0, logService);
  }
  constructor(b, c, d, raw, f) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.raw = raw;
    this.f = f;
    this.a = /* @__PURE__ */ new Map();
  }
  get rawConfiguration() {
    if (!this.g) {
      if (this.raw?.length) {
        const rawConfigurationModels = this.raw.map((raw) => {
          if (raw instanceof _$0o) {
            return raw;
          }
          const parser = new $$o("", this.f);
          parser.parseRaw(raw);
          return parser.configurationModel;
        });
        this.g = rawConfigurationModels.reduce((previous, current) => current === previous ? current : previous.merge(current), rawConfigurationModels[0]);
      } else {
        this.g = this;
      }
    }
    return this.g;
  }
  get contents() {
    return this.b;
  }
  get overrides() {
    return this.d;
  }
  get keys() {
    return this.c;
  }
  isEmpty() {
    return this.c.length === 0 && Object.keys(this.b).length === 0 && this.d.length === 0;
  }
  getValue(section) {
    return section ? $Bj(this.contents, section) : this.contents;
  }
  inspect(section, overrideIdentifier) {
    const that = this;
    return {
      get value() {
        return freeze(that.rawConfiguration.getValue(section));
      },
      get override() {
        return overrideIdentifier ? freeze(that.rawConfiguration.getOverrideValue(section, overrideIdentifier)) : void 0;
      },
      get merged() {
        return freeze(overrideIdentifier ? that.rawConfiguration.override(overrideIdentifier).getValue(section) : that.rawConfiguration.getValue(section));
      },
      get overrides() {
        const overrides = [];
        for (const { contents, identifiers, keys } of that.rawConfiguration.overrides) {
          const value = new _$0o(contents, keys, [], void 0, that.f).getValue(section);
          if (value !== void 0) {
            overrides.push({ identifiers, value });
          }
        }
        return overrides.length ? freeze(overrides) : void 0;
      }
    };
  }
  getOverrideValue(section, overrideIdentifier) {
    const overrideContents = this.j(overrideIdentifier);
    return overrideContents ? section ? $Bj(overrideContents, section) : overrideContents : void 0;
  }
  getKeysForOverrideIdentifier(identifier) {
    const keys = [];
    for (const override of this.overrides) {
      if (override.identifiers.includes(identifier)) {
        keys.push(...override.keys);
      }
    }
    return $Zb(keys);
  }
  getAllOverrideIdentifiers() {
    const result = [];
    for (const override of this.overrides) {
      result.push(...override.identifiers);
    }
    return $Zb(result);
  }
  override(identifier) {
    let overrideConfigurationModel = this.a.get(identifier);
    if (!overrideConfigurationModel) {
      overrideConfigurationModel = this.h(identifier);
      this.a.set(identifier, overrideConfigurationModel);
    }
    return overrideConfigurationModel;
  }
  merge(...others) {
    const contents = $zo(this.contents);
    const overrides = $zo(this.overrides);
    const keys = [...this.keys];
    const raws = this.raw?.length ? [...this.raw] : [this];
    for (const other of others) {
      raws.push(...other.raw?.length ? other.raw : [other]);
      if (other.isEmpty()) {
        continue;
      }
      this.i(contents, other.contents);
      for (const otherOverride of other.overrides) {
        const [override] = overrides.filter((o) => $Hb(o.identifiers, otherOverride.identifiers));
        if (override) {
          this.i(override.contents, otherOverride.contents);
          override.keys.push(...otherOverride.keys);
          override.keys = $Zb(override.keys);
        } else {
          overrides.push($zo(otherOverride));
        }
      }
      for (const key of other.keys) {
        if (keys.indexOf(key) === -1) {
          keys.push(key);
        }
      }
    }
    return new _$0o(contents, keys, overrides, raws.every((raw) => raw instanceof _$0o) ? void 0 : raws, this.f);
  }
  h(identifier) {
    const overrideContents = this.j(identifier);
    if (!overrideContents || typeof overrideContents !== "object" || !Object.keys(overrideContents).length) {
      return this;
    }
    const contents = {};
    for (const key of $Zb([...Object.keys(this.contents), ...Object.keys(overrideContents)])) {
      let contentsForKey = this.contents[key];
      const overrideContentsForKey = overrideContents[key];
      if (overrideContentsForKey) {
        if (typeof contentsForKey === "object" && typeof overrideContentsForKey === "object") {
          contentsForKey = $zo(contentsForKey);
          this.i(contentsForKey, overrideContentsForKey);
        } else {
          contentsForKey = overrideContentsForKey;
        }
      }
      contents[key] = contentsForKey;
    }
    return new _$0o(contents, this.keys, this.overrides, void 0, this.f);
  }
  i(source, target) {
    for (const key of Object.keys(target)) {
      if (key in source) {
        if ($Ag(source[key]) && $Ag(target[key])) {
          this.i(source[key], target[key]);
          continue;
        }
      }
      source[key] = $zo(target[key]);
    }
  }
  j(identifier) {
    let contentsForIdentifierOnly = null;
    let contents = null;
    const mergeContents = (contentsToMerge) => {
      if (contentsToMerge) {
        if (contents) {
          this.i(contents, contentsToMerge);
        } else {
          contents = $zo(contentsToMerge);
        }
      }
    };
    for (const override of this.overrides) {
      if (override.identifiers.length === 1 && override.identifiers[0] === identifier) {
        contentsForIdentifierOnly = override.contents;
      } else if (override.identifiers.includes(identifier)) {
        mergeContents(override.contents);
      }
    }
    mergeContents(contentsForIdentifierOnly);
    return contents;
  }
  toJSON() {
    return {
      contents: this.contents,
      overrides: this.overrides,
      keys: this.keys
    };
  }
  // Update methods
  addValue(key, value) {
    this.k(key, value, true);
  }
  setValue(key, value) {
    this.k(key, value, false);
  }
  removeValue(key) {
    const index = this.keys.indexOf(key);
    if (index === -1) {
      return;
    }
    this.keys.splice(index, 1);
    $Aj(this.contents, key);
    if ($2o.test(key)) {
      this.overrides.splice(this.overrides.findIndex((o) => $Hb(o.identifiers, $3o(key))), 1);
    }
  }
  k(key, value, add) {
    $zj(this.contents, key, value, (e) => this.f.error(e));
    add = add || this.keys.indexOf(key) === -1;
    if (add) {
      this.keys.push(key);
    }
    if ($2o.test(key)) {
      const identifiers = $3o(key);
      const override = {
        identifiers,
        keys: Object.keys(this.contents[key]),
        contents: $yj(this.contents[key], (message) => this.f.error(message))
      };
      const index = this.overrides.findIndex((o) => $Hb(o.identifiers, identifiers));
      if (index !== -1) {
        this.overrides[index] = override;
      } else {
        this.overrides.push(override);
      }
    }
  }
};
var $$o = class {
  constructor(f, g) {
    this.f = f;
    this.g = g;
    this.a = null;
    this.b = null;
    this.c = [];
    this.d = [];
  }
  get configurationModel() {
    return this.b || $0o.createEmptyModel(this.g);
  }
  get restrictedConfigurations() {
    return this.c;
  }
  get errors() {
    return this.d;
  }
  parse(content, options) {
    if (!$Hg(content)) {
      const raw = this.h(content);
      this.parseRaw(raw, options);
    }
  }
  reparse(options) {
    if (this.a) {
      this.parseRaw(this.a, options);
    }
  }
  parseRaw(raw, options) {
    this.a = raw;
    const { contents, keys, overrides, restricted, hasExcludedProperties } = this.i(raw, options);
    this.b = new $0o(contents, keys, overrides, hasExcludedProperties ? [raw] : void 0, this.g);
    this.c = restricted || [];
  }
  h(content) {
    let raw = {};
    let currentProperty = null;
    let currentParent = [];
    const previousParents = [];
    const parseErrors = [];
    function onValue(value) {
      if (Array.isArray(currentParent)) {
        currentParent.push(value);
      } else if (currentProperty !== null) {
        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) => {
        parseErrors.push({ error, offset, length });
      }
    };
    if (content) {
      try {
        $oo(content, visitor);
        raw = currentParent[0] || {};
      } catch (e) {
        this.g.error(`Error while parsing settings file ${this.f}: ${e}`);
        this.d = [e];
      }
    }
    return raw;
  }
  i(raw, options) {
    const configurationProperties = $Mo.as($Ro.Configuration).getConfigurationProperties();
    const filtered = this.j(raw, configurationProperties, true, options);
    raw = filtered.raw;
    const contents = $yj(raw, (message) => this.g.error(`Conflict in settings file ${this.f}: ${message}`));
    const keys = Object.keys(raw);
    const overrides = this.l(raw, (message) => this.g.error(`Conflict in settings file ${this.f}: ${message}`));
    return { contents, keys, overrides, restricted: filtered.restricted, hasExcludedProperties: filtered.hasExcludedProperties };
  }
  j(properties, configurationProperties, filterOverriddenProperties, options) {
    let hasExcludedProperties = false;
    if (!options?.scopes && !options?.skipRestricted && !options?.exclude?.length) {
      return { raw: properties, restricted: [], hasExcludedProperties };
    }
    const raw = {};
    const restricted = [];
    for (const key in properties) {
      if ($2o.test(key) && filterOverriddenProperties) {
        const result = this.j(properties[key], configurationProperties, false, options);
        raw[key] = result.raw;
        hasExcludedProperties = hasExcludedProperties || result.hasExcludedProperties;
        restricted.push(...result.restricted);
      } else {
        const propertySchema = configurationProperties[key];
        const scope = propertySchema ? typeof propertySchema.scope !== "undefined" ? propertySchema.scope : 3 : void 0;
        if (propertySchema?.restricted) {
          restricted.push(key);
        }
        if (!options.exclude?.includes(key) && (options.include?.includes(key) || (scope === void 0 || options.scopes === void 0 || options.scopes.includes(scope)) && !(options.skipRestricted && propertySchema?.restricted))) {
          raw[key] = properties[key];
        } else {
          hasExcludedProperties = true;
        }
      }
    }
    return { raw, restricted, hasExcludedProperties };
  }
  l(raw, conflictReporter) {
    const overrides = [];
    for (const key of Object.keys(raw)) {
      if ($2o.test(key)) {
        const overrideRaw = {};
        for (const keyInOverrideRaw in raw[key]) {
          overrideRaw[keyInOverrideRaw] = raw[key][keyInOverrideRaw];
        }
        overrides.push({
          identifiers: $3o(key),
          keys: Object.keys(overrideRaw),
          contents: $yj(overrideRaw, conflictReporter)
        });
      }
    }
    return overrides;
  }
};
var $_o = class extends $0c {
  constructor(c, f, extUri, g, h) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h;
    this.b = this.B(new $De());
    this.onDidChange = this.b.event;
    this.a = new $$o(this.c.toString(), h);
    this.B(this.g.watch(extUri.dirname(this.c)));
    this.B(this.g.watch(this.c));
    this.B(Event.any(Event.filter(this.g.onDidFilesChange, (e) => e.contains(this.c)), Event.filter(this.g.onDidRunOperation, (e) => (e.isOperation(
      0
      /* FileOperation.CREATE */
    ) || e.isOperation(
      3
      /* FileOperation.COPY */
    ) || e.isOperation(
      1
      /* FileOperation.DELETE */
    ) || e.isOperation(
      4
      /* FileOperation.WRITE */
    )) && extUri.isEqual(e.resource, c)))(() => this.b.fire()));
  }
  async loadConfiguration() {
    try {
      const content = await this.g.readFile(this.c);
      this.a.parse(content.value.toString() || "{}", this.f);
      return this.a.configurationModel;
    } catch (e) {
      return $0o.createEmptyModel(this.h);
    }
  }
  reparse(parseOptions) {
    if (parseOptions) {
      this.f = parseOptions;
    }
    this.a.reparse(this.f);
    return this.a.configurationModel;
  }
  getRestrictedSettings() {
    return this.a.restrictedConfigurations;
  }
};
var ConfigurationInspectValue = class {
  constructor(a, b, c, overrideIdentifiers, d, f, g, h, i, j, k, l, m) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.overrideIdentifiers = overrideIdentifiers;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h;
    this.i = i;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
  }
  get value() {
    return freeze(this.c);
  }
  n(inspectValue) {
    return inspectValue?.value !== void 0 || inspectValue?.override !== void 0 || inspectValue?.overrides !== void 0 ? inspectValue : void 0;
  }
  get q() {
    if (!this.p) {
      this.p = this.d.inspect(this.a, this.b.overrideIdentifier);
    }
    return this.p;
  }
  get defaultValue() {
    return this.q.merged;
  }
  get default() {
    return this.n(this.q);
  }
  get s() {
    if (this.r === void 0) {
      this.r = this.f ? this.f.inspect(this.a) : null;
    }
    return this.r;
  }
  get policyValue() {
    return this.s?.merged;
  }
  get policy() {
    return this.s?.value !== void 0 ? { value: this.s.value } : void 0;
  }
  get u() {
    if (this.t === void 0) {
      this.t = this.g ? this.g.inspect(this.a) : null;
    }
    return this.t;
  }
  get applicationValue() {
    return this.u?.merged;
  }
  get application() {
    return this.n(this.u);
  }
  get w() {
    if (!this.v) {
      this.v = this.h.inspect(this.a, this.b.overrideIdentifier);
    }
    return this.v;
  }
  get userValue() {
    return this.w.merged;
  }
  get user() {
    return this.n(this.w);
  }
  get y() {
    if (!this.x) {
      this.x = this.i.inspect(this.a, this.b.overrideIdentifier);
    }
    return this.x;
  }
  get userLocalValue() {
    return this.y.merged;
  }
  get userLocal() {
    return this.n(this.y);
  }
  get A() {
    if (!this.z) {
      this.z = this.j.inspect(this.a, this.b.overrideIdentifier);
    }
    return this.z;
  }
  get userRemoteValue() {
    return this.A.merged;
  }
  get userRemote() {
    return this.n(this.A);
  }
  get D() {
    if (this.B === void 0) {
      this.B = this.k ? this.k.inspect(this.a, this.b.overrideIdentifier) : null;
    }
    return this.B;
  }
  get workspaceValue() {
    return this.D?.merged;
  }
  get workspace() {
    return this.n(this.D);
  }
  get F() {
    if (this.E === void 0) {
      this.E = this.l ? this.l.inspect(this.a, this.b.overrideIdentifier) : null;
    }
    return this.E;
  }
  get workspaceFolderValue() {
    return this.F?.merged;
  }
  get workspaceFolder() {
    return this.n(this.F);
  }
  get H() {
    if (this.G === void 0) {
      this.G = this.m.inspect(this.a, this.b.overrideIdentifier);
    }
    return this.G;
  }
  get memoryValue() {
    return this.H.merged;
  }
  get memory() {
    return this.n(this.H);
  }
};
var $ap = class _$ap {
  constructor(j, l, m, n, p, q, r, s, t, u) {
    this.j = j;
    this.l = l;
    this.m = m;
    this.n = n;
    this.p = p;
    this.q = q;
    this.r = r;
    this.s = s;
    this.t = t;
    this.u = u;
    this.h = null;
    this.i = new $Mc();
    this.v = null;
  }
  getValue(section, overrides, workspace) {
    const consolidateConfigurationModel = this.w(section, overrides, workspace);
    return consolidateConfigurationModel.getValue(section);
  }
  updateValue(key, value, overrides = {}) {
    let memoryConfiguration;
    if (overrides.resource) {
      memoryConfiguration = this.t.get(overrides.resource);
      if (!memoryConfiguration) {
        memoryConfiguration = $0o.createEmptyModel(this.u);
        this.t.set(overrides.resource, memoryConfiguration);
      }
    } else {
      memoryConfiguration = this.s;
    }
    if (value === void 0) {
      memoryConfiguration.removeValue(key);
    } else {
      memoryConfiguration.setValue(key, value);
    }
    if (!overrides.resource) {
      this.h = null;
    }
  }
  inspect(key, overrides, workspace) {
    const consolidateConfigurationModel = this.w(key, overrides, workspace);
    const folderConfigurationModel = this.A(overrides.resource, workspace);
    const memoryConfigurationModel = overrides.resource ? this.t.get(overrides.resource) || this.s : this.s;
    const overrideIdentifiers = /* @__PURE__ */ new Set();
    for (const override of consolidateConfigurationModel.overrides) {
      for (const overrideIdentifier of override.identifiers) {
        if (consolidateConfigurationModel.getOverrideValue(key, overrideIdentifier) !== void 0) {
          overrideIdentifiers.add(overrideIdentifier);
        }
      }
    }
    return new ConfigurationInspectValue(key, overrides, consolidateConfigurationModel.getValue(key), overrideIdentifiers.size ? [...overrideIdentifiers] : void 0, this.j, this.l.isEmpty() ? void 0 : this.l, this.applicationConfiguration.isEmpty() ? void 0 : this.applicationConfiguration, this.userConfiguration, this.localUserConfiguration, this.remoteUserConfiguration, workspace ? this.q : void 0, folderConfigurationModel ? folderConfigurationModel : void 0, memoryConfigurationModel);
  }
  keys(workspace) {
    const folderConfigurationModel = this.A(void 0, workspace);
    return {
      default: this.j.keys.slice(0),
      user: this.userConfiguration.keys.slice(0),
      workspace: this.q.keys.slice(0),
      workspaceFolder: folderConfigurationModel ? folderConfigurationModel.keys.slice(0) : []
    };
  }
  updateDefaultConfiguration(defaultConfiguration) {
    this.j = defaultConfiguration;
    this.h = null;
    this.i.clear();
  }
  updatePolicyConfiguration(policyConfiguration) {
    this.l = policyConfiguration;
  }
  updateApplicationConfiguration(applicationConfiguration) {
    this.m = applicationConfiguration;
    this.h = null;
    this.i.clear();
  }
  updateLocalUserConfiguration(localUserConfiguration) {
    this.n = localUserConfiguration;
    this.v = null;
    this.h = null;
    this.i.clear();
  }
  updateRemoteUserConfiguration(remoteUserConfiguration) {
    this.p = remoteUserConfiguration;
    this.v = null;
    this.h = null;
    this.i.clear();
  }
  updateWorkspaceConfiguration(workspaceConfiguration) {
    this.q = workspaceConfiguration;
    this.h = null;
    this.i.clear();
  }
  updateFolderConfiguration(resource, configuration) {
    this.r.set(resource, configuration);
    this.i.delete(resource);
  }
  deleteFolderConfiguration(resource) {
    this.folderConfigurations.delete(resource);
    this.i.delete(resource);
  }
  compareAndUpdateDefaultConfiguration(defaults, keys) {
    const overrides = [];
    if (!keys) {
      const { added, updated, removed } = compare2(this.j, defaults);
      keys = [...added, ...updated, ...removed];
    }
    for (const key of keys) {
      for (const overrideIdentifier of $3o(key)) {
        const fromKeys = this.j.getKeysForOverrideIdentifier(overrideIdentifier);
        const toKeys = defaults.getKeysForOverrideIdentifier(overrideIdentifier);
        const keys2 = [
          ...toKeys.filter((key2) => fromKeys.indexOf(key2) === -1),
          ...fromKeys.filter((key2) => toKeys.indexOf(key2) === -1),
          ...fromKeys.filter((key2) => !$Do(this.j.override(overrideIdentifier).getValue(key2), defaults.override(overrideIdentifier).getValue(key2)))
        ];
        overrides.push([overrideIdentifier, keys2]);
      }
    }
    this.updateDefaultConfiguration(defaults);
    return { keys, overrides };
  }
  compareAndUpdatePolicyConfiguration(policyConfiguration) {
    const { added, updated, removed } = compare2(this.l, policyConfiguration);
    const keys = [...added, ...updated, ...removed];
    if (keys.length) {
      this.updatePolicyConfiguration(policyConfiguration);
    }
    return { keys, overrides: [] };
  }
  compareAndUpdateApplicationConfiguration(application) {
    const { added, updated, removed, overrides } = compare2(this.applicationConfiguration, application);
    const keys = [...added, ...updated, ...removed];
    if (keys.length) {
      this.updateApplicationConfiguration(application);
    }
    return { keys, overrides };
  }
  compareAndUpdateLocalUserConfiguration(user) {
    const { added, updated, removed, overrides } = compare2(this.localUserConfiguration, user);
    const keys = [...added, ...updated, ...removed];
    if (keys.length) {
      this.updateLocalUserConfiguration(user);
    }
    return { keys, overrides };
  }
  compareAndUpdateRemoteUserConfiguration(user) {
    const { added, updated, removed, overrides } = compare2(this.remoteUserConfiguration, user);
    const keys = [...added, ...updated, ...removed];
    if (keys.length) {
      this.updateRemoteUserConfiguration(user);
    }
    return { keys, overrides };
  }
  compareAndUpdateWorkspaceConfiguration(workspaceConfiguration) {
    const { added, updated, removed, overrides } = compare2(this.workspaceConfiguration, workspaceConfiguration);
    const keys = [...added, ...updated, ...removed];
    if (keys.length) {
      this.updateWorkspaceConfiguration(workspaceConfiguration);
    }
    return { keys, overrides };
  }
  compareAndUpdateFolderConfiguration(resource, folderConfiguration) {
    const currentFolderConfiguration = this.folderConfigurations.get(resource);
    const { added, updated, removed, overrides } = compare2(currentFolderConfiguration, folderConfiguration);
    const keys = [...added, ...updated, ...removed];
    if (keys.length || !currentFolderConfiguration) {
      this.updateFolderConfiguration(resource, folderConfiguration);
    }
    return { keys, overrides };
  }
  compareAndDeleteFolderConfiguration(folder) {
    const folderConfig = this.folderConfigurations.get(folder);
    if (!folderConfig) {
      throw new Error("Unknown folder");
    }
    this.deleteFolderConfiguration(folder);
    const { added, updated, removed, overrides } = compare2(folderConfig, void 0);
    return { keys: [...added, ...updated, ...removed], overrides };
  }
  get defaults() {
    return this.j;
  }
  get applicationConfiguration() {
    return this.m;
  }
  get userConfiguration() {
    if (!this.v) {
      this.v = this.p.isEmpty() ? this.n : this.n.merge(this.p);
    }
    return this.v;
  }
  get localUserConfiguration() {
    return this.n;
  }
  get remoteUserConfiguration() {
    return this.p;
  }
  get workspaceConfiguration() {
    return this.q;
  }
  get folderConfigurations() {
    return this.r;
  }
  w(section, overrides, workspace) {
    let configurationModel = this.x(overrides, workspace);
    if (overrides.overrideIdentifier) {
      configurationModel = configurationModel.override(overrides.overrideIdentifier);
    }
    if (!this.l.isEmpty() && this.l.getValue(section) !== void 0) {
      configurationModel = configurationModel.merge(this.l);
    }
    return configurationModel;
  }
  x({ resource }, workspace) {
    let consolidateConfiguration = this.y();
    if (workspace && resource) {
      const root = workspace.getFolder(resource);
      if (root) {
        consolidateConfiguration = this.z(root.uri) || consolidateConfiguration;
      }
      const memoryConfigurationForResource = this.t.get(resource);
      if (memoryConfigurationForResource) {
        consolidateConfiguration = consolidateConfiguration.merge(memoryConfigurationForResource);
      }
    }
    return consolidateConfiguration;
  }
  y() {
    if (!this.h) {
      this.h = this.j.merge(this.applicationConfiguration, this.userConfiguration, this.q, this.s);
    }
    return this.h;
  }
  z(folder) {
    let folderConsolidatedConfiguration = this.i.get(folder);
    if (!folderConsolidatedConfiguration) {
      const workspaceConsolidateConfiguration = this.y();
      const folderConfiguration = this.r.get(folder);
      if (folderConfiguration) {
        folderConsolidatedConfiguration = workspaceConsolidateConfiguration.merge(folderConfiguration);
        this.i.set(folder, folderConsolidatedConfiguration);
      } else {
        folderConsolidatedConfiguration = workspaceConsolidateConfiguration;
      }
    }
    return folderConsolidatedConfiguration;
  }
  A(resource, workspace) {
    if (workspace && resource) {
      const root = workspace.getFolder(resource);
      if (root) {
        return this.r.get(root.uri);
      }
    }
    return void 0;
  }
  toData() {
    return {
      defaults: {
        contents: this.j.contents,
        overrides: this.j.overrides,
        keys: this.j.keys
      },
      policy: {
        contents: this.l.contents,
        overrides: this.l.overrides,
        keys: this.l.keys
      },
      application: {
        contents: this.applicationConfiguration.contents,
        overrides: this.applicationConfiguration.overrides,
        keys: this.applicationConfiguration.keys
      },
      user: {
        contents: this.userConfiguration.contents,
        overrides: this.userConfiguration.overrides,
        keys: this.userConfiguration.keys
      },
      workspace: {
        contents: this.q.contents,
        overrides: this.q.overrides,
        keys: this.q.keys
      },
      folders: [...this.r.keys()].reduce((result, folder) => {
        const { contents, overrides, keys } = this.r.get(folder);
        result.push([folder, { contents, overrides, keys }]);
        return result;
      }, [])
    };
  }
  allKeys() {
    const keys = /* @__PURE__ */ new Set();
    this.j.keys.forEach((key) => keys.add(key));
    this.userConfiguration.keys.forEach((key) => keys.add(key));
    this.q.keys.forEach((key) => keys.add(key));
    this.r.forEach((folderConfiguration) => folderConfiguration.keys.forEach((key) => keys.add(key)));
    return [...keys.values()];
  }
  B() {
    const keys = /* @__PURE__ */ new Set();
    this.j.getAllOverrideIdentifiers().forEach((key) => keys.add(key));
    this.userConfiguration.getAllOverrideIdentifiers().forEach((key) => keys.add(key));
    this.q.getAllOverrideIdentifiers().forEach((key) => keys.add(key));
    this.r.forEach((folderConfiguration) => folderConfiguration.getAllOverrideIdentifiers().forEach((key) => keys.add(key)));
    return [...keys.values()];
  }
  D(overrideIdentifier) {
    const keys = /* @__PURE__ */ new Set();
    this.j.getKeysForOverrideIdentifier(overrideIdentifier).forEach((key) => keys.add(key));
    this.userConfiguration.getKeysForOverrideIdentifier(overrideIdentifier).forEach((key) => keys.add(key));
    this.q.getKeysForOverrideIdentifier(overrideIdentifier).forEach((key) => keys.add(key));
    this.r.forEach((folderConfiguration) => folderConfiguration.getKeysForOverrideIdentifier(overrideIdentifier).forEach((key) => keys.add(key)));
    return [...keys.values()];
  }
  static parse(data, logService) {
    const defaultConfiguration = this.E(data.defaults, logService);
    const policyConfiguration = this.E(data.policy, logService);
    const applicationConfiguration = this.E(data.application, logService);
    const userConfiguration = this.E(data.user, logService);
    const workspaceConfiguration = this.E(data.workspace, logService);
    const folders = data.folders.reduce((result, value) => {
      result.set(URI.revive(value[0]), this.E(value[1], logService));
      return result;
    }, new $Mc());
    return new _$ap(defaultConfiguration, policyConfiguration, applicationConfiguration, userConfiguration, $0o.createEmptyModel(logService), workspaceConfiguration, folders, $0o.createEmptyModel(logService), new $Mc(), logService);
  }
  static E(model, logService) {
    return new $0o(model.contents, model.keys, model.overrides, void 0, logService);
  }
};
var $cp = class {
  constructor(change, f, g, h, i) {
    this.change = change;
    this.f = f;
    this.g = g;
    this.h = h;
    this.i = i;
    this.a = "\n";
    this.b = this.a.charCodeAt(0);
    this.c = ".".charCodeAt(0);
    this.affectedKeys = /* @__PURE__ */ new Set();
    this.j = void 0;
    for (const key of change.keys) {
      this.affectedKeys.add(key);
    }
    for (const [, keys] of change.overrides) {
      for (const key of keys) {
        this.affectedKeys.add(key);
      }
    }
    this.d = this.a;
    for (const key of this.affectedKeys) {
      this.d += key + this.a;
    }
  }
  get previousConfiguration() {
    if (!this.j && this.f) {
      this.j = $ap.parse(this.f.data, this.i);
    }
    return this.j;
  }
  affectsConfiguration(section, overrides) {
    const needle = this.a + section;
    const idx = this.d.indexOf(needle);
    if (idx < 0) {
      return false;
    }
    const pos = idx + needle.length;
    if (pos >= this.d.length) {
      return false;
    }
    const code2 = this.d.charCodeAt(pos);
    if (code2 !== this.b && code2 !== this.c) {
      return false;
    }
    if (overrides) {
      const value1 = this.previousConfiguration ? this.previousConfiguration.getValue(section, overrides, this.f?.workspace) : void 0;
      const value2 = this.g.getValue(section, overrides, this.h);
      return !$Do(value1, value2);
    }
    return true;
  }
};
function compare2(from, to) {
  const { added, removed, updated } = compareConfigurationContents(to?.rawConfiguration, from?.rawConfiguration);
  const overrides = [];
  const fromOverrideIdentifiers = from?.getAllOverrideIdentifiers() || [];
  const toOverrideIdentifiers = to?.getAllOverrideIdentifiers() || [];
  if (to) {
    const addedOverrideIdentifiers = toOverrideIdentifiers.filter((key) => !fromOverrideIdentifiers.includes(key));
    for (const identifier of addedOverrideIdentifiers) {
      overrides.push([identifier, to.getKeysForOverrideIdentifier(identifier)]);
    }
  }
  if (from) {
    const removedOverrideIdentifiers = fromOverrideIdentifiers.filter((key) => !toOverrideIdentifiers.includes(key));
    for (const identifier of removedOverrideIdentifiers) {
      overrides.push([identifier, from.getKeysForOverrideIdentifier(identifier)]);
    }
  }
  if (to && from) {
    for (const identifier of fromOverrideIdentifiers) {
      if (toOverrideIdentifiers.includes(identifier)) {
        const result = compareConfigurationContents({ contents: from.getOverrideValue(void 0, identifier) || {}, keys: from.getKeysForOverrideIdentifier(identifier) }, { contents: to.getOverrideValue(void 0, identifier) || {}, keys: to.getKeysForOverrideIdentifier(identifier) });
        overrides.push([identifier, [...result.added, ...result.removed, ...result.updated]]);
      }
    }
  }
  return { added, removed, updated, overrides };
}
function compareConfigurationContents(to, from) {
  const added = to ? from ? to.keys.filter((key) => from.keys.indexOf(key) === -1) : [...to.keys] : [];
  const removed = from ? to ? from.keys.filter((key) => to.keys.indexOf(key) === -1) : [...from.keys] : [];
  const updated = [];
  if (to && from) {
    for (const key of from.keys) {
      if (to.keys.indexOf(key) !== -1) {
        const value1 = $Bj(from.contents, key);
        const value2 = $Bj(to.contents, key);
        if (!$Do(value1, value2)) {
          updated.push(key);
        }
      }
    }
  }
  return { added, removed, updated };
}

// out-build/vs/platform/configuration/common/configurations.js
var $dp = class extends $0c {
  get configurationModel() {
    return this.b;
  }
  constructor(c) {
    super();
    this.c = c;
    this.a = this.B(new $De());
    this.onDidChangeConfiguration = this.a.event;
    this.b = $0o.createEmptyModel(this.c);
  }
  async initialize() {
    this.h();
    this.B($Mo.as($Ro.Configuration).onDidUpdateConfiguration(({ properties, defaultsOverrides }) => this.f(Array.from(properties), defaultsOverrides)));
    return this.configurationModel;
  }
  reload() {
    this.h();
    return this.configurationModel;
  }
  f(properties, defaultsOverrides) {
    this.j(properties, $Mo.as($Ro.Configuration).getConfigurationProperties());
    this.a.fire({ defaults: this.configurationModel, properties });
  }
  g() {
    return {};
  }
  h() {
    this.b = $0o.createEmptyModel(this.c);
    const properties = $Mo.as($Ro.Configuration).getConfigurationProperties();
    this.j(Object.keys(properties), properties);
  }
  j(properties, configurationProperties) {
    const configurationDefaultsOverrides = this.g();
    for (const key of properties) {
      const defaultOverrideValue = configurationDefaultsOverrides[key];
      const propertySchema = configurationProperties[key];
      if (defaultOverrideValue !== void 0) {
        this.b.setValue(key, defaultOverrideValue);
      } else if (propertySchema) {
        this.b.setValue(key, propertySchema.default);
      } else {
        this.b.removeValue(key);
      }
    }
  }
};
var $ep = class {
  constructor() {
    this.onDidChangeConfiguration = Event.None;
    this.configurationModel = $0o.createEmptyModel(new $Hk());
  }
  async initialize() {
    return this.configurationModel;
  }
};
var $fp = class $fp2 extends $0c {
  get configurationModel() {
    return this.b;
  }
  constructor(c, f, g) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = this.B(new $De());
    this.onDidChangeConfiguration = this.a.event;
    this.b = $0o.createEmptyModel(this.g);
  }
  async initialize() {
    this.g.trace("PolicyConfiguration#initialize");
    this.m(await this.h(this.c.configurationModel.keys), false);
    this.B(this.f.onDidChange((policyNames) => this.j(policyNames)));
    this.B(this.c.onDidChangeConfiguration(async ({ properties }) => this.m(await this.h(properties), true)));
    return this.b;
  }
  async h(properties) {
    this.g.trace("PolicyConfiguration#updatePolicyDefinitions", properties);
    const policyDefinitions = {};
    const keys = [];
    const configurationProperties = $Mo.as($Ro.Configuration).getConfigurationProperties();
    for (const key of properties) {
      const config = configurationProperties[key];
      if (!config) {
        keys.push(key);
        continue;
      }
      if (config.policy) {
        if (config.type !== "string" && config.type !== "number") {
          this.g.warn(`Policy ${config.policy.name} has unsupported type ${config.type}`);
          continue;
        }
        keys.push(key);
        policyDefinitions[config.policy.name] = { type: config.type };
      }
    }
    if (!$Lg(policyDefinitions)) {
      await this.f.updatePolicyDefinitions(policyDefinitions);
    }
    return keys;
  }
  j(policyNames) {
    this.g.trace("PolicyConfiguration#onDidChangePolicies", policyNames);
    const policyConfigurations = $Mo.as($Ro.Configuration).getPolicyConfigurations();
    const keys = $Ub(policyNames.map((policyName) => policyConfigurations.get(policyName)));
    this.m(keys, true);
  }
  m(keys, trigger) {
    this.g.trace("PolicyConfiguration#update", keys);
    const configurationProperties = $Mo.as($Ro.Configuration).getConfigurationProperties();
    const changed = [];
    const wasEmpty = this.b.isEmpty();
    for (const key of keys) {
      const policyName = configurationProperties[key]?.policy?.name;
      if (policyName) {
        const policyValue = this.f.getPolicyValue(policyName);
        if (wasEmpty ? policyValue !== void 0 : !$Do(this.b.getValue(key), policyValue)) {
          changed.push([key, policyValue]);
        }
      } else {
        if (this.b.getValue(key) !== void 0) {
          changed.push([key, void 0]);
        }
      }
    }
    if (changed.length) {
      this.g.trace("PolicyConfiguration#changed", changed);
      const old = this.b;
      this.b = $0o.createEmptyModel(this.g);
      for (const key of old.keys) {
        this.b.setValue(key, old.getValue(key));
      }
      for (const [key, policyValue] of changed) {
        if (policyValue === void 0) {
          this.b.removeValue(key);
        } else {
          this.b.setValue(key, policyValue);
        }
      }
      if (trigger) {
        this.a.fire(this.b);
      }
    }
  }
};
$fp = __decorate([
  __param(1, $Oo),
  __param(2, $uk)
], $fp);

// out-build/vs/platform/configuration/common/configurationService.js
var $gp = class extends $0c {
  constructor(m, fileService, policyService, n) {
    super();
    this.m = m;
    this.n = n;
    this.h = this.B(new $De());
    this.onDidChangeConfiguration = this.h.event;
    this.b = this.B(new $dp(n));
    this.c = policyService instanceof $Qo ? new $ep() : this.B(new $fp(this.b, policyService, n));
    this.f = this.B(new $_o(this.m, {}, $rh, fileService, n));
    this.a = new $ap(this.b.configurationModel, this.c.configurationModel, $0o.createEmptyModel(n), $0o.createEmptyModel(n), $0o.createEmptyModel(n), $0o.createEmptyModel(n), new $Mc(), $0o.createEmptyModel(n), new $Mc(), n);
    this.j = new ConfigurationEditing(m, fileService, this);
    this.g = this.B(new $_h(() => this.reloadConfiguration(), 50));
    this.B(this.b.onDidChangeConfiguration(({ defaults, properties }) => this.s(defaults, properties)));
    this.B(this.c.onDidChangeConfiguration((model) => this.t(model)));
    this.B(this.f.onDidChange(() => this.g.schedule()));
  }
  async initialize() {
    const [defaultModel, policyModel, userModel] = await Promise.all([this.b.initialize(), this.c.initialize(), this.f.loadConfiguration()]);
    this.a = new $ap(defaultModel, policyModel, $0o.createEmptyModel(this.n), userModel, $0o.createEmptyModel(this.n), $0o.createEmptyModel(this.n), new $Mc(), $0o.createEmptyModel(this.n), new $Mc(), this.n);
  }
  getConfigurationData() {
    return this.a.toData();
  }
  getValue(arg1, arg2) {
    const section = typeof arg1 === "string" ? arg1 : void 0;
    const overrides = $uj(arg1) ? arg1 : $uj(arg2) ? arg2 : {};
    return this.a.getValue(section, overrides, void 0);
  }
  async updateValue(key, value, arg3, arg4, options) {
    const overrides = $vj(arg3) ? arg3 : $uj(arg3) ? { resource: arg3.resource, overrideIdentifiers: arg3.overrideIdentifier ? [arg3.overrideIdentifier] : void 0 } : void 0;
    const target = overrides ? arg4 : arg3;
    if (target !== void 0) {
      if (target !== 3 && target !== 2) {
        throw new Error(`Unable to write ${key} to target ${target}.`);
      }
    }
    if (overrides?.overrideIdentifiers) {
      overrides.overrideIdentifiers = $Zb(overrides.overrideIdentifiers);
      overrides.overrideIdentifiers = overrides.overrideIdentifiers.length ? overrides.overrideIdentifiers : void 0;
    }
    const inspect = this.inspect(key, { resource: overrides?.resource, overrideIdentifier: overrides?.overrideIdentifiers ? overrides.overrideIdentifiers[0] : void 0 });
    if (inspect.policyValue !== void 0) {
      throw new Error(`Unable to write ${key} because it is configured in system policy.`);
    }
    if ($Do(value, inspect.defaultValue)) {
      value = void 0;
    }
    if (overrides?.overrideIdentifiers?.length && overrides.overrideIdentifiers.length > 1) {
      const overrideIdentifiers = overrides.overrideIdentifiers.sort();
      const existingOverrides = this.a.localUserConfiguration.overrides.find((override) => $Hb([...override.identifiers].sort(), overrideIdentifiers));
      if (existingOverrides) {
        overrides.overrideIdentifiers = existingOverrides.identifiers;
      }
    }
    const path3 = overrides?.overrideIdentifiers?.length ? [$4o(overrides.overrideIdentifiers), key] : [key];
    await this.j.write(path3, value);
    await this.reloadConfiguration();
  }
  inspect(key, overrides = {}) {
    return this.a.inspect(key, overrides, void 0);
  }
  keys() {
    return this.a.keys(void 0);
  }
  async reloadConfiguration() {
    const configurationModel = await this.f.loadConfiguration();
    this.r(configurationModel);
  }
  r(userConfigurationModel) {
    const previous = this.a.toData();
    const change = this.a.compareAndUpdateLocalUserConfiguration(userConfigurationModel);
    this.u(
      change,
      previous,
      2
      /* ConfigurationTarget.USER */
    );
  }
  s(defaultConfigurationModel, properties) {
    const previous = this.a.toData();
    const change = this.a.compareAndUpdateDefaultConfiguration(defaultConfigurationModel, properties);
    this.u(
      change,
      previous,
      7
      /* ConfigurationTarget.DEFAULT */
    );
  }
  t(policyConfiguration) {
    const previous = this.a.toData();
    const change = this.a.compareAndUpdatePolicyConfiguration(policyConfiguration);
    this.u(
      change,
      previous,
      7
      /* ConfigurationTarget.DEFAULT */
    );
  }
  u(configurationChange, previous, source) {
    const event = new $cp(configurationChange, { data: previous }, this.a, void 0, this.n);
    event.source = source;
    this.h.fire(event);
  }
};
var ConfigurationEditing = class {
  constructor(b, c, d) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.a = new $7h();
  }
  write(path3, value) {
    return this.a.queue(() => this.e(path3, value));
  }
  async e(path3, value) {
    let content;
    try {
      const fileContent = await this.c.readFile(this.b);
      content = fileContent.value.toString();
    } catch (error) {
      if (error.fileOperationResult === 1) {
        content = "{}";
      } else {
        throw error;
      }
    }
    const parseErrors = [];
    $ho(content, parseErrors, { allowTrailingComma: true, allowEmptyContent: true });
    if (parseErrors.length > 0) {
      throw new Error("Unable to write into the settings file. Please open the file to correct errors/warnings in the file and try again.");
    }
    const edits = this.f(content, path3, value);
    content = $yo(content, edits);
    await this.c.writeFile(this.b, $7e.fromString(content));
  }
  f(content, path3, value) {
    const { tabSize, insertSpaces, eol } = this.h;
    if (!path3.length) {
      const content2 = JSON.stringify(value, null, insertSpaces ? " ".repeat(tabSize) : "	");
      return [{
        content: content2,
        length: content2.length,
        offset: 0
      }];
    }
    return $vo(content, path3, value, { tabSize, insertSpaces, eol });
  }
  get h() {
    if (!this.g) {
      let eol = OS === 3 || OS === 2 ? "\n" : "\r\n";
      const configuredEol = this.d.getValue("files.eol", { overrideIdentifier: "jsonc" });
      if (configuredEol && typeof configuredEol === "string" && configuredEol !== "auto") {
        eol = configuredEol;
      }
      this.g = {
        eol,
        insertSpaces: !!this.d.getValue("editor.insertSpaces", { overrideIdentifier: "jsonc" }),
        tabSize: this.d.getValue("editor.tabSize", { overrideIdentifier: "jsonc" })
      };
    }
    return this.g;
  }
};

// out-build/vs/platform/diagnostics/node/diagnosticsService.js
import * as fs12 from "fs";
import * as osLib from "os";
var workspaceStatsCache = /* @__PURE__ */ new Map();
async function $it(folder, filter) {
  const cacheKey = `${folder}::${filter.join(":")}`;
  const cached = workspaceStatsCache.get(cacheKey);
  if (cached) {
    return cached;
  }
  const configFilePatterns = [
    { tag: "grunt.js", filePattern: /^gruntfile\.js$/i },
    { tag: "gulp.js", filePattern: /^gulpfile\.js$/i },
    { tag: "tsconfig.json", filePattern: /^tsconfig\.json$/i },
    { tag: "package.json", filePattern: /^package\.json$/i },
    { tag: "jsconfig.json", filePattern: /^jsconfig\.json$/i },
    { tag: "tslint.json", filePattern: /^tslint\.json$/i },
    { tag: "eslint.json", filePattern: /^eslint\.json$/i },
    { tag: "tasks.json", filePattern: /^tasks\.json$/i },
    { tag: "launch.json", filePattern: /^launch\.json$/i },
    { tag: "settings.json", filePattern: /^settings\.json$/i },
    { tag: "webpack.config.js", filePattern: /^webpack\.config\.js$/i },
    { tag: "project.json", filePattern: /^project\.json$/i },
    { tag: "makefile", filePattern: /^makefile$/i },
    { tag: "sln", filePattern: /^.+\.sln$/i },
    { tag: "csproj", filePattern: /^.+\.csproj$/i },
    { tag: "cmake", filePattern: /^.+\.cmake$/i },
    { tag: "github-actions", filePattern: /^.+\.ya?ml$/i, relativePathPattern: /^\.github(?:\/|\\)workflows$/i },
    { tag: "devcontainer.json", filePattern: /^devcontainer\.json$/i },
    { tag: "dockerfile", filePattern: /^(dockerfile|docker\-compose\.ya?ml)$/i },
    { tag: "cursorrules", filePattern: /^\.cursorrules$/i }
  ];
  const fileTypes = /* @__PURE__ */ new Map();
  const configFiles = /* @__PURE__ */ new Map();
  const MAX_FILES = 2e4;
  function collect(root, dir, filter2, token) {
    const relativePath = dir.substring(root.length + 1);
    return Promises.withAsyncBody(async (resolve2) => {
      let files;
      token.readdirCount++;
      try {
        files = await Promises2.readdir(dir, { withFileTypes: true });
      } catch (error) {
        resolve2();
        return;
      }
      if (token.count >= MAX_FILES) {
        token.count += files.length;
        token.maxReached = true;
        resolve2();
        return;
      }
      let pending = files.length;
      if (pending === 0) {
        resolve2();
        return;
      }
      let filesToRead = files;
      if (token.count + files.length > MAX_FILES) {
        token.maxReached = true;
        pending = MAX_FILES - token.count;
        filesToRead = files.slice(0, pending);
      }
      token.count += files.length;
      for (const file of filesToRead) {
        if (file.isDirectory()) {
          if (!filter2.includes(file.name)) {
            await collect(root, $vc(dir, file.name), filter2, token);
          }
          if (--pending === 0) {
            resolve2();
            return;
          }
        } else {
          const index = file.name.lastIndexOf(".");
          if (index >= 0) {
            const fileType = file.name.substring(index + 1);
            if (fileType) {
              fileTypes.set(fileType, (fileTypes.get(fileType) ?? 0) + 1);
            }
          }
          for (const configFile of configFilePatterns) {
            if (configFile.relativePathPattern?.test(relativePath) !== false && configFile.filePattern.test(file.name)) {
              configFiles.set(configFile.tag, (configFiles.get(configFile.tag) ?? 0) + 1);
            }
          }
          if (--pending === 0) {
            resolve2();
            return;
          }
        }
      }
    });
  }
  const statsPromise = Promises.withAsyncBody(async (resolve2) => {
    const token = { count: 0, maxReached: false, readdirCount: 0 };
    const sw = new $xe(true);
    await collect(folder, folder, filter, token);
    const launchConfigs = await $kt(folder);
    resolve2({
      configFiles: asSortedItems(configFiles),
      fileTypes: asSortedItems(fileTypes),
      fileCount: token.count,
      maxFilesReached: token.maxReached,
      launchConfigFiles: launchConfigs,
      totalScanTime: sw.elapsed(),
      totalReaddirCount: token.readdirCount
    });
  });
  workspaceStatsCache.set(cacheKey, statsPromise);
  return statsPromise;
}
function asSortedItems(items) {
  return Array.from(items.entries(), ([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count);
}
function $jt() {
  const machineInfo = {
    os: `${osLib.type()} ${osLib.arch()} ${osLib.release()}`,
    memory: `${(osLib.totalmem() / $3l.GB).toFixed(2)}GB (${(osLib.freemem() / $3l.GB).toFixed(2)}GB free)`,
    vmHint: `${Math.round($bo.value() * 100)}%`
  };
  const cpus3 = osLib.cpus();
  if (cpus3 && cpus3.length > 0) {
    machineInfo.cpus = `${cpus3[0].model} (${cpus3.length} x ${cpus3[0].speed})`;
  }
  return machineInfo;
}
async function $kt(folder) {
  try {
    const launchConfigs = /* @__PURE__ */ new Map();
    const launchConfig = $vc(folder, ".vscode", "launch.json");
    const contents = await fs12.promises.readFile(launchConfig);
    const errors = [];
    const json = $ho(contents.toString(), errors);
    if (errors.length) {
      console.log(`Unable to parse ${launchConfig}`);
      return [];
    }
    if ($po(json) === "object" && json["configurations"]) {
      for (const each of json["configurations"]) {
        const type4 = each["type"];
        if (type4) {
          if (launchConfigs.has(type4)) {
            launchConfigs.set(type4, launchConfigs.get(type4) + 1);
          } else {
            launchConfigs.set(type4, 1);
          }
        }
      }
    }
    return asSortedItems(launchConfigs);
  } catch (error) {
    return [];
  }
}
var $lt = class $lt2 {
  constructor(c, d) {
    this.c = c;
    this.d = d;
  }
  f(info) {
    const output = [];
    output.push(`OS Version:       ${info.os}`);
    output.push(`CPUs:             ${info.cpus}`);
    output.push(`Memory (System):  ${info.memory}`);
    output.push(`VM:               ${info.vmHint}`);
    return output.join("\n");
  }
  g(info) {
    const output = [];
    output.push(`Version:          ${this.d.nameShort} ${this.d.version} (${this.d.commit || "Commit unknown"}, ${this.d.date || "Date unknown"})`);
    output.push(`OS Version:       ${osLib.type()} ${osLib.arch()} ${osLib.release()}`);
    const cpus3 = osLib.cpus();
    if (cpus3 && cpus3.length > 0) {
      output.push(`CPUs:             ${cpus3[0].model} (${cpus3.length} x ${cpus3[0].speed})`);
    }
    output.push(`Memory (System):  ${(osLib.totalmem() / $3l.GB).toFixed(2)}GB (${(osLib.freemem() / $3l.GB).toFixed(2)}GB free)`);
    if (!$l) {
      output.push(`Load (avg):       ${osLib.loadavg().map((l) => Math.round(l)).join(", ")}`);
    }
    output.push(`VM:               ${Math.round($bo.value() * 100)}%`);
    output.push(`Screen Reader:    ${info.screenReader ? "yes" : "no"}`);
    output.push(`Process Argv:     ${info.mainArguments.join(" ")}`);
    output.push(`GPU Status:       ${this.j(info.gpuFeatureStatus)}`);
    return output.join("\n");
  }
  async getPerformanceInfo(info, remoteData) {
    return Promise.all([$ht(info.mainPID), this.k(info)]).then(async (result) => {
      let [rootProcess, workspaceInfo] = result;
      let processInfo = this.m(info, rootProcess);
      remoteData.forEach((diagnostics) => {
        if ($cn(diagnostics)) {
          processInfo += `
${diagnostics.errorMessage}`;
          workspaceInfo += `
${diagnostics.errorMessage}`;
        } else {
          processInfo += `

Remote: ${diagnostics.hostName}`;
          if (diagnostics.processes) {
            processInfo += `
${this.m(info, diagnostics.processes)}`;
          }
          if (diagnostics.workspaceMetadata) {
            workspaceInfo += `
|  Remote: ${diagnostics.hostName}`;
            for (const folder of Object.keys(diagnostics.workspaceMetadata)) {
              const metadata = diagnostics.workspaceMetadata[folder];
              let countMessage = `${metadata.fileCount} files`;
              if (metadata.maxFilesReached) {
                countMessage = `more than ${countMessage}`;
              }
              workspaceInfo += `|    Folder (${folder}): ${countMessage}`;
              workspaceInfo += this.h(metadata);
            }
          }
        }
      });
      return {
        processInfo,
        workspaceInfo
      };
    });
  }
  async getSystemInfo(info, remoteData) {
    const { memory, vmHint, os: os6, cpus: cpus3 } = $jt();
    const systemInfo = {
      os: os6,
      memory,
      cpus: cpus3,
      vmHint,
      processArgs: `${info.mainArguments.join(" ")}`,
      gpuStatus: info.gpuFeatureStatus,
      screenReader: `${info.screenReader ? "yes" : "no"}`,
      remoteData
    };
    if (!$l) {
      systemInfo.load = `${osLib.loadavg().map((l) => Math.round(l)).join(", ")}`;
    }
    if ($n) {
      systemInfo.linuxEnv = {
        desktopSession: process.env["DESKTOP_SESSION"],
        xdgSessionDesktop: process.env["XDG_SESSION_DESKTOP"],
        xdgCurrentDesktop: process.env["XDG_CURRENT_DESKTOP"],
        xdgSessionType: process.env["XDG_SESSION_TYPE"]
      };
    }
    return Promise.resolve(systemInfo);
  }
  async getDiagnostics(info, remoteDiagnostics) {
    const output = [];
    return $ht(info.mainPID).then(async (rootProcess) => {
      output.push("");
      output.push(this.g(info));
      output.push("");
      output.push(this.m(info, rootProcess));
      if (info.windows.some((window2) => window2.folderURIs && window2.folderURIs.length > 0 && !window2.remoteAuthority)) {
        output.push("");
        output.push("Workspace Stats: ");
        output.push(await this.k(info));
      }
      remoteDiagnostics.forEach((diagnostics) => {
        if ($cn(diagnostics)) {
          output.push(`
${diagnostics.errorMessage}`);
        } else {
          output.push("\n\n");
          output.push(`Remote:           ${diagnostics.hostName}`);
          output.push(this.f(diagnostics.machineInfo));
          if (diagnostics.processes) {
            output.push(this.m(info, diagnostics.processes));
          }
          if (diagnostics.workspaceMetadata) {
            for (const folder of Object.keys(diagnostics.workspaceMetadata)) {
              const metadata = diagnostics.workspaceMetadata[folder];
              let countMessage = `${metadata.fileCount} files`;
              if (metadata.maxFilesReached) {
                countMessage = `more than ${countMessage}`;
              }
              output.push(`Folder (${folder}): ${countMessage}`);
              output.push(this.h(metadata));
            }
          }
        }
      });
      output.push("");
      output.push("");
      return output.join("\n");
    });
  }
  h(workspaceStats) {
    const output = [];
    const lineLength = 60;
    let col = 0;
    const appendAndWrap = (name, count) => {
      const item = ` ${name}(${count})`;
      if (col + item.length > lineLength) {
        output.push(line);
        line = "|                 ";
        col = line.length;
      } else {
        col += item.length;
      }
      line += item;
    };
    let line = "|      File types:";
    const maxShown = 10;
    const max = workspaceStats.fileTypes.length > maxShown ? maxShown : workspaceStats.fileTypes.length;
    for (let i = 0; i < max; i++) {
      const item = workspaceStats.fileTypes[i];
      appendAndWrap(item.name, item.count);
    }
    output.push(line);
    if (workspaceStats.configFiles.length >= 0) {
      line = "|      Conf files:";
      col = 0;
      workspaceStats.configFiles.forEach((item) => {
        appendAndWrap(item.name, item.count);
      });
      output.push(line);
    }
    if (workspaceStats.launchConfigFiles.length > 0) {
      let line2 = "|      Launch Configs:";
      workspaceStats.launchConfigFiles.forEach((each) => {
        const item = each.count > 1 ? ` ${each.name}(${each.count})` : ` ${each.name}`;
        line2 += item;
      });
      output.push(line2);
    }
    return output.join("\n");
  }
  j(gpuFeatures) {
    const longestFeatureName = Math.max(...Object.keys(gpuFeatures).map((feature) => feature.length));
    return Object.keys(gpuFeatures).map((feature) => `${feature}:  ${" ".repeat(longestFeatureName - feature.length)}  ${gpuFeatures[feature]}`).join("\n                  ");
  }
  k(info) {
    const output = [];
    const workspaceStatPromises = [];
    info.windows.forEach((window2) => {
      if (window2.folderURIs.length === 0 || !!window2.remoteAuthority) {
        return;
      }
      output.push(`|  Window (${window2.title})`);
      window2.folderURIs.forEach((uriComponents) => {
        const folderUri = URI.revive(uriComponents);
        if (folderUri.scheme === Schemas.file) {
          const folder = folderUri.fsPath;
          workspaceStatPromises.push($it(folder, ["node_modules", ".git"]).then((stats) => {
            let countMessage = `${stats.fileCount} files`;
            if (stats.maxFilesReached) {
              countMessage = `more than ${countMessage}`;
            }
            output.push(`|    Folder (${$zc(folder)}): ${countMessage}`);
            output.push(this.h(stats));
          }).catch((error) => {
            output.push(`|      Error: Unable to collect workspace stats for folder ${folder} (${error.toString()})`);
          }));
        } else {
          output.push(`|    Folder (${folderUri.toString()}): Workspace stats not available.`);
        }
      });
    });
    return Promise.all(workspaceStatPromises).then((_) => output.join("\n")).catch((e) => `Unable to collect workspace stats: ${e}`);
  }
  m(info, rootProcess) {
    const mapProcessToName = /* @__PURE__ */ new Map();
    info.windows.forEach((window2) => mapProcessToName.set(window2.pid, `window [${window2.id}] (${window2.title})`));
    info.pidToNames.forEach(({ pid, name }) => mapProcessToName.set(pid, name));
    const output = [];
    output.push("CPU %	Mem MB	   PID	Process");
    if (rootProcess) {
      this.n(info.mainPID, mapProcessToName, output, rootProcess, 0);
    }
    return output.join("\n");
  }
  n(mainPid, mapProcessToName, output, item, indent) {
    const isRoot = indent === 0;
    let name;
    if (isRoot) {
      name = item.pid === mainPid ? `${this.d.applicationName} main` : "remote agent";
    } else {
      if (mapProcessToName.has(item.pid)) {
        name = mapProcessToName.get(item.pid);
      } else {
        name = `${"  ".repeat(indent)} ${item.name}`;
      }
    }
    const memory = process.platform === "win32" ? item.mem : osLib.totalmem() * (item.mem / 100);
    output.push(`${item.load.toFixed(0).padStart(5, " ")}	${(memory / $3l.MB).toFixed(0).padStart(6, " ")}	${item.pid.toFixed(0).padStart(6, " ")}	${name}`);
    if (Array.isArray(item.children)) {
      item.children.forEach((child) => this.n(mainPid, mapProcessToName, output, child, indent + 1));
    }
  }
  async getWorkspaceFileExtensions(workspace) {
    const items = /* @__PURE__ */ new Set();
    for (const { uri } of workspace.folders) {
      const folderUri = URI.revive(uri);
      if (folderUri.scheme !== Schemas.file) {
        continue;
      }
      const folder = folderUri.fsPath;
      try {
        const stats = await $it(folder, ["node_modules", ".git"]);
        stats.fileTypes.forEach((item) => items.add(item.name));
      } catch {
      }
    }
    return { extensions: [...items] };
  }
  async reportWorkspaceStats(workspace) {
    for (const { uri } of workspace.folders) {
      const folderUri = URI.revive(uri);
      if (folderUri.scheme !== Schemas.file) {
        continue;
      }
      const folder = folderUri.fsPath;
      try {
        const stats = await $it(folder, ["node_modules", ".git"]);
        this.c.publicLog2("workspace.stats", {
          "workspace.id": workspace.telemetryId,
          rendererSessionId: workspace.rendererSessionId
        });
        stats.fileTypes.forEach((e) => {
          this.c.publicLog2("workspace.stats.file", {
            rendererSessionId: workspace.rendererSessionId,
            type: e.name,
            count: e.count
          });
        });
        stats.launchConfigFiles.forEach((e) => {
          this.c.publicLog2("workspace.stats.launchConfigFile", {
            rendererSessionId: workspace.rendererSessionId,
            type: e.name,
            count: e.count
          });
        });
        stats.configFiles.forEach((e) => {
          this.c.publicLog2("workspace.stats.configFiles", {
            rendererSessionId: workspace.rendererSessionId,
            type: e.name,
            count: e.count
          });
        });
        this.c.publicLog2("workspace.stats.metadata", { duration: stats.totalScanTime, reachedLimit: stats.maxFilesReached, fileCount: stats.fileCount, readdirCount: stats.totalReaddirCount });
      } catch {
      }
    }
  }
};
$lt = __decorate([
  __param(0, $tm),
  __param(1, $Nk)
], $lt);

// out-build/vs/platform/environment/node/wait.js
import { writeFileSync as writeFileSync2 } from "fs";
import { tmpdir as tmpdir6 } from "os";
function $Plc(verbose) {
  const randomWaitMarkerPath = $8g(tmpdir6());
  try {
    writeFileSync2(randomWaitMarkerPath, "");
    if (verbose) {
      console.log(`Marker file for --wait created: ${randomWaitMarkerPath}`);
    }
    return randomWaitMarkerPath;
  } catch (err) {
    if (verbose) {
      console.error(`Failed to create marker file for --wait: ${err}`);
    }
    return void 0;
  }
}

// out-build/vs/platform/files/common/fileService.js
var $mr_1;
var $mr = class $mr2 extends $0c {
  static {
    $mr_1 = this;
  }
  constructor(b) {
    super();
    this.b = b;
    this.a = 256 * 1024;
    this.c = this.B(new $De());
    this.onDidChangeFileSystemProviderRegistrations = this.c.event;
    this.f = this.B(new $De());
    this.onWillActivateFileSystemProvider = this.f.event;
    this.g = this.B(new $De());
    this.onDidChangeFileSystemProviderCapabilities = this.g.event;
    this.h = /* @__PURE__ */ new Map();
    this.r = this.B(new $De());
    this.onDidRunOperation = this.r.event;
    this.X = this.B(new $De());
    this.Y = this.B(new $De());
    this.onDidFilesChange = this.Y.event;
    this.Z = this.B(new $De());
    this.onDidWatchError = this.Z.event;
    this.$ = /* @__PURE__ */ new Map();
    this.cb = this.B(new $9h());
  }
  registerProvider(scheme, provider) {
    if (this.h.has(scheme)) {
      throw new Error(`A filesystem provider for the scheme '${scheme}' is already registered.`);
    }
    mark(`code/registerFilesystem/${scheme}`);
    const providerDisposables = new $9c();
    this.h.set(scheme, provider);
    this.c.fire({ added: true, scheme, provider });
    providerDisposables.add(provider.onDidChangeFile((changes) => {
      const event = new $Nl(changes, !this.S(provider));
      this.X.fire(event);
      if (!event.hasCorrelation()) {
        this.Y.fire(event);
      }
    }));
    if (typeof provider.onDidWatchError === "function") {
      providerDisposables.add(provider.onDidWatchError((error) => this.Z.fire(new Error(error))));
    }
    providerDisposables.add(provider.onDidChangeCapabilities(() => this.g.fire({ provider, scheme })));
    return $8c(() => {
      this.c.fire({ added: false, scheme, provider });
      this.h.delete(scheme);
      $5c(providerDisposables);
    });
  }
  getProvider(scheme) {
    return this.h.get(scheme);
  }
  async activateProvider(scheme) {
    const joiners = [];
    this.f.fire({
      scheme,
      join(promise) {
        joiners.push(promise);
      }
    });
    if (this.h.has(scheme)) {
      return;
    }
    await Promises.settled(joiners);
  }
  async canHandleResource(resource) {
    await this.activateProvider(resource.scheme);
    return this.hasProvider(resource);
  }
  hasProvider(resource) {
    return this.h.has(resource.scheme);
  }
  hasCapability(resource, capability) {
    const provider = this.h.get(resource.scheme);
    return !!(provider && provider.capabilities & capability);
  }
  listCapabilities() {
    return Iterable.map(this.h, ([scheme, provider]) => ({ scheme, capabilities: provider.capabilities }));
  }
  async j(resource) {
    if (!$Eh(resource)) {
      throw new $Pl(
        localize(1885, null, this.sb(resource)),
        8
        /* FileOperationResult.FILE_INVALID_PATH */
      );
    }
    await this.activateProvider(resource.scheme);
    const provider = this.h.get(resource.scheme);
    if (!provider) {
      const error = new $ob();
      error.message = localize(1886, null, resource.toString());
      throw error;
    }
    return provider;
  }
  async m(resource) {
    const provider = await this.j(resource);
    if ($Al(provider) || $xl(provider) || $Bl(provider)) {
      return provider;
    }
    throw new Error(`Filesystem provider for scheme '${resource.scheme}' neither has FileReadWrite, FileReadStream nor FileOpenReadWriteClose capability which is needed for the read operation.`);
  }
  async n(resource) {
    const provider = await this.j(resource);
    if ($Al(provider) || $xl(provider)) {
      return provider;
    }
    throw new Error(`Filesystem provider for scheme '${resource.scheme}' neither has FileReadWrite nor FileOpenReadWriteClose capability which is needed for the write operation.`);
  }
  async resolve(resource, options) {
    try {
      return await this.s(resource, options);
    } catch (error) {
      if ($Kl(error) === FileSystemProviderErrorCode.FileNotFound) {
        throw new $Pl(
          localize(1887, null, this.sb(resource)),
          1
          /* FileOperationResult.FILE_NOT_FOUND */
        );
      }
      throw $Il(error);
    }
  }
  async s(resource, options) {
    const provider = await this.j(resource);
    const isPathCaseSensitive = this.S(provider);
    const resolveTo = options?.resolveTo;
    const resolveSingleChildDescendants = options?.resolveSingleChildDescendants;
    const resolveMetadata = options?.resolveMetadata;
    const stat = await provider.stat(resource);
    let trie;
    return this.t(provider, resource, stat, void 0, !!resolveMetadata, (stat2, siblings) => {
      if (!trie) {
        trie = $6i.forUris(() => !isPathCaseSensitive);
        trie.set(resource, true);
        if (resolveTo) {
          trie.fill(true, resolveTo);
        }
      }
      if (trie.get(stat2.resource) || trie.findSuperstr(stat2.resource.with(
        { query: null, fragment: null }
        /* required for https://github.com/microsoft/vscode/issues/128151 */
      ))) {
        return true;
      }
      if (stat2.isDirectory && resolveSingleChildDescendants) {
        return siblings === 1;
      }
      return false;
    });
  }
  async t(provider, resource, stat, siblings, resolveMetadata, recurse) {
    const { providerExtUri } = this.R(provider);
    const fileStat = {
      resource,
      name: providerExtUri.basename(resource),
      isFile: (stat.type & FileType.File) !== 0,
      isDirectory: (stat.type & FileType.Directory) !== 0,
      isSymbolicLink: (stat.type & FileType.SymbolicLink) !== 0,
      mtime: stat.mtime,
      ctime: stat.ctime,
      size: stat.size,
      readonly: Boolean((stat.permissions ?? 0) & FilePermission.Readonly) || Boolean(
        provider.capabilities & 2048
        /* FileSystemProviderCapabilities.Readonly */
      ),
      locked: Boolean((stat.permissions ?? 0) & FilePermission.Locked),
      etag: $1l({ mtime: stat.mtime, size: stat.size }),
      children: void 0
    };
    if (fileStat.isDirectory && recurse(fileStat, siblings)) {
      try {
        const entries = await provider.readdir(resource);
        const resolvedEntries = await Promises.settled(entries.map(async ([name, type4]) => {
          try {
            const childResource = providerExtUri.joinPath(resource, name);
            const childStat = resolveMetadata ? await provider.stat(childResource) : { type: type4 };
            return await this.t(provider, childResource, childStat, entries.length, resolveMetadata, recurse);
          } catch (error) {
            this.b.trace(error);
            return null;
          }
        }));
        fileStat.children = $Ub(resolvedEntries);
      } catch (error) {
        this.b.trace(error);
        fileStat.children = [];
      }
      return fileStat;
    }
    return fileStat;
  }
  async resolveAll(toResolve) {
    return Promises.settled(toResolve.map(async (entry) => {
      try {
        return { stat: await this.s(entry.resource, entry.options), success: true };
      } catch (error) {
        this.b.trace(error);
        return { stat: void 0, success: false };
      }
    }));
  }
  async stat(resource) {
    const provider = await this.j(resource);
    const stat = await provider.stat(resource);
    return this.t(
      provider,
      resource,
      stat,
      void 0,
      true,
      () => false
      /* Do not resolve any children */
    );
  }
  async exists(resource) {
    const provider = await this.j(resource);
    try {
      const stat = await provider.stat(resource);
      return !!stat;
    } catch (error) {
      return false;
    }
  }
  //#endregion
  //#region File Reading/Writing
  async canCreateFile(resource, options) {
    try {
      await this.u(resource, options);
    } catch (error) {
      return error;
    }
    return true;
  }
  async u(resource, options) {
    if (!options?.overwrite && await this.exists(resource)) {
      throw new $Pl(localize(1888, null, this.sb(resource)), 3, options);
    }
  }
  async createFile(resource, bufferOrReadableOrStream = $7e.fromString(""), options) {
    await this.u(resource, options);
    const fileStat = await this.writeFile(resource, bufferOrReadableOrStream);
    this.r.fire(new $Ml(resource, 0, fileStat));
    return fileStat;
  }
  async writeFile(resource, bufferOrReadableOrStream, options) {
    const provider = this.qb(await this.n(resource), resource);
    const { providerExtUri } = this.R(provider);
    let writeFileOptions = options;
    if ($Dl(provider) && !writeFileOptions?.atomic) {
      const enforcedAtomicWrite = provider.enforceAtomicWriteFile?.(resource);
      if (enforcedAtomicWrite) {
        writeFileOptions = { ...options, atomic: enforcedAtomicWrite };
      }
    }
    try {
      const stat = await this.w(provider, resource, writeFileOptions);
      if (!stat) {
        await this.U(provider, providerExtUri.dirname(resource));
      }
      let bufferOrReadableOrStreamOrBufferedStream;
      if ($xl(provider) && !(bufferOrReadableOrStream instanceof $7e)) {
        if ($Se(bufferOrReadableOrStream)) {
          const bufferedStream = await $Ze(bufferOrReadableOrStream, 3);
          if (bufferedStream.ended) {
            bufferOrReadableOrStreamOrBufferedStream = $7e.concat(bufferedStream.buffer);
          } else {
            bufferOrReadableOrStreamOrBufferedStream = bufferedStream;
          }
        } else {
          bufferOrReadableOrStreamOrBufferedStream = $We(bufferOrReadableOrStream, (data) => $7e.concat(data), 3);
        }
      } else {
        bufferOrReadableOrStreamOrBufferedStream = bufferOrReadableOrStream;
      }
      if (!$Al(provider) || // buffered writing is unsupported
      $xl(provider) && bufferOrReadableOrStreamOrBufferedStream instanceof $7e || // data is a full buffer already
      $xl(provider) && $Dl(provider) && writeFileOptions?.atomic) {
        await this.hb(provider, resource, writeFileOptions, bufferOrReadableOrStreamOrBufferedStream);
      } else {
        await this.db(provider, resource, writeFileOptions, bufferOrReadableOrStreamOrBufferedStream instanceof $7e ? $ff(bufferOrReadableOrStreamOrBufferedStream) : bufferOrReadableOrStreamOrBufferedStream);
      }
      this.r.fire(new $Ml(
        resource,
        4
        /* FileOperation.WRITE */
      ));
    } catch (error) {
      throw new $Pl(localize(1889, null, this.sb(resource), $Il(error).toString()), $Ll(error), writeFileOptions);
    }
    return this.resolve(resource, { resolveMetadata: true });
  }
  async w(provider, resource, options) {
    const unlock = !!options?.unlock;
    if (unlock && !(provider.capabilities & 8192)) {
      throw new Error(localize(1890, null, this.sb(resource)));
    }
    const atomic = !!options?.atomic;
    if (atomic) {
      if (!(provider.capabilities & 32768)) {
        throw new Error(localize(1891, null, this.sb(resource)));
      }
      if (!(provider.capabilities & 2)) {
        throw new Error(localize(1892, null, this.sb(resource)));
      }
      if (unlock) {
        throw new Error(localize(1893, null, this.sb(resource)));
      }
    }
    let stat = void 0;
    try {
      stat = await provider.stat(resource);
    } catch (error) {
      return void 0;
    }
    if ((stat.type & FileType.Directory) !== 0) {
      throw new $Pl(localize(1894, null, this.sb(resource)), 0, options);
    }
    this.rb(resource, stat);
    if (typeof options?.mtime === "number" && typeof options.etag === "string" && options.etag !== $Zl && typeof stat.mtime === "number" && typeof stat.size === "number" && options.mtime < stat.mtime && options.etag !== $1l({ mtime: options.mtime, size: stat.size })) {
      throw new $Pl(localize(1895, null), 3, options);
    }
    return stat;
  }
  async readFile(resource, options, token) {
    const provider = await this.m(resource);
    if (options?.atomic) {
      return this.z(provider, resource, options, token);
    }
    return this.C(provider, resource, options, token);
  }
  async z(provider, resource, options, token) {
    return new Promise((resolve2, reject) => {
      this.cb.queueFor(resource, async () => {
        try {
          const content = await this.C(provider, resource, options, token);
          resolve2(content);
        } catch (error) {
          reject(error);
        }
      }, this.R(provider).providerExtUri);
    });
  }
  async C(provider, resource, options, token) {
    const stream = await this.D(provider, resource, {
      ...options,
      // optimization: since we know that the caller does not
      // care about buffering, we indicate this to the reader.
      // this reduces all the overhead the buffered reading
      // has (open, read, close) if the provider supports
      // unbuffered reading.
      preferUnbuffered: true
    }, token);
    return {
      ...stream,
      value: await $gf(stream.value)
    };
  }
  async readFileStream(resource, options, token) {
    const provider = await this.m(resource);
    return this.D(provider, resource, options, token);
  }
  async D(provider, resource, options, token) {
    const cancellableSource = new $Pe(token);
    let readFileOptions = options;
    if ($Cl(provider) && provider.enforceAtomicReadFile?.(resource)) {
      readFileOptions = { ...options, atomic: true };
    }
    const statPromise = this.J(resource, readFileOptions).then((stat) => stat, (error) => {
      cancellableSource.dispose(true);
      throw error;
    });
    let fileStream = void 0;
    try {
      if (typeof readFileOptions?.etag === "string" && readFileOptions.etag !== $Zl) {
        await statPromise;
      }
      if (readFileOptions?.atomic && $Cl(provider) || // atomic reads are always unbuffered
      !($Al(provider) || $Bl(provider)) || // provider has no buffered capability
      $xl(provider) && readFileOptions?.preferUnbuffered) {
        fileStream = this.I(provider, resource, readFileOptions);
      } else if ($Bl(provider)) {
        fileStream = this.G(provider, resource, cancellableSource.token, readFileOptions);
      } else {
        fileStream = this.H(provider, resource, cancellableSource.token, readFileOptions);
      }
      fileStream.on("end", () => cancellableSource.dispose());
      fileStream.on("error", () => cancellableSource.dispose());
      const fileStat = await statPromise;
      return {
        ...fileStat,
        value: fileStream
      };
    } catch (error) {
      if (fileStream) {
        await $Xe(fileStream);
      }
      throw this.F(error, resource, readFileOptions);
    }
  }
  F(error, resource, options) {
    const message = localize(1896, null, this.sb(resource), $Il(error).toString());
    if (error instanceof $Rl) {
      return new $Rl(message, error.stat, options);
    }
    if (error instanceof $Ql) {
      return new $Ql(message, error.fileOperationResult, error.size, error.options);
    }
    return new $Pl(message, $Ll(error), options);
  }
  G(provider, resource, token, options = /* @__PURE__ */ Object.create(null)) {
    const fileStream = provider.readFileStream(resource, options, token);
    return $4e(fileStream, {
      data: (data) => data instanceof $7e ? data : $7e.wrap(data),
      error: (error) => this.F(error, resource, options)
    }, (data) => $7e.concat(data));
  }
  H(provider, resource, token, options = /* @__PURE__ */ Object.create(null)) {
    const stream = $kf();
    $lr(provider, resource, stream, (data) => data, {
      ...options,
      bufferSize: this.a,
      errorTransformer: (error) => this.F(error, resource, options)
    }, token);
    return stream;
  }
  I(provider, resource, options) {
    const stream = $Ue((data) => $7e.concat(data));
    (async () => {
      try {
        let buffer;
        if (options?.atomic && $Cl(provider)) {
          buffer = await provider.readFile(resource, { atomic: true });
        } else {
          buffer = await provider.readFile(resource);
        }
        if (typeof options?.position === "number") {
          buffer = buffer.slice(options.position);
        }
        if (typeof options?.length === "number") {
          buffer = buffer.slice(0, options.length);
        }
        this.L(resource, buffer.byteLength, options);
        stream.end($7e.wrap(buffer));
      } catch (err) {
        stream.error(err);
        stream.end();
      }
    })();
    return stream;
  }
  async J(resource, options) {
    const stat = await this.resolve(resource, { resolveMetadata: true });
    if (stat.isDirectory) {
      throw new $Pl(localize(1897, null, this.sb(resource)), 0, options);
    }
    if (typeof options?.etag === "string" && options.etag !== $Zl && options.etag === stat.etag) {
      throw new $Rl(localize(1898, null), stat, options);
    }
    this.L(resource, stat.size, options);
    return stat;
  }
  L(resource, size, options) {
    if (typeof options?.limits?.size === "number" && size > options.limits.size) {
      throw new $Ql(localize(1899, null, this.sb(resource)), 7, size, options);
    }
  }
  //#endregion
  //#region Move/Copy/Delete/Create Folder
  async canMove(source, target, overwrite) {
    return this.M(source, target, "move", overwrite);
  }
  async canCopy(source, target, overwrite) {
    return this.M(source, target, "copy", overwrite);
  }
  async M(source, target, mode, overwrite) {
    if (source.toString() !== target.toString()) {
      try {
        const sourceProvider = mode === "move" ? this.qb(await this.n(source), source) : await this.m(source);
        const targetProvider = this.qb(await this.n(target), target);
        await this.Q(sourceProvider, source, targetProvider, target, mode, overwrite);
      } catch (error) {
        return error;
      }
    }
    return true;
  }
  async move(source, target, overwrite) {
    const sourceProvider = this.qb(await this.n(source), source);
    const targetProvider = this.qb(await this.n(target), target);
    const mode = await this.N(sourceProvider, source, targetProvider, target, "move", !!overwrite);
    const fileStat = await this.resolve(target, { resolveMetadata: true });
    this.r.fire(new $Ml(source, mode === "move" ? 2 : 3, fileStat));
    return fileStat;
  }
  async copy(source, target, overwrite) {
    const sourceProvider = await this.m(source);
    const targetProvider = this.qb(await this.n(target), target);
    const mode = await this.N(sourceProvider, source, targetProvider, target, "copy", !!overwrite);
    const fileStat = await this.resolve(target, { resolveMetadata: true });
    this.r.fire(new $Ml(source, mode === "copy" ? 3 : 2, fileStat));
    return fileStat;
  }
  async N(sourceProvider, source, targetProvider, target, mode, overwrite) {
    if (source.toString() === target.toString()) {
      return mode;
    }
    const { exists, isSameResourceWithDifferentPathCase } = await this.Q(sourceProvider, source, targetProvider, target, mode, overwrite);
    if (exists && !isSameResourceWithDifferentPathCase && overwrite) {
      await this.del(target, { recursive: true });
    }
    await this.U(targetProvider, this.R(targetProvider).providerExtUri.dirname(target));
    if (mode === "copy") {
      if (sourceProvider === targetProvider && $yl(sourceProvider)) {
        await sourceProvider.copy(source, target, { overwrite });
      } else {
        const sourceFile = await this.resolve(source);
        if (sourceFile.isDirectory) {
          await this.P(sourceProvider, sourceFile, targetProvider, target);
        } else {
          await this.O(sourceProvider, source, targetProvider, target);
        }
      }
      return mode;
    } else {
      if (sourceProvider === targetProvider) {
        await sourceProvider.rename(source, target, { overwrite });
        return mode;
      } else {
        await this.N(sourceProvider, source, targetProvider, target, "copy", overwrite);
        await this.del(source, { recursive: true });
        return "copy";
      }
    }
  }
  async O(sourceProvider, source, targetProvider, target) {
    if ($Al(sourceProvider) && $Al(targetProvider)) {
      return this.jb(sourceProvider, source, targetProvider, target);
    }
    if ($Al(sourceProvider) && $xl(targetProvider)) {
      return this.pb(sourceProvider, source, targetProvider, target);
    }
    if ($xl(sourceProvider) && $Al(targetProvider)) {
      return this.nb(sourceProvider, source, targetProvider, target);
    }
    if ($xl(sourceProvider) && $xl(targetProvider)) {
      return this.lb(sourceProvider, source, targetProvider, target);
    }
  }
  async P(sourceProvider, sourceFolder, targetProvider, targetFolder) {
    await targetProvider.mkdir(targetFolder);
    if (Array.isArray(sourceFolder.children)) {
      await Promises.settled(sourceFolder.children.map(async (sourceChild) => {
        const targetChild = this.R(targetProvider).providerExtUri.joinPath(targetFolder, sourceChild.name);
        if (sourceChild.isDirectory) {
          return this.P(sourceProvider, await this.resolve(sourceChild.resource), targetProvider, targetChild);
        } else {
          return this.O(sourceProvider, sourceChild.resource, targetProvider, targetChild);
        }
      }));
    }
  }
  async Q(sourceProvider, source, targetProvider, target, mode, overwrite) {
    let isSameResourceWithDifferentPathCase = false;
    if (sourceProvider === targetProvider) {
      const { providerExtUri, isPathCaseSensitive } = this.R(sourceProvider);
      if (!isPathCaseSensitive) {
        isSameResourceWithDifferentPathCase = providerExtUri.isEqual(source, target);
      }
      if (isSameResourceWithDifferentPathCase && mode === "copy") {
        throw new Error(localize(1900, null, this.sb(source), this.sb(target)));
      }
      if (!isSameResourceWithDifferentPathCase && providerExtUri.isEqualOrParent(target, source)) {
        throw new Error(localize(1901, null, this.sb(source), this.sb(target)));
      }
    }
    const exists = await this.exists(target);
    if (exists && !isSameResourceWithDifferentPathCase) {
      if (!overwrite) {
        throw new $Pl(
          localize(1902, null, this.sb(source), this.sb(target)),
          4
          /* FileOperationResult.FILE_MOVE_CONFLICT */
        );
      }
      if (sourceProvider === targetProvider) {
        const { providerExtUri } = this.R(sourceProvider);
        if (providerExtUri.isEqualOrParent(source, target)) {
          throw new Error(localize(1903, null, this.sb(source), this.sb(target)));
        }
      }
    }
    return { exists, isSameResourceWithDifferentPathCase };
  }
  R(provider) {
    const isPathCaseSensitive = this.S(provider);
    return {
      providerExtUri: isPathCaseSensitive ? $qh : $sh,
      isPathCaseSensitive
    };
  }
  S(provider) {
    return !!(provider.capabilities & 1024);
  }
  async createFolder(resource) {
    const provider = this.qb(await this.j(resource), resource);
    await this.U(provider, resource);
    const fileStat = await this.resolve(resource, { resolveMetadata: true });
    this.r.fire(new $Ml(resource, 0, fileStat));
    return fileStat;
  }
  async U(provider, directory) {
    const directoriesToCreate = [];
    const { providerExtUri } = this.R(provider);
    while (!providerExtUri.isEqual(directory, providerExtUri.dirname(directory))) {
      try {
        const stat = await provider.stat(directory);
        if ((stat.type & FileType.Directory) === 0) {
          throw new Error(localize(1904, null, this.sb(directory)));
        }
        break;
      } catch (error) {
        if ($Kl(error) !== FileSystemProviderErrorCode.FileNotFound) {
          throw error;
        }
        directoriesToCreate.push(providerExtUri.basename(directory));
        directory = providerExtUri.dirname(directory);
      }
    }
    for (let i = directoriesToCreate.length - 1; i >= 0; i--) {
      directory = providerExtUri.joinPath(directory, directoriesToCreate[i]);
      try {
        await provider.mkdir(directory);
      } catch (error) {
        if ($Kl(error) !== FileSystemProviderErrorCode.FileExists) {
          throw error;
        }
      }
    }
  }
  async canDelete(resource, options) {
    try {
      await this.W(resource, options);
    } catch (error) {
      return error;
    }
    return true;
  }
  async W(resource, options) {
    const provider = this.qb(await this.j(resource), resource);
    const useTrash = !!options?.useTrash;
    if (useTrash && !(provider.capabilities & 4096)) {
      throw new Error(localize(1905, null, this.sb(resource)));
    }
    const atomic = options?.atomic;
    if (atomic && !(provider.capabilities & 65536)) {
      throw new Error(localize(1906, null, this.sb(resource)));
    }
    if (useTrash && atomic) {
      throw new Error(localize(1907, null, this.sb(resource)));
    }
    let stat = void 0;
    try {
      stat = await provider.stat(resource);
    } catch (error) {
    }
    if (stat) {
      this.rb(resource, stat);
    } else {
      throw new $Pl(
        localize(1908, null, this.sb(resource)),
        1
        /* FileOperationResult.FILE_NOT_FOUND */
      );
    }
    const recursive = !!options?.recursive;
    if (!recursive) {
      const stat2 = await this.resolve(resource);
      if (stat2.isDirectory && Array.isArray(stat2.children) && stat2.children.length > 0) {
        throw new Error(localize(1909, null, this.sb(resource)));
      }
    }
    return provider;
  }
  async del(resource, options) {
    const provider = await this.W(resource, options);
    let deleteFileOptions = options;
    if ($El(provider) && !deleteFileOptions?.atomic) {
      const enforcedAtomicDelete = provider.enforceAtomicDelete?.(resource);
      if (enforcedAtomicDelete) {
        deleteFileOptions = { ...options, atomic: enforcedAtomicDelete };
      }
    }
    const useTrash = !!deleteFileOptions?.useTrash;
    const recursive = !!deleteFileOptions?.recursive;
    const atomic = deleteFileOptions?.atomic ?? false;
    await provider.delete(resource, { recursive, useTrash, atomic });
    this.r.fire(new $Ml(
      resource,
      1
      /* FileOperation.DELETE */
    ));
  }
  //#endregion
  //#region Clone File
  async cloneFile(source, target) {
    const sourceProvider = await this.j(source);
    const targetProvider = this.qb(await this.n(target), target);
    if (sourceProvider === targetProvider && this.R(sourceProvider).providerExtUri.isEqual(source, target)) {
      return;
    }
    if (sourceProvider === targetProvider && $zl(sourceProvider)) {
      return sourceProvider.cloneFile(source, target);
    }
    await this.U(targetProvider, this.R(targetProvider).providerExtUri.dirname(target));
    if (sourceProvider === targetProvider && $yl(sourceProvider)) {
      return this.cb.queueFor(source, () => sourceProvider.copy(source, target, { overwrite: true }), this.R(sourceProvider).providerExtUri);
    }
    return this.cb.queueFor(source, () => this.O(sourceProvider, source, targetProvider, target), this.R(sourceProvider).providerExtUri);
  }
  static {
    this.ab = 0;
  }
  createWatcher(resource, options) {
    return this.watch(resource, {
      ...options,
      // Explicitly set a correlation id so that file events that originate
      // from requests from extensions are exclusively routed back to the
      // extension host and not into the workbench.
      correlationId: $mr_1.ab++
    });
  }
  watch(resource, options = { recursive: false, excludes: [] }) {
    const disposables = new $9c();
    let watchDisposed = false;
    let disposeWatch = () => {
      watchDisposed = true;
    };
    disposables.add($8c(() => disposeWatch()));
    (async () => {
      try {
        const disposable = await this.bb(resource, options);
        if (watchDisposed) {
          $5c(disposable);
        } else {
          disposeWatch = () => $5c(disposable);
        }
      } catch (error) {
        this.b.error(error);
      }
    })();
    const correlationId = options.correlationId;
    if (typeof correlationId === "number") {
      const fileChangeEmitter = disposables.add(new $De());
      disposables.add(this.X.event((e) => {
        if (e.correlates(correlationId)) {
          fileChangeEmitter.fire(e);
        }
      }));
      const watcher = {
        onDidChange: fileChangeEmitter.event,
        dispose: () => disposables.dispose()
      };
      return watcher;
    }
    return disposables;
  }
  async bb(resource, options) {
    const provider = await this.j(resource);
    const watchHash = $Nj([this.R(provider).providerExtUri.getComparisonKey(resource), options]);
    let watcher = this.$.get(watchHash);
    if (!watcher) {
      watcher = {
        count: 0,
        disposable: provider.watch(resource, options)
      };
      this.$.set(watchHash, watcher);
    }
    watcher.count += 1;
    return $8c(() => {
      if (watcher) {
        watcher.count--;
        if (watcher.count === 0) {
          $5c(watcher.disposable);
          this.$.delete(watchHash);
        }
      }
    });
  }
  dispose() {
    super.dispose();
    for (const [, watcher] of this.$) {
      $5c(watcher.disposable);
    }
    this.$.clear();
  }
  async db(provider, resource, options, readableOrStreamOrBufferedStream) {
    return this.cb.queueFor(resource, async () => {
      const handle = await provider.open(resource, { create: true, unlock: options?.unlock ?? false });
      try {
        if ($Se(readableOrStreamOrBufferedStream) || $Te(readableOrStreamOrBufferedStream)) {
          await this.eb(provider, handle, readableOrStreamOrBufferedStream);
        } else {
          await this.fb(provider, handle, readableOrStreamOrBufferedStream);
        }
      } catch (error) {
        throw $Il(error);
      } finally {
        await provider.close(handle);
      }
    }, this.R(provider).providerExtUri);
  }
  async eb(provider, handle, streamOrBufferedStream) {
    let posInFile = 0;
    let stream;
    if ($Te(streamOrBufferedStream)) {
      if (streamOrBufferedStream.buffer.length > 0) {
        const chunk = $7e.concat(streamOrBufferedStream.buffer);
        await this.gb(provider, handle, chunk, chunk.byteLength, posInFile, 0);
        posInFile += chunk.byteLength;
      }
      if (streamOrBufferedStream.ended) {
        return;
      }
      stream = streamOrBufferedStream.stream;
    } else {
      stream = streamOrBufferedStream;
    }
    return new Promise((resolve2, reject) => {
      $Ye(stream, {
        onData: async (chunk) => {
          stream.pause();
          try {
            await this.gb(provider, handle, chunk, chunk.byteLength, posInFile, 0);
          } catch (error) {
            return reject(error);
          }
          posInFile += chunk.byteLength;
          setTimeout(() => stream.resume());
        },
        onError: (error) => reject(error),
        onEnd: () => resolve2()
      });
    });
  }
  async fb(provider, handle, readable) {
    let posInFile = 0;
    let chunk;
    while ((chunk = readable.read()) !== null) {
      await this.gb(provider, handle, chunk, chunk.byteLength, posInFile, 0);
      posInFile += chunk.byteLength;
    }
  }
  async gb(provider, handle, buffer, length, posInFile, posInBuffer) {
    let totalBytesWritten = 0;
    while (totalBytesWritten < length) {
      const bytesWritten = await provider.write(handle, posInFile + totalBytesWritten, buffer.buffer, posInBuffer + totalBytesWritten, length - totalBytesWritten);
      totalBytesWritten += bytesWritten;
    }
  }
  async hb(provider, resource, options, bufferOrReadableOrStreamOrBufferedStream) {
    return this.cb.queueFor(resource, () => this.ib(provider, resource, options, bufferOrReadableOrStreamOrBufferedStream), this.R(provider).providerExtUri);
  }
  async ib(provider, resource, options, bufferOrReadableOrStreamOrBufferedStream) {
    let buffer;
    if (bufferOrReadableOrStreamOrBufferedStream instanceof $7e) {
      buffer = bufferOrReadableOrStreamOrBufferedStream;
    } else if ($Se(bufferOrReadableOrStreamOrBufferedStream)) {
      buffer = await $gf(bufferOrReadableOrStreamOrBufferedStream);
    } else if ($Te(bufferOrReadableOrStreamOrBufferedStream)) {
      buffer = await $hf(bufferOrReadableOrStreamOrBufferedStream);
    } else {
      buffer = $ef(bufferOrReadableOrStreamOrBufferedStream);
    }
    await provider.writeFile(resource, buffer.buffer, { create: true, overwrite: true, unlock: options?.unlock ?? false, atomic: options?.atomic ?? false });
  }
  async jb(sourceProvider, source, targetProvider, target) {
    return this.cb.queueFor(target, () => this.kb(sourceProvider, source, targetProvider, target), this.R(targetProvider).providerExtUri);
  }
  async kb(sourceProvider, source, targetProvider, target) {
    let sourceHandle = void 0;
    let targetHandle = void 0;
    try {
      sourceHandle = await sourceProvider.open(source, { create: false });
      targetHandle = await targetProvider.open(target, { create: true, unlock: false });
      const buffer = $7e.alloc(this.a);
      let posInFile = 0;
      let posInBuffer = 0;
      let bytesRead = 0;
      do {
        bytesRead = await sourceProvider.read(sourceHandle, posInFile, buffer.buffer, posInBuffer, buffer.byteLength - posInBuffer);
        await this.gb(targetProvider, targetHandle, buffer, bytesRead, posInFile, posInBuffer);
        posInFile += bytesRead;
        posInBuffer += bytesRead;
        if (posInBuffer === buffer.byteLength) {
          posInBuffer = 0;
        }
      } while (bytesRead > 0);
    } catch (error) {
      throw $Il(error);
    } finally {
      await Promises.settled([
        typeof sourceHandle === "number" ? sourceProvider.close(sourceHandle) : Promise.resolve(),
        typeof targetHandle === "number" ? targetProvider.close(targetHandle) : Promise.resolve()
      ]);
    }
  }
  async lb(sourceProvider, source, targetProvider, target) {
    return this.cb.queueFor(target, () => this.mb(sourceProvider, source, targetProvider, target), this.R(targetProvider).providerExtUri);
  }
  async mb(sourceProvider, source, targetProvider, target) {
    return targetProvider.writeFile(target, await sourceProvider.readFile(source), { create: true, overwrite: true, unlock: false, atomic: false });
  }
  async nb(sourceProvider, source, targetProvider, target) {
    return this.cb.queueFor(target, () => this.ob(sourceProvider, source, targetProvider, target), this.R(targetProvider).providerExtUri);
  }
  async ob(sourceProvider, source, targetProvider, target) {
    const targetHandle = await targetProvider.open(target, { create: true, unlock: false });
    try {
      const buffer = await sourceProvider.readFile(source);
      await this.gb(targetProvider, targetHandle, $7e.wrap(buffer), buffer.byteLength, 0, 0);
    } catch (error) {
      throw $Il(error);
    } finally {
      await targetProvider.close(targetHandle);
    }
  }
  async pb(sourceProvider, source, targetProvider, target) {
    const buffer = await $gf(this.H(sourceProvider, source, CancellationToken.None));
    await this.hb(targetProvider, target, void 0, buffer);
  }
  qb(provider, resource) {
    if (provider.capabilities & 2048) {
      throw new $Pl(
        localize(1910, null, this.sb(resource)),
        6
        /* FileOperationResult.FILE_PERMISSION_DENIED */
      );
    }
    return provider;
  }
  rb(resource, stat) {
    if ((stat.permissions ?? 0) & FilePermission.Readonly) {
      throw new $Pl(
        localize(1911, null, this.sb(resource)),
        6
        /* FileOperationResult.FILE_PERMISSION_DENIED */
      );
    }
  }
  sb(resource) {
    if (resource.scheme === Schemas.file) {
      return resource.fsPath;
    }
    return resource.toString(true);
  }
};
$mr = $mr_1 = __decorate([
  __param(0, $uk)
], $mr);

// out-build/vs/platform/instantiation/common/graph.js
var $Qr = class {
  constructor(key, data) {
    this.key = key;
    this.data = data;
    this.incoming = /* @__PURE__ */ new Map();
    this.outgoing = /* @__PURE__ */ new Map();
  }
};
var $Rr = class {
  constructor(b) {
    this.b = b;
    this.a = /* @__PURE__ */ new Map();
  }
  roots() {
    const ret = [];
    for (const node of this.a.values()) {
      if (node.outgoing.size === 0) {
        ret.push(node);
      }
    }
    return ret;
  }
  insertEdge(from, to) {
    const fromNode = this.lookupOrInsertNode(from);
    const toNode = this.lookupOrInsertNode(to);
    fromNode.outgoing.set(toNode.key, toNode);
    toNode.incoming.set(fromNode.key, fromNode);
  }
  removeNode(data) {
    const key = this.b(data);
    this.a.delete(key);
    for (const node of this.a.values()) {
      node.outgoing.delete(key);
      node.incoming.delete(key);
    }
  }
  lookupOrInsertNode(data) {
    const key = this.b(data);
    let node = this.a.get(key);
    if (!node) {
      node = new $Qr(key, data);
      this.a.set(key, node);
    }
    return node;
  }
  lookup(data) {
    return this.a.get(this.b(data));
  }
  isEmpty() {
    return this.a.size === 0;
  }
  toString() {
    const data = [];
    for (const [key, value] of this.a) {
      data.push(`${key}
	(-> incoming)[${[...value.incoming.keys()].join(", ")}]
	(outgoing ->)[${[...value.outgoing.keys()].join(",")}]
`);
    }
    return data.join("\n");
  }
  /**
   * This is brute force and slow and **only** be used
   * to trouble shoot.
   */
  findCycleSlow() {
    for (const [id2, node] of this.a) {
      const seen = /* @__PURE__ */ new Set([id2]);
      const res = this.c(node, seen);
      if (res) {
        return res;
      }
    }
    return void 0;
  }
  c(node, seen) {
    for (const [id2, outgoing] of node.outgoing) {
      if (seen.has(id2)) {
        return [...seen, id2].join(" -> ");
      }
      seen.add(id2);
      const value = this.c(outgoing, seen);
      if (value) {
        return value;
      }
      seen.delete(id2);
    }
    return void 0;
  }
};

// out-build/vs/platform/instantiation/common/instantiationService.js
var _enableAllTracing = false;
var CyclicDependencyError = class extends Error {
  constructor(graph) {
    super("cyclic dependency between services");
    this.message = graph.findCycleSlow() ?? `UNABLE to detect cycle, dumping graph: 
${graph.toString()}`;
  }
};
var $Sr = class _$Sr {
  constructor(i = new $Xi(), j = false, k, l = _enableAllTracing) {
    this.i = i;
    this.j = j;
    this.k = k;
    this.l = l;
    this.f = false;
    this.g = /* @__PURE__ */ new Set();
    this.h = /* @__PURE__ */ new Set();
    this.t = /* @__PURE__ */ new Set();
    this.i.set($Yi, this);
    this._globalGraph = l ? k?._globalGraph ?? new $Rr((e) => e) : void 0;
  }
  dispose() {
    if (!this.f) {
      this.f = true;
      $5c(this.h);
      this.h.clear();
      for (const candidate of this.g) {
        if ($4c(candidate)) {
          candidate.dispose();
        }
      }
      this.g.clear();
    }
  }
  m() {
    if (this.f) {
      throw new Error("InstantiationService has been disposed");
    }
  }
  createChild(services, store) {
    this.m();
    const that = this;
    const result = new class extends _$Sr {
      dispose() {
        that.h.delete(result);
        super.dispose();
      }
    }(services, this.j, this, this.l);
    this.h.add(result);
    store?.add(result);
    return result;
  }
  invokeFunction(fn, ...args) {
    this.m();
    const _trace = $Tr.traceInvocation(this.l, fn);
    let _done = false;
    try {
      const accessor = {
        get: (id2) => {
          if (_done) {
            throw $ib("service accessor is only valid during the invocation of its target method");
          }
          const result = this.s(id2, _trace);
          if (!result) {
            throw new Error(`[invokeFunction] unknown service '${id2}'`);
          }
          return result;
        }
      };
      return fn(accessor, ...args);
    } finally {
      _done = true;
      _trace.stop();
    }
  }
  createInstance(ctorOrDescriptor, ...rest) {
    this.m();
    let _trace;
    let result;
    if (ctorOrDescriptor instanceof $Wi) {
      _trace = $Tr.traceCreation(this.l, ctorOrDescriptor.ctor);
      result = this.o(ctorOrDescriptor.ctor, ctorOrDescriptor.staticArguments.concat(rest), _trace);
    } else {
      _trace = $Tr.traceCreation(this.l, ctorOrDescriptor);
      result = this.o(ctorOrDescriptor, rest, _trace);
    }
    _trace.stop();
    return result;
  }
  o(ctor, args = [], _trace) {
    const serviceDependencies = _util.getServiceDependencies(ctor).sort((a, b) => a.index - b.index);
    const serviceArgs = [];
    for (const dependency of serviceDependencies) {
      const service = this.s(dependency.id, _trace);
      if (!service) {
        this.y(`[createInstance] ${ctor.name} depends on UNKNOWN service ${dependency.id}.`, false);
      }
      serviceArgs.push(service);
    }
    const firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : args.length;
    if (args.length !== firstServiceArgPos) {
      console.trace(`[createInstance] First service dependency of ${ctor.name} at position ${firstServiceArgPos + 1} conflicts with ${args.length} static arguments`);
      const delta = firstServiceArgPos - args.length;
      if (delta > 0) {
        args = args.concat(new Array(delta));
      } else {
        args = args.slice(0, firstServiceArgPos);
      }
    }
    return Reflect.construct(ctor, args.concat(serviceArgs));
  }
  q(id2, instance) {
    if (this.i.get(id2) instanceof $Wi) {
      this.i.set(id2, instance);
    } else if (this.k) {
      this.k.q(id2, instance);
    } else {
      throw new Error("illegalState - setting UNKNOWN service instance");
    }
  }
  r(id2) {
    const instanceOrDesc = this.i.get(id2);
    if (!instanceOrDesc && this.k) {
      return this.k.r(id2);
    } else {
      return instanceOrDesc;
    }
  }
  s(id2, _trace) {
    if (this._globalGraph && this.c) {
      this._globalGraph.insertEdge(this.c, String(id2));
    }
    const thing = this.r(id2);
    if (thing instanceof $Wi) {
      return this.u(id2, thing, _trace.branch(id2, true));
    } else {
      _trace.branch(id2, false);
      return thing;
    }
  }
  u(id2, desc, _trace) {
    if (this.t.has(id2)) {
      throw new Error(`illegal state - RECURSIVELY instantiating service '${id2}'`);
    }
    this.t.add(id2);
    try {
      return this.v(id2, desc, _trace);
    } finally {
      this.t.delete(id2);
    }
  }
  v(id2, desc, _trace) {
    const graph = new $Rr((data) => data.id.toString());
    let cycleCount = 0;
    const stack = [{ id: id2, desc, _trace }];
    const seen = /* @__PURE__ */ new Set();
    while (stack.length) {
      const item = stack.pop();
      if (seen.has(String(item.id))) {
        continue;
      }
      seen.add(String(item.id));
      graph.lookupOrInsertNode(item);
      if (cycleCount++ > 1e3) {
        throw new CyclicDependencyError(graph);
      }
      for (const dependency of _util.getServiceDependencies(item.desc.ctor)) {
        const instanceOrDesc = this.r(dependency.id);
        if (!instanceOrDesc) {
          this.y(`[createInstance] ${id2} depends on ${dependency.id} which is NOT registered.`, true);
        }
        this._globalGraph?.insertEdge(String(item.id), String(dependency.id));
        if (instanceOrDesc instanceof $Wi) {
          const d = { id: dependency.id, desc: instanceOrDesc, _trace: item._trace.branch(dependency.id, true) };
          graph.insertEdge(item, d);
          stack.push(d);
        }
      }
    }
    while (true) {
      const roots = graph.roots();
      if (roots.length === 0) {
        if (!graph.isEmpty()) {
          throw new CyclicDependencyError(graph);
        }
        break;
      }
      for (const { data } of roots) {
        const instanceOrDesc = this.r(data.id);
        if (instanceOrDesc instanceof $Wi) {
          const instance = this.w(data.id, data.desc.ctor, data.desc.staticArguments, data.desc.supportsDelayedInstantiation, data._trace);
          this.q(data.id, instance);
        }
        graph.removeNode(data);
      }
    }
    return this.r(id2);
  }
  w(id2, ctor, args = [], supportsDelayedInstantiation, _trace) {
    if (this.i.get(id2) instanceof $Wi) {
      return this.x(id2, ctor, args, supportsDelayedInstantiation, _trace, this.g);
    } else if (this.k) {
      return this.k.w(id2, ctor, args, supportsDelayedInstantiation, _trace);
    } else {
      throw new Error(`illegalState - creating UNKNOWN service instance ${ctor.name}`);
    }
  }
  x(id2, ctor, args = [], supportsDelayedInstantiation, _trace, disposeBucket) {
    if (!supportsDelayedInstantiation) {
      const result = this.o(ctor, args, _trace);
      disposeBucket.add(result);
      return result;
    } else {
      const child = new _$Sr(void 0, this.j, this, this.l);
      child.c = String(id2);
      const earlyListeners = /* @__PURE__ */ new Map();
      const idle = new $gi(() => {
        const result = child.o(ctor, args, _trace);
        for (const [key, values] of earlyListeners) {
          const candidate = result[key];
          if (typeof candidate === "function") {
            for (const value of values) {
              value.disposable = candidate.apply(result, value.listener);
            }
          }
        }
        earlyListeners.clear();
        disposeBucket.add(result);
        return result;
      });
      return new Proxy(/* @__PURE__ */ Object.create(null), {
        get(target, key) {
          if (!idle.isInitialized) {
            if (typeof key === "string" && (key.startsWith("onDid") || key.startsWith("onWill"))) {
              let list = earlyListeners.get(key);
              if (!list) {
                list = new $hd();
                earlyListeners.set(key, list);
              }
              const event = (callback, thisArg, disposables) => {
                if (idle.isInitialized) {
                  return idle.value[key](callback, thisArg, disposables);
                } else {
                  const entry = { listener: [callback, thisArg, disposables], disposable: void 0 };
                  const rm = list.push(entry);
                  const result = $8c(() => {
                    rm();
                    entry.disposable?.dispose();
                  });
                  return result;
                }
              };
              return event;
            }
          }
          if (key in target) {
            return target[key];
          }
          const obj = idle.value;
          let prop = obj[key];
          if (typeof prop !== "function") {
            return prop;
          }
          prop = prop.bind(obj);
          target[key] = prop;
          return prop;
        },
        set(_target, p, value) {
          idle.value[p] = value;
          return true;
        },
        getPrototypeOf(_target) {
          return ctor.prototype;
        }
      });
    }
  }
  y(msg, printWarning) {
    if (printWarning) {
      console.warn(msg);
    }
    if (this.j) {
      throw new Error(msg);
    }
  }
};
var TraceType;
(function(TraceType2) {
  TraceType2[TraceType2["None"] = 0] = "None";
  TraceType2[TraceType2["Creation"] = 1] = "Creation";
  TraceType2[TraceType2["Invocation"] = 2] = "Invocation";
  TraceType2[TraceType2["Branch"] = 3] = "Branch";
})(TraceType || (TraceType = {}));
var $Tr = class _$Tr {
  static {
    this.all = /* @__PURE__ */ new Set();
  }
  static {
    this.c = new class extends _$Tr {
      constructor() {
        super(0, null);
      }
      stop() {
      }
      branch() {
        return this;
      }
    }();
  }
  static traceInvocation(_enableTracing, ctor) {
    return !_enableTracing ? _$Tr.c : new _$Tr(2, ctor.name || new Error().stack.split("\n").slice(3, 4).join("\n"));
  }
  static traceCreation(_enableTracing, ctor) {
    return !_enableTracing ? _$Tr.c : new _$Tr(1, ctor.name);
  }
  static {
    this.f = 0;
  }
  constructor(type4, name) {
    this.type = type4;
    this.name = name;
    this.g = Date.now();
    this.h = [];
  }
  branch(id2, first) {
    const child = new _$Tr(3, id2.toString());
    this.h.push([id2, first, child]);
    return child;
  }
  stop() {
    const dur = Date.now() - this.g;
    _$Tr.f += dur;
    let causedCreation = false;
    function printChild(n, trace) {
      const res = [];
      const prefix = new Array(n + 1).join("	");
      for (const [id2, first, child] of trace.h) {
        if (first && child) {
          causedCreation = true;
          res.push(`${prefix}CREATES -> ${id2}`);
          const nested = printChild(n + 1, child);
          if (nested) {
            res.push(nested);
          }
        } else {
          res.push(`${prefix}uses -> ${id2}`);
        }
      }
      return res.join("\n");
    }
    const lines = [
      `${this.type === 1 ? "CREATE" : "CALL"} ${this.name}`,
      `${printChild(1, this)}`,
      `DONE, took ${dur.toFixed(2)}ms (grand total ${_$Tr.f.toFixed(2)}ms)`
    ];
    if (dur > 2 || causedCreation) {
      _$Tr.all.add(lines.join("\n"));
    }
  }
};

// out-build/vs/platform/log/common/bufferLog.js
var $bhc = class extends $Ak {
  constructor(logLevel = $xk) {
    super();
    this.m = [];
    this.n = void 0;
    this.r = this.B(new $$c());
    this.setLevel(logLevel);
  }
  set logger(logger) {
    this.n = logger;
    this.setLevel(logger.getLevel());
    this.r.value = logger.onDidChangeLogLevel(this.setLevel, this);
    for (const { level, message } of this.m) {
      log(logger, level, message);
    }
    this.m = [];
  }
  g(level, message) {
    if (this.n) {
      log(this.n, level, message);
    } else if (this.getLevel() <= level) {
      this.m.push({ level, message });
    }
  }
  dispose() {
    this.n?.dispose();
    super.dispose();
  }
  flush() {
    this.n?.flush();
  }
};

// out-build/vs/platform/protocol/electron-main/protocolMainService.js
import { session as session2 } from "electron";
var $Qlc = class $Qlc2 extends $0c {
  constructor(c, userDataProfilesService, f) {
    super();
    this.c = c;
    this.f = f;
    this.a = $6i.forPaths(!$n);
    this.b = /* @__PURE__ */ new Set([".svg", ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp", ".mp4"]);
    this.addValidFileRoot(c.appRoot);
    this.addValidFileRoot(c.extensionsPath);
    this.addValidFileRoot(userDataProfilesService.defaultProfile.globalStorageHome.with({ scheme: Schemas.file }).fsPath);
    this.addValidFileRoot(c.workspaceStorageHome.with({ scheme: Schemas.file }).fsPath);
    this.g();
  }
  g() {
    const { defaultSession } = session2;
    defaultSession.protocol.registerFileProtocol(Schemas.vscodeFileResource, (request, callback) => this.j(request, callback));
    defaultSession.protocol.interceptFileProtocol(Schemas.file, (request, callback) => this.h(request, callback));
    this.B($8c(() => {
      defaultSession.protocol.unregisterProtocol(Schemas.vscodeFileResource);
      defaultSession.protocol.uninterceptProtocol(Schemas.file);
    }));
  }
  addValidFileRoot(root) {
    const normalizedRoot = $tc(root);
    if (!this.a.get(normalizedRoot)) {
      this.a.set(normalizedRoot, true);
      return $8c(() => this.a.delete(normalizedRoot));
    }
    return $0c.None;
  }
  //#region file://
  h(request, callback) {
    const uri = URI.parse(request.url);
    this.f.error(`Refused to load resource ${uri.fsPath} from ${Schemas.file}: protocol (original URL: ${request.url})`);
    return callback({
      error: -3
      /* ABORTED */
    });
  }
  //#endregion
  //#region vscode-file://
  j(request, callback) {
    const path3 = this.m(request);
    let headers;
    if (this.c.crossOriginIsolated) {
      const pathBasename = $zc(path3);
      if (pathBasename === "workbench.html" || pathBasename === "workbench-dev.html" || pathBasename === "workbench.esm.html" || pathBasename === "workbench-dev.esm.html") {
        headers = COI.CoopAndCoep;
      } else {
        headers = COI.getHeadersFromQuery(request.url);
      }
    }
    if (this.a.findSubstr(path3)) {
      return callback({ path: path3, headers });
    }
    if (this.b.has($Ac(path3).toLowerCase())) {
      return callback({ path: path3 });
    }
    this.f.error(`${Schemas.vscodeFileResource}: Refused to load resource ${path3} from ${Schemas.vscodeFileResource}: protocol (original URL: ${request.url})`);
    return callback({
      error: -3
      /* ABORTED */
    });
  }
  m(request) {
    const requestUri = URI.parse(request.url);
    const unnormalizedFileUri = $hh.uriToFileUri(requestUri);
    return $tc(unnormalizedFileUri.fsPath);
  }
  //#endregion
  //#region IPC Object URLs
  createIPCObjectUrl() {
    let obj = void 0;
    const resource = URI.from({
      scheme: "vscode",
      // used for all our IPC communication (vscode:<channel>)
      path: $jh()
    });
    const channel = resource.toString();
    const handler = async () => obj;
    $ZY.handle(channel, handler);
    this.f.trace(`IPC Object URL: Registered new channel ${channel}.`);
    return {
      resource,
      update: (updatedObj) => obj = updatedObj,
      dispose: () => {
        this.f.trace(`IPC Object URL: Removed channel ${channel}.`);
        $ZY.removeHandler(channel);
      }
    };
  }
};
$Qlc = __decorate([
  __param(0, $8i),
  __param(1, $7l),
  __param(2, $uk)
], $Qlc);

// out-build/vs/platform/tunnel/common/tunnel.js
var $ax = $Zi("tunnelService");
var $bx = $Zi("sharedTunnelsService");
var TunnelProtocol;
(function(TunnelProtocol2) {
  TunnelProtocol2["Http"] = "http";
  TunnelProtocol2["Https"] = "https";
})(TunnelProtocol || (TunnelProtocol = {}));
var TunnelPrivacyId;
(function(TunnelPrivacyId2) {
  TunnelPrivacyId2["ConstantPrivate"] = "constantPrivate";
  TunnelPrivacyId2["Private"] = "private";
  TunnelPrivacyId2["Public"] = "public";
})(TunnelPrivacyId || (TunnelPrivacyId = {}));
function $cx(addressOrTunnelProvider) {
  return !!addressOrTunnelProvider.forwardPort;
}
var ProvidedOnAutoForward;
(function(ProvidedOnAutoForward2) {
  ProvidedOnAutoForward2[ProvidedOnAutoForward2["Notify"] = 1] = "Notify";
  ProvidedOnAutoForward2[ProvidedOnAutoForward2["OpenBrowser"] = 2] = "OpenBrowser";
  ProvidedOnAutoForward2[ProvidedOnAutoForward2["OpenPreview"] = 3] = "OpenPreview";
  ProvidedOnAutoForward2[ProvidedOnAutoForward2["Silent"] = 4] = "Silent";
  ProvidedOnAutoForward2[ProvidedOnAutoForward2["Ignore"] = 5] = "Ignore";
  ProvidedOnAutoForward2[ProvidedOnAutoForward2["OpenBrowserOnce"] = 6] = "OpenBrowserOnce";
})(ProvidedOnAutoForward || (ProvidedOnAutoForward = {}));
function $dx(uri) {
  if (uri.scheme !== "http" && uri.scheme !== "https") {
    return void 0;
  }
  const localhostMatch = /^(localhost|127\.0\.0\.1|0\.0\.0\.0):(\d+)$/.exec(uri.authority);
  if (!localhostMatch) {
    return void 0;
  }
  return {
    address: localhostMatch[1],
    port: +localhostMatch[2]
  };
}
var $fx = ["localhost", "127.0.0.1", "0:0:0:0:0:0:0:1", "::1"];
function $gx(host) {
  return $fx.indexOf(host) >= 0;
}
var $hx = ["0.0.0.0", "0:0:0:0:0:0:0:0", "::"];
function $ix(host) {
  return $hx.indexOf(host) >= 0;
}
function $jx(port, host, os6, osRelease) {
  if (os6 === 1) {
    return false;
  }
  if (os6 === 2) {
    if ($ix(host)) {
      const osVersion = /(\d+)\.(\d+)\.(\d+)/g.exec(osRelease);
      if (osVersion?.length === 4) {
        const major2 = parseInt(osVersion[1]);
        if (major2 >= 18) {
          return false;
        }
      }
    }
  }
  return port < 1024;
}
var $lx = class $lx2 extends $0c {
  constructor(r, s) {
    super();
    this.r = r;
    this.s = s;
    this.a = new $De();
    this.onTunnelOpened = this.a.event;
    this.b = new $De();
    this.onTunnelClosed = this.b.event;
    this.c = new $De();
    this.onAddedTunnelProvider = this.c.event;
    this.f = /* @__PURE__ */ new Map();
    this.h = false;
    this.j = true;
    this.m = [];
    this.n = /* @__PURE__ */ new Set();
  }
  get hasTunnelProvider() {
    return !!this.g;
  }
  get t() {
    const settingValue = this.s.getValue("remote.localPortHost");
    return !settingValue || settingValue === "localhost" ? "127.0.0.1" : "0.0.0.0";
  }
  setTunnelProvider(provider) {
    this.g = provider;
    if (!provider) {
      this.h = false;
      this.m = [];
      this.c.fire();
      return {
        dispose: () => {
        }
      };
    }
    this.c.fire();
    return {
      dispose: () => {
        this.g = void 0;
        this.h = false;
        this.m = [];
      }
    };
  }
  setTunnelFeatures(features) {
    this.h = features.elevation;
    this.m = features.privacyOptions;
    this.j = features.protocol;
  }
  get canChangeProtocol() {
    return this.j;
  }
  get canElevate() {
    return this.h;
  }
  get canChangePrivacy() {
    return this.m.length > 0;
  }
  get privacyOptions() {
    return this.m;
  }
  get tunnels() {
    return this.u();
  }
  async u() {
    const tunnels = [];
    const tunnelArray = Array.from(this.f.values());
    for (const portMap of tunnelArray) {
      const portArray = Array.from(portMap.values());
      for (const x of portArray) {
        const tunnelValue = await x.value;
        if (tunnelValue && typeof tunnelValue !== "string") {
          tunnels.push(tunnelValue);
        }
      }
    }
    return tunnels;
  }
  async dispose() {
    super.dispose();
    for (const portMap of this.f.values()) {
      for (const { value } of portMap.values()) {
        await value.then((tunnel) => typeof tunnel !== "string" ? tunnel?.dispose() : void 0);
      }
      portMap.clear();
    }
    this.f.clear();
  }
  setEnvironmentTunnel(remoteHost, remotePort, localAddress, privacy, protocol3) {
    this.z(remoteHost, remotePort, Promise.resolve({
      tunnelRemoteHost: remoteHost,
      tunnelRemotePort: remotePort,
      localAddress,
      privacy,
      protocol: protocol3,
      dispose: () => Promise.resolve()
    }));
  }
  async getExistingTunnel(remoteHost, remotePort) {
    if ($ix(remoteHost) || $gx(remoteHost)) {
      remoteHost = $fx[0];
    }
    const existing = this.D(remoteHost, remotePort);
    if (existing) {
      ++existing.refcount;
      return existing.value;
    }
    return void 0;
  }
  openTunnel(addressProvider, remoteHost, remotePort, localHost, localPort, elevateIfNeeded = false, privacy, protocol3) {
    this.r.trace(`ForwardedPorts: (TunnelService) openTunnel request for ${remoteHost}:${remotePort} on local port ${localPort}.`);
    const addressOrTunnelProvider = this.g ?? addressProvider;
    if (!addressOrTunnelProvider) {
      return void 0;
    }
    if (!remoteHost) {
      remoteHost = "localhost";
    }
    if (!localHost) {
      localHost = this.t;
    }
    if (this.g && this.n.has(remotePort)) {
      this.r.debug(`ForwardedPorts: (TunnelService) Another call to create a tunnel with the same address has occurred before the last one completed. This call will be ignored.`);
      return;
    }
    const resolvedTunnel = this.F(addressOrTunnelProvider, remoteHost, remotePort, localHost, localPort, elevateIfNeeded, privacy, protocol3);
    if (!resolvedTunnel) {
      this.r.trace(`ForwardedPorts: (TunnelService) Tunnel was not created.`);
      return resolvedTunnel;
    }
    return resolvedTunnel.then((tunnel) => {
      if (!tunnel) {
        this.r.trace("ForwardedPorts: (TunnelService) New tunnel is undefined.");
        this.C(remoteHost, remotePort);
        return void 0;
      } else if (typeof tunnel === "string") {
        this.r.trace("ForwardedPorts: (TunnelService) The tunnel provider returned an error when creating the tunnel.");
        this.C(remoteHost, remotePort);
        return tunnel;
      }
      this.r.trace("ForwardedPorts: (TunnelService) New tunnel established.");
      const newTunnel = this.w(tunnel);
      if (tunnel.tunnelRemoteHost !== remoteHost || tunnel.tunnelRemotePort !== remotePort) {
        this.r.warn("ForwardedPorts: (TunnelService) Created tunnel does not match requirements of requested tunnel. Host or port mismatch.");
      }
      if (privacy && tunnel.privacy !== privacy) {
        this.r.warn("ForwardedPorts: (TunnelService) Created tunnel does not match requirements of requested tunnel. Privacy mismatch.");
      }
      this.a.fire(newTunnel);
      return newTunnel;
    });
  }
  w(tunnel) {
    return {
      tunnelRemotePort: tunnel.tunnelRemotePort,
      tunnelRemoteHost: tunnel.tunnelRemoteHost,
      tunnelLocalPort: tunnel.tunnelLocalPort,
      localAddress: tunnel.localAddress,
      privacy: tunnel.privacy,
      protocol: tunnel.protocol,
      dispose: async () => {
        this.r.trace(`ForwardedPorts: (TunnelService) dispose request for ${tunnel.tunnelRemoteHost}:${tunnel.tunnelRemotePort} `);
        const existingHost = this.f.get(tunnel.tunnelRemoteHost);
        if (existingHost) {
          const existing = existingHost.get(tunnel.tunnelRemotePort);
          if (existing) {
            existing.refcount--;
            await this.y(tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort, existing);
          }
        }
      }
    };
  }
  async y(remoteHost, remotePort, tunnel) {
    if (tunnel.refcount <= 0) {
      this.r.trace(`ForwardedPorts: (TunnelService) Tunnel is being disposed ${remoteHost}:${remotePort}.`);
      const disposePromise = tunnel.value.then(async (tunnel2) => {
        if (tunnel2 && typeof tunnel2 !== "string") {
          await tunnel2.dispose(true);
          this.b.fire({ host: tunnel2.tunnelRemoteHost, port: tunnel2.tunnelRemotePort });
        }
      });
      if (this.f.has(remoteHost)) {
        this.f.get(remoteHost).delete(remotePort);
      }
      return disposePromise;
    }
  }
  async closeTunnel(remoteHost, remotePort) {
    this.r.trace(`ForwardedPorts: (TunnelService) close request for ${remoteHost}:${remotePort} `);
    const portMap = this.f.get(remoteHost);
    if (portMap && portMap.has(remotePort)) {
      const value = portMap.get(remotePort);
      value.refcount = 0;
      await this.y(remoteHost, remotePort, value);
    }
  }
  z(remoteHost, remotePort, tunnel) {
    if (!this.f.has(remoteHost)) {
      this.f.set(remoteHost, /* @__PURE__ */ new Map());
    }
    this.f.get(remoteHost).set(remotePort, { refcount: 1, value: tunnel });
  }
  async C(remoteHost, remotePort) {
    const hostMap = this.f.get(remoteHost);
    if (hostMap) {
      const tunnel = hostMap.get(remotePort);
      const tunnelResult = tunnel ? await tunnel.value : void 0;
      if (!tunnelResult || typeof tunnelResult === "string") {
        hostMap.delete(remotePort);
      }
      if (hostMap.size === 0) {
        this.f.delete(remoteHost);
      }
    }
  }
  D(remoteHost, remotePort) {
    const hosts = [remoteHost];
    if ($gx(remoteHost)) {
      hosts.push(...$fx);
      hosts.push(...$hx);
    } else if ($ix(remoteHost)) {
      hosts.push(...$hx);
    }
    const existingPortMaps = hosts.map((host) => this.f.get(host));
    for (const map of existingPortMaps) {
      const existingTunnel = map?.get(remotePort);
      if (existingTunnel) {
        return existingTunnel;
      }
    }
    return void 0;
  }
  canTunnel(uri) {
    return !!$dx(uri);
  }
  G(tunnelProvider, remoteHost, remotePort, localPort, elevateIfNeeded, privacy, protocol3) {
    this.r.trace(`ForwardedPorts: (TunnelService) Creating tunnel with provider ${remoteHost}:${remotePort} on local port ${localPort}.`);
    const key = remotePort;
    this.n.add(key);
    const preferredLocalPort = localPort === void 0 ? remotePort : localPort;
    const creationInfo = { elevationRequired: elevateIfNeeded ? this.isPortPrivileged(preferredLocalPort) : false };
    const tunnelOptions = { remoteAddress: { host: remoteHost, port: remotePort }, localAddressPort: localPort, privacy, public: privacy ? privacy !== TunnelPrivacyId.Private : void 0, protocol: protocol3 };
    const tunnel = tunnelProvider.forwardPort(tunnelOptions, creationInfo);
    if (tunnel) {
      this.z(remoteHost, remotePort, tunnel);
      tunnel.finally(() => {
        this.r.trace("ForwardedPorts: (TunnelService) Tunnel created by provider.");
        this.n.delete(key);
      });
    } else {
      this.n.delete(key);
    }
    return tunnel;
  }
};
$lx = __decorate([
  __param(0, $uk),
  __param(1, $tj)
], $lx);

// out-build/vs/platform/tunnel/node/tunnelService.js
import * as net2 from "net";
import * as os5 from "os";

// out-build/vs/platform/remote/common/remoteAuthorityResolver.js
var $_l = $Zi("remoteAuthorityResolverService");
var RemoteConnectionType;
(function(RemoteConnectionType2) {
  RemoteConnectionType2[RemoteConnectionType2["WebSocket"] = 0] = "WebSocket";
  RemoteConnectionType2[RemoteConnectionType2["Managed"] = 1] = "Managed";
})(RemoteConnectionType || (RemoteConnectionType = {}));
var RemoteAuthorityResolverErrorCode;
(function(RemoteAuthorityResolverErrorCode2) {
  RemoteAuthorityResolverErrorCode2["Unknown"] = "Unknown";
  RemoteAuthorityResolverErrorCode2["NotAvailable"] = "NotAvailable";
  RemoteAuthorityResolverErrorCode2["TemporarilyNotAvailable"] = "TemporarilyNotAvailable";
  RemoteAuthorityResolverErrorCode2["NoResolverFound"] = "NoResolverFound";
  RemoteAuthorityResolverErrorCode2["InvalidAuthority"] = "InvalidAuthority";
})(RemoteAuthorityResolverErrorCode || (RemoteAuthorityResolverErrorCode = {}));
var $cm = class _$cm extends $ob {
  static isNotAvailable(err) {
    return err instanceof _$cm && err._code === RemoteAuthorityResolverErrorCode.NotAvailable;
  }
  static isTemporarilyNotAvailable(err) {
    return err instanceof _$cm && err._code === RemoteAuthorityResolverErrorCode.TemporarilyNotAvailable;
  }
  static isNoResolverFound(err) {
    return err instanceof _$cm && err._code === RemoteAuthorityResolverErrorCode.NoResolverFound;
  }
  static isInvalidAuthority(err) {
    return err instanceof _$cm && err._code === RemoteAuthorityResolverErrorCode.InvalidAuthority;
  }
  static isHandled(err) {
    return err instanceof _$cm && err.isHandled;
  }
  constructor(message, code2 = RemoteAuthorityResolverErrorCode.Unknown, detail) {
    super(message);
    this._message = message;
    this._code = code2;
    this._detail = detail;
    this.isHandled = code2 === RemoteAuthorityResolverErrorCode.NotAvailable && detail === true;
    Object.setPrototypeOf(this, _$cm.prototype);
  }
};

// out-build/vs/platform/remote/common/remoteAgentConnection.js
var RECONNECT_TIMEOUT = 30 * 1e3;
var ConnectionType;
(function(ConnectionType2) {
  ConnectionType2[ConnectionType2["Management"] = 1] = "Management";
  ConnectionType2[ConnectionType2["ExtensionHost"] = 2] = "ExtensionHost";
  ConnectionType2[ConnectionType2["Tunnel"] = 3] = "Tunnel";
})(ConnectionType || (ConnectionType = {}));
function connectionTypeToString(connectionType) {
  switch (connectionType) {
    case 1:
      return "Management";
    case 2:
      return "ExtensionHost";
    case 3:
      return "Tunnel";
  }
}
function createTimeoutCancellation(millis) {
  const source = new $Pe();
  setTimeout(() => source.cancel(), millis);
  return source.token;
}
function combineTimeoutCancellation(a, b) {
  if (a.isCancellationRequested || b.isCancellationRequested) {
    return CancellationToken.Cancelled;
  }
  const source = new $Pe();
  a.onCancellationRequested(() => source.cancel());
  b.onCancellationRequested(() => source.cancel());
  return source.token;
}
var PromiseWithTimeout = class {
  get didTimeout() {
    return this.c === "timedout";
  }
  constructor(timeoutCancellationToken) {
    this.c = "pending";
    this.d = new $9c();
    ({ promise: this.promise, resolve: this.f, reject: this.g } = $Sh());
    if (timeoutCancellationToken.isCancellationRequested) {
      this.h();
    } else {
      this.d.add(timeoutCancellationToken.onCancellationRequested(() => this.h()));
    }
  }
  registerDisposable(disposable) {
    if (this.c === "pending") {
      this.d.add(disposable);
    } else {
      disposable.dispose();
    }
  }
  h() {
    if (this.c !== "pending") {
      return;
    }
    this.d.dispose();
    this.c = "timedout";
    this.g(this.i());
  }
  i() {
    const err = new Error("Time limit reached");
    err.code = "ETIMEDOUT";
    err.syscall = "connect";
    return err;
  }
  resolve(value) {
    if (this.c !== "pending") {
      return;
    }
    this.d.dispose();
    this.c = "resolved";
    this.f(value);
  }
  reject(err) {
    if (this.c !== "pending") {
      return;
    }
    this.d.dispose();
    this.c = "rejected";
    this.g(err);
  }
};
function readOneControlMessage(protocol3, timeoutCancellationToken) {
  const result = new PromiseWithTimeout(timeoutCancellationToken);
  result.registerDisposable(protocol3.onControlMessage((raw) => {
    const msg = JSON.parse(raw.toString());
    const error = getErrorFromMessage(msg);
    if (error) {
      result.reject(error);
    } else {
      result.resolve(msg);
    }
  }));
  return result.promise;
}
function createSocket(logService, remoteSocketFactoryService, connectTo, path3, query, debugConnectionType, debugLabel, timeoutCancellationToken) {
  const result = new PromiseWithTimeout(timeoutCancellationToken);
  const sw = $xe.create(false);
  logService.info(`Creating a socket (${debugLabel})...`);
  mark(`code/willCreateSocket/${debugConnectionType}`);
  remoteSocketFactoryService.connect(connectTo, path3, query, debugLabel).then((socket) => {
    if (result.didTimeout) {
      mark(`code/didCreateSocketError/${debugConnectionType}`);
      logService.info(`Creating a socket (${debugLabel}) finished after ${sw.elapsed()} ms, but this is too late and has timed out already.`);
      socket?.dispose();
    } else {
      mark(`code/didCreateSocketOK/${debugConnectionType}`);
      logService.info(`Creating a socket (${debugLabel}) was successful after ${sw.elapsed()} ms.`);
      result.resolve(socket);
    }
  }, (err) => {
    mark(`code/didCreateSocketError/${debugConnectionType}`);
    logService.info(`Creating a socket (${debugLabel}) returned an error after ${sw.elapsed()} ms.`);
    logService.error(err);
    result.reject(err);
  });
  return result.promise;
}
function raceWithTimeoutCancellation(promise, timeoutCancellationToken) {
  const result = new PromiseWithTimeout(timeoutCancellationToken);
  promise.then((res) => {
    if (!result.didTimeout) {
      result.resolve(res);
    }
  }, (err) => {
    if (!result.didTimeout) {
      result.reject(err);
    }
  });
  return result.promise;
}
async function connectToRemoteExtensionHostAgent(options, connectionType, args, timeoutCancellationToken) {
  const logPrefix = connectLogPrefix(options, connectionType);
  options.logService.trace(`${logPrefix} 1/6. invoking socketFactory.connect().`);
  let socket;
  try {
    socket = await createSocket(options.logService, options.remoteSocketFactoryService, options.connectTo, $ah.getServerRootPath(), `reconnectionToken=${options.reconnectionToken}&reconnection=${options.reconnectionProtocol ? "true" : "false"}`, connectionTypeToString(connectionType), `renderer-${connectionTypeToString(connectionType)}-${options.reconnectionToken}`, timeoutCancellationToken);
  } catch (error) {
    options.logService.error(`${logPrefix} socketFactory.connect() failed or timed out. Error:`);
    options.logService.error(error);
    throw error;
  }
  options.logService.trace(`${logPrefix} 2/6. socketFactory.connect() was successful.`);
  let protocol3;
  let ownsProtocol;
  if (options.reconnectionProtocol) {
    options.reconnectionProtocol.beginAcceptReconnection(socket, null);
    protocol3 = options.reconnectionProtocol;
    ownsProtocol = false;
  } else {
    protocol3 = new $Ni({ socket });
    ownsProtocol = true;
  }
  options.logService.trace(`${logPrefix} 3/6. sending AuthRequest control message.`);
  const message = await raceWithTimeoutCancellation(options.signService.createNewMessage($jh()), timeoutCancellationToken);
  const authRequest = {
    type: "auth",
    auth: options.connectionToken || "00000000000000000000",
    data: message.data
  };
  protocol3.sendControl($7e.fromString(JSON.stringify(authRequest)));
  try {
    const msg = await readOneControlMessage(protocol3, combineTimeoutCancellation(timeoutCancellationToken, createTimeoutCancellation(1e4)));
    if (msg.type !== "sign" || typeof msg.data !== "string") {
      const error = new Error("Unexpected handshake message");
      error.code = "VSCODE_CONNECTION_ERROR";
      throw error;
    }
    options.logService.trace(`${logPrefix} 4/6. received SignRequest control message.`);
    const isValid = await raceWithTimeoutCancellation(options.signService.validate(message, msg.signedData), timeoutCancellationToken);
    if (!isValid) {
      const error = new Error("Refused to connect to unsupported server");
      error.code = "VSCODE_CONNECTION_ERROR";
      throw error;
    }
    const signed = await raceWithTimeoutCancellation(options.signService.sign(msg.data), timeoutCancellationToken);
    const connTypeRequest = {
      type: "connectionType",
      commit: options.commit,
      signedData: signed,
      desiredConnectionType: connectionType
    };
    if (args) {
      connTypeRequest.args = args;
    }
    options.logService.trace(`${logPrefix} 5/6. sending ConnectionTypeRequest control message.`);
    protocol3.sendControl($7e.fromString(JSON.stringify(connTypeRequest)));
    return { protocol: protocol3, ownsProtocol };
  } catch (error) {
    if (error && error.code === "ETIMEDOUT") {
      options.logService.error(`${logPrefix} the handshake timed out. Error:`);
      options.logService.error(error);
    }
    if (error && error.code === "VSCODE_CONNECTION_ERROR") {
      options.logService.error(`${logPrefix} received error control message when negotiating connection. Error:`);
      options.logService.error(error);
    }
    if (ownsProtocol) {
      safeDisposeProtocolAndSocket(protocol3);
    }
    throw error;
  }
}
async function doConnectRemoteAgentTunnel(options, startParams, timeoutCancellationToken) {
  const startTime = Date.now();
  const logPrefix = connectLogPrefix(
    options,
    3
    /* ConnectionType.Tunnel */
  );
  const { protocol: protocol3 } = await connectToRemoteExtensionHostAgent(options, 3, startParams, timeoutCancellationToken);
  options.logService.trace(`${logPrefix} 6/6. handshake finished, connection is up and running after ${logElapsed(startTime)}!`);
  return protocol3;
}
async function resolveConnectionOptions(options, reconnectionToken, reconnectionProtocol) {
  const { connectTo, connectionToken } = await options.addressProvider.getAddress();
  return {
    commit: options.commit,
    quality: options.quality,
    connectTo,
    connectionToken,
    reconnectionToken,
    reconnectionProtocol,
    remoteSocketFactoryService: options.remoteSocketFactoryService,
    signService: options.signService,
    logService: options.logService
  };
}
async function $km(options, tunnelRemoteHost, tunnelRemotePort) {
  const simpleOptions = await resolveConnectionOptions(options, $jh(), null);
  const protocol3 = await doConnectRemoteAgentTunnel(simpleOptions, { host: tunnelRemoteHost, port: tunnelRemotePort }, CancellationToken.None);
  return protocol3;
}
function sleep(seconds) {
  return $Mh((token) => {
    return new Promise((resolve2, reject) => {
      const timeout = setTimeout(resolve2, seconds * 1e3);
      token.onCancellationRequested(() => {
        clearTimeout(timeout);
        resolve2();
      });
    });
  });
}
var PersistentConnectionEventType;
(function(PersistentConnectionEventType2) {
  PersistentConnectionEventType2[PersistentConnectionEventType2["ConnectionLost"] = 0] = "ConnectionLost";
  PersistentConnectionEventType2[PersistentConnectionEventType2["ReconnectionWait"] = 1] = "ReconnectionWait";
  PersistentConnectionEventType2[PersistentConnectionEventType2["ReconnectionRunning"] = 2] = "ReconnectionRunning";
  PersistentConnectionEventType2[PersistentConnectionEventType2["ReconnectionPermanentFailure"] = 3] = "ReconnectionPermanentFailure";
  PersistentConnectionEventType2[PersistentConnectionEventType2["ConnectionGain"] = 4] = "ConnectionGain";
})(PersistentConnectionEventType || (PersistentConnectionEventType = {}));
var $lm = class {
  constructor(reconnectionToken, millisSinceLastIncomingData) {
    this.reconnectionToken = reconnectionToken;
    this.millisSinceLastIncomingData = millisSinceLastIncomingData;
    this.type = 0;
  }
};
var $mm = class {
  constructor(reconnectionToken, millisSinceLastIncomingData, durationSeconds, c) {
    this.reconnectionToken = reconnectionToken;
    this.millisSinceLastIncomingData = millisSinceLastIncomingData;
    this.durationSeconds = durationSeconds;
    this.c = c;
    this.type = 1;
  }
  skipWait() {
    this.c.cancel();
  }
};
var $nm = class {
  constructor(reconnectionToken, millisSinceLastIncomingData, attempt) {
    this.reconnectionToken = reconnectionToken;
    this.millisSinceLastIncomingData = millisSinceLastIncomingData;
    this.attempt = attempt;
    this.type = 2;
  }
};
var $om = class {
  constructor(reconnectionToken, millisSinceLastIncomingData, attempt) {
    this.reconnectionToken = reconnectionToken;
    this.millisSinceLastIncomingData = millisSinceLastIncomingData;
    this.attempt = attempt;
    this.type = 4;
  }
};
var $pm = class {
  constructor(reconnectionToken, millisSinceLastIncomingData, attempt, handled) {
    this.reconnectionToken = reconnectionToken;
    this.millisSinceLastIncomingData = millisSinceLastIncomingData;
    this.attempt = attempt;
    this.handled = handled;
    this.type = 3;
  }
};
var $qm = class _$qm extends $0c {
  static triggerPermanentFailure(millisSinceLastIncomingData, attempt, handled) {
    this._permanentFailure = true;
    this.f = millisSinceLastIncomingData;
    this.g = attempt;
    this.h = handled;
    this.j.forEach((instance) => instance.D(this.f, this.g, this.h));
  }
  static debugTriggerReconnection() {
    this.j.forEach((instance) => instance.y());
  }
  static debugPauseSocketWriting() {
    this.j.forEach((instance) => instance.F());
  }
  static {
    this._permanentFailure = false;
  }
  static {
    this.f = 0;
  }
  static {
    this.g = 0;
  }
  static {
    this.h = false;
  }
  static {
    this.j = [];
  }
  get n() {
    return this.c || _$qm._permanentFailure;
  }
  constructor(t, u, reconnectionToken, protocol3, w) {
    super();
    this.t = t;
    this.u = u;
    this.reconnectionToken = reconnectionToken;
    this.protocol = protocol3;
    this.w = w;
    this.m = this.B(new $De());
    this.onDidStateChange = this.m.event;
    this.c = false;
    this.r = false;
    this.s = false;
    this.m.fire(new $om(this.reconnectionToken, 0, 0));
    this.B(protocol3.onSocketClose((e) => {
      const logPrefix = commonLogPrefix(this.t, this.reconnectionToken, true);
      if (!e) {
        this.u.logService.info(`${logPrefix} received socket close event.`);
      } else if (e.type === 0) {
        this.u.logService.info(`${logPrefix} received socket close event (hadError: ${e.hadError}).`);
        if (e.error) {
          this.u.logService.error(e.error);
        }
      } else {
        this.u.logService.info(`${logPrefix} received socket close event (wasClean: ${e.wasClean}, code: ${e.code}, reason: ${e.reason}).`);
        if (e.event) {
          this.u.logService.error(e.event);
        }
      }
      this.y();
    }));
    this.B(protocol3.onSocketTimeout((e) => {
      const logPrefix = commonLogPrefix(this.t, this.reconnectionToken, true);
      this.u.logService.info(`${logPrefix} received socket timeout event (unacknowledgedMsgCount: ${e.unacknowledgedMsgCount}, timeSinceOldestUnacknowledgedMsg: ${e.timeSinceOldestUnacknowledgedMsg}, timeSinceLastReceivedSomeData: ${e.timeSinceLastReceivedSomeData}).`);
      this.y();
    }));
    _$qm.j.push(this);
    this.B($8c(() => {
      const myIndex = _$qm.j.indexOf(this);
      if (myIndex >= 0) {
        _$qm.j.splice(myIndex, 1);
      }
    }));
    if (this.n) {
      this.D(_$qm.f, _$qm.g, _$qm.h);
    }
  }
  dispose() {
    super.dispose();
    this.s = true;
  }
  async y() {
    if (this.r) {
      return;
    }
    try {
      this.r = true;
      await this.z();
    } finally {
      this.r = false;
    }
  }
  async z() {
    if (this.n || this.s) {
      return;
    }
    const logPrefix = commonLogPrefix(this.t, this.reconnectionToken, true);
    this.u.logService.info(`${logPrefix} starting reconnecting loop. You can get more information with the trace log level.`);
    this.m.fire(new $lm(this.reconnectionToken, this.protocol.getMillisSinceLastIncomingData()));
    const TIMES = [0, 5, 5, 10, 10, 10, 10, 10, 30];
    let attempt = -1;
    do {
      attempt++;
      const waitTime = attempt < TIMES.length ? TIMES[attempt] : TIMES[TIMES.length - 1];
      try {
        if (waitTime > 0) {
          const sleepPromise = sleep(waitTime);
          this.m.fire(new $mm(this.reconnectionToken, this.protocol.getMillisSinceLastIncomingData(), waitTime, sleepPromise));
          this.u.logService.info(`${logPrefix} waiting for ${waitTime} seconds before reconnecting...`);
          try {
            await sleepPromise;
          } catch {
          }
        }
        if (this.n) {
          this.u.logService.error(`${logPrefix} permanent failure occurred while running the reconnecting loop.`);
          break;
        }
        this.m.fire(new $nm(this.reconnectionToken, this.protocol.getMillisSinceLastIncomingData(), attempt + 1));
        this.u.logService.info(`${logPrefix} resolving connection...`);
        const simpleOptions = await resolveConnectionOptions(this.u, this.reconnectionToken, this.protocol);
        this.u.logService.info(`${logPrefix} connecting to ${simpleOptions.connectTo}...`);
        await this.G(simpleOptions, createTimeoutCancellation(RECONNECT_TIMEOUT));
        this.u.logService.info(`${logPrefix} reconnected!`);
        this.m.fire(new $om(this.reconnectionToken, this.protocol.getMillisSinceLastIncomingData(), attempt + 1));
        break;
      } catch (err) {
        if (err.code === "VSCODE_CONNECTION_ERROR") {
          this.u.logService.error(`${logPrefix} A permanent error occurred in the reconnecting loop! Will give up now! Error:`);
          this.u.logService.error(err);
          this.C(this.protocol.getMillisSinceLastIncomingData(), attempt + 1, false);
          break;
        }
        if (attempt > 360) {
          this.u.logService.error(`${logPrefix} An error occurred while reconnecting, but it will be treated as a permanent error because the reconnection grace time has expired! Will give up now! Error:`);
          this.u.logService.error(err);
          this.C(this.protocol.getMillisSinceLastIncomingData(), attempt + 1, false);
          break;
        }
        if ($cm.isTemporarilyNotAvailable(err)) {
          this.u.logService.info(`${logPrefix} A temporarily not available error occurred while trying to reconnect, will try again...`);
          this.u.logService.trace(err);
          continue;
        }
        if ((err.code === "ETIMEDOUT" || err.code === "ENETUNREACH" || err.code === "ECONNREFUSED" || err.code === "ECONNRESET") && err.syscall === "connect") {
          this.u.logService.info(`${logPrefix} A network error occurred while trying to reconnect, will try again...`);
          this.u.logService.trace(err);
          continue;
        }
        if ($eb(err)) {
          this.u.logService.info(`${logPrefix} A promise cancelation error occurred while trying to reconnect, will try again...`);
          this.u.logService.trace(err);
          continue;
        }
        if (err instanceof $cm) {
          this.u.logService.error(`${logPrefix} A RemoteAuthorityResolverError occurred while trying to reconnect. Will give up now! Error:`);
          this.u.logService.error(err);
          this.C(this.protocol.getMillisSinceLastIncomingData(), attempt + 1, $cm.isHandled(err));
          break;
        }
        this.u.logService.error(`${logPrefix} An unknown error occurred while trying to reconnect, since this is an unknown case, it will be treated as a permanent error! Will give up now! Error:`);
        this.u.logService.error(err);
        this.C(this.protocol.getMillisSinceLastIncomingData(), attempt + 1, false);
        break;
      }
    } while (!this.n && !this.s);
  }
  C(millisSinceLastIncomingData, attempt, handled) {
    if (this.w) {
      _$qm.triggerPermanentFailure(millisSinceLastIncomingData, attempt, handled);
    } else {
      this.D(millisSinceLastIncomingData, attempt, handled);
    }
  }
  D(millisSinceLastIncomingData, attempt, handled) {
    this.m.fire(new $pm(this.reconnectionToken, millisSinceLastIncomingData, attempt, handled));
    safeDisposeProtocolAndSocket(this.protocol);
  }
  F() {
    this.protocol.pauseSocketWriting();
  }
};
function safeDisposeProtocolAndSocket(protocol3) {
  try {
    protocol3.acceptDisconnect();
    const socket = protocol3.getSocket();
    protocol3.dispose();
    socket.dispose();
  } catch (err) {
    $ab(err);
  }
}
function getErrorFromMessage(msg) {
  if (msg && msg.type === "error") {
    const error = new Error(`Connection error: ${msg.reason}`);
    error.code = "VSCODE_CONNECTION_ERROR";
    return error;
  }
  return null;
}
function stringRightPad(str, len) {
  while (str.length < len) {
    str += " ";
  }
  return str;
}
function _commonLogPrefix(connectionType, reconnectionToken) {
  return `[remote-connection][${stringRightPad(connectionTypeToString(connectionType), 13)}][${reconnectionToken.substr(0, 5)}\u2026]`;
}
function commonLogPrefix(connectionType, reconnectionToken, isReconnect) {
  return `${_commonLogPrefix(connectionType, reconnectionToken)}[${isReconnect ? "reconnect" : "initial"}]`;
}
function connectLogPrefix(options, connectionType) {
  return `${commonLogPrefix(connectionType, options.reconnectionToken, !!options.reconnectionProtocol)}[${options.connectTo}]`;
}
function logElapsed(startTime) {
  return `${Date.now() - startTime} ms`;
}

// out-build/vs/platform/remote/common/remoteSocketFactoryService.js
var $em = $Zi("remoteSocketFactoryService");

// out-build/vs/platform/tunnel/node/tunnelService.js
async function createRemoteTunnel(options, defaultTunnelHost, tunnelRemoteHost, tunnelRemotePort, tunnelLocalPort) {
  let readyTunnel;
  for (let attempts = 3; attempts; attempts--) {
    readyTunnel?.dispose();
    const tunnel = new $Rlc(options, defaultTunnelHost, tunnelRemoteHost, tunnelRemotePort, tunnelLocalPort);
    readyTunnel = await tunnel.waitForReady();
    if (tunnelLocalPort && $mh[tunnelLocalPort] || !$mh[readyTunnel.tunnelLocalPort]) {
      break;
    }
  }
  return readyTunnel;
}
var $Rlc = class extends $0c {
  constructor(options, m, tunnelRemoteHost, tunnelRemotePort, n) {
    super();
    this.m = m;
    this.n = n;
    this.privacy = TunnelPrivacyId.Private;
    this.j = /* @__PURE__ */ new Map();
    this.a = options;
    this.b = net2.createServer();
    this.c = new $Yh();
    this.f = () => this.c.open();
    this.b.on("listening", this.f);
    this.g = (socket) => this.r(socket);
    this.b.on("connection", this.g);
    this.h = () => {
    };
    this.b.on("error", this.h);
    this.tunnelRemotePort = tunnelRemotePort;
    this.tunnelRemoteHost = tunnelRemoteHost;
  }
  async dispose() {
    super.dispose();
    this.b.removeListener("listening", this.f);
    this.b.removeListener("connection", this.g);
    this.b.removeListener("error", this.h);
    this.b.close();
    const disposers = Array.from(this.j.values());
    disposers.forEach((disposer) => {
      disposer();
    });
  }
  async waitForReady() {
    const startPort = this.n ?? this.tunnelRemotePort;
    const hostname3 = $ix(this.m) ? "0.0.0.0" : "127.0.0.1";
    let localPort = await $nh(startPort, 2, 1e3, hostname3);
    let address = null;
    this.b.listen(localPort, this.m);
    await this.c.wait();
    address = this.b.address();
    if (!address) {
      localPort = 0;
      this.b.listen(localPort, this.m);
      await this.c.wait();
      address = this.b.address();
    }
    this.tunnelLocalPort = address.port;
    this.localAddress = `${this.tunnelRemoteHost === "127.0.0.1" ? "127.0.0.1" : "localhost"}:${address.port}`;
    return this;
  }
  async r(localSocket) {
    localSocket.pause();
    const tunnelRemoteHost = $gx(this.tunnelRemoteHost) || $ix(this.tunnelRemoteHost) ? "localhost" : this.tunnelRemoteHost;
    const protocol3 = await $km(this.a, tunnelRemoteHost, this.tunnelRemotePort);
    const remoteSocket = protocol3.getSocket();
    const dataChunk = protocol3.readEntireBuffer();
    protocol3.dispose();
    if (dataChunk.byteLength > 0) {
      localSocket.write(dataChunk.buffer);
    }
    localSocket.on("end", () => {
      if (localSocket.localAddress) {
        this.j.delete(localSocket.localAddress);
      }
      remoteSocket.end();
    });
    localSocket.on("close", () => remoteSocket.end());
    localSocket.on("error", () => {
      if (localSocket.localAddress) {
        this.j.delete(localSocket.localAddress);
      }
      if (remoteSocket instanceof $Oi) {
        remoteSocket.socket.destroy();
      } else {
        remoteSocket.end();
      }
    });
    if (remoteSocket instanceof $Oi) {
      this.t(localSocket, remoteSocket);
    } else {
      this.s(localSocket, remoteSocket);
    }
    if (localSocket.localAddress) {
      this.j.set(localSocket.localAddress, () => {
        localSocket.end();
        remoteSocket.end();
      });
    }
  }
  s(localSocket, remoteSocket) {
    remoteSocket.onClose(() => localSocket.destroy());
    remoteSocket.onEnd(() => localSocket.end());
    remoteSocket.onData((d) => localSocket.write(d.buffer));
    localSocket.on("data", (d) => remoteSocket.write($7e.wrap(d)));
    localSocket.resume();
  }
  t(localSocket, remoteNodeSocket) {
    const remoteSocket = remoteNodeSocket.socket;
    remoteSocket.on("end", () => localSocket.end());
    remoteSocket.on("close", () => localSocket.end());
    remoteSocket.on("error", () => {
      localSocket.destroy();
    });
    remoteSocket.pipe(localSocket);
    localSocket.pipe(remoteSocket);
  }
};
var $Slc = class $Slc2 extends $lx {
  constructor(H, logService, I, J, configurationService) {
    super(logService, configurationService);
    this.H = H;
    this.I = I;
    this.J = J;
  }
  isPortPrivileged(port) {
    return $jx(port, this.t, OS, os5.release());
  }
  F(addressOrTunnelProvider, remoteHost, remotePort, localHost, localPort, elevateIfNeeded, privacy, protocol3) {
    const existing = this.D(remoteHost, remotePort);
    if (existing) {
      ++existing.refcount;
      return existing.value;
    }
    if ($cx(addressOrTunnelProvider)) {
      return this.G(addressOrTunnelProvider, remoteHost, remotePort, localPort, elevateIfNeeded, privacy, protocol3);
    } else {
      this.r.trace(`ForwardedPorts: (TunnelService) Creating tunnel without provider ${remoteHost}:${remotePort} on local port ${localPort}.`);
      const options = {
        commit: this.J.commit,
        quality: this.J.quality,
        addressProvider: addressOrTunnelProvider,
        remoteSocketFactoryService: this.H,
        signService: this.I,
        logService: this.r,
        ipcLogger: null
      };
      const tunnel = createRemoteTunnel(options, localHost, remoteHost, remotePort, localPort);
      this.r.trace("ForwardedPorts: (TunnelService) Tunnel created without provider.");
      this.z(remoteHost, remotePort, tunnel);
      return tunnel;
    }
  }
};
$Slc = __decorate([
  __param(0, $em),
  __param(1, $uk),
  __param(2, $hm),
  __param(3, $Nk),
  __param(4, $tj)
], $Slc);
var $Tlc = class $Tlc2 extends $Slc {
  constructor(remoteSocketFactoryService, logService, signService, productService, configurationService) {
    super(remoteSocketFactoryService, logService, signService, productService, configurationService);
  }
};
$Tlc = __decorate([
  __param(0, $em),
  __param(1, $uk),
  __param(2, $hm),
  __param(3, $Nk),
  __param(4, $tj)
], $Tlc);
var $Ulc = class $Ulc2 extends $0c {
  constructor(b, c, f, g, h) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h;
    this.a = /* @__PURE__ */ new Map();
  }
  async openTunnel(authority, addressProvider, remoteHost, remotePort, localHost, localPort, elevateIfNeeded, privacy, protocol3) {
    this.c.trace(`ForwardedPorts: (SharedTunnelService) openTunnel request for ${remoteHost}:${remotePort} on local port ${localPort}.`);
    if (!this.a.has(authority)) {
      const tunnelService = new $Tlc(this.b, this.c, this.g, this.f, this.h);
      this.B(tunnelService);
      this.a.set(authority, tunnelService);
      tunnelService.onTunnelClosed(async () => {
        if ((await tunnelService.tunnels).length === 0) {
          tunnelService.dispose();
          this.a.delete(authority);
        }
      });
    }
    return this.a.get(authority).openTunnel(addressProvider, remoteHost, remotePort, localHost, localPort, elevateIfNeeded, privacy, protocol3);
  }
};
$Ulc = __decorate([
  __param(0, $em),
  __param(1, $uk),
  __param(2, $Nk),
  __param(3, $hm),
  __param(4, $tj)
], $Ulc);

// out-build/vs/platform/request/electron-utility/requestService.js
import { net as net3 } from "electron";

// out-build/vs/platform/request/node/requestService.js
import { parse as parseUrl2 } from "url";

// out-build/vs/platform/request/node/proxy.js
import { parse as parseUrl } from "url";
function getSystemProxyURI(requestURL, env2) {
  if (requestURL.protocol === "http:") {
    return env2.HTTP_PROXY || env2.http_proxy || null;
  } else if (requestURL.protocol === "https:") {
    return env2.HTTPS_PROXY || env2.https_proxy || env2.HTTP_PROXY || env2.http_proxy || null;
  }
  return null;
}
async function $As(rawRequestURL, env2, options = {}) {
  const requestURL = parseUrl(rawRequestURL);
  const proxyURL = options.proxyUrl || getSystemProxyURI(requestURL, env2);
  if (!proxyURL) {
    return null;
  }
  const proxyEndpoint = parseUrl(proxyURL);
  if (!/^https?:$/.test(proxyEndpoint.protocol || "")) {
    return null;
  }
  const opts = {
    host: proxyEndpoint.hostname || "",
    port: (proxyEndpoint.port ? +proxyEndpoint.port : 0) || (proxyEndpoint.protocol === "https" ? 443 : 80),
    auth: proxyEndpoint.auth,
    rejectUnauthorized: $Eg(options.strictSSL) ? options.strictSSL : true
  };
  if (requestURL.protocol === "http:") {
    const { default: mod } = await import("http-proxy-agent");
    return new mod.HttpProxyAgent(proxyURL, opts);
  } else {
    const { default: mod } = await import("https-proxy-agent");
    return new mod.HttpsProxyAgent(proxyURL, opts);
  }
}

// out-build/vs/platform/request/node/requestService.js
import { createGunzip } from "zlib";
var $Bs = class $Bs2 extends $rq {
  constructor(m, n, logService) {
    super(logService);
    this.m = m;
    this.n = n;
    this.r();
    this.B(m.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("http")) {
        this.r();
      }
    }));
  }
  r() {
    const config = this.m.getValue("http");
    this.f = config?.proxy;
    this.g = !!config?.proxyStrictSSL;
    this.h = config?.proxyAuthorization;
  }
  async request(options, token) {
    const { f: proxyUrl, g: strictSSL } = this;
    let shellEnv = void 0;
    try {
      shellEnv = await $_m(this.m, this.b, this.n.args, process.env);
    } catch (error) {
      if (!this.j) {
        this.j = true;
        this.b.error(`resolving shell environment failed`, $kb(error));
      }
    }
    const env2 = {
      ...process.env,
      ...shellEnv
    };
    const agent = options.agent ? options.agent : await $As(options.url || "", env2, { proxyUrl, strictSSL });
    options.agent = agent;
    options.strictSSL = strictSSL;
    if (this.h) {
      options.headers = {
        ...options.headers || {},
        "Proxy-Authorization": this.h
      };
    }
    return this.c(options, () => $Cs(options, token));
  }
  async resolveProxy(url) {
    return void 0;
  }
  async lookupAuthorization(authInfo) {
    return void 0;
  }
  async lookupKerberosAuthorization(urlStr) {
    try {
      const kerberos = await import("kerberos");
      const url = new URL(urlStr);
      const spn = this.m.getValue("http.proxyKerberosServicePrincipal") || (process.platform === "win32" ? `HTTP/${url.hostname}` : `HTTP@${url.hostname}`);
      this.b.debug("RequestService#lookupKerberosAuthorization Kerberos authentication lookup", `proxyURL:${url}`, `spn:${spn}`);
      const client = await kerberos.initializeClient(spn);
      const response = await client.step("");
      return "Negotiate " + response;
    } catch (err) {
      this.b.debug("RequestService#lookupKerberosAuthorization Kerberos authentication failed", err);
      return void 0;
    }
  }
  async loadCertificates() {
    const proxyAgent = await import("@vscode/proxy-agent");
    return proxyAgent.loadSystemCertificates({ log: this.b });
  }
};
$Bs = __decorate([
  __param(0, $tj),
  __param(1, $8i),
  __param(2, $uk)
], $Bs);
async function getNodeRequest(options) {
  const endpoint = parseUrl2(options.url);
  const module6 = endpoint.protocol === "https:" ? await import("https") : await import("http");
  return module6.request;
}
async function $Cs(options, token) {
  return Promises.withAsyncBody(async (resolve2, reject) => {
    const endpoint = parseUrl2(options.url);
    const rawRequest = options.getRawRequest ? options.getRawRequest(options) : await getNodeRequest(options);
    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: $Eg(options.strictSSL) ? options.strictSSL : true
    };
    if (options.user && options.password) {
      opts.auth = options.user + ":" + options.password;
    }
    const req = rawRequest(opts, (res) => {
      const followRedirects = $Cg(options.followRedirects) ? options.followRedirects : 3;
      if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && followRedirects > 0 && res.headers["location"]) {
        $Cs({
          ...options,
          url: res.headers["location"],
          followRedirects: followRedirects - 1
        }, token).then(resolve2, reject);
      } else {
        let stream = res;
        if (!options.isChromiumNetwork && res.headers["content-encoding"] === "gzip") {
          stream = res.pipe(createGunzip());
        }
        resolve2({ res, stream: $jf(stream) });
      }
    });
    req.on("error", reject);
    if (options.timeout) {
      req.setTimeout(options.timeout);
    }
    if (options.isChromiumNetwork) {
      req.removeHeader("Content-Length");
    }
    if (options.data) {
      if (typeof options.data === "string") {
        req.write(options.data);
      }
    }
    req.end();
    token.onCancellationRequested(() => {
      req.abort();
      reject(new $fb());
    });
  });
}

// out-build/vs/platform/request/electron-utility/requestService.js
function getRawRequest(options) {
  return net3.request;
}
var $Vlc = class extends $Bs {
  request(options, token) {
    return super.request({ ...options || {}, getRawRequest, isChromiumNetwork: true }, token);
  }
};

// out-build/vs/platform/sign/common/abstractSignService.js
var $Egc = class _$Egc {
  constructor() {
    this.b = /* @__PURE__ */ new Map();
  }
  static {
    this.a = 1;
  }
  async createNewMessage(value) {
    try {
      const validator = await this.c();
      if (validator) {
        const id2 = String(_$Egc.a++);
        this.b.set(id2, validator);
        return {
          id: id2,
          data: validator.createNewMessage(value)
        };
      }
    } catch (e) {
    }
    return { id: "", data: value };
  }
  async validate(message, value) {
    if (!message.id) {
      return true;
    }
    const validator = this.b.get(message.id);
    if (!validator) {
      return false;
    }
    this.b.delete(message.id);
    try {
      return validator.validate(value) === "ok";
    } catch (e) {
      return false;
    } finally {
      validator.dispose?.();
    }
  }
  async sign(value) {
    try {
      return await this.d(value);
    } catch (e) {
    }
    return value;
  }
};

// out-build/vs/platform/sign/node/signService.js
var $Wlc = class extends $Egc {
  c() {
    return this.h().then((vsda) => new vsda.validator());
  }
  d(arg) {
    return this.h().then((vsda) => new vsda.signer().sign(arg));
  }
  async h() {
    if (typeof $Oq === "function") {
    }
    const mod = "vsda";
    const { default: vsda } = await import(mod);
    return vsda;
  }
};

// out-build/vs/platform/policy/node/nativePolicyService.js
var $Xlc = class $Xlc2 extends $Po {
  constructor(m, n) {
    super();
    this.m = m;
    this.n = n;
    this.a = new $Th();
    this.b = this.B(new $$c());
  }
  async j(policyDefinitions) {
    this.m.trace(`NativePolicyService#_updatePolicyDefinitions - Found ${Object.keys(policyDefinitions).length} policy definitions`);
    const { createWatcher } = await import("@vscode/policy-watcher");
    await this.a.queue(() => new Promise((c, e) => {
      try {
        this.b.value = createWatcher(this.n, policyDefinitions, (update) => {
          this.t(update);
          c();
        });
      } catch (err) {
        this.m.error(`NativePolicyService#_updatePolicyDefinitions - Error creating watcher:`, err);
        e(err);
      }
    }));
  }
  t(update) {
    this.m.trace(`NativePolicyService#_onDidPolicyChange - Updated policy values: ${JSON.stringify(update)}`);
    for (const key in update) {
      const value = update[key];
      if (value === void 0) {
        this.g.delete(key);
      } else {
        this.g.set(key, value);
      }
    }
    this.h.fire(Object.keys(update));
  }
};
$Xlc = __decorate([
  __param(0, $uk)
], $Xlc);

// out-build/vs/platform/policy/common/filePolicyService.js
function keysDiff(a, b) {
  const result = [];
  for (const key of new Set(Iterable.concat(a.keys(), b.keys()))) {
    if (a.get(key) !== b.get(key)) {
      result.push(key);
    }
  }
  return result;
}
var $Ylc = class $Ylc2 extends $Po {
  constructor(m, n, s) {
    super();
    this.m = m;
    this.n = n;
    this.s = s;
    this.c = this.B(new $Xh(500));
    const onDidChangePolicyFile = Event.filter(n.onDidFilesChange, (e) => e.affects(m));
    this.B(n.watch(m));
    this.B(onDidChangePolicyFile(() => this.c.trigger(() => this.w())));
  }
  async j() {
    await this.w();
  }
  async u() {
    const policies = /* @__PURE__ */ new Map();
    try {
      const content = await this.n.readFile(this.m);
      const raw = JSON.parse(content.value.toString());
      if (!$Ag(raw)) {
        throw new Error("Policy file isn't a JSON object");
      }
      for (const key of Object.keys(raw)) {
        if (this.f[key]) {
          policies.set(key, raw[key]);
        }
      }
    } catch (error) {
      if (error.fileOperationResult !== 1) {
        this.s.error(`[FilePolicyService] Failed to read policies`, error);
      }
    }
    return policies;
  }
  async w() {
    const policies = await this.u();
    const diff2 = keysDiff(this.g, policies);
    this.g = policies;
    if (diff2.length > 0) {
      this.h.fire(diff2);
    }
  }
};
$Ylc = __decorate([
  __param(1, $ul),
  __param(2, $uk)
], $Ylc);

// out-build/vs/base/common/skipList.js
var _a3;
var Node2 = class {
  constructor(level, key, value) {
    this.level = level;
    this.key = key;
    this.value = value;
    this.forward = [];
  }
};
var NIL = void 0;
var $dt = class _$dt {
  /**
   *
   * @param capacity Capacity at which the list performs best
   */
  constructor(comparator, capacity = 2 ** 16) {
    this.comparator = comparator;
    this[_a3] = "SkipList";
    this.d = 0;
    this.f = 0;
    this.c = Math.max(1, Math.log2(capacity) | 0);
    this.e = new Node2(this.c, NIL, NIL);
  }
  get size() {
    return this.f;
  }
  clear() {
    this.e = new Node2(this.c, NIL, NIL);
    this.f = 0;
  }
  has(key) {
    return Boolean(_$dt.g(this, key, this.comparator));
  }
  get(key) {
    return _$dt.g(this, key, this.comparator)?.value;
  }
  set(key, value) {
    if (_$dt.h(this, key, value, this.comparator)) {
      this.f += 1;
    }
    return this;
  }
  delete(key) {
    const didDelete = _$dt.k(this, key, this.comparator);
    if (didDelete) {
      this.f -= 1;
    }
    return didDelete;
  }
  // --- iteration
  forEach(callbackfn, thisArg) {
    let node = this.e.forward[0];
    while (node) {
      callbackfn.call(thisArg, node.value, node.key, this);
      node = node.forward[0];
    }
  }
  [(_a3 = Symbol.toStringTag, Symbol.iterator)]() {
    return this.entries();
  }
  *entries() {
    let node = this.e.forward[0];
    while (node) {
      yield [node.key, node.value];
      node = node.forward[0];
    }
  }
  *keys() {
    let node = this.e.forward[0];
    while (node) {
      yield node.key;
      node = node.forward[0];
    }
  }
  *values() {
    let node = this.e.forward[0];
    while (node) {
      yield node.value;
      node = node.forward[0];
    }
  }
  toString() {
    let result = "[SkipList]:";
    let node = this.e.forward[0];
    while (node) {
      result += `node(${node.key}, ${node.value}, lvl:${node.level})`;
      node = node.forward[0];
    }
    return result;
  }
  // from https://www.epaperpress.com/sortsearch/download/skiplist.pdf
  static g(list, searchKey, comparator) {
    let x = list.e;
    for (let i = list.d - 1; i >= 0; i--) {
      while (x.forward[i] && comparator(x.forward[i].key, searchKey) < 0) {
        x = x.forward[i];
      }
    }
    x = x.forward[0];
    if (x && comparator(x.key, searchKey) === 0) {
      return x;
    }
    return void 0;
  }
  static h(list, searchKey, value, comparator) {
    const update = [];
    let x = list.e;
    for (let i = list.d - 1; i >= 0; i--) {
      while (x.forward[i] && comparator(x.forward[i].key, searchKey) < 0) {
        x = x.forward[i];
      }
      update[i] = x;
    }
    x = x.forward[0];
    if (x && comparator(x.key, searchKey) === 0) {
      x.value = value;
      return false;
    } else {
      const lvl = _$dt.j(list);
      if (lvl > list.d) {
        for (let i = list.d; i < lvl; i++) {
          update[i] = list.e;
        }
        list.d = lvl;
      }
      x = new Node2(lvl, searchKey, value);
      for (let i = 0; i < lvl; i++) {
        x.forward[i] = update[i].forward[i];
        update[i].forward[i] = x;
      }
      return true;
    }
  }
  static j(list, p = 0.5) {
    let lvl = 1;
    while (Math.random() < p && lvl < list.c) {
      lvl += 1;
    }
    return lvl;
  }
  static k(list, searchKey, comparator) {
    const update = [];
    let x = list.e;
    for (let i = list.d - 1; i >= 0; i--) {
      while (x.forward[i] && comparator(x.forward[i].key, searchKey) < 0) {
        x = x.forward[i];
      }
      update[i] = x;
    }
    x = x.forward[0];
    if (!x || comparator(x.key, searchKey) !== 0) {
      return false;
    }
    for (let i = 0; i < list.d; i++) {
      if (update[i].forward[i] !== x) {
        break;
      }
      update[i].forward[i] = x.forward[i];
    }
    while (list.d > 0 && list.e.forward[list.d - 1] === NIL) {
      list.d -= 1;
    }
    return true;
  }
};

// out-build/vs/platform/uriIdentity/common/uriIdentityService.js
var Entry = class _Entry {
  static {
    this._clock = 0;
  }
  constructor(uri) {
    this.uri = uri;
    this.time = _Entry._clock++;
  }
  touch() {
    this.time = _Entry._clock++;
    return this;
  }
};
var $et = class $et2 {
  constructor(g) {
    this.g = g;
    this.c = new $9c();
    this.f = 2 ** 16;
    const schemeIgnoresPathCasingCache = /* @__PURE__ */ new Map();
    const ignorePathCasing = (uri) => {
      let ignorePathCasing2 = schemeIgnoresPathCasingCache.get(uri.scheme);
      if (ignorePathCasing2 === void 0) {
        ignorePathCasing2 = g.hasProvider(uri) && !this.g.hasCapability(
          uri,
          1024
          /* FileSystemProviderCapabilities.PathCaseSensitive */
        );
        schemeIgnoresPathCasingCache.set(uri.scheme, ignorePathCasing2);
      }
      return ignorePathCasing2;
    };
    this.c.add(Event.any(g.onDidChangeFileSystemProviderRegistrations, g.onDidChangeFileSystemProviderCapabilities)((e) => {
      schemeIgnoresPathCasingCache.delete(e.scheme);
    }));
    this.extUri = new $ph(ignorePathCasing);
    this.d = new $dt((a, b) => this.extUri.compare(a, b, true), this.f);
  }
  dispose() {
    this.c.dispose();
    this.d.clear();
  }
  asCanonicalUri(uri) {
    if (this.g.hasProvider(uri)) {
      uri = $Bh(uri);
    }
    const item = this.d.get(uri);
    if (item) {
      return item.touch().uri.with({ fragment: uri.fragment });
    }
    this.d.set(uri, new Entry(uri));
    this.h();
    return uri;
  }
  h() {
    if (this.d.size < this.f) {
      return;
    }
    const entries = [...this.d.entries()].sort((a, b) => {
      if (a[1].time < b[1].time) {
        return 1;
      } else if (a[1].time > b[1].time) {
        return -1;
      } else {
        return 0;
      }
    });
    Entry._clock = 0;
    this.d.clear();
    const newSize = this.f * 0.5;
    for (let i = 0; i < newSize; i++) {
      this.d.set(entries[i][0], entries[i][1].touch());
    }
  }
};
$et = __decorate([
  __param(0, $ul)
], $et);
$bt(
  $5l,
  $et,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/platform/log/common/logService.js
var $JS = class extends $0c {
  constructor(primaryLogger, otherLoggers = []) {
    super();
    this.a = new $Ek([primaryLogger, ...otherLoggers]);
    this.B(primaryLogger.onDidChangeLogLevel((level) => this.setLevel(level)));
  }
  get onDidChangeLogLevel() {
    return this.a.onDidChangeLogLevel;
  }
  setLevel(level) {
    this.a.setLevel(level);
  }
  getLevel() {
    return this.a.getLevel();
  }
  trace(message, ...args) {
    this.a.trace(message, ...args);
  }
  debug(message, ...args) {
    this.a.debug(message, ...args);
  }
  info(message, ...args) {
    this.a.info(message, ...args);
  }
  warn(message, ...args) {
    this.a.warn(message, ...args);
  }
  error(message, ...args) {
    this.a.error(message, ...args);
  }
  flush() {
    this.a.flush();
  }
};

// out-build/vs/platform/userData/common/fileUserDataProvider.js
var $Zlc = class extends $0c {
  constructor(f, g, h, j, m, n) {
    super();
    this.f = f;
    this.g = g;
    this.h = h;
    this.j = j;
    this.m = m;
    this.n = n;
    this.capabilities = this.g.capabilities;
    this.onDidChangeCapabilities = this.g.onDidChangeCapabilities;
    this.a = this.B(new $De());
    this.onDidChangeFile = this.a.event;
    this.b = $6i.forUris(() => !(this.capabilities & 1024));
    this.c = new $Nc((uri) => this.m.extUri.getComparisonKey(this.t(uri)));
    this.r();
    this.B(j.onDidChangeProfiles(() => this.r()));
    this.B(this.g.onDidChangeFile((e) => this.s(e)));
  }
  r() {
    this.c.clear();
    for (const profile of this.j.profiles) {
      this.c.add(profile.settingsResource);
      this.c.add(profile.keybindingsResource);
      this.c.add(profile.tasksResource);
      this.c.add(profile.extensionsResource);
    }
  }
  open(resource, opts) {
    return this.g.open(this.t(resource), opts);
  }
  close(fd) {
    return this.g.close(fd);
  }
  read(fd, pos, data, offset, length) {
    return this.g.read(fd, pos, data, offset, length);
  }
  write(fd, pos, data, offset, length) {
    return this.g.write(fd, pos, data, offset, length);
  }
  watch(resource, opts) {
    this.b.set(resource, resource);
    const disposable = this.g.watch(this.t(resource), opts);
    return $8c(() => {
      this.b.delete(resource);
      disposable.dispose();
    });
  }
  stat(resource) {
    return this.g.stat(this.t(resource));
  }
  mkdir(resource) {
    return this.g.mkdir(this.t(resource));
  }
  rename(from, to, opts) {
    return this.g.rename(this.t(from), this.t(to), opts);
  }
  readFile(resource, opts) {
    return this.g.readFile(this.t(resource), opts);
  }
  readFileStream(resource, opts, token) {
    return this.g.readFileStream(this.t(resource), opts, token);
  }
  readdir(resource) {
    return this.g.readdir(this.t(resource));
  }
  enforceAtomicReadFile(resource) {
    return this.c.has(resource);
  }
  writeFile(resource, content, opts) {
    return this.g.writeFile(this.t(resource), content, opts);
  }
  enforceAtomicWriteFile(resource) {
    if (this.c.has(resource)) {
      return { postfix: ".vsctmp" };
    }
    return false;
  }
  delete(resource, opts) {
    return this.g.delete(this.t(resource), opts);
  }
  copy(from, to, opts) {
    if ($yl(this.g)) {
      return this.g.copy(this.t(from), this.t(to), opts);
    }
    throw new Error("copy not supported");
  }
  cloneFile(from, to) {
    if ($zl(this.g)) {
      return this.g.cloneFile(this.t(from), this.t(to));
    }
    throw new Error("clone not supported");
  }
  s(changes) {
    const userDataChanges = [];
    for (const change of changes) {
      if (change.resource.scheme !== this.f) {
        continue;
      }
      const userDataResource = this.u(change.resource);
      if (this.b.findSubstr(userDataResource)) {
        userDataChanges.push({
          resource: userDataResource,
          type: change.type,
          cId: change.cId
        });
      }
    }
    if (userDataChanges.length) {
      this.n.debug("User data changed");
      this.a.fire(userDataChanges);
    }
  }
  t(userDataResource) {
    return userDataResource.with({ scheme: this.f });
  }
  u(fileSystemResource) {
    return fileSystemResource.with({ scheme: this.h });
  }
};

// out-build/vs/code/electron-main/main.js
var CodeMain = class {
  main() {
    try {
      this.a();
    } catch (error) {
      console.error(error.message);
      app13.exit(1);
    }
  }
  async a() {
    setUnexpectedErrorHandler((err) => console.error(err));
    const [instantiationService, instanceEnvironment, environmentMainService, configurationService, stateMainService, bufferLogger, productService, userDataProfilesMainService] = this.b();
    try {
      try {
        await this.d(environmentMainService, userDataProfilesMainService, configurationService, stateMainService, productService);
      } catch (error) {
        this.g(environmentMainService, productService, error);
        throw error;
      }
      await instantiationService.invokeFunction(async (accessor) => {
        const logService = accessor.get($uk);
        const lifecycleMainService = accessor.get($9jc);
        const fileService = accessor.get($ul);
        const loggerService = accessor.get($vk);
        const mainProcessNodeIpcServer = await this.f(logService, environmentMainService, lifecycleMainService, instantiationService, productService, true);
        Promises2.writeFile(environmentMainService.mainLockfile, String(process.pid)).catch((err) => {
          logService.warn(`app#startup(): Error writing main lockfile: ${err.stack}`);
        });
        bufferLogger.logger = loggerService.createLogger("main", { name: localize(154, null) });
        Event.once(lifecycleMainService.onWillShutdown)((evt) => {
          fileService.dispose();
          configurationService.dispose();
          evt.join("instanceLockfile", promises15.unlink(environmentMainService.mainLockfile).catch(() => {
          }));
        });
        return instantiationService.createInstance($Olc, mainProcessNodeIpcServer, instanceEnvironment).startup();
      });
    } catch (error) {
      instantiationService.invokeFunction(this.j, error);
    }
  }
  b() {
    const services = new $Xi();
    const disposables = new $9c();
    process.once("exit", () => disposables.dispose());
    const productService = { _serviceBrand: void 0, ...product_default };
    services.set($Nk, productService);
    const environmentMainService = new $Djc(this.k(), productService);
    const instanceEnvironment = this.c(environmentMainService);
    services.set($Cjc, environmentMainService);
    const loggerService = new $5jc($Ik(environmentMainService), environmentMainService.logsHome);
    services.set($4jc, loggerService);
    const bufferLogger = new $bhc(loggerService.getLogLevel());
    const logService = disposables.add(new $JS(bufferLogger, [new $Bk(loggerService.getLogLevel())]));
    services.set($uk, logService);
    const fileService = new $mr(logService);
    services.set($ul, fileService);
    const diskFileSystemProvider = new $Pr(logService);
    fileService.registerProvider(Schemas.file, diskFileSystemProvider);
    const uriIdentityService = new $et(fileService);
    services.set($5l, uriIdentityService);
    const stateService = new $ES(1, environmentMainService, logService, fileService);
    services.set($AS, stateService);
    services.set($BS, stateService);
    const userDataProfilesMainService = new $Tjc(stateService, uriIdentityService, environmentMainService, fileService, logService);
    services.set($Sjc, userDataProfilesMainService);
    fileService.registerProvider(Schemas.vscodeUserData, new $Zlc(Schemas.file, diskFileSystemProvider, Schemas.vscodeUserData, userDataProfilesMainService, uriIdentityService, logService));
    const policyService = $l && productService.win32RegValueName ? disposables.add(new $Xlc(logService, productService.win32RegValueName)) : environmentMainService.policyFile ? disposables.add(new $Ylc(environmentMainService.policyFile, fileService, logService)) : new $Qo();
    services.set($Oo, policyService);
    const configurationService = new $gp(userDataProfilesMainService.defaultProfile.settingsResource, fileService, policyService, logService);
    services.set($tj, configurationService);
    services.set($9jc, new $Wi($0jc, void 0, false));
    services.set($qq, new $Wi($Vlc, void 0, true));
    services.set($Njc, new $Wi($Ojc));
    services.set($hm, new $Wi(
      $Wlc,
      void 0,
      false
      /* proxied to other processes */
    ));
    services.set($ax, new $Wi($Tlc));
    services.set($Mjc, new $Qlc(environmentMainService, userDataProfilesMainService, logService));
    return [new $Sr(services, true), instanceEnvironment, environmentMainService, configurationService, stateService, bufferLogger, productService, userDataProfilesMainService];
  }
  c(environmentMainService) {
    const instanceEnvironment = {
      VSCODE_IPC_HOOK: environmentMainService.mainIPCHandle
    };
    ["VSCODE_NLS_CONFIG", "VSCODE_PORTABLE"].forEach((key) => {
      const value = process.env[key];
      if (typeof value === "string") {
        instanceEnvironment[key] = value;
      }
    });
    Object.assign(process.env, instanceEnvironment);
    return instanceEnvironment;
  }
  async d(environmentMainService, userDataProfilesMainService, configurationService, stateService, productService) {
    await Promises.settled([
      // Environment service (paths)
      Promise.all([
        this.e(environmentMainService.extensionsPath),
        // enable extension paths on UNC drives...
        environmentMainService.codeCachePath,
        // ...other user-data-derived paths should already be enlisted from `main.js`
        environmentMainService.logsHome.with({ scheme: Schemas.file }).fsPath,
        userDataProfilesMainService.defaultProfile.globalStorageHome.with({ scheme: Schemas.file }).fsPath,
        environmentMainService.workspaceStorageHome.with({ scheme: Schemas.file }).fsPath,
        environmentMainService.localHistoryHome.with({ scheme: Schemas.file }).fsPath,
        environmentMainService.backupHome
      ].map((path3) => path3 ? promises15.mkdir(path3, { recursive: true }) : void 0)),
      // State service
      stateService.init(),
      // Configuration service
      configurationService.initialize()
    ]);
    userDataProfilesMainService.init();
  }
  e(path3) {
    if ($l) {
      const host = getUNCHost(path3);
      if (host) {
        addUNCHostToAllowlist(host);
      }
    }
    return path3;
  }
  async f(logService, environmentMainService, lifecycleMainService, instantiationService, productService, retry) {
    let mainProcessNodeIpcServer;
    try {
      mark("code/willStartMainServer");
      mainProcessNodeIpcServer = await $Ui(environmentMainService.mainIPCHandle);
      mark("code/didStartMainServer");
      Event.once(lifecycleMainService.onWillShutdown)(() => mainProcessNodeIpcServer.dispose());
    } catch (error) {
      if (error.code !== "EADDRINUSE") {
        this.g(environmentMainService, productService, error);
        throw error;
      }
      let client;
      try {
        client = await $Vi(environmentMainService.mainIPCHandle, "main");
      } catch (error2) {
        if (!retry || $l || error2.code !== "ECONNREFUSED") {
          if (error2.code === "EPERM") {
            this.h(localize(155, null, productService.nameShort), localize(156, null), productService);
          }
          throw error2;
        }
        try {
          unlinkSync2(environmentMainService.mainIPCHandle);
        } catch (error3) {
          logService.warn("Could not delete obsolete instance handle", error3);
          throw error3;
        }
        return this.f(logService, environmentMainService, lifecycleMainService, instantiationService, productService, false);
      }
      if (environmentMainService.extensionTestsLocationURI && !environmentMainService.debugExtensionHost.break) {
        const msg = `Running extension tests from the command line is currently only supported if no other instance of ${productService.nameShort} is running.`;
        logService.error(msg);
        client.dispose();
        throw new Error(msg);
      }
      let startupWarningDialogHandle = void 0;
      if (!environmentMainService.args.wait && !environmentMainService.args.status) {
        startupWarningDialogHandle = setTimeout(() => {
          this.h(localize(157, null, productService.nameShort), localize(158, null), productService);
        }, 1e4);
      }
      const otherInstanceLaunchMainService = ProxyChannel.toService(client.getChannel("launch"), { disableMarshalling: true });
      const otherInstanceDiagnosticsMainService = ProxyChannel.toService(client.getChannel("diagnostics"), { disableMarshalling: true });
      if (environmentMainService.args.status) {
        return instantiationService.invokeFunction(async () => {
          const diagnosticsService = new $lt($Up, productService);
          const mainDiagnostics = await otherInstanceDiagnosticsMainService.getMainDiagnostics();
          const remoteDiagnostics = await otherInstanceDiagnosticsMainService.getRemoteDiagnostics({ includeProcesses: true, includeWorkspaceMetadata: true });
          const diagnostics = await diagnosticsService.getDiagnostics(mainDiagnostics, remoteDiagnostics);
          console.log(diagnostics);
          throw new $nb();
        });
      }
      if ($l) {
        await this.i(otherInstanceLaunchMainService, logService);
      }
      logService.trace("Sending env to running instance...");
      await otherInstanceLaunchMainService.start(environmentMainService.args, process.env);
      client.dispose();
      if (startupWarningDialogHandle) {
        clearTimeout(startupWarningDialogHandle);
      }
      throw new $nb("Sent env to running instance. Terminating...");
    }
    if (environmentMainService.args.status) {
      console.log(localize(159, null, productService.nameShort));
      throw new $nb("Terminating...");
    }
    process.env["VSCODE_PID"] = String(process.pid);
    return mainProcessNodeIpcServer;
  }
  g(environmentMainService, productService, error) {
    if (error.code === "EACCES" || error.code === "EPERM") {
      const directories = $Ub([environmentMainService.userDataPath, environmentMainService.extensionsPath, $Qi]).map((folder) => $rx(URI.file(folder), { os: OS, tildify: environmentMainService }));
      this.h(localize(160, null), localize(161, null, $Kj(error), directories.join("\n")), productService);
    }
  }
  h(message, detail, productService) {
    dialog.showMessageBoxSync($Fx({
      type: "warning",
      buttons: [localize(162, null)],
      message,
      detail
    }, productService).options);
  }
  async i(launchMainService, logService) {
    if ($l) {
      const processId = await launchMainService.getMainProcessId();
      logService.trace("Sending some foreground love to the running instance:", processId);
      try {
        (await import("windows-foreground-love")).allowSetForegroundWindow(processId);
      } catch (error) {
        logService.error(error);
      }
    }
  }
  j(accessor, reason) {
    const logService = accessor.get($uk);
    const lifecycleMainService = accessor.get($9jc);
    let exitCode = 0;
    if (reason) {
      if (reason.isExpected) {
        if (reason.message) {
          logService.trace(reason.message);
        }
      } else {
        exitCode = 1;
        if (reason.stack) {
          logService.error(reason.stack);
        } else {
          logService.error(`Startup error: ${reason.toString()}`);
        }
      }
    }
    lifecycleMainService.kill(exitCode);
  }
  //#region Command line arguments utilities
  k() {
    const args = this.l($2m(process.argv));
    if (args.wait && !args.waitMarkerFilePath) {
      const waitMarkerFilePath = $Plc(args.verbose);
      if (waitMarkerFilePath) {
        $4m(process.argv, "--waitMarkerFilePath", waitMarkerFilePath);
        args.waitMarkerFilePath = waitMarkerFilePath;
      }
    }
    return args;
  }
  l(args) {
    if (args["open-url"]) {
      args._urls = args._;
      args._ = [];
    }
    if (!args["remote"]) {
      const paths = this.m(args._, args.goto);
      args._ = paths;
    }
    return args;
  }
  m(args, gotoLineMode) {
    const currentWorkingDir = cwd();
    const result = args.map((arg) => {
      let pathCandidate = String(arg);
      let parsedPath = void 0;
      if (gotoLineMode) {
        parsedPath = $7g(pathCandidate);
        pathCandidate = parsedPath.path;
      }
      if (pathCandidate) {
        pathCandidate = this.n(currentWorkingDir, pathCandidate);
      }
      const sanitizedFilePath = $1g(pathCandidate, currentWorkingDir);
      const filePathBasename = $zc(sanitizedFilePath);
      if (filePathBasename && !$Wg(filePathBasename)) {
        return null;
      }
      if (gotoLineMode && parsedPath) {
        parsedPath.path = sanitizedFilePath;
        return this.o(parsedPath);
      }
      return sanitizedFilePath;
    });
    const caseInsensitive = $l || $m;
    const distinctPaths = $Zb(result, (path3) => path3 && caseInsensitive ? path3.toLowerCase() : path3 || "");
    return $Ub(distinctPaths);
  }
  n(cwd2, path3) {
    if ($l) {
      path3 = $Gf(path3, '"');
    }
    path3 = $Ef($Ef(path3, " "), "	");
    if ($l) {
      path3 = $wc(cwd2, path3);
      path3 = $Gf(path3, ".");
    }
    return path3;
  }
  o(pathWithLineAndCol) {
    const segments = [pathWithLineAndCol.path];
    if (typeof pathWithLineAndCol.line === "number") {
      segments.push(String(pathWithLineAndCol.line));
    }
    if (typeof pathWithLineAndCol.column === "number") {
      segments.push(String(pathWithLineAndCol.column));
    }
    return segments.join(":");
  }
};
var code = new CodeMain();
code.main();

//# sourceMappingURL=main.js.map
